From tsila.hassine at gmail.com  Thu Mar  1 00:35:04 2007
From: tsila.hassine at gmail.com (Tsila Hassine)
Date: Thu, 1 Mar 2007 00:35:04 +0100
Subject: [Tutor] "IOError: decoder jpeg not available"
In-Reply-To: <45E5F628.8070006@h-lab.net>
References: <da5291e90702280849g2b59ba7ak4fd22633b006d34d@mail.gmail.com>
	<45E5F628.8070006@h-lab.net>
Message-ID: <da5291e90702281535j6cf2a462wdf44f154be511780@mail.gmail.com>

Hello all!

sorry - pretty much of a novice....
here's a snippet I am running from the Python interactive interface  - and
the error I am getting:


>>> import Image, imghdr
>>> im=Image.open('test406.jpg')
>>> new_image=im.resize((100.0,100.0), Image.ANTIALIAS)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File
"/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-packages/PIL/Image.py",
line 1188, in resize
    self.load()
  File
"/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-packages/PIL/ImageFile.py",
line 180, in load
    d = Image._getdecoder(self.mode, d, a, self.decoderconfig)
  File
"/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-packages/PIL/Image.py",
line 328, in _getdecoder
    raise IOError("decoder %s not available" % decoder_name)
IOError: decoder jpeg not available





I seem to have PIL in stalled in 2 different locations (don't know if that
may cause the problem):
1: ./Library/Python/2.3/PIL

2: ./Library/Python/2.3/site-packages/PIL

when I tried to reinstall imaging1.1.5 I got the following :

--- TKINTER support ok
*** JPEG support not available
--- ZLIB (PNG/ZIP) support ok
*** FREETYPE2 support not available



although I have jpeg-6b in ./jpeg6-and I also re installed adn got the
following :
% make -n install
/usr/bin/install -c cjpeg /usr/local/bin/cjpeg
/usr/bin/install -c djpeg /usr/local/bin/djpeg
/usr/bin/install -c jpegtran /usr/local/bin/jpegtran
/usr/bin/install -c rdjpgcom /usr/local/bin/rdjpgcom
/usr/bin/install -c wrjpgcom /usr/local/bin/wrjpgcom
/usr/bin/install -c -m 644 ./cjpeg.1 /usr/local/man/man1/cjpeg.1
/usr/bin/install -c -m 644 ./djpeg.1 /usr/local/man/man1/djpeg.1
/usr/bin/install -c -m 644 ./jpegtran.1 /usr/local/man/man1/jpegtran.1
/usr/bin/install -c -m 644 ./rdjpgcom.1 /usr/local/man/man1/rdjpgcom.1
/usr/bin/install -c -m 644 ./wrjpgcom.1 /usr/local/man/man1/wrjpgcom.1


I hope this provides some further insite....

thanks,
Tsila

On 2/28/07, Hugo Gonz?lez Monteverde <hugonz-lists at h-lab.net> wrote:
>
> Hi,
>
> It looks like there is a capability you don't have installed in your
> image processing lib. but you really give us nothing. Please tell us:
>
>   - Was this working before in any other operating system or python
> version?
>   - What module are you using for working with jpeg?
>   - Show us the code that throws this exception, or how you use it..
>
> And maybe we'll have some info to help you out.
>
>
> Tsila Hassine wrote:
> > Dear fellow Pythoneers,
> >
> > I have recently upgraded to Mac 10.4, and since then this error appears
> > when trying to manipulate an image (resize it actually),
> > can anyone help me out ?
> >
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070301/752d38c6/attachment.html 

From tsila.hassine at gmail.com  Thu Mar  1 01:57:04 2007
From: tsila.hassine at gmail.com (Tsila Hassine)
Date: Thu, 1 Mar 2007 01:57:04 +0100
Subject: [Tutor] "IOError: decoder jpeg not available"
In-Reply-To: <da5291e90702281535j6cf2a462wdf44f154be511780@mail.gmail.com>
References: <da5291e90702280849g2b59ba7ak4fd22633b006d34d@mail.gmail.com>
	<45E5F628.8070006@h-lab.net>
	<da5291e90702281535j6cf2a462wdf44f154be511780@mail.gmail.com>
Message-ID: <da5291e90702281657r45c4e0fan93cf0d90465bbe18@mail.gmail.com>

Hello again,

Problem finally solved : had to reinstall and rebuild PIL (from tar) - this
time pointing the setup.py to the right location of jpeg-6b library, and
ONLY THEN running setup.py build_ext -i of Imaging1.1.6

hope someone can make use of this,
Tsila

On 3/1/07, Tsila Hassine <tsila.hassine at gmail.com> wrote:
>
> Hello all!
>
> sorry - pretty much of a novice....
> here's a snippet I am running from the Python interactive interface  - and
> the error I am getting:
>
>
> >>> import Image, imghdr
> >>> im= Image.open('test406.jpg')
> >>> new_image=im.resize((100.0,100.0), Image.ANTIALIAS)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File
> "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-packages/PIL/Image.py",
> line 1188, in resize
>     self.load()
>   File
> "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-packages/PIL/ImageFile.py",
> line 180, in load
>     d = Image._getdecoder(self.mode, d, a, self.decoderconfig )
>   File
> "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-packages/PIL/Image.py",
> line 328, in _getdecoder
>     raise IOError("decoder %s not available" % decoder_name)
> IOError: decoder jpeg not available
>
>
>
>
>
> I seem to have PIL in stalled in 2 different locations (don't know if that
> may cause the problem):
> 1: ./Library/Python/2.3/PIL
>
> 2: ./Library/Python/2.3/site-packages/PIL
>
> when I tried to reinstall imaging1.1.5 I got the following :
>
> --- TKINTER support ok
> *** JPEG support not available
> --- ZLIB (PNG/ZIP) support ok
> *** FREETYPE2 support not available
>
>
>
> although I have jpeg-6b in ./jpeg6-and I also re installed adn got the
> following :
> % make -n install
> /usr/bin/install -c cjpeg /usr/local/bin/cjpeg
> /usr/bin/install -c djpeg /usr/local/bin/djpeg
> /usr/bin/install -c jpegtran /usr/local/bin/jpegtran
> /usr/bin/install -c rdjpgcom /usr/local/bin/rdjpgcom
> /usr/bin/install -c wrjpgcom /usr/local/bin/wrjpgcom
> /usr/bin/install -c -m 644 ./cjpeg.1 /usr/local/man/man1/cjpeg.1
> /usr/bin/install -c -m 644 ./djpeg.1 /usr/local/man/man1/djpeg.1
> /usr/bin/install -c -m 644 ./jpegtran.1 /usr/local/man/man1/jpegtran.1
> /usr/bin/install -c -m 644 ./rdjpgcom.1 /usr/local/man/man1/rdjpgcom.1
> /usr/bin/install -c -m 644 ./wrjpgcom.1 /usr/local/man/man1/wrjpgcom.1
>
>
> I hope this provides some further insite....
>
> thanks,
> Tsila
>
> On 2/28/07, Hugo Gonz?lez Monteverde <hugonz-lists at h-lab.net> wrote:
> >
> > Hi,
> >
> > It looks like there is a capability you don't have installed in your
> > image processing lib. but you really give us nothing. Please tell us:
> >
> >   - Was this working before in any other operating system or python
> > version?
> >   - What module are you using for working with jpeg?
> >   - Show us the code that throws this exception, or how you use it..
> >
> > And maybe we'll have some info to help you out.
> >
> >
> > Tsila Hassine wrote:
> > > Dear fellow Pythoneers,
> > >
> > > I have recently upgraded to Mac 10.4, and since then this error
> > appears
> > > when trying to manipulate an image (resize it actually),
> > > can anyone help me out ?
> > >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070301/84b8ade0/attachment.html 

From bgailer at alum.rpi.edu  Thu Mar  1 03:29:56 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Wed, 28 Feb 2007 18:29:56 -0800
Subject: [Tutor] howto call DOM with python
In-Reply-To: <BAY106-F28865BCC51F23C60116695A2810@phx.gbl>
References: <BAY106-F28865BCC51F23C60116695A2810@phx.gbl>
Message-ID: <45E63AA4.1090308@alum.rpi.edu>

Ismael Farf?n Estrada wrote:
> hi there
>
> I was wondering wheter someone knows how to use python to write
> a client-side scripts like if it were java, I want to get someting like
> this working
> <html>
> <script type="text/python">
> window.alert("python")
> </script>
> </html>
>
> but nothing happens. I don't know javascript but this code works
> if I put javascript instead of python, I've also tried with pythonscript
> python-source, etc
>
> hope you can help me, I'm using GNU/Suse, Opera, and Firefox for test
>   
As others have pointed out, browsers only know JavaScript. But take a 
look at pyjamas: http://pyjamas.pyworks.org/ which translates Python 
into browser-specific JavaScript. It is designed around a Python port of 
Google Web Toolkit, but you don't need to use that aspect of it. Of 
course the ability to create web pages using the ported GWT widgets is 
pretty impressive. No more HTML!

Take a look at the pyjamas helloworld example.

-- 
Bob Gailer
510-978-4454


From janos.juhasz at VELUX.com  Thu Mar  1 08:01:08 2007
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Thu, 1 Mar 2007 08:01:08 +0100
Subject: [Tutor] howto call DOM with python
In-Reply-To: <mailman.14308.1172710673.32030.tutor@python.org>
Message-ID: <OFAAF695D3.C7FF0688-ONC1257291.0025D29D-C1257291.00268D7F@velux.com>

hi

there are same samples about it in the activepython 2.4 installation 
folder
c:\Python24\Lib\site-packages\win32comext\axscript\Demos\client\ie\
on my xp, but it isn't working. I have just repaired my activepython and 
reinstalled it but no success.

As I remenber, it was working under activepython 2.3 anyway.


Yours sincerely,
______________________________
J?nos Juh?sz


> Date: Wed, 28 Feb 2007 15:40:59 -0600
> From: Hugo Gonz?lez Monteverde <hugonz-lists at h-lab.net>
> Subject: Re: [Tutor] howto call DOM with python
> To: tutor at python.org
> Message-ID: <45E5F6EB.30408 at h-lab.net>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed

> I too wish it worked. In javascript, it works because the browser has a
> Javascript implementation. There's no stock browser with a Python
> implementation, and I've looked for any client side implementation with
> no success.

> Hugo

> Ismael Farf?n Estrada wrote:
> > hi there
> >
> > I was wondering wheter someone knows how to use python to write
> > a client-side scripts like if it were java, I want to get someting 
like
> > this working
> > <html>
> > <script type="text/python">
> > window.alert("python")
> > </script>
> > </html>
> >
> > but nothing happens. I don't know javascript but this code works
> > if I put javascript instead of python, I've also tried with 
pythonscript
> > python-source, etc
> >
> > hope you can help me, I'm using GNU/Suse, Opera, and Firefox for test
> >
> > _________________________________________________________________
> > El mejor destino, con los mejores contenidos 
http://www.prodigy.msn.com
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >



From bnpurcel at indiana.edu  Thu Mar  1 07:40:45 2007
From: bnpurcel at indiana.edu (Purcell,  Brittany Nicole)
Date: Thu,  1 Mar 2007 01:40:45 -0500
Subject: [Tutor] python problem
Message-ID: <20070301014045.j2kzy0pwggkog4o4@webmail.iu.edu>

I have no idea how to even begin to program something like this and 
what I need to do is:
To complete the skeleton by replacing ellipsis (in this case vertical) 
with a  solution. The number of dot indicates the number of lines of 
the solution, and fill in the following dots:

def every_nth(s, n):
    """Return a string composed of every n_th character of s, starting from the
    first; that is, those characters with indices 0, 1*n, 2*n, ...

    >>> every_nth('abcdefg', 2)
    'aceg'
    >>> every_nth('abcdefg', 3)
    'adg'
    >>> every_nth('abcdefg', 1)
    'abcdefg'
    >>> every_nth('abcdefg', 20)
    'a'
    >>>
    """
    .
    .
    .
    .
    .
    .


def space_separate(s):
    """Return a copy of string s with a space inserted between each of the
    characters of string s.

    Use iteration over the characters of s.

    >>> assert space_separate('abc') == 'a b c'
    >>> assert space_separate('') == ''
    >>>
    """
    .
    .
    .
    .
    .
    .

def reverse(s):
    """Return a string with the characters of string s in reverse order.

    Implement with a while loop and indexing.

    >>> assert reverse('abc') == 'cba'
    >>> assert reverse('') == ''
    >>>
    """
    .
    .
    .
    .
    .
    .

def test():
    """Tests for this file."""
    # add a few tests for each function below using assert statements

if __name__ == '__main__':
    test()



From kent37 at tds.net  Thu Mar  1 16:54:36 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 1 Mar 2007 10:54:36 -0500
Subject: [Tutor] python problem
Message-ID: <20070301155436.JZFD14201.outaamta02.mail.tds.net@smtp.tds.net>

> 
> From: "Purcell,  Brittany Nicole" <bnpurcel at indiana.edu>
> Date: 2007/03/01 Thu AM 01:40:45 EST
> To: tutor at python.org
> Subject: [Tutor] python problem
> 
> I have no idea how to even begin to program something like this and 
> what I need to do is:
> To complete the skeleton by replacing ellipsis (in this case vertical) 
> with a  solution. The number of dot indicates the number of lines of 
> the solution, and fill in the following dots:

This looks like homework to me. We won't do your homework for you. We will answer questions and help you when you have trouble but you have to try.

What have you learned so far in class? How might you apply that to these exercises?

Kent
> 
> def every_nth(s, n):
>     """Return a string composed of every n_th character of s, starting from the
>     first; that is, those characters with indices 0, 1*n, 2*n, ...
> 
>     >>> every_nth('abcdefg', 2)
>     'aceg'
>     >>> every_nth('abcdefg', 3)
>     'adg'
>     >>> every_nth('abcdefg', 1)
>     'abcdefg'
>     >>> every_nth('abcdefg', 20)
>     'a'
>     >>>
>     """
>     .
>     .
>     .
>     .
>     .
>     .
> 
> 
> def space_separate(s):
>     """Return a copy of string s with a space inserted between each of the
>     characters of string s.
> 
>     Use iteration over the characters of s.
> 
>     >>> assert space_separate('abc') == 'a b c'
>     >>> assert space_separate('') == ''
>     >>>
>     """
>     .
>     .
>     .
>     .
>     .
>     .
> 
> def reverse(s):
>     """Return a string with the characters of string s in reverse order.
> 
>     Implement with a while loop and indexing.
> 
>     >>> assert reverse('abc') == 'cba'
>     >>> assert reverse('') == ''
>     >>>
>     """
>     .
>     .
>     .
>     .
>     .
>     .
> 
> def test():
>     """Tests for this file."""
>     # add a few tests for each function below using assert statements
> 
> if __name__ == '__main__':
>     test()
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



From singh01 at gmail.com  Thu Mar  1 17:18:26 2007
From: singh01 at gmail.com (Nagendra Singh)
Date: Thu, 1 Mar 2007 11:18:26 -0500
Subject: [Tutor] Problem with Import
In-Reply-To: <5850ed90702281212v44da18b7t945af7698acb79be@mail.gmail.com>
References: <cd2d0ceb0702281007n3fb09979k1d223863721080f9@mail.gmail.com>
	<5850ed90702281212v44da18b7t945af7698acb79be@mail.gmail.com>
Message-ID: <cd2d0ceb0703010818l56f9c6acrfd07dfdd32d04868@mail.gmail.com>

Thanks for the suggestion, the Python path is correct. After a bit of
experimenting I found out that it works with Python 2.3 but not 2.4 but I
have no clue as to why.

Nagendra

On 2/28/07, Jalil <jalilsan at gmail.com> wrote:
>
> check your python path
>
> On 2/28/07, Nagendra Singh <singh01 at gmail.com> wrote:
>
> > Hi all,
> >
> > I am running python on Cygwin and I have also installed gdal which is a
> > raster translator library. When I run the command import gdal, Python gives
> > me an error :
> >
> > Python 2.4.3 (#1, May 18 2006, 07:40:45)
> > [GCC 3.3.3 (cygwin special)] on cygwin
> > Type "help", "copyright", "credits" or "license" for more information.
> > >>> import gdal
> > Traceback (most recent call last):
> >   File "<stdin>", line 1, in ?
> >   File "/usr/lib/python2.4/site-packages/gdal.py", line 191, in ?
> >     import _gdal
> > ImportError: No module named _gdal
> >
> > The file gdal.py and gdal.pyc are in : /usr/lib/python2.4/site-packages,
> > but still it gives this error.
> >
> > Thanks
> >
> > Singh
> >
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070301/54499b18/attachment.html 

From rikard.bosnjakovic at gmail.com  Thu Mar  1 17:19:32 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Thu, 1 Mar 2007 17:19:32 +0100
Subject: [Tutor] python problem
In-Reply-To: <20070301014045.j2kzy0pwggkog4o4@webmail.iu.edu>
References: <20070301014045.j2kzy0pwggkog4o4@webmail.iu.edu>
Message-ID: <d9e88eaf0703010819o3d724399i21810fc7cc8a09e@mail.gmail.com>

On 3/1/07, Purcell,  Brittany Nicole <bnpurcel at indiana.edu> wrote:
> I have no idea how to even begin to program something like this and
> what I need to do is:

We won't do your homework unless you atleast show that you are
interested in learning what you are doing, and not only going for
grade points.

-- 
- Rikard.

From kent37 at tds.net  Thu Mar  1 17:27:44 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 1 Mar 2007 11:27:44 -0500
Subject: [Tutor] python problem
Message-ID: <20070301162744.KRBS14201.outaamta02.mail.tds.net@smtp.tds.net>

> From: "Ted Roche" <tedroche at gmail.com>
> Sounds like A201 to me...
> 
> http://www.cs.indiana.edu/classes/a201/Syllabus.html

Yes, assignment 7 lab work
http://www.cs.indiana.edu/classes/a201/a/7/index.html

Kent



From andreas at kostyrka.org  Thu Mar  1 18:49:11 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Thu,  1 Mar 2007 18:49:11 +0100
Subject: [Tutor] python problem
Message-ID: <rwKKStbwtxj6.dfGLZBx2@heaven.kostyrka.org>

Why does that look like a homework to me? One where you are supposed to solve it by yourself?

Andreas

_____ Urspr?ngliche Mitteilung _____
Betreff:	[Tutor] python problem
Autor:	"Purcell, Brittany Nicole" <bnpurcel at indiana.edu>
Datum:		1. M?rz 2007 7:40:45

I have no idea how to even begin to program something like this and 
what I need to do is:
To complete the skeleton by replacing ellipsis (in this case vertical) 
with a  solution. The number of dot indicates the number of lines of 
the solution, and fill in the following dots:

def every_nth(s, n):
    """Return a string composed of every n_th character of s, starting from the
    first; that is, those characters with indices 0, 1*n, 2*n, ...

    >>> every_nth('abcdefg', 2)
    'aceg'
    >>> every_nth('abcdefg', 3)
    'adg'
    >>> every_nth('abcdefg', 1)
    'abcdefg'
    >>> every_nth('abcdefg', 20)
    'a'
    >>>
    """
    .
    .
    .
    .
    .
    .


def space_separate(s):
    """Return a copy of string s with a space inserted between each of the
    characters of string s.

    Use iteration over the characters of s.

    >>> assert space_separate('abc') == 'a b c'
    >>> assert space_separate('') == ''
    >>>
    """
    .
    .
    .
    .
    .
    .

def reverse(s):
    """Return a string with the characters of string s in reverse order.

    Implement with a while loop and indexing.

    >>> assert reverse('abc') == 'cba'
    >>> assert reverse('') == ''
    >>>
    """
    .
    .
    .
    .
    .
    .

def test():
    """Tests for this file."""
    # add a few tests for each function below using assert statements

if __name__ == '__main__':
    test()


_______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070301/94797c7c/attachment.html 

From pyro9219 at gmail.com  Thu Mar  1 23:30:49 2007
From: pyro9219 at gmail.com (Chris Hengge)
Date: Thu, 1 Mar 2007 14:30:49 -0800
Subject: [Tutor] httpd in your laptop?!? serve web pages and wikis in
	your notebook?
In-Reply-To: <45E5188F.7010902@gmail.com>
References: <45E50446.8060502@verizon.net> <45E5188F.7010902@gmail.com>
Message-ID: <c25107380703011430n3fb9369ckd7701c28494c6b1b@mail.gmail.com>

I was using Abyss web server for a long time since it has multi-OS support
and a friendly web based UI for administration. Seemed extremely light
weight to me.

On 2/27/07, Luke Paireepinart <rabidpoobear at gmail.com> wrote:
>
> Kirk Bailey wrote:
> > ok, I realized  SOME TIME BACK that to run MANY THINGS in your windows
> > computer you need a server in there- and a nice SMALL one if it is going
> > to coexist with everything else going on.
> You need a server for what now?
> Web pages?  FTP? SVN?
> I can't think of much else.
>
> I run apache and ftp services on my windows machine, and they're
> using... let me check...
> 4 MB of ram for the FTP server, and 4.6 MB of ram for Apache.  neither
> of these are considered 'lightweight' apps.  Both are fully-featured.
> Neither are listed as using more than 0% CPU.
> My IM client uses 14 MB, my music program uses 32 MB, my browser is
> using 63 MB, and my e-mail client is using 47 MB.
> I would consider Apache fairly resource-friendly, compared to these
> other apps.  Not to mention it's used on over 50% of EVERY web server,
> so I'm pretty sure it's reliable.  And I don't see a need to use
> anything else.  If your software asked me to install some obscure web
> server I've never heard of, I would probably cancel the installation and
> forget about it, for fear it would interfere with my already-established
> Apache server.
> >  I found one in python, and
> > posted it, and it caused a stirr.
> I don't know what you're referring to, maybe it was before I joined the
> list.
> >  Well, I found a LISTING of them, and
> > tried all the more promising ones. here is that page:
> > http://microsoft.toddverbeek.com/phttpd.html
> >
> Can I ask why are you looking into this?
> As far as I can tell, the software you're writing (miniwiki) will be
> served from the client's computer directly to the client's web
> browser.  No actual web stuff is necessary, right?
> I don't understand why you'd want to make the user have to install
> another webserver to use your program.  You're writing it in Python, why
> not use a Python HTTP server library, and have that included in your
> distribution when you py2exe it?
> It seems by far a better solution.
>
> JMO,
> -Luke
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070301/f00c3f90/attachment-0001.htm 

From brunson at brunson.com  Thu Mar  1 23:17:24 2007
From: brunson at brunson.com (Eric Brunson)
Date: Thu, 01 Mar 2007 15:17:24 -0700
Subject: [Tutor] Explanation of this lambda
In-Reply-To: <20070222103724.D4E42168C6@mail.accesstel.co.za>
References: <20070222103724.D4E42168C6@mail.accesstel.co.za>
Message-ID: <45E750F4.7070402@brunson.com>

Johan Geldenhuys wrote:
> Thanks, Alan.
>
> That makes it a lot easier to understand. I'll play around with other
> examples to see what it is doing.
>
> Johan 
>   

A good first step to understanding a confusing lambda is to convert it 
to a normal function.\

Just my $.02,
e.

> -----Original Message-----
> From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf
> Of Alan Gauld
> Sent: 22 February 2007 11:46 AM
> To: tutor at python.org
> Subject: Re: [Tutor] Explanation of this lambda
>
>
> "Johan Geldenhuys" <johan at accesstel.co.za> wrote
>
>   
>> Would somebody care to explain what is happening in this process?
>>
>> def intToBin(self, x, count=8):
>>        return "".join(map(lambda y:str((x>>y)&1), range(count-1, -1, 
>> -1)))
>>     
>
> "".join()   turns a list into a string
> map() returns a list where each item is the result of applying the lambda to
> the range()
>
> lamda y: .....  is a function to be applied
>
> str() converts to a string
>
> x>>y   shifts the bits of x right by y places  010 -> 001
>
> & 1 bitwise ands with 1 which returns 1 if the last bit is one.
>
> put the bits together and it should be clear.
>
> HTH,
>
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


From Barry.Carroll at psc.com  Fri Mar  2 00:45:45 2007
From: Barry.Carroll at psc.com (Carroll, Barry)
Date: Thu, 1 Mar 2007 15:45:45 -0800
Subject: [Tutor] python problem
In-Reply-To: <mailman.14428.1172788256.32030.tutor@python.org>
Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595B17@eugsrv400.psc.pscnet.com>

> -----Original Message-----
> Date: Thu, 1 Mar 2007 10:54:36 -0500
> From: Kent Johnson <kent37 at tds.net>
> Subject: Re: [Tutor] python problem
> To: "Purcell,  Brittany Nicole" <bnpurcel at indiana.edu>,
> 	<tutor at python.org>
> Message-ID:
> 	<20070301155436.JZFD14201.outaamta02.mail.tds.net at smtp.tds.net>
> Content-Type: text/plain; charset=ISO-8859-1
> 
> >
> > From: "Purcell,  Brittany Nicole" <bnpurcel at indiana.edu>
> > Date: 2007/03/01 Thu AM 01:40:45 EST
> > To: tutor at python.org
> > Subject: [Tutor] python problem
> >
> > I have no idea how to even begin to program something like this and
> > what I need to do is:
> > To complete the skeleton by replacing ellipsis (in this case
vertical)
> > with a  solution. The number of dot indicates the number of lines of
> > the solution, and fill in the following dots:
> 
> This looks like homework to me. We won't do your homework for you. We
will
> answer questions and help you when you have trouble but you have to
try.
> 
> What have you learned so far in class? How might you apply that to
these
> exercises?
> 
> Kent
> >
<<snip>>
> >
Hello, Brittany.

I agree with Kent, et al: I'm not doing to do the work for you.  That
doesn't do you any good and besides, we all have our own work to do.
But, just saying, "go do it yourself" isn't very good tutoring, IMHO.
So, here are a couple of hints, and a method (algorithm for you
theoretical CS types) that will help you get better results from the
folks on this mailing list.

	1. Consider the following (here come the hints):
		* All of these exercises deal with string manipulation.
		* In Python, a string is a type of sequence.
		* Pieces of a Python sequence can be accessed using
indices 
		  (singular: index) and slices.
	2. Read what your text (and class notes, if you have them) has
to 
	   say on these topics.  
	3. Fire up your Python interpreter and try out some of the
examples
	   you found in 2.  
	4. Make up some examples of your own and try them out.
	5. Try solving one or more of your exercises using what you've
learned
	   from 1. - 4.  
	6. If your solution doesn't work, send another e-mail here,
including 
	   your code and any output and error messages you get, asking
for 
	   suggestions, explanations, etc.  

This really is a great place to get help, once you've made an honest
effort to help yourself.  

Good luck.

Barry
barry.carroll at psc.com
541-302-1107
________________________
We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed




From alan.gauld at btinternet.com  Fri Mar  2 01:09:09 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 2 Mar 2007 00:09:09 -0000
Subject: [Tutor] Problem with Import
References: <cd2d0ceb0702281007n3fb09979k1d223863721080f9@mail.gmail.com><5850ed90702281212v44da18b7t945af7698acb79be@mail.gmail.com>
	<cd2d0ceb0703010818l56f9c6acrfd07dfdd32d04868@mail.gmail.com>
Message-ID: <es7psq$j5$1@sea.gmane.org>


"Nagendra Singh" <singh01 at gmail.com> wrote

> experimenting I found out that it works with Python 2.3 but not 2.4

>> > >>> import gdal
>> > Traceback (most recent call last):
>> >   File "<stdin>", line 1, in ?
>> >   File "/usr/lib/python2.4/site-packages/gdal.py", line 191, in ?
>> >     import _gdal
>> > ImportError: No module named _gdal

Note its complaining that gdal is importing _gdal which doesn't exist.
It seems likely that import _gdal is looking for a compiled library
(ie a .so)  file.

Do you have the 2.4 binary library installed as well as the .py file?

Just a guess...

Alan G. 



From alan.gauld at btinternet.com  Fri Mar  2 01:17:47 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 2 Mar 2007 00:17:47 -0000
Subject: [Tutor] howto call DOM with python
References: <BAY106-F28865BCC51F23C60116695A2810@phx.gbl>
Message-ID: <es7qcu$20m$1@sea.gmane.org>

"Ismael Farf?n Estrada" <sulfurfff at hotmail.com> wrote

> I was wondering wheter someone knows how to use python to write
> a client-side scripts like if it were java, I want to get someting 
> like
> this working
> <html>
> <script type="text/python">
> window.alert("python")
> </script>
> </html>

You can do that in Internet Explorer provided you
a) Have the winall package installed and
b) Have turned on Activce Scripting so that Pythonm is
recognised as a language

> but nothing happens. I don't know javascript but this code works
> if I put javascript instead of python,

JavaScript is built in to most browsers (and VBScript is built into 
IE)
Any other scripting languages will need to be installed on the
target users machine. That is quite unlikely on the web so
most folks stick to JavaScript for browser based scripting.

Java applets will run if a JVM is installed (which it usually is)
and so you can write applets in Jython and compile them to
JVM code and they will work too.

> I've also tried with pythonscript python-source, etc

No, it has to be a valid interpreter. But the interpreter must also
be installed in the browser...

> hope you can help me, I'm using GNU/Suse, Opera, and Firefox for 
> test

I don't think you can make it work under Linux. The Jython applet
is your nearest option. You will be better learing the ninimum of
JavaScript IMHO. Try my tutorial as a quickl way in, especially
if you know Python...

Finally, you may be able to do what you want using the urllib
module to replace the browser entirely!

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




From andreas at kostyrka.org  Fri Mar  2 03:49:35 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Fri, 2 Mar 2007 03:49:35 +0100
Subject: [Tutor] python problem
In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A4304595B17@eugsrv400.psc.pscnet.com>
References: <mailman.14428.1172788256.32030.tutor@python.org>
	<2BBAEE949D384D40A2B851287ADB6A4304595B17@eugsrv400.psc.pscnet.com>
Message-ID: <20070302024935.GI30027@andi-lap.la.revver.com>

Actually, it's a corner case, because the posted exercise seems to be
the lab exercise where students are allowed to cooperate and ask for
help. The second part of the exercise they need to do themselves alone.

Andreas

From dhirajsharma at optonline.net  Fri Mar  2 06:16:00 2007
From: dhirajsharma at optonline.net (Dhiraj Sharma)
Date: Fri, 02 Mar 2007 00:16:00 -0500
Subject: [Tutor] Difficulty with the subprocess module
Message-ID: <000201c75c89$e5645020$0401a8c0@hp1140>

I am using the subprocess module to capture the 
input/output of a process on a Windows machine 
with Python 2.5 and ran into a puzzling problem.

The following works well:
----------------
   p = subprocess.Popen("cat", buffer=0, stdin=subprocess.PIPE,
       stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
   # "cat" is installed as a cygwin program, but this script is running
   # in a Command.com windows. I am not on Linux.

   fdata = open('input');
   for l in fdata:
      p.stdin.write(l)
      m = p.stdout.readline()
      sys.stdout.write(m)
----------------

If I replace the "cat" process by "sed -e s/a/x/g", the 
script hangs on the readline() call -- as indicated by 
the following messages obtained after entering Ctl-C:
----------------
Traceback (most recent call last):
  File "x.py", line 39, in <module>
    pipe_ex2()
  File "x.py", line 34, in pipe_ex2
    m = p.stdout.readline()
KeyboardInterrupt
----------------

Finally, if I replace "cat" by "python cat.py", the 
script hangs so badly that even Ctl-C does not work,
and I have to close the Command.com window. All by
itseld the cat.py script works fine and is given below:
----------------
import sys, os

fin = sys.stdin; fout = sys.stdout;
for l in fin:
   fout.write(l)
----------------

I would appreciate guidance regarding:
1. Why is the script behaving differently for cat and sed?
2. Why the python subprocess "kills" the parent script?
3. What is the right way to write the above scripts?

Thanks very much
D.Sharma
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070302/5d08304c/attachment.html 

From deliberatus at verizon.net  Fri Mar  2 08:43:10 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Fri, 02 Mar 2007 02:43:10 -0500
Subject: [Tutor] httpd in your laptop?!? serve web pages and wikis in
 your notebook?
In-Reply-To: <c25107380703011430n3fb9369ckd7701c28494c6b1b@mail.gmail.com>
References: <45E50446.8060502@verizon.net> <45E5188F.7010902@gmail.com>
	<c25107380703011430n3fb9369ckd7701c28494c6b1b@mail.gmail.com>
Message-ID: <45E7D58E.1030107@verizon.net>

it is good, no arguement, I have a copy. I am trying to come up with the 
solution that has the MINIMUM impact on the system so as to be 
supportable on an obsolete laptop with an underpowered processor, so 
size and clock cycle demands are high priorities. abyss is very good,
but not so small, and only moderately thrifty on cycles. So far, i 
cannot measure the impact tinyweb is having on this laptop I am writing 
to you on while tiny is running. and being totally free even if issued 
with sold products, the legal aspect is quite acceptable, unlike another 
high scoring server i tested and found acceptable.

It comes from the people who wrote and sell the bat, an email client.




Chris Hengge wrote:
> I was using Abyss web server for a long time since it has multi-OS 
> support and a friendly web based UI for administration. Seemed extremely 
> light weight to me.
> 
> On 2/27/07, * Luke Paireepinart* <rabidpoobear at gmail.com 
> <mailto:rabidpoobear at gmail.com>> wrote:
> 
>     Kirk Bailey wrote:
>      > ok, I realized  SOME TIME BACK that to run MANY THINGS in your
>     windows
>      > computer you need a server in there- and a nice SMALL one if it
>     is going
>      > to coexist with everything else going on.
>     You need a server for what now?
>     Web pages?  FTP? SVN?
>     I can't think of much else.
> 
>     I run apache and ftp services on my windows machine, and they're
>     using... let me check...
>     4 MB of ram for the FTP server, and 4.6 MB of ram for Apache.  neither
>     of these are considered 'lightweight' apps.  Both are fully-featured.
>     Neither are listed as using more than 0% CPU.
>     My IM client uses 14 MB, my music program uses 32 MB, my browser is
>     using 63 MB, and my e-mail client is using 47 MB.
>     I would consider Apache fairly resource-friendly, compared to these
>     other apps.  Not to mention it's used on over 50% of EVERY web server,
>     so I'm pretty sure it's reliable.  And I don't see a need to use
>     anything else.  If your software asked me to install some obscure web
>     server I've never heard of, I would probably cancel the installation and
>     forget about it, for fear it would interfere with my
>     already-established
>     Apache server.
>      >  I found one in python, and
>      > posted it, and it caused a stirr.
>     I don't know what you're referring to, maybe it was before I joined the
>     list.
>      >  Well, I found a LISTING of them, and
>      > tried all the more promising ones. here is that page:
>      > http://microsoft.toddverbeek.com/phttpd.html
>      >
>     Can I ask why are you looking into this?
>     As far as I can tell, the software you're writing (miniwiki) will be
>     served from the client's computer directly to the client's web
>     browser.  No actual web stuff is necessary, right?
>     I don't understand why you'd want to make the user have to install
>     another webserver to use your program.  You're writing it in Python, why
>     not use a Python HTTP server library, and have that included in your
>     distribution when you py2exe it?
>     It seems by far a better solution.
> 
>     JMO,
>     -Luke
> 
>     _______________________________________________
>     Tutor maillist  -  Tutor at python.org <mailto:Tutor at python.org>
>     http://mail.python.org/mailman/listinfo/tutor
>     <http://mail.python.org/mailman/listinfo/tutor>
> 
> 
> 
> ------------------------------------------------------------------------
> 
> No virus found in this incoming message.
> Checked by AVG Free Edition.
> Version: 7.5.446 / Virus Database: 268.18.4/705 - Release Date: 2/27/2007 3:24 PM

-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From alan.gauld at btinternet.com  Fri Mar  2 09:13:49 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 2 Mar 2007 08:13:49 -0000
Subject: [Tutor] Difficulty with the subprocess module
References: <000201c75c89$e5645020$0401a8c0@hp1140>
Message-ID: <es8m84$3e2$1@sea.gmane.org>


"Dhiraj Sharma" <dhirajsharma at optonline.net> wrote 

> ----------------
>   p = subprocess.Popen("cat", buffer=0, stdin=subprocess.PIPE,
>       stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
> 
>   fdata = open('input');
>   for l in fdata:
>      p.stdin.write(l)
>      m = p.stdout.readline()
>      sys.stdout.write(m)
> ----------------
> 
> If I replace the "cat" process by "sed -e s/a/x/g", the 
> script hangs on the readline() call -- as indicated by 

> I would appreciate guidance regarding:
> 1. Why is the script behaving differently for cat and sed?

At a guess... sed doesn't process the data line by line so 
you will have to send all lines to sed (plus maybe an EOF marker?)
before trying to read the output.
Frankly that would surprise me since sed is supposed to be a 
steam editor so I wold expect it to be line oriented, but 
it would be one explanation...

Another might be that you have to explicitly flush() stdin 
after writing to it?

> 2. Why the python subprocess "kills" the parent script?

No idea!

> 3. What is the right way to write the above scripts?

You look to be on the right track to me.
But any kind of communication between programs via stdin/stdout
is frought with difficulty because of the inconsistencies in the 
behaviours of programs. Its always much better to use an API 
if one exists. And often its easier to just write the specific 
function you need in Python.

In the case of sed a regex replace function is probably easier!
And probably faster too since it avoids the process startup 
overhead...

HTH,

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


From mail at timgolden.me.uk  Fri Mar  2 10:13:17 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Fri, 02 Mar 2007 09:13:17 +0000
Subject: [Tutor] howto call DOM with python
In-Reply-To: <es7qcu$20m$1@sea.gmane.org>
References: <BAY106-F28865BCC51F23C60116695A2810@phx.gbl>
	<es7qcu$20m$1@sea.gmane.org>
Message-ID: <45E7EAAD.6050006@timgolden.me.uk>

Alan Gauld wrote:

> You can do that in Internet Explorer provided you
> a) Have the winall package installed and

Just an aid to newcomers: the "winall" package
referred to here are the windows-oriented
extension modules by Mark Hammond which used to
be known as win32all and are now known as pywin32:

   http://pywin32.sf.net

TJG


(Sorry, Alan, just that searching for python winall
didn't yield entirely helpful results)

From alan.gauld at btinternet.com  Fri Mar  2 10:25:27 2007
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Fri, 2 Mar 2007 09:25:27 +0000 (GMT)
Subject: [Tutor] howto call DOM with python
Message-ID: <120189.58368.qm@web86108.mail.ird.yahoo.com>

Thanks for the update Tim. 
I haven't downloaded the package in a while since
I've been using ActiveStates version on my Windows box 
which includes the extensions in the bundle.

Alan g.


----- Original Message ----
From: Tim Golden <mail at timgolden.me.uk>
To: Alan Gauld <alan.gauld at btinternet.com>
Cc: tutor at python.org
Sent: Friday, 2 March, 2007 9:13:17 AM
Subject: Re: [Tutor] howto call DOM with python

Alan Gauld wrote:

> You can do that in Internet Explorer provided you
> a) Have the winall package installed and

Just an aid to newcomers: the "winall" package
referred to here are the windows-oriented
extension modules by Mark Hammond which used to
be known as win32all and are now known as pywin32:

   http://pywin32.sf.net

TJG


(Sorry, Alan, just that searching for python winall
didn't yield entirely helpful results)





	
	
		
___________________________________________________________ 
New Yahoo! Mail is the ultimate force in competitive emailing. Find out more at the Yahoo! Mail Championships. Plus: play games and win prizes. 
http://uk.rd.yahoo.com/evt=44106/*http://mail.yahoo.net/uk 

From David.Barton at nottingham.ac.uk  Fri Mar  2 12:25:54 2007
From: David.Barton at nottingham.ac.uk (Barton David)
Date: Fri, 2 Mar 2007 11:25:54 -0000
Subject: [Tutor] using tarfile on strings or filelike objects
Message-ID: <BAA2EE790D828F4E8B262F17B3B0A7A30363CEE5@VUIEXCH1.ad.nottingham.ac.uk>

I like that I can access the contents of a zip archive that's stored in
memory (rather than on disk) by packing the archive contents into a
StringIO or cStringIO object and feeding that to ZipFile...
 
i.e. 
 
filelike=cStringIO.StringIO(archive_as_string)
zf=zipfile.ZipFile(filelike)
content=zf.read(archive_member_name)
zf.close()
filelike.close()
 
but I can't get the same thing to work with TarFile. Is there any way to
do this? (Other than first saving the archive data to disk and then
passing the path to TarFile.open?) The tarfile module documentation
talks about an optional fileobj flag but this doesn't seem to work.
 
cheers
Dave

This message has been checked for viruses but the contents of an attachment
may still contain software viruses, which could damage your computer system:
you are advised to perform your own checks. Email communications with the
University of Nottingham may be monitored as permitted by UK legislation.

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

From flickita at gmail.com  Fri Mar  2 15:32:40 2007
From: flickita at gmail.com (Cecilia Alm)
Date: Fri, 2 Mar 2007 08:32:40 -0600
Subject: [Tutor] executing a string representing python code
Message-ID: <7a4620dc0703020632q615c53b6me8a187685406dbbd@mail.gmail.com>

I know that there are several ways to execute a string which represents a
piece of python code.
Out of curiosity, is it only eval which returns a value? (as below, where
the string corresponds to a defined function).

>>> def addone(val):
...     return val + 1
...
>>> res = eval('addone(10)')

Thanks!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070302/9cb8ce53/attachment.htm 

From jsmith at medplus.com  Fri Mar  2 16:18:18 2007
From: jsmith at medplus.com (Smith, Jeff)
Date: Fri, 2 Mar 2007 10:18:18 -0500
Subject: [Tutor] Yet another list comprehension question
Message-ID: <288A3B43F7B2224D9C8441C9FC5D6A02012E34B1@EXCHMAIL01.corp.medplus.com>

I find a common thing to do is

l = list()
for i in some-iterator:
    if somefum(i) != list:
    	l.append(somefun(i))

In other words, applying somefun to the results of the iterator return
duplicates but I want the constructed list to contain none.

l = [somefun(i) for i some-iterator]

will produce the redundancies

l = [somefun(i) for i some-iterator if somefun(i) not in l]

doesn't work (not that I expected it to).

Is there a more Pythonic idiom to do this than the for/if block?

Thanks,
Jeff


From singh01 at gmail.com  Fri Mar  2 16:28:15 2007
From: singh01 at gmail.com (Nagendra Singh)
Date: Fri, 2 Mar 2007 10:28:15 -0500
Subject: [Tutor]  Problem with Import
Message-ID: <cd2d0ceb0703020728n36669525j5f1269e6b35aa9f7@mail.gmail.com>

Hi Alan,

I had installed Python through cygwin and then installed Gdal from
source. I have tried everything but it does not work, my guess is I am
missing something trivial, I am planning to uninstall everything
(Cygwin and Gdal) and then reinstall all of it again over the weekend,
this is my last option.

thanks
Nagendra

From alan.gauld at btinternet.com  Fri Mar  2 16:56:52 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 2 Mar 2007 15:56:52 -0000
Subject: [Tutor] Yet another list comprehension question
References: <288A3B43F7B2224D9C8441C9FC5D6A02012E34B1@EXCHMAIL01.corp.medplus.com>
Message-ID: <es9hcb$34q$1@sea.gmane.org>


"Smith, Jeff" <jsmith at medplus.com> wrote

> In other words, applying somefun to the results of the iterator 
> return
> duplicates but I want the constructed list to contain none.

> l = [somefun(i) for i some-iterator if somefun(i) not in l]
>
> doesn't work (not that I expected it to).

Why not use a Set?

s = Set([somefun(i) for i in some-iterator])

Might be slow for big lists though...

Alan g 



From smnordby at yahoo.com  Fri Mar  2 17:06:57 2007
From: smnordby at yahoo.com (Steve N)
Date: Fri, 2 Mar 2007 08:06:57 -0800 (PST)
Subject: [Tutor] CGI request handler bug?
In-Reply-To: <mailman.45.1172833215.23053.tutor@python.org>
Message-ID: <693739.1739.qm@web55314.mail.re4.yahoo.com>

Hi all,
I was playing with some simple HTTP CGI server code
and discovered what I think may be a bug in
CGIHTTPServer.CGIHTTPRequestHandler. A "GET" request
without a leading '/' from a telnet session displays
the CGI script rather than the script's output. If the
request includes the leading '/', the script is run as
expected. Is this a bug?
Windows 2000
Python 2.4.3

<server>
import os, sys, socket
from BaseHTTPServer import HTTPServer
from CGIHTTPServer import CGIHTTPRequestHandler
os.chdir('docs')
myip = '127.0.0.1'
serv = HTTPServer((myip, 8000), CGIHTTPRequestHandler)
serv.serve_forever()
</server>

<docs/cgi-bin/hello.py>
print 'Content-type: text/html\n'
print '<html><head><title>Hello</title></head>'
print '<body><h1>Hello</h1></body></html>'
</docs/cgi-bin/hello.py>

Telnet without a leading '/' in the request displays
the script:
<telnet>
telnet localhost 8000
GET cgi-bin/hello.py

print 'Content-type: text/html\n'
print '<html><head><title>Hello</title></head>'
print '<body><h1>Hello</h1></body></html>'


Connection to host lost.
</telnet>

Telnet with a leading '/' in the request runs the
script:
<telnet>
telnet localhost 8000
GET /cgi-bin/hello.py

Content-type: text/html

                      
<html><head><title>Hello</title></head>
                                                      
       <body><h1>Hello</h
1></body></html>


Connection to host lost.
</telnet>

--
SteveN



 
____________________________________________________________________________________
8:00? 8:25? 8:40? Find a flick in no time 
with the Yahoo! Search movie showtime shortcut.
http://tools.search.yahoo.com/shortcuts/#news

From rabidpoobear at gmail.com  Fri Mar  2 17:40:58 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Fri, 02 Mar 2007 10:40:58 -0600
Subject: [Tutor] httpd in your laptop?!? serve web pages and wikis in
 your	notebook?
In-Reply-To: <45E83D21.6080205@verizon.net>
References: <45E50446.8060502@verizon.net> <45E5188F.7010902@gmail.com>
	<45E52949.9090705@verizon.net> <45E7E4B1.8070707@gmail.com>
	<45E83D21.6080205@verizon.net>
Message-ID: <45E8539A.8050307@gmail.com>


> forth uses a dictionary to locate and execute all its functions and 
> subfunctions. it is a threaded language. so it spends much of it's 
> time looking up functions in the dictionary. in large programs this 
> results in the majority of it's excecutiojn time being spent in the 
> dictionary, and as complexity increases so does dictionary time as a 
> percentage of total time spent on the program- therefore efficency 
> falls as size and complexity rises. while very good for small programs 
> to imbed into controller cpu's to bury inside some machine, when used 
> for a large and very complex application, it falls off in terms of 
> speed and efficency. still, it is a very unusual and powerful 
> language, with a fair sized following. Most progammers find is is SO 
> different that rank beginners learn it faster than experienced hands 
> do. it's just so damn odd.
That sounds really interesting.  I'll have to read up on that after 
class :)
>
>>  From what I can see it's overkill and makes things needlessly 
>> complicated.
>>
> Actually, the server is simple to find and install, saves me the 
> trouble of writing it, and the one I settled on has very light impact 
> and is free. I do have a python server script, but it tends to break 
> at the least exception for some reason, and the reason is not 
> apparent. this program  i found is pretty bullet proof, after i 
> pounded on it to no error or failure, so this also gains a gold star. 
> the python script does not like to be handed mangled links and a few 
> other naughties. as I said, the wiki is still under devlopment, so it 
> sometimes is in a momentary state when it is emitting strange data, 
> and it's a bother to restart the server over and over. while the wiki 
> is now to the point this is not a big problem, it still occasionally 
> happens- i am working on why- and a server that does not break is an 
> assett.
I see your point.
Another advantage for using a Python server, though, is that you can get 
the request objects directly.
So you can, for example, have the query http://yoursite/SomeExampleName and
http://yoursite/SomeSynonymousName actually read from the same source of 
data.
In the non-python solution you'd have to make a new .html file for every 
page you wanted.
Unless I misunderstand how you're using the server.



From rabidpoobear at gmail.com  Fri Mar  2 17:43:52 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Fri, 02 Mar 2007 10:43:52 -0600
Subject: [Tutor] using tarfile on strings or filelike objects
In-Reply-To: <BAA2EE790D828F4E8B262F17B3B0A7A30363CEE5@VUIEXCH1.ad.nottingham.ac.uk>
References: <BAA2EE790D828F4E8B262F17B3B0A7A30363CEE5@VUIEXCH1.ad.nottingham.ac.uk>
Message-ID: <45E85448.6090700@gmail.com>

Barton David wrote:
> I like that I can access the contents of a zip archive that's stored 
> in memory (rather than on disk) by packing the archive contents into a 
> StringIO or cStringIO object and feeding that to ZipFile...
>  
> i.e.
>  
> filelike=cStringIO.StringIO(archive_as_string)
> zf=zipfile.ZipFile(filelike)
> content=zf.read(archive_member_name)
> zf.close()
> filelike.close()
>  
> but I can't get the same thing to work with TarFile. Is there any way 
> to do this? (Other than first saving the archive data to disk and then 
> passing the path to TarFile.open?) The tarfile module documentation 
> talks about an optional fileobj flag but this doesn't seem to work.
What did you try? What was the error message?

>  
> cheers
> Dave
>
> This message has been checked for viruses but the contents of an 
> attachment may still contain software viruses, which could damage your 
> computer system: you are advised to perform your own checks. Email 
> communications with the University of Nottingham may be monitored as 
> permitted by UK legislation.
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From greenbergj at wit.edu  Fri Mar  2 17:10:04 2007
From: greenbergj at wit.edu (Jordan Greenberg)
Date: Fri, 02 Mar 2007 11:10:04 -0500
Subject: [Tutor] Yet another list comprehension question
In-Reply-To: <288A3B43F7B2224D9C8441C9FC5D6A02012E34B1@EXCHMAIL01.corp.medplus.com>
References: <288A3B43F7B2224D9C8441C9FC5D6A02012E34B1@EXCHMAIL01.corp.medplus.com>
Message-ID: <45E84C5C.60402@wit.edu>

Smith, Jeff wrote:
> I find a common thing to do is
> 
> l = list()
> for i in some-iterator:
>     if somefum(i) != list:
>     	l.append(somefun(i))

How about using the same condition you do in the if? Like:
l=[somefun(i) for i in some-iterator if not type(somefun(i)) is list]

HTH
Jordan

From project5 at redrival.net  Fri Mar  2 18:18:36 2007
From: project5 at redrival.net (Andrei)
Date: Fri, 2 Mar 2007 17:18:36 +0000 (UTC)
Subject: [Tutor] Yet another list comprehension question
References: <288A3B43F7B2224D9C8441C9FC5D6A02012E34B1@EXCHMAIL01.corp.medplus.com>
	<es9hcb$34q$1@sea.gmane.org>
Message-ID: <loom.20070302T181509-612@post.gmane.org>

> "Smith, Jeff" <jsmith <at> medplus.com> wrote
> 
> > In other words, applying somefun to the results of the iterator 
> > return
> > duplicates but I want the constructed list to contain none.
> 
> > l = [somefun(i) for i some-iterator if somefun(i) not in l]
> >
> > doesn't work (not that I expected it to).
> 
> Why not use a Set?
> 
> s = Set([somefun(i) for i in some-iterator])
> 

Alternatively, you could put the results as keys in a dictionary, then request
mydict.keys() to get a list of unique outcomes.

Yours,

Andrei


From alan.gauld at btinternet.com  Fri Mar  2 18:24:29 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 2 Mar 2007 17:24:29 -0000
Subject: [Tutor] httpd in your laptop?!? serve web pages and wikis in
	your	notebook?
References: <45E50446.8060502@verizon.net>
	<45E5188F.7010902@gmail.com><45E52949.9090705@verizon.net>
	<45E7E4B1.8070707@gmail.com><45E83D21.6080205@verizon.net>
	<45E8539A.8050307@gmail.com>
Message-ID: <es9mgk$v07$1@sea.gmane.org>


"Luke Paireepinart" <rabidpoobear at gmail.com> wrote
>
>> forth ... while very good for small programs
>> to imbed into controller cpu's to bury inside some machine,

It's a relatively little known fact that Sun use Forth as the
monitor/bootloader  in their servers. When you do a shutdown
on a Sun box it takes you into a Forth interpreter!

>> different that rank beginners learn it faster than experienced 
>> hands
>> do. it's just so damn odd.

Yep, it's one of the few languages that I just gave up on,
the pain wasn't worth the gain. I wound up moving to Tcl;
and Tcl isn't exactly mainstream! But it was a lot more
conventional than Forth. The only language I've used that
was equally different was Prolog.

Alan G. 



From dperlman at wisc.edu  Fri Mar  2 18:23:51 2007
From: dperlman at wisc.edu (David Perlman)
Date: Fri, 02 Mar 2007 11:23:51 -0600
Subject: [Tutor] Yet another list comprehension question
In-Reply-To: <es9hcb$34q$1@sea.gmane.org>
References: <288A3B43F7B2224D9C8441C9FC5D6A02012E34B1@EXCHMAIL01.corp.medplus.com>
	<es9hcb$34q$1@sea.gmane.org>
Message-ID: <05F17ED5-C85A-492A-94FC-D1C58FE787E9@wisc.edu>


On Mar 2, 2007, at 9:56 AM, Alan Gauld wrote:

> Why not use a Set?
>
> s = Set([somefun(i) for i in some-iterator])
>
> Might be slow for big lists though...

I'm curious why using a Set would be slower than doing it in a loop?   
In either case, the processor has to scan through all the data  
looking for duplicates.  I suppose in this case it's doing it in two  
passes, though.  On the other hand, the "not in l" check has to scan  
through the whole l each time.

I'd be really interested in seeing benchmarks comparing the  
methods...  no time to do it myself though... :)

--
-dave----------------------------------------------------------------
Science arose from poetry... when times change the two can meet again
on a higher level as friends. -G?the



From mail at timgolden.me.uk  Fri Mar  2 18:26:26 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Fri, 02 Mar 2007 17:26:26 +0000
Subject: [Tutor] Yet another list comprehension question
In-Reply-To: <loom.20070302T181509-612@post.gmane.org>
References: <288A3B43F7B2224D9C8441C9FC5D6A02012E34B1@EXCHMAIL01.corp.medplus.com>	<es9hcb$34q$1@sea.gmane.org>
	<loom.20070302T181509-612@post.gmane.org>
Message-ID: <45E85E42.2070500@timgolden.me.uk>

Andrei wrote:
>> "Smith, Jeff" <jsmith <at> medplus.com> wrote
>>
>>> In other words, applying somefun to the results of the iterator 
>>> return
>>> duplicates but I want the constructed list to contain none.
>>> l = [somefun(i) for i some-iterator if somefun(i) not in l]
>>>
>>> doesn't work (not that I expected it to).
>> Why not use a Set?
>>
>> s = Set([somefun(i) for i in some-iterator])
>>
> 
> Alternatively, you could put the results as keys in a dictionary, then request
> mydict.keys() to get a list of unique outcomes.

While true, I wouldn't advocate that technique for any half-recent
version of Python. Sets have been supported -- first as an external
module, later as builtin -- since Python 2.3 (I think) with supported
modules before that, which may or may not have been based on dicts.
If you're *only* using a dict to remove the duplicates, better to
use a set. Obviously, if you need other facilities a dict offers you, 
say to associate something else to your keys, then it's the best thing

:)

TJG

From doug.shawhan at gmail.com  Fri Mar  2 18:34:28 2007
From: doug.shawhan at gmail.com (doug shawhan)
Date: Fri, 2 Mar 2007 11:34:28 -0600
Subject: [Tutor] Regular expressions - Ignoring linefeeds
Message-ID: <5e1ceb8a0703020934k4f427dc7m50507175f286b27e@mail.gmail.com>

I've been looking through various sites, but cannot find the magic button
that allows me to match a string with linefeeds
I'd rather not strip out the linefeeds, then stick them back in. :-)

I'm attempting something that should be fairly simple:

snippy = re.compile('Hi there.*Bye there.')

s = '''Good gravy! Hi there.
I'm some text someone
wants to match.
Bye there. See you around'''

yield = re.match(snippy)

Anything after the linefeed is not matched, yielding naught but pain.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070302/fcbe7865/attachment.html 

From malaclypse2 at gmail.com  Fri Mar  2 19:07:50 2007
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Fri, 2 Mar 2007 13:07:50 -0500
Subject: [Tutor] Regular expressions - Ignoring linefeeds
In-Reply-To: <5e1ceb8a0703020934k4f427dc7m50507175f286b27e@mail.gmail.com>
References: <5e1ceb8a0703020934k4f427dc7m50507175f286b27e@mail.gmail.com>
Message-ID: <16651e80703021007x68bdb1c5xda035cf7fb9b69d9@mail.gmail.com>

On 3/2/07, doug shawhan <doug.shawhan at gmail.com> wrote:
> I've been looking through various sites, but cannot find the magic button
> that allows me to match a string with linefeeds
> I'd rather not strip out the linefeeds, then stick them back in. :-)

Try this:

>>> s = '''Good gravy! Hi there.
I'm some text someone
wants to match.
Bye there. See you around'''

>>> snippy = re.compile('Hi there.*Bye there.', re.DOTALL)

>>> yeild = re.search(snippy, s)

>>> yeild.group()
"Hi there.\nI'm some text someone\nwants to match.\nBye there."

The important bits are compiling your regular expression with
re.DOTALL so that a dot will match newlines, and using re.search
instead of re.match.

-- 
Jerry

From rabidpoobear at gmail.com  Fri Mar  2 19:09:33 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Fri, 02 Mar 2007 12:09:33 -0600
Subject: [Tutor] Regular expressions - Ignoring linefeeds
In-Reply-To: <5e1ceb8a0703020934k4f427dc7m50507175f286b27e@mail.gmail.com>
References: <5e1ceb8a0703020934k4f427dc7m50507175f286b27e@mail.gmail.com>
Message-ID: <45E8685D.3010302@gmail.com>

doug shawhan wrote:
> I've been looking through various sites, but cannot find the magic 
> button that allows me to match a string with linefeeds
> I'd rather not strip out the linefeeds, then stick them back in. :-)
>
> I'm attempting something that should be fairly simple:
>
> snippy = re.compile('Hi there.*Bye there.')
Your RE is wrong.
Refer to http://docs.python.org/lib/re-syntax.html
* Causes the resulting RE to match 0 or more repetitions of the 
preceding RE, as many repetitions as are possible. ab* will match 'a', 
'ab', or 'a' followed by any number of 'b's.
>
> s = '''Good gravy! Hi there.
> I'm some text someone
> wants to match.
> Bye there. See you around'''
>
> yield = re.match (snippy)
There are multiple errors in this call.
First, yield is a reserved keyword in python 2.4+ (probably earlier, too.)
Second, re.match takes 2 arguments, not 1.
What you really want to do is re.match(snippy,s)
>
> Anything after the linefeed is not matched, yielding naught but pain.
Nothing is matched because the code doesn't work.
HTH,
-Luke

From kent37 at tds.net  Fri Mar  2 19:10:38 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 02 Mar 2007 13:10:38 -0500
Subject: [Tutor] Regular expressions - Ignoring linefeeds
In-Reply-To: <5e1ceb8a0703020934k4f427dc7m50507175f286b27e@mail.gmail.com>
References: <5e1ceb8a0703020934k4f427dc7m50507175f286b27e@mail.gmail.com>
Message-ID: <45E8689E.2020700@tds.net>

doug shawhan wrote:
> I've been looking through various sites, but cannot find the magic 
> button that allows me to match a string with linefeeds
> I'd rather not strip out the linefeeds, then stick them back in. :-)
> 
> I'm attempting something that should be fairly simple:
> 
> snippy = re.compile('Hi there.*Bye there.')

For . to match a newline you have to compile with re.DOT_ALL:
snippy = re.compile('Hi there.*Bye there.', re.DOT_ALL)

> 
> s = '''Good gravy! Hi there.
> I'm some text someone
> wants to match.
> Bye there. See you around'''
> 
> yield = re.match (snippy)

re.match() only matches at the start of the string; use re.search()

Kent
> 
> Anything after the linefeed is not matched, yielding naught but pain.
> 
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


From kent37 at tds.net  Fri Mar  2 20:16:54 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 02 Mar 2007 14:16:54 -0500
Subject: [Tutor] Regular expressions - Ignoring linefeeds
In-Reply-To: <45E8685D.3010302@gmail.com>
References: <5e1ceb8a0703020934k4f427dc7m50507175f286b27e@mail.gmail.com>
	<45E8685D.3010302@gmail.com>
Message-ID: <45E87826.5090003@tds.net>

Luke Paireepinart wrote:
> doug shawhan wrote:
>> I've been looking through various sites, but cannot find the magic 
>> button that allows me to match a string with linefeeds
>> I'd rather not strip out the linefeeds, then stick them back in. :-)
>>
>> I'm attempting something that should be fairly simple:
>>
>> snippy = re.compile('Hi there.*Bye there.')
> Your RE is wrong.
> Refer to http://docs.python.org/lib/re-syntax.html
> * Causes the resulting RE to match 0 or more repetitions of the 
> preceding RE, as many repetitions as are possible. ab* will match 'a', 
> 'ab', or 'a' followed by any number of 'b's.

The RE that is repeated is . which is the intent.

>> s = '''Good gravy! Hi there.
>> I'm some text someone
>> wants to match.
>> Bye there. See you around'''
>>
>> yield = re.match (snippy)
> There are multiple errors in this call.
> First, yield is a reserved keyword in python 2.4+ (probably earlier, too.)
> Second, re.match takes 2 arguments, not 1.
> What you really want to do is re.match(snippy,s)

or snippy.match(s)

Kent

From rabidpoobear at gmail.com  Fri Mar  2 20:22:12 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Fri, 02 Mar 2007 13:22:12 -0600
Subject: [Tutor] Regular expressions - Ignoring linefeeds
In-Reply-To: <45E87826.5090003@tds.net>
References: <5e1ceb8a0703020934k4f427dc7m50507175f286b27e@mail.gmail.com>	<45E8685D.3010302@gmail.com>
	<45E87826.5090003@tds.net>
Message-ID: <45E87964.1030100@gmail.com>

Kent Johnson wrote:
> Luke Paireepinart wrote:
>   
>> doug shawhan wrote:
>>     
>>> I've been looking through various sites, but cannot find the magic 
>>> button that allows me to match a string with linefeeds
>>> I'd rather not strip out the linefeeds, then stick them back in. :-)
>>>
>>> I'm attempting something that should be fairly simple:
>>>
>>> snippy = re.compile('Hi there.*Bye there.')
>>>       
>> Your RE is wrong.
>> Refer to http://docs.python.org/lib/re-syntax.html
>> * Causes the resulting RE to match 0 or more repetitions of the 
>> preceding RE, as many repetitions as are possible. ab* will match 'a', 
>> 'ab', or 'a' followed by any number of 'b's.
>>     
>
> The RE that is repeated is . which is the intent.
>   
Yeah, sorry.  I thought there was a space after the ., which wouldn't 
work, right?


From kent37 at tds.net  Fri Mar  2 20:25:43 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 02 Mar 2007 14:25:43 -0500
Subject: [Tutor] Regular expressions - Ignoring linefeeds
In-Reply-To: <45E87964.1030100@gmail.com>
References: <5e1ceb8a0703020934k4f427dc7m50507175f286b27e@mail.gmail.com>	<45E8685D.3010302@gmail.com>
	<45E87826.5090003@tds.net> <45E87964.1030100@gmail.com>
Message-ID: <45E87A37.6040909@tds.net>

Luke Paireepinart wrote:
> Kent Johnson wrote:
>> Luke Paireepinart wrote:
>>> Your RE is wrong.
>>> Refer to http://docs.python.org/lib/re-syntax.html
>>> * Causes the resulting RE to match 0 or more repetitions of the 
>>> preceding RE, as many repetitions as are possible. ab* will match 
>>> 'a', 'ab', or 'a' followed by any number of 'b's.
>>>     
>>
>> The RE that is repeated is . which is the intent.
>>   
> Yeah, sorry.  I thought there was a space after the ., which wouldn't 
> work, right?

Right, if there was a space, the space would be the repeated item.

Kent

From deliberatus at verizon.net  Fri Mar  2 20:33:04 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Fri, 02 Mar 2007 14:33:04 -0500
Subject: [Tutor] httpd in your laptop?!? serve web pages and wikis in
	your	notebook?
In-Reply-To: <es9mgk$v07$1@sea.gmane.org>
References: <45E50446.8060502@verizon.net>
	<45E5188F.7010902@gmail.com><45E52949.9090705@verizon.net>
	<45E7E4B1.8070707@gmail.com><45E83D21.6080205@verizon.net>
	<45E8539A.8050307@gmail.com> <es9mgk$v07$1@sea.gmane.org>
Message-ID: <45E87BF0.6050302@verizon.net>

Yeppers, prolog is about as normal as a chocolate glazed neon donut.

Alan Gauld wrote:
> "Luke Paireepinart" <rabidpoobear at gmail.com> wrote
>>> forth ... while very good for small programs
>>> to imbed into controller cpu's to bury inside some machine,
> 
> It's a relatively little known fact that Sun use Forth as the
> monitor/bootloader  in their servers. When you do a shutdown
> on a Sun box it takes you into a Forth interpreter!
> 
>>> different that rank beginners learn it faster than experienced 
>>> hands
>>> do. it's just so damn odd.
> 
> Yep, it's one of the few languages that I just gave up on,
> the pain wasn't worth the gain. I wound up moving to Tcl;
> and Tcl isn't exactly mainstream! But it was a lot more
> conventional than Forth. The only language I've used that
> was equally different was Prolog.
> 
> Alan G. 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From deliberatus at verizon.net  Fri Mar  2 20:48:28 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Fri, 02 Mar 2007 14:48:28 -0500
Subject: [Tutor] forth
Message-ID: <45E87F8C.6060006@verizon.net>

Hello world

: helloWorld ."Hello World!;

that's it.

HelloWorld is now part of the language. Now if your language instance 
lets you compile it down, it will include all functions to create that 
function, and leave all others out, resulting in a executable. Mine came 
in at 263 bytes.

Microsoft C came in at 47 K.

to add 2+ 2:

2
2
+
.

As it uses Reverse Polish Notation and is stack oriented, doing math is 
rather intresting, different, and novel. It's a novel language. VERY 
good for controllers giving you maximum program in a small device such 
as your usuall PIC chip. Really SHINES in this venue.

Here's a link to wikipedia:
http://en.wikipedia.org/wiki/Forth_(programming_language)

But this is python list, so enough of comparitive languages.



-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From hgfernan at lsi.usp.br  Fri Mar  2 21:00:06 2007
From: hgfernan at lsi.usp.br (Hilton Garcia Fernandes)
Date: Fri, 2 Mar 2007 17:00:06 -0300
Subject: [Tutor] forth
In-Reply-To: <45E87F8C.6060006@verizon.net>
References: <45E87F8C.6060006@verizon.net>
Message-ID: <200703021700.07897.hgfernan@lsi.usp.br>

in python:

print "Hello world!"

21 bytes. 

all the best,
hilton
 
Em Sexta 02 Mar?o 2007 16:48, Kirk Bailey escreveu:
> Hello world
>
> : helloWorld ."Hello World!;
>
> that's it.
>
> HelloWorld is now part of the language. Now if your language instance
> lets you compile it down, it will include all functions to create that
> function, and leave all others out, resulting in a executable. Mine came
> in at 263 bytes.
>
> Microsoft C came in at 47 K.
>
> to add 2+ 2:
>
> 2
> 2
> +
> .
>
> As it uses Reverse Polish Notation and is stack oriented, doing math is
> rather intresting, different, and novel. It's a novel language. VERY
> good for controllers giving you maximum program in a small device such
> as your usuall PIC chip. Really SHINES in this venue.
>
> Here's a link to wikipedia:
> http://en.wikipedia.org/wiki/Forth_(programming_language)
>
> But this is python list, so enough of comparitive languages.

-- 
Hilton Garcia Fernandes
Nucleo de Tecnologias sem Fio (NTSF) -- Wireless Technologies Team
Lab de Sistemas Integraveis Tecnologico (LSI) -- Integrable Systems Lab
Escola Politecnica (Poli) -- Engineering School
Univ S Paulo (USP)
Tel: (5511)3091-5676 (work)
    (5511)8131-5213 (mobile)
Av. Prof. Luciano Gualberto,158 trav.3 CEP 05508-900
S. Paulo -- SP -- Brazil
Pagina inicial: http://www.lsi.usp.br/~hgfernan

From smnordby at yahoo.com  Fri Mar  2 22:33:13 2007
From: smnordby at yahoo.com (Steve N)
Date: Fri, 2 Mar 2007 13:33:13 -0800 (PST)
Subject: [Tutor] CGI request handler bug?
In-Reply-To: <mailman.14565.1172855943.32030.tutor@python.org>
Message-ID: <22912.10232.qm@web55306.mail.re4.yahoo.com>

> I was playing with some simple HTTP CGI server code
> and discovered what I think may be a bug in
> CGIHTTPServer.CGIHTTPRequestHandler. A "GET" request
> without a leading '/' from a telnet session displays
> the CGI script rather than the script's output. If >
the
> request includes the leading '/', the script is run
as
> expected. Is this a bug?

I think I've solved my problem by adding subclassing
CGIHTTPRequestHandler and adding this at the start of
the is_cgi() method:

        if not self.path.startswith('/'):
            self.path = '/' + self.path
--
SteveN



 
____________________________________________________________________________________
Have a burning question?  
Go to www.Answers.yahoo.com and get answers from real people who know.

From lnhaig at gmail.com  Fri Mar  2 22:58:11 2007
From: lnhaig at gmail.com (Lance Haig)
Date: Fri, 02 Mar 2007 21:58:11 +0000
Subject: [Tutor] Can you tell me if this C or python please
Message-ID: <45E89DF3.2020805@gmail.com>

Hi,

I am helping on an OS project called bongo-project and I am trying to 
debug a script that is used for migration. When I run the file I get an 
error. I have traced it down to a file called libs.c.

I know that the file looks like a c file but I am confused by some of 
the code in it. I would appreciate it if someone could look at the file 
for me and tell me if it is c so I can pass it back to the c guys and 
ask them.

Thanks

Lance

From bgailer at alum.rpi.edu  Fri Mar  2 23:02:15 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Fri, 02 Mar 2007 14:02:15 -0800
Subject: [Tutor] Can you tell me if this C or python please
In-Reply-To: <45E89DF3.2020805@gmail.com>
References: <45E89DF3.2020805@gmail.com>
Message-ID: <45E89EE7.9050308@alum.rpi.edu>

Lance Haig wrote:
> Hi,
>
> I am helping on an OS project called bongo-project and I am trying to 
> debug a script that is used for migration. When I run the file I get an 
> error. I have traced it down to a file called libs.c.
>
> I know that the file looks like a c file but I am confused by some of 
> the code in it. I would appreciate it if someone could look at the file 
> for me and tell me if it is c so I can pass it back to the c guys and 
> ask them.
>   
OK. Show us the file (if not too big as body text).

-- 
Bob Gailer
510-978-4454


From lnhaig at gmail.com  Fri Mar  2 23:07:21 2007
From: lnhaig at gmail.com (Lance Haig)
Date: Fri, 02 Mar 2007 22:07:21 +0000
Subject: [Tutor] Can you tell me if this C or python please
In-Reply-To: <45E89EE7.9050308@alum.rpi.edu>
References: <45E89DF3.2020805@gmail.com> <45E89EE7.9050308@alum.rpi.edu>
Message-ID: <45E8A019.8090103@gmail.com>

Bob Gailer wrote:
> Lance Haig wrote:
>> Hi,
>>
>> I am helping on an OS project called bongo-project and I am trying to 
>> debug a script that is used for migration. When I run the file I get 
>> an error. I have traced it down to a file called libs.c.
>>
>> I know that the file looks like a c file but I am confused by some of 
>> the code in it. I would appreciate it if someone could look at the 
>> file for me and tell me if it is c so I can pass it back to the c 
>> guys and ask them.
>>   
> OK. Show us the file (if not too big as body text).
>
sorry I should have attached it

/****************************************************************************
 *
 * Copyright (c) 2006 Novell, Inc.
 * All Rights Reserved.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of version 2.1 of the GNU Lesser General Public
 * License as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, contact Novell, Inc.
 *
 * To contact Novell about this file by physical or electronic mail,
 * you may find current contact information at www.novell.com
 *
 ****************************************************************************/

#include <Python.h>
#include "libs.h"
#include "pybongo.h"
#include <bongo-config.h>
#include <xpl.h>
#include <mdb.h>
#include <connio.h>
#include <memmgr.h>
#include <msgapi.h>
#include <nmlib.h>
#include <streamio.h>
#include <bongojson.h>

#ifdef __cplusplus
extern "C" {
#endif

static PyMethodDef ModuleMethods[] = { {NULL} };

/* Pull in the methods from the bindings */
extern PyMethodDef CalCmdMethods[];
extern EnumItemDef CalCmdEnums[];
extern PyMethodDef CalMethods[];
extern PyMethodDef MdbMethods[];
extern EnumItemDef MdbEnums[];
extern PyMethodDef MsgApiMethods[];
extern EnumItemDef MsgApiEnums[];
extern PyMethodDef StreamIOMethods[];
extern PyMethodDef BongoJsonMethods[];
extern PyMethodDef BongoUtilMethods[];


PyMODINIT_FUNC
initlibs()
{
    MDBHandle directoryHandle=NULL;
    char dbfdir[PATH_MAX];

    /* Initialize the various bongo libraries */
    if (!MemoryManagerOpen((unsigned char*)"pybongo")) {
        PyErr_SetString(PyExc_ImportError,
                        "bongo.libs error: MemoryManagerOpen() failed");
        return;
    }

    if (!ConnStartup(DEFAULT_CONNECTION_TIMEOUT, TRUE)) {
        PyErr_SetString(PyExc_ImportError,
                        "bongo.libs error: ConnStartup() failed");
        return;
    }

    directoryHandle = MsgInit();
    if (!directoryHandle) {
        PyErr_SetString(PyExc_ImportError,
                        "bongo.libs error: MsgInit() failed");
        return;
    }

    MsgGetDBFDir(dbfdir);

    if (!BongoCalInit(dbfdir)) {
        PyErr_SetString(PyExc_ImportError,
                        "bongo.libs error: BongoCalInit() failed");
        return;
    }

    if (!NMAPInitialize(directoryHandle)) {
        PyErr_SetString(PyExc_ImportError,
                        "bongo.libs error: NMAPInitialize() failed");
        return;
    }

    if (!StreamioInit()) {
        PyErr_SetString(PyExc_ImportError,
                        "bongo.libs error: StreamioInit() failed");
        return;
    }

    if (!BongoJsonPreInit()) {
        PyErr_SetString(PyExc_ImportError,
                        "bongo.libs error: BongoJsonPreInit() failed");
        return;
    }
   
    /* Create the libs module */
    PyObject *module = Py_InitModule("libs", ModuleMethods);

    /* Add the Bongo libs */
    AddLibrary(module, "cal", CalMethods, NULL);
    AddLibrary(module, "calcmd", CalCmdMethods, CalCmdEnums);
    AddLibrary(module, "mdb", MdbMethods, MdbEnums);
    AddLibrary(module, "msgapi", MsgApiMethods, MsgApiEnums);
    AddLibrary(module, "streamio", StreamIOMethods, NULL);
    AddLibrary(module, "bongojson", BongoJsonMethods, NULL);
    AddLibrary(module, "bongoutil", BongoUtilMethods, NULL);

    BongoJsonPostInit(module);
    BongoCalPostInit(module);
}

#ifdef __cplusplus
}
#endif

From sulfurfff at hotmail.com  Fri Mar  2 23:43:24 2007
From: sulfurfff at hotmail.com (=?iso-8859-1?B?SXNtYWVsIEZhcmbhbiBFc3RyYWRh?=)
Date: Fri, 02 Mar 2007 22:43:24 +0000
Subject: [Tutor] howto call DOM with python
In-Reply-To: <es7qcu$20m$1@sea.gmane.org>
Message-ID: <BAY106-F17AB9A6FE86C797AEEF91EA2870@phx.gbl>

>
>I don't think you can make it work under Linux. The Jython applet
>is your nearest option. You will be better learing the ninimum of
>JavaScript IMHO. Try my tutorial as a quickl way in, especially
>if you know Python...
>
>Finally, you may be able to do what you want using the urllib
>module to replace the browser entirely!
>
>http://www.freenetpages.co.uk/hp/alan.gauld
>

By any chance is this your tutorial?
http://www.freenetpages.co.uk/hp/alan.gauld
I entered there but the parts "Writing web clients" and "Writing
Web Applications" are dissabled

Maybe you can send the direct ling to how to use that jython
applet, I'll give it a try. And now that we are here mabe a tutorial
for DOM to, I entered to the page of DOM but I found no
downloadable tutorial or a reference manual


Tanks for your time

_________________________________________________________________
Te gusta estar en control, crea tu propia experiencia en Internet 
http://live.com


From bgailer at alum.rpi.edu  Fri Mar  2 23:54:04 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Fri, 02 Mar 2007 14:54:04 -0800
Subject: [Tutor] forth
In-Reply-To: <200703021700.07897.hgfernan@lsi.usp.br>
References: <45E87F8C.6060006@verizon.net>
	<200703021700.07897.hgfernan@lsi.usp.br>
Message-ID: <45E8AB0C.4090405@alum.rpi.edu>

Hilton Garcia Fernandes wrote:
> in python:
>
> print "Hello world!"
>
> 21 bytes. 
>   
True, but the forth program is (as I read it) more equivalent to:

def helloWorld():
    print "Hello World!"

although is says 'resulting in a [sic] executable". Not sure what that 
means, unless the obvious - an .exe file which when run displays "Hello 
World!". In that case 263 bytes is remarkable.
> all the best,
> hilton
>  
> Em Sexta 02 Mar?o 2007 16:48, Kirk Bailey escreveu:
>   
>> Hello world
>>
>> : helloWorld ."Hello World!;
>>
>> that's it.
>>
>> HelloWorld is now part of the language. Now if your language instance
>> lets you compile it down, it will include all functions to create that
>> function, and leave all others out, resulting in a executable. Mine came
>> in at 263 bytes.
>>
>> Microsoft C came in at 47 K.
>>
>> to add 2+ 2:
>>
>> 2
>> 2
>> +
>> .
>>
>> As it uses Reverse Polish Notation and is stack oriented, doing math is
>> rather intresting, different, and novel. It's a novel language. VERY
>> good for controllers giving you maximum program in a small device such
>> as your usuall PIC chip. Really SHINES in this venue.
>>
>> Here's a link to wikipedia:
>> http://en.wikipedia.org/wiki/Forth_(programming_language)
>>
>> But this is python list, so enough of comparitive languages.
>>     
>
>   


-- 
Bob Gailer
510-978-4454


From bgailer at alum.rpi.edu  Sat Mar  3 00:11:02 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Fri, 02 Mar 2007 15:11:02 -0800
Subject: [Tutor] Can you tell me if this C or python please
In-Reply-To: <45E8A019.8090103@gmail.com>
References: <45E89DF3.2020805@gmail.com> <45E89EE7.9050308@alum.rpi.edu>
	<45E8A019.8090103@gmail.com>
Message-ID: <45E8AF06.1010707@alum.rpi.edu>

Lance Haig wrote:
> Bob Gailer wrote:
>> Lance Haig wrote:
>>> Hi,
>>>
>>> I am helping on an OS project called bongo-project and I am trying 
>>> to debug a script that is used for migration. When I run the file I 
>>> get an error. I have traced it down to a file called libs.c.
>>>
>>> I know that the file looks like a c file but I am confused by some 
>>> of the code in it. I would appreciate it if someone could look at 
>>> the file for me and tell me if it is c so I can pass it back to the 
>>> c guys and ask them.
>>>   
>> OK. Show us the file (if not too big as body text).
>>
> sorry I should have attached it
That is C. It looks like it is written to be called from a Python program.

Clues that it is C rather than python:
  # compiler directives (e.g. #include)
  Variable declarations e.g. static ..., extern ...
  Use of {} to group statements
  Use of ; to terminate statements
  Use of /* */ to enclose comments
>
> /**************************************************************************** 
>
> *
> * Copyright (c) 2006 Novell, Inc.
> * All Rights Reserved.
> *
> * This program is free software; you can redistribute it and/or
> * modify it under the terms of version 2.1 of the GNU Lesser General 
> Public
> * License as published by the Free Software Foundation.
> *
> * This program is distributed in the hope that it will be useful,
> * but WITHOUT ANY WARRANTY; without even the implied warranty of
> * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
> * GNU Lesser General Public License for more details.
> *
> * You should have received a copy of the GNU Lesser General Public 
> License
> * along with this program; if not, contact Novell, Inc.
> *
> * To contact Novell about this file by physical or electronic mail,
> * you may find current contact information at www.novell.com
> *
> ****************************************************************************/ 
>
>
> #include <Python.h>
> #include "libs.h"
> #include "pybongo.h"
> #include <bongo-config.h>
> #include <xpl.h>
> #include <mdb.h>
> #include <connio.h>
> #include <memmgr.h>
> #include <msgapi.h>
> #include <nmlib.h>
> #include <streamio.h>
> #include <bongojson.h>
>
> #ifdef __cplusplus
> extern "C" {
> #endif
>
> static PyMethodDef ModuleMethods[] = { {NULL} };
>
> /* Pull in the methods from the bindings */
> extern PyMethodDef CalCmdMethods[];
> extern EnumItemDef CalCmdEnums[];
> extern PyMethodDef CalMethods[];
> extern PyMethodDef MdbMethods[];
> extern EnumItemDef MdbEnums[];
> extern PyMethodDef MsgApiMethods[];
> extern EnumItemDef MsgApiEnums[];
> extern PyMethodDef StreamIOMethods[];
> extern PyMethodDef BongoJsonMethods[];
> extern PyMethodDef BongoUtilMethods[];
>
>
> PyMODINIT_FUNC
> initlibs()
> {
>    MDBHandle directoryHandle=NULL;
>    char dbfdir[PATH_MAX];
>
>    /* Initialize the various bongo libraries */
>    if (!MemoryManagerOpen((unsigned char*)"pybongo")) {
>        PyErr_SetString(PyExc_ImportError,
>                        "bongo.libs error: MemoryManagerOpen() failed");
>        return;
>    }
>
>    if (!ConnStartup(DEFAULT_CONNECTION_TIMEOUT, TRUE)) {
>        PyErr_SetString(PyExc_ImportError,
>                        "bongo.libs error: ConnStartup() failed");
>        return;
>    }
>
>    directoryHandle = MsgInit();
>    if (!directoryHandle) {
>        PyErr_SetString(PyExc_ImportError,
>                        "bongo.libs error: MsgInit() failed");
>        return;
>    }
>
>    MsgGetDBFDir(dbfdir);
>
>    if (!BongoCalInit(dbfdir)) {
>        PyErr_SetString(PyExc_ImportError,
>                        "bongo.libs error: BongoCalInit() failed");
>        return;
>    }
>
>    if (!NMAPInitialize(directoryHandle)) {
>        PyErr_SetString(PyExc_ImportError,
>                        "bongo.libs error: NMAPInitialize() failed");
>        return;
>    }
>
>    if (!StreamioInit()) {
>        PyErr_SetString(PyExc_ImportError,
>                        "bongo.libs error: StreamioInit() failed");
>        return;
>    }
>
>    if (!BongoJsonPreInit()) {
>        PyErr_SetString(PyExc_ImportError,
>                        "bongo.libs error: BongoJsonPreInit() failed");
>        return;
>    }
>      /* Create the libs module */
>    PyObject *module = Py_InitModule("libs", ModuleMethods);
>
>    /* Add the Bongo libs */
>    AddLibrary(module, "cal", CalMethods, NULL);
>    AddLibrary(module, "calcmd", CalCmdMethods, CalCmdEnums);
>    AddLibrary(module, "mdb", MdbMethods, MdbEnums);
>    AddLibrary(module, "msgapi", MsgApiMethods, MsgApiEnums);
>    AddLibrary(module, "streamio", StreamIOMethods, NULL);
>    AddLibrary(module, "bongojson", BongoJsonMethods, NULL);
>    AddLibrary(module, "bongoutil", BongoUtilMethods, NULL);
>
>    BongoJsonPostInit(module);
>    BongoCalPostInit(module);
> }
>
> #ifdef __cplusplus
> }
> #endif
>


-- 
Bob Gailer
510-978-4454


From lnhaig at gmail.com  Sat Mar  3 00:14:05 2007
From: lnhaig at gmail.com (Lance Haig)
Date: Fri, 02 Mar 2007 23:14:05 +0000
Subject: [Tutor] Can you tell me if this C or python please
In-Reply-To: <45E8AF06.1010707@alum.rpi.edu>
References: <45E89DF3.2020805@gmail.com> <45E89EE7.9050308@alum.rpi.edu>
	<45E8A019.8090103@gmail.com> <45E8AF06.1010707@alum.rpi.edu>
Message-ID: <45E8AFBD.7030207@gmail.com>

Bob,

Thanks a million

I will start talking to the other guys

Thanks

Lance

From Barry.Carroll at psc.com  Sat Mar  3 00:58:36 2007
From: Barry.Carroll at psc.com (Carroll, Barry)
Date: Fri, 2 Mar 2007 15:58:36 -0800
Subject: [Tutor] forth
In-Reply-To: <mailman.14613.1172877067.32030.tutor@python.org>
Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595B19@eugsrv400.psc.pscnet.com>

> -----Original Message-----
> Date: Fri, 02 Mar 2007 14:54:04 -0800
> From: Bob Gailer <bgailer at alum.rpi.edu>
> Subject: Re: [Tutor] forth
> To: Hilton Garcia Fernandes <hgfernan at lsi.usp.br>
> Cc: tutor at python.org
> Message-ID: <45E8AB0C.4090405 at alum.rpi.edu>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
> 
> Hilton Garcia Fernandes wrote:
> > in python:
> >
> > print "Hello world!"
> >
> > 21 bytes.
> >
> True, but the forth program is (as I read it) more equivalent to:
> 
> def helloWorld():
>     print "Hello World!"
> 
> although is says 'resulting in a [sic] executable". Not sure what that
> means, unless the obvious - an .exe file which when run displays
"Hello
> World!". In that case 263 bytes is remarkable.
> > all the best,
> > hilton
> >
> > Em Sexta 02 Mar?o 2007 16:48, Kirk Bailey escreveu:
> >
> >> Hello world
> >>
> >> : helloWorld ."Hello World!;
> >>
> >> that's it.
> >>
> >> HelloWorld is now part of the language. Now if your language
instance
> >> lets you compile it down, it will include all functions to create
that
> >> function, and leave all others out, resulting in a executable. Mine
> came
> >> in at 263 bytes.
> >>
> >> Microsoft C came in at 47 K.
> >>
> >> to add 2+ 2:
> >>
> >> 2
> >> 2
> >> +
> >> .
> >>
> >> As it uses Reverse Polish Notation and is stack oriented, doing
math is
> >> rather intresting, different, and novel. It's a novel language.
VERY
> >> good for controllers giving you maximum program in a small device
such
> >> as your usuall PIC chip. Really SHINES in this venue.
> >>
> >> Here's a link to wikipedia:
> >> http://en.wikipedia.org/wiki/Forth_(programming_language)
> >>
> >> But this is python list, so enough of comparitive languages.
> >>
> >
> 
> --
> Bob Gailer
> 510-978-4454

Okay.  Here's my "Hello World" script.

<CONSOLE>
J:\ >dir helloworld.py
 Volume in drive J is EUGSRV340
 Volume Serial Number is 0435-C18F

 Directory of J:\

03/02/2007  03:20 PM                43 helloworld.py
               1 File(s)             43 bytes
               0 Dir(s)  23,540,051,968 bytes free

J:\ >type helloworld.py
#!/usr/bin/python2.3
print "Hello World"

J:\ >helloworld.py
Hello World

J:\ >
</CONSOLE>

This script will run on a Windows XP box with the Python interpreter
installed.  At 43 bytes, it's not too bad.  Running on a box without
Python is a different story.  I can make a .exe file using py2exe:

<CONSOLE>
J:\ >type setup.py
# setup.py
from distutils.core import setup
import py2exe

setup(
    zipfile=None, # append zip-archive to the executable.
    options = {"py2exe": {"compressed": 1,
                          "optimize": 2,
                          "ascii": 1,   # to make a smaller executable,
                                        # don't include the encodings
                          "packages": ["xml.sax.drivers",
                                       "xml.sax.drivers2",],
                         }
              },
    console=["helloworld.py"]
    )


J:\ >python setup.py py2exe

<<py2exe output snipped>>

J:\ >cd dist

J:\dist >dir *.exe
 Volume in drive J is EUGSRV340
 Volume Serial Number is 0435-C18F

 Directory of J:\dist

03/02/2007  03:39 PM           493,826 helloworld.exe
05/11/2005  07:03 PM            16,384 w9xpopen.exe
               2 File(s)        510,210 bytes
               0 Dir(s)  23,504,711,680 bytes free

J:\dist >helloworld
Hello World

J:\dist >
</CONSOLE>

I'm a novice at py2exe.  There are probably ways to tweak the setup file
to make the .exe file smaller.  

I wonder if Kirk's 263 byte Forth program is self-contained?

Barry
barry.carroll at psc.com
541-302-1107
________________________
We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed




From alan.gauld at btinternet.com  Sat Mar  3 02:57:38 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 3 Mar 2007 01:57:38 -0000
Subject: [Tutor] howto call DOM with python
References: <es7qcu$20m$1@sea.gmane.org>
	<BAY106-F17AB9A6FE86C797AEEF91EA2870@phx.gbl>
Message-ID: <esakip$6vq$1@sea.gmane.org>

"Ismael Farf?n Estrada" <sulfurfff at hotmail.com> wrote

> By any chance is this your tutorial?
> http://www.freenetpages.co.uk/hp/alan.gauld

Yes that's it.

> I entered there but the parts "Writing web clients" and "Writing
> Web Applications" are dissabled

I'm writing them at the moment. :-)

But the early two sections of the tutorial teach the basics
of JavaScript, comparing it to Python.

> Maybe you can send the direct ling to how to use that jython
> applet,

There is a Jython community out there who can do that better
than me, but basically you just write an applet in Jython then
link to it from your web page. The browser will download it
and run it in the JVM. The biggest challenge is passing data
between the web page (DOM) and the applet - that is where
JavaScript scores.

HTH,

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



From alan.gauld at btinternet.com  Sat Mar  3 02:59:51 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 3 Mar 2007 01:59:51 -0000
Subject: [Tutor] Yet another list comprehension question
References: <288A3B43F7B2224D9C8441C9FC5D6A02012E34B1@EXCHMAIL01.corp.medplus.com><es9hcb$34q$1@sea.gmane.org>
	<loom.20070302T181509-612@post.gmane.org>
Message-ID: <esakn3$77p$1@sea.gmane.org>


"Andrei" <project5 at redrival.net> wrote

> Alternatively, you could put the results as keys in a dictionary, 
> then request
> mydict.keys() to get a list of unique outcomes.

I thought of that too, but couldn't think how to do it in a list
comprehension. It seemed like it should be possible but I
couldn't think of how - and didn't have a python interpreter
handy...

Alan G. 



From alan.gauld at btinternet.com  Sat Mar  3 03:09:33 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 3 Mar 2007 02:09:33 -0000
Subject: [Tutor] forth
References: <45E87F8C.6060006@verizon.net><200703021700.07897.hgfernan@lsi.usp.br>
	<45E8AB0C.4090405@alum.rpi.edu>
Message-ID: <esal94$8ef$1@sea.gmane.org>


"Bob Gailer" <bgailer at alum.rpi.edu> wrote

> although is says 'resulting in a [sic] executable". Not sure what 
> that
> means, unless the obvious - an .exe file which when run displays 
> "Hello
> World!". In that case 263 bytes is remarkable.

It does and it is. That is Forth's strong point, it is often in the
same sort of size as assembler. Often tighter than C (which
needs to statically link its stdlib). Forth has such a small
runtime footprint and the compiler only links in the lib functions
it actually needs. As the programs get bigger they use more
of the library functions and quickly grow to be comparable
to C - hence the reason Sun used it for their bootloader but
not for their OS!

But it is wierd...

>> 2
>> 2
>> +
>> .
>>
>> As it uses Reverse Polish Notation and is stack oriented

Again very powerfuil in producing small code.
My first pocket calculator was a Novus which used RPN
(I couldn't afford an HP!) and once you get used to it you
can do amazing things in far fewer keystrokes than on
a conventional calculator.

Alan G. 



From deliberatus at verizon.net  Sat Mar  3 07:26:31 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Sat, 03 Mar 2007 01:26:31 -0500
Subject: [Tutor] miniwiki 1.3.0 beta now available
Message-ID: <45E91517.7060406@verizon.net>

May The Gods have mercy on my soul.

MiniWiki is now offered for downloading. 1.3.0 is not in presentable 
condition for them what would like to kick it around some.

http://www.tinylist.org/MiniWIKI130.zip

Included in it is the zip archive for the server I settled on which is a 
very nice little tool I have yet to break regardless of how I stick my 
thumbs in it's eye. Robust is an understatement, it is bulletproof. 
Alas, it will NOT parse ssi includes, but WILL support scripts with 
environment data and go retreived specified interpeters declared in the 
shebang line, so it's not so terrible. It is free PERIOD, even if 
included in commercial releases, as long as you credit the authors- 
well, I included everything they released, including source code, so go 
for it.

My zip file includes subdirectories and seedpages. One should create a 
folder such as 'c:\localhost', place the zip in it, and unpack it there. 
you will get \www, \cgi-bin, \cgi-bin\texts, www\images, and several 
files in the texts directory.

If I got this thing to zip up properly. sheesh. I'm going to bed.


-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From alan.gauld at btinternet.com  Sat Mar  3 09:56:58 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 3 Mar 2007 08:56:58 -0000
Subject: [Tutor] howto call DOM with python
References: <BAY106-F28865BCC51F23C60116695A2810@phx.gbl>
	<es7qcu$20m$1@sea.gmane.org>
Message-ID: <esbd51$lki$1@sea.gmane.org>


"Alan Gauld" <alan.gauld at btinternet.com> wrote 
> You will be better learing the minimum of
> JavaScript IMHO. 

I meant to add that you can make JavaScript more 
Pythonic, if thats an issue, by using mochikit.

http://mochikit.com/

Mochikit provides JavaScript functions that replicate 
many Python idioms in JavaScript.

HTH

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


From project5 at redrival.net  Sat Mar  3 13:40:05 2007
From: project5 at redrival.net (Andrei)
Date: Sat, 03 Mar 2007 13:40:05 +0100
Subject: [Tutor] geeks like us and the rest of THEM
In-Reply-To: <45E13742.4070208@verizon.net>
References: <45E06524.2090805@verizon.net> <45E06BA8.8020802@tds.net>
	<45E13742.4070208@verizon.net>
Message-ID: <esbqal$qpu$1@sea.gmane.org>

<snip>
> That's part of it. a good installer is another, and I am loo]king at a 
> couple.  A solid and drool-proof server is the remaining leg of the 
> tripod. So far, none of the servers I have seen are satisfactory on all 
> scores- simplicity to install, reliability, economy of cost, (free or 
> unlimited license to me for a modest fee) and ease to configure if the 
> use\r so wishes. the closest I have yet seen SMALL HTTP SERVER. And it 
> is very good.
> http://smallsrv.com/

You could have a look at Aprelium's Abyss server (X1, which is freely 
distributable in unmodified form IIRC, but closed source). It has a good 
looking webbased configuration console and is cross-platform if you ever 
need that. However, you'll probably end up digging in its config 
programmatically to set up paths and such for the user - shouldn't be 
too hard using some webscraping if the files are not readily modifiable. 
Its setup is about 350 kB.

In terms of installers, NSIS (with the package to make it look modern, 
instead of that awful default look - forgot its name) or InnoSetup are 
the usual suspects. NSIS has a smaller overhead, but an uglier language.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info:
''.join([''.join(s) for s in zip(
"poet at aao.l pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
"rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])


From project5 at redrival.net  Sat Mar  3 14:18:24 2007
From: project5 at redrival.net (Andrei)
Date: Sat, 03 Mar 2007 14:18:24 +0100
Subject: [Tutor] dictionaries and memory handling
In-Reply-To: <5FD775B0-2883-4221-BD09-D35F4E33AC87@stud.ntnu.no>
References: <AC8DD8F2-947F-415D-9F97-4DD3DC827FD0@stud.ntnu.no>
	<5FD775B0-2883-4221-BD09-D35F4E33AC87@stud.ntnu.no>
Message-ID: <esbsif$6ec$1@sea.gmane.org>

> But most of my dictionaries are nested, and since both keys and values 
> in the dbm 'dictionaries' have to be strings, I can't immediately see 
> how I could get it to work.
> 
> A bit more detail: I deal with conditional probabilities, with up to 4 
> parameters. These parameters are numbers or words and determine the 
> value (which is always a number). E.g. I have a dictionary 
> {p1:{p2:{p3:{p4:value}}}}, where the p's are different parameters. I 
> sometimes need to sum over one or more of the parameters ? for now I 
> have managed to structure the dictionaries so that I only need to sum 
> over the innermost parameter, although this has been a bit cumbersome.

Depends a bit on how many keys each of the dictionaries is going to have 
and in what order they're filled. You can pickle/cPickle an arbitrary 
amount of data as one value, so the whole {p2:{p3:{p4:value}}} story 
could be a value of the p1 key in the bsddb. However, you may not like 
this if you need to retrieve p1 and add new stuff to it all the time, 
because the pickling and unpickling cycles may not be beneficial to the 
performance.

If you find this is a problem, you could opt to e.g. keep the first 
layer of the dictionary in memory, but map each value to a separate 
bsddb, so that you'd need to do less pickling/unpickling.

Alternatively you could choose to store them as a sort of path in the 
bsddb, like this (obviously wasteful in terms of space):
'p1/p2/p3/p4': '20'
'p1/p2/p3/p5': '45'

Combinations of the approaches above are also possible and I have no 
idea which would be best.

>> - Will the dictionaries take up less memory if I use numbers rather  
>> than words as keys (i.e. will {3:45, 6:77, 9:33} consume less memory  
>> than {"eloquent":45, "helpless":77, "samaritan":33} )? And if so:  
>> Slightly less, or substantially less memory?

Here's a simple test:

 >>> x = [str(i) for i in range(100000, 1000000)]
vs.
 >>> x = [i for i in range(100000, 1000000)]

The interpreter takes about 50 MB for the str() version and about 20 for 
the non-str() version - eyeballed in the Task manager. So it does make a 
significant difference, though not an order-of-magnitude difference. 
That may be enough for now, but if this script stays in use, you're 
bound at some point to need even more.

>> - What are common methods to monitor the memory usage of a script?  
>> Can I add a snippet to the code that prints out how many MBs of  
>> memory a certain dictionary takes up at that particular time?

Not as such. In your case, I think the task manager would be enough. You 
only have this one demanding data structure I assume, so in a rough 
approximation you can pretend that whatever the task manager reports 
(have a look at VM and peak memory usage columns, not just memory usage) 
is caused by the contents of the dictionary.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info:
''.join([''.join(s) for s in zip(
"poet at aao.l pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
"rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])


From kent37 at tds.net  Sat Mar  3 14:47:55 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 03 Mar 2007 08:47:55 -0500
Subject: [Tutor] Yet another list comprehension question
In-Reply-To: <es9hcb$34q$1@sea.gmane.org>
References: <288A3B43F7B2224D9C8441C9FC5D6A02012E34B1@EXCHMAIL01.corp.medplus.com>
	<es9hcb$34q$1@sea.gmane.org>
Message-ID: <45E97C8B.1060205@tds.net>

Alan Gauld wrote:
> "Smith, Jeff" <jsmith at medplus.com> wrote
> 
>> In other words, applying somefun to the results of the iterator 
>> return
>> duplicates but I want the constructed list to contain none.
> 
>> l = [somefun(i) for i some-iterator if somefun(i) not in l]
>>
>> doesn't work (not that I expected it to).
> 
> Why not use a Set?
> 
> s = Set([somefun(i) for i in some-iterator])
> 
> Might be slow for big lists though...

This is a popular question. It comes up frequently on comp.lang.python 
and there are many recipes in the online cookbook. Here is a FAQ:
http://www.effbot.org/pyfaq/how-do-you-remove-duplicates-from-a-list.htm

I think using a set is the fastest solution if the list items are 
hashable and you don't care about order.

If the list items are hashable and you do care about order then there is 
this mild hack:
s = set()
[ i for i in lst if i not in s and not s.add(i) ]

but with the requirement of calling somefunc(i) my guess is that an 
explicit loop will be faster.

The cookbook is down right now but there is a link in the above FAQ.

Kent

From clay.wiedemann at gmail.com  Sat Mar  3 14:50:09 2007
From: clay.wiedemann at gmail.com (Clay Wiedemann)
Date: Sat, 3 Mar 2007 08:50:09 -0500
Subject: [Tutor] trouble understanding the python environment in OSX
Message-ID: <781164cc0703030550i509e79e5waa2f2c3a4950faad@mail.gmail.com>

Hi,

I am not only new to Python, but new to programming in an environment
like this, where knowing a little of how the underpinning work is
essential.*

I am running the latest OSX (10.4.8) and know a little about moving
about in the terminal. But the world of paths, etc. has me a little
confused. And now it is getting in my way. I was wondering if I could
get a little help with some things.

- Can anyone point me to a well-regarded and pithy tutorial regarding
the UNIX underpinnings of OSX, especially anything that would help
with Python. (e.g., I can navigate to Python.framework and versions
but see 2.5 and Current, which confuses me since 2.5 is the current
version.) I would love to know what the structure of the Python
installation means.

- I am having trouble installing the BeautifulSoup package. The
installer stumbles on a unicode issue (that the Soup developer says is
a problem with my Python installation) -- so what is the best way to
manually install this? And does the 2.5 / Current divide matter?



Thanks in advance for any help with these basic issues.

Good morning from Brooklyn,
Clay


* Any experience with coding webpages is not helping here



- - - - - - -

Clay S. Wiedemann

aim: khlav
wii: 3905 4571 6175 2469
twitter: seastokes

From alan.gauld at btinternet.com  Sat Mar  3 15:22:11 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 3 Mar 2007 14:22:11 -0000
Subject: [Tutor] trouble understanding the python environment in OSX
References: <781164cc0703030550i509e79e5waa2f2c3a4950faad@mail.gmail.com>
Message-ID: <esc06r$g49$1@sea.gmane.org>


"Clay Wiedemann" <clay.wiedemann at gmail.com> wrote

> I am not only new to Python, but new to programming in an 
> environment
> like this, where knowing a little of how the underpinning work is
> essential.*

Actually I very rarely need to do anything with the environment.
Most of my iBook Python programming is done in the
src/python folder of my home directory. I just import
stuff and it works...

> I am running the latest OSX (10.4.8) and know a little about moving
> about in the terminal. But the world of paths, etc. has me a little
> confused.

If you have specific situations where paths are tripping you
up we can probably offer help. In general you should only need
1) The path to Python set up in your login shell script PATH
2) The path to Pythons modules in PYTHONPATH
ie. in your file:  ~/.bash_profile.
(I assume you use bash since think thats the new default
in 10.4 - I am still on 10.2 which uses tcsh as shell)

> - Can anyone point me to a well-regarded and pithy tutorial 
> regarding
> the UNIX underpinnings of OSX, especially anything that would help
> with Python.

Apple have lots of guidance, this is a good jump off page:

http://developer.apple.com/referencelibrary/GettingStarted/GS_MacOSXServer/index.html

Or more usefully there is Pogue's Missing Manual book.
This is probably best for traditional Mac users stepping into Unix
for the first time.
For more depth I found MacOS X Unleashed good, but longgggg
And finally MacOSX Hacks is good but not really a tutorial.

HTH,


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



From kent37 at tds.net  Sat Mar  3 15:20:43 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 03 Mar 2007 09:20:43 -0500
Subject: [Tutor] trouble understanding the python environment in OSX
In-Reply-To: <781164cc0703030550i509e79e5waa2f2c3a4950faad@mail.gmail.com>
References: <781164cc0703030550i509e79e5waa2f2c3a4950faad@mail.gmail.com>
Message-ID: <45E9843B.3030703@tds.net>

Clay Wiedemann wrote:

> I am running the latest OSX (10.4.8) and know a little about moving
> about in the terminal. But the world of paths, etc. has me a little
> confused. And now it is getting in my way. I was wondering if I could
> get a little help with some things.
> 
> - Can anyone point me to a well-regarded and pithy tutorial regarding
> the UNIX underpinnings of OSX, especially anything that would help
> with Python. (e.g., I can navigate to Python.framework and versions
> but see 2.5 and Current, which confuses me since 2.5 is the current
> version.) I would love to know what the structure of the Python
> installation means.

Current is an alias for 2.5, which is the current install.
> 
> - I am having trouble installing the BeautifulSoup package. The
> installer stumbles on a unicode issue (that the Soup developer says is
> a problem with my Python installation) -- so what is the best way to
> manually install this? And does the 2.5 / Current divide matter?

What is the error you get in the installer?

The installer is not really needed in this case. You should be able to 
just download the single file and put it in
.../Current/lib/python2.5/site-packages

Kent
> 
> 
> 
> Thanks in advance for any help with these basic issues.
> 
> Good morning from Brooklyn,
> Clay
> 
> 
> * Any experience with coding webpages is not helping here
> 
> 
> 
> - - - - - - -
> 
> Clay S. Wiedemann
> 
> aim: khlav
> wii: 3905 4571 6175 2469
> twitter: seastokes
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


From project5 at redrival.net  Sat Mar  3 16:43:00 2007
From: project5 at redrival.net (Andrei)
Date: Sat, 03 Mar 2007 16:43:00 +0100
Subject: [Tutor] Yet another list comprehension question
In-Reply-To: <esakn3$77p$1@sea.gmane.org>
References: <288A3B43F7B2224D9C8441C9FC5D6A02012E34B1@EXCHMAIL01.corp.medplus.com><es9hcb$34q$1@sea.gmane.org>	<loom.20070302T181509-612@post.gmane.org>
	<esakn3$77p$1@sea.gmane.org>
Message-ID: <esc51k$t8k$1@sea.gmane.org>

>> Alternatively, you could put the results as keys in a dictionary, 
>> then request
>> mydict.keys() to get a list of unique outcomes.
> 
> I thought of that too, but couldn't think how to do it in a list
> comprehension. It seemed like it should be possible but I
> couldn't think of how - and didn't have a python interpreter
> handy...

I wouldn't do it in a list comprehension - I took a bit of liberty with 
the topic and looked more at the actual problem :). Of course the loop 
can be turned into a list comprehension, but it serves no purpose 
whatsoever:

 >>> d = {}
 >>> [d.__setitem__(s, '') for s in myiterator]

By the way, the fromkeys method of the dict type can turn this into a 
oneliner:

 >>> mylist = [1,2,3,1,2,4] # may also be some iterator
 >>> print dict.fromkeys(mylist).keys()
... [1,2,3,4]

The set solution is the Most Obvious Way to do it, but the dict one 
doesn't require an understanding of list comprehensions.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info:
''.join([''.join(s) for s in zip(
"poet at aao.l pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
"rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])


From kent37 at tds.net  Sat Mar  3 17:24:35 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 03 Mar 2007 11:24:35 -0500
Subject: [Tutor] Yet another list comprehension question
In-Reply-To: <esc51k$t8k$1@sea.gmane.org>
References: <288A3B43F7B2224D9C8441C9FC5D6A02012E34B1@EXCHMAIL01.corp.medplus.com><es9hcb$34q$1@sea.gmane.org>	<loom.20070302T181509-612@post.gmane.org>	<esakn3$77p$1@sea.gmane.org>
	<esc51k$t8k$1@sea.gmane.org>
Message-ID: <45E9A143.1040707@tds.net>

Andrei wrote:
>>> Alternatively, you could put the results as keys in a dictionary, 
>>> then request
>>> mydict.keys() to get a list of unique outcomes.
>> I thought of that too, but couldn't think how to do it in a list
>> comprehension. It seemed like it should be possible but I
>> couldn't think of how - and didn't have a python interpreter
>> handy...
> 
> I wouldn't do it in a list comprehension - I took a bit of liberty with 
> the topic and looked more at the actual problem :). Of course the loop 
> can be turned into a list comprehension, but it serves no purpose 
> whatsoever:
> 
>  >>> d = {}
>  >>> [d.__setitem__(s, '') for s in myiterator]
> 
> By the way, the fromkeys method of the dict type can turn this into a 
> oneliner:
> 
>  >>> mylist = [1,2,3,1,2,4] # may also be some iterator
>  >>> print dict.fromkeys(mylist).keys()
> ... [1,2,3,4]
> 
> The set solution is the Most Obvious Way to do it, but the dict one 
> doesn't require an understanding of list comprehensions.

The list comp in Alan's solution is just needed to introduce somefunc(). 
You have to do the same in yours to match the original problem. The set 
version of your solution doesn't need a list comp either, it is just
list(set(mylist))

There is really no reason in modern Python to use dicts as sets.

Kent

From meiermic at ee.ethz.ch  Sat Mar  3 20:01:52 2007
From: meiermic at ee.ethz.ch (Michael Meier)
Date: Sat, 03 Mar 2007 20:01:52 +0100
Subject: [Tutor] Lamdas and locality
In-Reply-To: <mailman.14688.1172939081.32030.tutor@python.org>
References: <mailman.14688.1172939081.32030.tutor@python.org>
Message-ID: <1172948513.5670.5.camel@napalm>

Hello

I ran the following code in python:

>>> ls = [(lambda op: op + i) for i in [1,2,3]]
>>> ls
[<function <lambda> at 0xb7de4cdc>, <function <lambda> at 0xb7de4d14>,
<function <lambda> at 0xb7de4d4c>]
>>> for l in ls:
...     print l(5)
...
8
8
8
>>>     


I am quite surprised of the result. I'm generating three lamdas. What I
want to do is that the first lamda adds 1 to the operand and returns it,
the second lamda return 2 plus the operand and so on.
However all the three lamdas, despite being not the same object in
memory, are all adding 3, so they've got to have a reference to and not
to 1,2,3 respectively.

Why are the lamdas having a reference to the same integer? What am I
getting wrong here? :P


On Sat, 2007-03-03 at 17:24 +0100, tutor-request at python.org wrote:
> Send Tutor mailing list submissions to
> 	tutor at python.org
> 
> To subscribe or unsubscribe via the World Wide Web, visit
> 	http://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body 'help' to
> 	tutor-request at python.org
> 
> You can reach the person managing the list at
> 	tutor-owner at python.org
> 
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Tutor digest..."
> 
> 
> Today's Topics:
> 
>    1. Re: geeks like us and the rest of THEM (Andrei)
>    2. Re: dictionaries and memory handling (Andrei)
>    3. Re: Yet another list comprehension question (Kent Johnson)
>    4. trouble understanding the python environment in OSX
>       (Clay Wiedemann)
>    5. Re: trouble understanding the python environment in OSX
>       (Alan Gauld)
>    6. Re: trouble understanding the python environment in OSX
>       (Kent Johnson)
>    7. Re: Yet another list comprehension question (Andrei)
>    8. Re: Yet another list comprehension question (Kent Johnson)
> 
> 
> ----------------------------------------------------------------------
> 
> Message: 1
> Date: Sat, 03 Mar 2007 13:40:05 +0100
> From: Andrei <project5 at redrival.net>
> Subject: Re: [Tutor] geeks like us and the rest of THEM
> To: tutor at python.org
> Message-ID: <esbqal$qpu$1 at sea.gmane.org>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
> 
> <snip>
> > That's part of it. a good installer is another, and I am loo]king at a 
> > couple.  A solid and drool-proof server is the remaining leg of the 
> > tripod. So far, none of the servers I have seen are satisfactory on all 
> > scores- simplicity to install, reliability, economy of cost, (free or 
> > unlimited license to me for a modest fee) and ease to configure if the 
> > use\r so wishes. the closest I have yet seen SMALL HTTP SERVER. And it 
> > is very good.
> > http://smallsrv.com/
> 
> You could have a look at Aprelium's Abyss server (X1, which is freely 
> distributable in unmodified form IIRC, but closed source). It has a good 
> looking webbased configuration console and is cross-platform if you ever 
> need that. However, you'll probably end up digging in its config 
> programmatically to set up paths and such for the user - shouldn't be 
> too hard using some webscraping if the files are not readily modifiable. 
> Its setup is about 350 kB.
> 
> In terms of installers, NSIS (with the package to make it look modern, 
> instead of that awful default look - forgot its name) or InnoSetup are 
> the usual suspects. NSIS has a smaller overhead, but an uglier language.
> 
> -- 
> Yours,
> 
> Andrei
> 
> =====
> Mail address in header catches spam. Real contact info:
> ''.join([''.join(s) for s in zip(
> "poet at aao.l pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
> "rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])
> 
> 
> 
> ------------------------------
> 
> Message: 2
> Date: Sat, 03 Mar 2007 14:18:24 +0100
> From: Andrei <project5 at redrival.net>
> Subject: Re: [Tutor] dictionaries and memory handling
> To: tutor at python.org
> Message-ID: <esbsif$6ec$1 at sea.gmane.org>
> Content-Type: text/plain; charset=windows-1252; format=flowed
> 
> > But most of my dictionaries are nested, and since both keys and values 
> > in the dbm 'dictionaries' have to be strings, I can't immediately see 
> > how I could get it to work.
> > 
> > A bit more detail: I deal with conditional probabilities, with up to 4 
> > parameters. These parameters are numbers or words and determine the 
> > value (which is always a number). E.g. I have a dictionary 
> > {p1:{p2:{p3:{p4:value}}}}, where the p's are different parameters. I 
> > sometimes need to sum over one or more of the parameters ? for now I 
> > have managed to structure the dictionaries so that I only need to sum 
> > over the innermost parameter, although this has been a bit cumbersome.
> 
> Depends a bit on how many keys each of the dictionaries is going to have 
> and in what order they're filled. You can pickle/cPickle an arbitrary 
> amount of data as one value, so the whole {p2:{p3:{p4:value}}} story 
> could be a value of the p1 key in the bsddb. However, you may not like 
> this if you need to retrieve p1 and add new stuff to it all the time, 
> because the pickling and unpickling cycles may not be beneficial to the 
> performance.
> 
> If you find this is a problem, you could opt to e.g. keep the first 
> layer of the dictionary in memory, but map each value to a separate 
> bsddb, so that you'd need to do less pickling/unpickling.
> 
> Alternatively you could choose to store them as a sort of path in the 
> bsddb, like this (obviously wasteful in terms of space):
> 'p1/p2/p3/p4': '20'
> 'p1/p2/p3/p5': '45'
> 
> Combinations of the approaches above are also possible and I have no 
> idea which would be best.
> 
> >> - Will the dictionaries take up less memory if I use numbers rather  
> >> than words as keys (i.e. will {3:45, 6:77, 9:33} consume less memory  
> >> than {"eloquent":45, "helpless":77, "samaritan":33} )? And if so:  
> >> Slightly less, or substantially less memory?
> 
> Here's a simple test:
> 
>  >>> x = [str(i) for i in range(100000, 1000000)]
> vs.
>  >>> x = [i for i in range(100000, 1000000)]
> 
> The interpreter takes about 50 MB for the str() version and about 20 for 
> the non-str() version - eyeballed in the Task manager. So it does make a 
> significant difference, though not an order-of-magnitude difference. 
> That may be enough for now, but if this script stays in use, you're 
> bound at some point to need even more.
> 
> >> - What are common methods to monitor the memory usage of a script?  
> >> Can I add a snippet to the code that prints out how many MBs of  
> >> memory a certain dictionary takes up at that particular time?
> 
> Not as such. In your case, I think the task manager would be enough. You 
> only have this one demanding data structure I assume, so in a rough 
> approximation you can pretend that whatever the task manager reports 
> (have a look at VM and peak memory usage columns, not just memory usage) 
> is caused by the contents of the dictionary.
> 
> -- 
> Yours,
> 
> Andrei
> 
> =====
> Mail address in header catches spam. Real contact info:
> ''.join([''.join(s) for s in zip(
> "poet at aao.l pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
> "rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])
> 
> 
> 
> ------------------------------
> 
> Message: 3
> Date: Sat, 03 Mar 2007 08:47:55 -0500
> From: Kent Johnson <kent37 at tds.net>
> Subject: Re: [Tutor] Yet another list comprehension question
> To: Alan Gauld <alan.gauld at btinternet.com>
> Cc: tutor at python.org
> Message-ID: <45E97C8B.1060205 at tds.net>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
> 
> Alan Gauld wrote:
> > "Smith, Jeff" <jsmith at medplus.com> wrote
> > 
> >> In other words, applying somefun to the results of the iterator 
> >> return
> >> duplicates but I want the constructed list to contain none.
> > 
> >> l = [somefun(i) for i some-iterator if somefun(i) not in l]
> >>
> >> doesn't work (not that I expected it to).
> > 
> > Why not use a Set?
> > 
> > s = Set([somefun(i) for i in some-iterator])
> > 
> > Might be slow for big lists though...
> 
> This is a popular question. It comes up frequently on comp.lang.python 
> and there are many recipes in the online cookbook. Here is a FAQ:
> http://www.effbot.org/pyfaq/how-do-you-remove-duplicates-from-a-list.htm
> 
> I think using a set is the fastest solution if the list items are 
> hashable and you don't care about order.
> 
> If the list items are hashable and you do care about order then there is 
> this mild hack:
> s = set()
> [ i for i in lst if i not in s and not s.add(i) ]
> 
> but with the requirement of calling somefunc(i) my guess is that an 
> explicit loop will be faster.
> 
> The cookbook is down right now but there is a link in the above FAQ.
> 
> Kent
> 
> 
> ------------------------------
> 
> Message: 4
> Date: Sat, 3 Mar 2007 08:50:09 -0500
> From: "Clay Wiedemann" <clay.wiedemann at gmail.com>
> Subject: [Tutor] trouble understanding the python environment in OSX
> To: tutor at python.org
> Message-ID:
> 	<781164cc0703030550i509e79e5waa2f2c3a4950faad at mail.gmail.com>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
> 
> Hi,
> 
> I am not only new to Python, but new to programming in an environment
> like this, where knowing a little of how the underpinning work is
> essential.*
> 
> I am running the latest OSX (10.4.8) and know a little about moving
> about in the terminal. But the world of paths, etc. has me a little
> confused. And now it is getting in my way. I was wondering if I could
> get a little help with some things.
> 
> - Can anyone point me to a well-regarded and pithy tutorial regarding
> the UNIX underpinnings of OSX, especially anything that would help
> with Python. (e.g., I can navigate to Python.framework and versions
> but see 2.5 and Current, which confuses me since 2.5 is the current
> version.) I would love to know what the structure of the Python
> installation means.
> 
> - I am having trouble installing the BeautifulSoup package. The
> installer stumbles on a unicode issue (that the Soup developer says is
> a problem with my Python installation) -- so what is the best way to
> manually install this? And does the 2.5 / Current divide matter?
> 
> 
> 
> Thanks in advance for any help with these basic issues.
> 
> Good morning from Brooklyn,
> Clay
> 
> 
> * Any experience with coding webpages is not helping here
> 
> 
> 
> - - - - - - -
> 
> Clay S. Wiedemann
> 
> aim: khlav
> wii: 3905 4571 6175 2469
> twitter: seastokes
> 
> 
> ------------------------------
> 
> Message: 5
> Date: Sat, 3 Mar 2007 14:22:11 -0000
> From: "Alan Gauld" <alan.gauld at btinternet.com>
> Subject: Re: [Tutor] trouble understanding the python environment in
> 	OSX
> To: tutor at python.org
> Message-ID: <esc06r$g49$1 at sea.gmane.org>
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
> 	reply-type=original
> 
> 
> "Clay Wiedemann" <clay.wiedemann at gmail.com> wrote
> 
> > I am not only new to Python, but new to programming in an 
> > environment
> > like this, where knowing a little of how the underpinning work is
> > essential.*
> 
> Actually I very rarely need to do anything with the environment.
> Most of my iBook Python programming is done in the
> src/python folder of my home directory. I just import
> stuff and it works...
> 
> > I am running the latest OSX (10.4.8) and know a little about moving
> > about in the terminal. But the world of paths, etc. has me a little
> > confused.
> 
> If you have specific situations where paths are tripping you
> up we can probably offer help. In general you should only need
> 1) The path to Python set up in your login shell script PATH
> 2) The path to Pythons modules in PYTHONPATH
> ie. in your file:  ~/.bash_profile.
> (I assume you use bash since think thats the new default
> in 10.4 - I am still on 10.2 which uses tcsh as shell)
> 
> > - Can anyone point me to a well-regarded and pithy tutorial 
> > regarding
> > the UNIX underpinnings of OSX, especially anything that would help
> > with Python.
> 
> Apple have lots of guidance, this is a good jump off page:
> 
> http://developer.apple.com/referencelibrary/GettingStarted/GS_MacOSXServer/index.html
> 
> Or more usefully there is Pogue's Missing Manual book.
> This is probably best for traditional Mac users stepping into Unix
> for the first time.
> For more depth I found MacOS X Unleashed good, but longgggg
> And finally MacOSX Hacks is good but not really a tutorial.
> 
> HTH,
> 
> 
> -- 
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld 
> 
> 
> 
> 
> ------------------------------
> 
> Message: 6
> Date: Sat, 03 Mar 2007 09:20:43 -0500
> From: Kent Johnson <kent37 at tds.net>
> Subject: Re: [Tutor] trouble understanding the python environment in
> 	OSX
> To: Clay Wiedemann <clay.wiedemann at gmail.com>
> Cc: tutor at python.org
> Message-ID: <45E9843B.3030703 at tds.net>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
> 
> Clay Wiedemann wrote:
> 
> > I am running the latest OSX (10.4.8) and know a little about moving
> > about in the terminal. But the world of paths, etc. has me a little
> > confused. And now it is getting in my way. I was wondering if I could
> > get a little help with some things.
> > 
> > - Can anyone point me to a well-regarded and pithy tutorial regarding
> > the UNIX underpinnings of OSX, especially anything that would help
> > with Python. (e.g., I can navigate to Python.framework and versions
> > but see 2.5 and Current, which confuses me since 2.5 is the current
> > version.) I would love to know what the structure of the Python
> > installation means.
> 
> Current is an alias for 2.5, which is the current install.
> > 
> > - I am having trouble installing the BeautifulSoup package. The
> > installer stumbles on a unicode issue (that the Soup developer says is
> > a problem with my Python installation) -- so what is the best way to
> > manually install this? And does the 2.5 / Current divide matter?
> 
> What is the error you get in the installer?
> 
> The installer is not really needed in this case. You should be able to 
> just download the single file and put it in
> .../Current/lib/python2.5/site-packages
> 
> Kent
> > 
> > 
> > 
> > Thanks in advance for any help with these basic issues.
> > 
> > Good morning from Brooklyn,
> > Clay
> > 
> > 
> > * Any experience with coding webpages is not helping here
> > 
> > 
> > 
> > - - - - - - -
> > 
> > Clay S. Wiedemann
> > 
> > aim: khlav
> > wii: 3905 4571 6175 2469
> > twitter: seastokes
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> > 
> 
> 
> 
> ------------------------------
> 
> Message: 7
> Date: Sat, 03 Mar 2007 16:43:00 +0100
> From: Andrei <project5 at redrival.net>
> Subject: Re: [Tutor] Yet another list comprehension question
> To: tutor at python.org
> Message-ID: <esc51k$t8k$1 at sea.gmane.org>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
> 
> >> Alternatively, you could put the results as keys in a dictionary, 
> >> then request
> >> mydict.keys() to get a list of unique outcomes.
> > 
> > I thought of that too, but couldn't think how to do it in a list
> > comprehension. It seemed like it should be possible but I
> > couldn't think of how - and didn't have a python interpreter
> > handy...
> 
> I wouldn't do it in a list comprehension - I took a bit of liberty with 
> the topic and looked more at the actual problem :). Of course the loop 
> can be turned into a list comprehension, but it serves no purpose 
> whatsoever:
> 
>  >>> d = {}
>  >>> [d.__setitem__(s, '') for s in myiterator]
> 
> By the way, the fromkeys method of the dict type can turn this into a 
> oneliner:
> 
>  >>> mylist = [1,2,3,1,2,4] # may also be some iterator
>  >>> print dict.fromkeys(mylist).keys()
> ... [1,2,3,4]
> 
> The set solution is the Most Obvious Way to do it, but the dict one 
> doesn't require an understanding of list comprehensions.
> 
> -- 
> Yours,
> 
> Andrei
> 
> =====
> Mail address in header catches spam. Real contact info:
> ''.join([''.join(s) for s in zip(
> "poet at aao.l pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
> "rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])
> 
> 
> 
> ------------------------------
> 
> Message: 8
> Date: Sat, 03 Mar 2007 11:24:35 -0500
> From: Kent Johnson <kent37 at tds.net>
> Subject: Re: [Tutor] Yet another list comprehension question
> To: Andrei <project5 at redrival.net>
> Cc: tutor at python.org
> Message-ID: <45E9A143.1040707 at tds.net>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
> 
> Andrei wrote:
> >>> Alternatively, you could put the results as keys in a dictionary, 
> >>> then request
> >>> mydict.keys() to get a list of unique outcomes.
> >> I thought of that too, but couldn't think how to do it in a list
> >> comprehension. It seemed like it should be possible but I
> >> couldn't think of how - and didn't have a python interpreter
> >> handy...
> > 
> > I wouldn't do it in a list comprehension - I took a bit of liberty with 
> > the topic and looked more at the actual problem :). Of course the loop 
> > can be turned into a list comprehension, but it serves no purpose 
> > whatsoever:
> > 
> >  >>> d = {}
> >  >>> [d.__setitem__(s, '') for s in myiterator]
> > 
> > By the way, the fromkeys method of the dict type can turn this into a 
> > oneliner:
> > 
> >  >>> mylist = [1,2,3,1,2,4] # may also be some iterator
> >  >>> print dict.fromkeys(mylist).keys()
> > ... [1,2,3,4]
> > 
> > The set solution is the Most Obvious Way to do it, but the dict one 
> > doesn't require an understanding of list comprehensions.
> 
> The list comp in Alan's solution is just needed to introduce somefunc(). 
> You have to do the same in yours to match the original problem. The set 
> version of your solution doesn't need a list comp either, it is just
> list(set(mylist))
> 
> There is really no reason in modern Python to use dicts as sets.
> 
> Kent
> 
> 
> ------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> End of Tutor Digest, Vol 37, Issue 10
> *************************************


From kent37 at tds.net  Sat Mar  3 23:12:18 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 03 Mar 2007 17:12:18 -0500
Subject: [Tutor] Lamdas and locality
In-Reply-To: <1172948513.5670.5.camel@napalm>
References: <mailman.14688.1172939081.32030.tutor@python.org>
	<1172948513.5670.5.camel@napalm>
Message-ID: <45E9F2C2.6070104@tds.net>

Michael Meier wrote:
> Hello
> 
> I ran the following code in python:
> 
>>>> ls = [(lambda op: op + i) for i in [1,2,3]]
>>>> ls
> [<function <lambda> at 0xb7de4cdc>, <function <lambda> at 0xb7de4d14>,
> <function <lambda> at 0xb7de4d4c>]
>>>> for l in ls:
> ...     print l(5)
> ...
> 8
> 8
> 8
>>>>     
> 
> 
> I am quite surprised of the result. I'm generating three lamdas. What I
> want to do is that the first lamda adds 1 to the operand and returns it,
> the second lamda return 2 plus the operand and so on.
> However all the three lamdas, despite being not the same object in
> memory, are all adding 3, so they've got to have a reference to and not
> to 1,2,3 respectively.
> 
> Why are the lamdas having a reference to the same integer? What am I
> getting wrong here? :P

This behaviour surprises many people. The lambda does not bind the value 
of i. When you execute the lambda it looks up the value of i in the 
enclosing scope which in this case is the global namespace. Each 
function will get the same value because they all look up i in the same 
place.

As a workaround you can bind the value of i to a default argument like this:
In [1]: ls = [(lambda op, i=i: op + i) for i in [1,2,3]]
In [2]: for f in ls:
    ...:     print f(5)
    ...:
6
7
8

Kent

PS When you reply to an archive please delete the parts of the archive 
that are not of interest.

From kent37 at tds.net  Sat Mar  3 23:26:06 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 03 Mar 2007 17:26:06 -0500
Subject: [Tutor] using tarfile on strings or filelike objects
In-Reply-To: <BAA2EE790D828F4E8B262F17B3B0A7A30363CEE5@VUIEXCH1.ad.nottingham.ac.uk>
References: <BAA2EE790D828F4E8B262F17B3B0A7A30363CEE5@VUIEXCH1.ad.nottingham.ac.uk>
Message-ID: <45E9F5FE.1030000@tds.net>

Barton David wrote:
> I like that I can access the contents of a zip archive that's stored in 
> memory (rather than on disk) by packing the archive contents into a 
> StringIO or cStringIO object and feeding that to ZipFile...
>  
> i.e.
>  
> filelike=cStringIO.StringIO(archive_as_string)
> zf=zipfile.ZipFile(filelike)
> content=zf.read(archive_member_name)
> zf.close()
> filelike.close()
>  
> but I can't get the same thing to work with TarFile. Is there any way to 
> do this? (Other than first saving the archive data to disk and then 
> passing the path to TarFile.open?) The tarfile module documentation 
> talks about an optional fileobj flag but this doesn't seem to work.

Just from reading the docs I would try
filelike = cStringIO...
tf = tarfile.open(mode='r|', fileobj=filelike)

This is based on the example in the docs of reading from stdin.

Kent


From amonroe at columbus.rr.com  Sun Mar  4 01:14:34 2007
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Sat, 3 Mar 2007 19:14:34 -0500
Subject: [Tutor] httpd in your laptop?!? serve web pages and wikis in
	your notebook?
In-Reply-To: <es9mgk$v07$1@sea.gmane.org>
References: <45E50446.8060502@verizon.net> <45E5188F.7010902@gmail.com>
	<45E52949.9090705@verizon.net> <45E7E4B1.8070707@gmail.com>
	<45E83D21.6080205@verizon.net> <45E8539A.8050307@gmail.com>
	<es9mgk$v07$1@sea.gmane.org>
Message-ID: <198176975437.20070303191434@columbus.rr.com>


> "Luke Paireepinart" <rabidpoobear at gmail.com> wrote
>>
>>> forth ... while very good for small programs
>>> to imbed into controller cpu's to bury inside some machine,

> It's a relatively little known fact that Sun use Forth as the
> monitor/bootloader  in their servers. When you do a shutdown
> on a Sun box it takes you into a Forth interpreter!

>>> different that rank beginners learn it faster than experienced 
>>> hands
>>> do. it's just so damn odd.

> Yep, it's one of the few languages that I just gave up on,
> the pain wasn't worth the gain. I wound up moving to Tcl;
> and Tcl isn't exactly mainstream! But it was a lot more
> conventional than Forth. The only language I've used that
> was equally different was Prolog.

Postscript borrows heavily from Forth, I think.

Alan


From clay.wiedemann at gmail.com  Sun Mar  4 04:22:05 2007
From: clay.wiedemann at gmail.com (Clay Wiedemann)
Date: Sat, 3 Mar 2007 22:22:05 -0500
Subject: [Tutor] beautifulsoup - getting an error when NavigableString
	object is returned
Message-ID: <781164cc0703031922q60ef1c34y65c38cf0c922ad2f@mail.gmail.com>

I wanted to strip the quotes from IMDB quote pages, just to start
learning python. Quotes are not nested, so I got the anchor links that
precede them. I thought I could walk down until I hit an HR tag,
meanwhile grabbing people and quotes via hits on <b> and <br>.
But once I tried to walk down from my hit on the anchor link and pull
the name, I found I kept getting a NavigableString instead of tag, so
asking for the .name attribute gave an error.

Any idea why this might happen?


This is the relevant chunk of IMDB code:

<a name="qt0210620"></a>

<b><a href="/name/nm0629454/">Bill</a></b>:
You're supposed to wear the blue dress when I wear this.
<br>

<b><a href="/name/nm0707043/">Mary</a></b>:
I don't want to dress like twins anymore.
<br>

<b><a href="/name/nm0629454/">Bill</a></b>:
We're not twins. We're a trio.
<br>
<hr width="30%">


---


And this is what I wrote (and if there are other awful things about
this, I would be happy to know):


#!/usr/bin/env python

import urllib2
from BeautifulSoup import BeautifulSoup
import re


# stubs --------------------------

movietitle_stub = "Nashville" 							#later search an pull first
result (if movie?)
movieurl_stub = "http://imdb.com/title/tt0073440/" 		#and get this



def soupifyPage(target):
	"""
	grab html from a page
	probably need real method of checking for failure, huh
	"""
	codeReq = urllib2.Request(target)
	response = urllib2.urlopen(codeReq)
	soupyhtml = BeautifulSoup(response)
	return soupyhtml


def pullQuote(curTag):
	# character is in bold
	print curTag.nextSibling.name
	'''
	if curTag.nextSibling.name == 'hr':
		#are done
		return quoteBlock
	print "seeing" + curTag.nextSibling.name
	quoteBlock = quoteBlock + " - " + curTag.nextSibling.name
	curTag = curTag.nextSibling
	'''




quotepage = movieurl_stub + "quotes"
print "Getting this:" + quotepage
print "---------------"
quotebag = soupifyPage(quotepage)


# each quote is preceded by anchorlink, begins with qt : example <a
name="qt0229419"></a>
# the end with an HR tag
# they are not nested

quotations = quotebag.findAll(attrs = {'name' : re.compile("^qt")})

for q in quotations:
	#pullQuote(q)
	print q.nextSibling.name  # attribute error: "'NavigableString'
object has no attribute 'name'"
	print "next!"
		



Thanks,
Clay

- - - - - - -

Clay S. Wiedemann

From deliberatus at verizon.net  Sun Mar  4 05:31:57 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Sat, 03 Mar 2007 23:31:57 -0500
Subject: [Tutor] geeks like us and the rest of THEM
In-Reply-To: <esbqal$qpu$1@sea.gmane.org>
References: <45E06524.2090805@verizon.net> <45E06BA8.8020802@tds.net>
	<45E13742.4070208@verizon.net> <esbqal$qpu$1@sea.gmane.org>
Message-ID: <45EA4BBD.7050607@verizon.net>



Andrei wrote:
> <snip>
>> That's part of it. a good installer is another, and I am loo]king at a 
>> couple.  A solid and drool-proof server is the remaining leg of the 
>> tripod. So far, none of the servers I have seen are satisfactory on all 
>> scores- simplicity to install, reliability, economy of cost, (free or 
>> unlimited license to me for a modest fee) and ease to configure if the 
>> use\r so wishes. the closest I have yet seen SMALL HTTP SERVER. And it 
>> is very good.
>> http://smallsrv.com/
> 
> You could have a look at Aprelium's Abyss server (X1, which is freely 
> distributable in unmodified form IIRC, but closed source). It has a good 
> looking webbased configuration console and is cross-platform if you ever 
> need that. However, you'll probably end up digging in its config 
> programmatically to set up paths and such for the user - shouldn't be 
> too hard using some webscraping if the files are not readily modifiable. 
> Its setup is about 350 kB.
I did. good, but fairly large and noticible impact on cycles as well as 
memory. smallserve is lighter, and tinyweb lighter yet- and it's terms 
of use let one include it with commercial products free. and I have yet 
to throw aqnything at it in spite of it's compact wtructure it could not 
deal with.
> 
> In terms of installers, NSIS (with the package to make it look modern, 
> instead of that awful default look - forgot its name) or InnoSetup are 
> the usual suspects. NSIS has a smaller overhead, but an uglier language.
> 
both look interesting, inno looks like a faster learning curve.

-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From deliberatus at verizon.net  Sun Mar  4 05:36:06 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Sat, 03 Mar 2007 23:36:06 -0500
Subject: [Tutor] miniwiki 1.3.0 beta now available
In-Reply-To: <45E91517.7060406@verizon.net>
References: <45E91517.7060406@verizon.net>
Message-ID: <45EA4CB6.4030502@verizon.net>

Anyone who had trouble downloading the file, try again, there was a 
problem in the server which is now fixed.

Kirk Bailey wrote:
> May The Gods have mercy on my soul.
> 
> MiniWiki is now offered for downloading. 1.3.0 is not in presentable 
> condition for them what would like to kick it around some.
> 
> http://www.tinylist.org/MiniWIKI130.zip
> 
> Included in it is the zip archive for the server I settled on which is a 
> very nice little tool I have yet to break regardless of how I stick my 
> thumbs in it's eye. Robust is an understatement, it is bulletproof. 
> Alas, it will NOT parse ssi includes, but WILL support scripts with 
> environment data and go retreived specified interpeters declared in the 
> shebang line, so it's not so terrible. It is free PERIOD, even if 
> included in commercial releases, as long as you credit the authors- 
> well, I included everything they released, including source code, so go 
> for it.
> 
> My zip file includes subdirectories and seedpages. One should create a 
> folder such as 'c:\localhost', place the zip in it, and unpack it there. 
> you will get \www, \cgi-bin, \cgi-bin\texts, www\images, and several 
> files in the texts directory.
> 
> If I got this thing to zip up properly. sheesh. I'm going to bed.
> 
> 

-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From meiermic at ee.ethz.ch  Sun Mar  4 10:43:47 2007
From: meiermic at ee.ethz.ch (Michael Meier)
Date: Sun, 04 Mar 2007 10:43:47 +0100
Subject: [Tutor] Lamdas and locality
In-Reply-To: <mailman.14735.1172978528.32030.tutor@python.org>
References: <mailman.14735.1172978528.32030.tutor@python.org>
Message-ID: <1173001427.5071.4.camel@napalm>

Thanks for your answer and your workaround! There's always something to
learn about lambdas and variable scope in Python ;)

I'm sorry I didn't delete the quoted Tutor Digest part, it was a stupid
mistake :(


cheers,
Michael


From andreas at kostyrka.org  Sun Mar  4 17:43:13 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Sun,  4 Mar 2007 17:43:13 +0100
Subject: [Tutor] httpd in your laptop?!? serve web pages and wikis in y
 our notebook?
Message-ID: <Ch0YtRzb2ZlD.rnScyhml@heaven.kostyrka.org>

forth and postscript are both rpn notated languages. stack oriented languages include also other stuff, e.g. the jvm assembly language. (Although the security verifier does place rather strict limitations on the allowed stuff)
but that's where the common things end. forth is a lowlevel language that manipulates memory directly, it's untyped too ;)

postscript otoh is a typed language with comparable safety to Python.

Andreas 

_____ Urspr?ngliche Mitteilung _____
Betreff:	Re: [Tutor] httpd in your laptop?!? serve web pages and wikis in your notebook?
Autor:	"R. Alan Monroe" <amonroe at columbus.rr.com>
Datum:		4. M?rz 2007 1:14:34


> "Luke Paireepinart" <rabidpoobear at gmail.com> wrote
>>
>>> forth ... while very good for small programs
>>> to imbed into controller cpu's to bury inside some machine,

> It's a relatively little known fact that Sun use Forth as the
> monitor/bootloader  in their servers. When you do a shutdown
> on a Sun box it takes you into a Forth interpreter!

>>> different that rank beginners learn it faster than experienced 
>>> hands
>>> do. it's just so damn odd.

> Yep, it's one of the few languages that I just gave up on,
> the pain wasn't worth the gain. I wound up moving to Tcl;
> and Tcl isn't exactly mainstream! But it was a lot more
> conventional than Forth. The only language I've used that
> was equally different was Prolog.

Postscript borrows heavily from Forth, I think.

Alan

_______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070304/fdd0ba38/attachment.html 

From kent37 at tds.net  Sun Mar  4 18:33:29 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 04 Mar 2007 12:33:29 -0500
Subject: [Tutor] httpd in your laptop?!? serve web pages and wikis in y
 our notebook?
In-Reply-To: <Ch0YtRzb2ZlD.rnScyhml@heaven.kostyrka.org>
References: <Ch0YtRzb2ZlD.rnScyhml@heaven.kostyrka.org>
Message-ID: <45EB02E9.4030205@tds.net>

Andreas Kostyrka wrote:
> forth and postscript are both rpn notated languages. stack oriented 
> languages include also other stuff, e.g. the jvm assembly language. 

The CPython virtual machine is also a stack-based language. The 
operations are defined here:
http://python.org/doc/current/lib/bytecodes.html

Kent

From chris.arndt at web.de  Sun Mar  4 23:11:07 2007
From: chris.arndt at web.de (Christopher Arndt)
Date: Sun, 04 Mar 2007 23:11:07 +0100
Subject: [Tutor] How does datetime.now() get timezone?
Message-ID: <45EB43FB.4040500@web.de>

Hi all,

this is maybe more of a Linux question or about how Python plays together with
the OS:

I have a virtual server on which I installed Ubuntu Dapper LTS with a minimal
install plus the things I needed. If I do

from datetime import datetime
t = datetime.now()

there, 't' is a naive datetme object, i.e. t.tzinfo is None.

If I do the same on my developing machine, which has also Ubuntu Dapper, I get
a timezone-aware datatime object.

What do I have to do to set the timezone so that Python can recognize it? I
already installed the 'locales' package, ran 'tzconfig' and installed
timezoneconf and ran that, but to no avail.

Chris

From pine508 at hotmail.com  Mon Mar  5 00:23:36 2007
From: pine508 at hotmail.com (Che M)
Date: Sun, 04 Mar 2007 18:23:36 -0500
Subject: [Tutor] basic plotting questions (pyplot vs matplotlib, etc)
Message-ID: <BAY18-F19F1E46EA2082D437A9970E0850@phx.gbl>

I'd like to learn to use basic plotting in a wxPython GUI app,
with plots embedded in the GUI.  Some questions about this:

1) Of pyplot or matplotlib, which might you recommend?  My needs are:

- embedded plots in GUI (either can AFAIK)
- basic point/line/pie/bar graphs, regression lines, clickable points. (not 
sure if pyplot does regression
  lines or pie charts.)
- get the datapoints from a SQLite database queries
- reasonably do-able for a determined beginner programmer (me)
- not too memory intensive/app-bloating

Clearly matplotlib can do it all but I'm unsure if it is overkill for my 
needs?

2) What does "DC" mean?  As in wxDC?

3) I'd like to try a simple embedded plot in pyplot to get started.  Boa 
Constructor will place
a plot canvas to start, but I'm having trouble wading through the code of 
the pyplot example
from the wxPython demo.  Could someone help me with the barest bones of a 
simple line
plot on a canvas?  Just x = (1,2,3,4,5), y = (2,4,6,8,10) sort of thing.

TIA,
Che

_________________________________________________________________
Mortgage rates as low as 4.625% - Refinance $150,000 loan for $579 a month. 
Intro*Terms  
https://www2.nextag.com/goto.jsp?product=100000035&url=%2fst.jsp&tm=y&search=mortgage_text_links_88_h27f6&disc=y&vers=743&s=4056&p=5117


From alan.gauld at btinternet.com  Mon Mar  5 01:29:03 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 5 Mar 2007 00:29:03 -0000
Subject: [Tutor] basic plotting questions (pyplot vs matplotlib, etc)
References: <BAY18-F19F1E46EA2082D437A9970E0850@phx.gbl>
Message-ID: <esfo4n$u11$1@sea.gmane.org>

"Che M" <pine508 at hotmail.com> wrote 

> 1) Of pyplot or matplotlib, which might you recommend?  

Sorry, no real experience of either.

> 2) What does "DC" mean?  As in wxDC?

I'm guessing, but based on my previous experience of 
other GUIs, it will be a Device Context. A DC is a concept which 
tries to abstract the hardware used for graphics so that you 
can create the same graphic and display it on a screen or on 
a printer with minimal change. You just pass in the appropriate 
DC to the graphics functions. This is good for WYSIWYG type 
work, but can mean that "simple" priniting (eg text) is much more 
difficult than would normally be the case!

HTH,


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


From atpridgen at mail.utexas.edu  Mon Mar  5 09:16:57 2007
From: atpridgen at mail.utexas.edu (Adam Pridgen)
Date: Mon, 5 Mar 2007 02:16:57 -0600
Subject: [Tutor]  executing a string representing python code
In-Reply-To: <f989e6210703050015g3cca2364l991d87ec028b58e4@mail.gmail.com>
References: <7a4620dc0703020632q615c53b6me8a187685406dbbd@mail.gmail.com>
	<f989e6210703050015g3cca2364l991d87ec028b58e4@mail.gmail.com>
Message-ID: <f989e6210703050016o434d8247xc09b5e102f33850a@mail.gmail.com>

here's the magic you are looking for:

func_str = \
'''
def some_func(value):
# youwould check value instance here and do something to it
    print "Hello World", value
    return "Done"
'''
exec(func_str)
f = locals()["some_func"]
print f("wasn't that cool!")

When you exec the str, it will create a function object, and then you
can obtain the object by accessing the object by kwd in the locals()
dictionary.  Guess it's not really magic, but I think it is still
pretty cool ;)  There also several variations to this method, but this
is the most readable IMHO.

Cheers,

Adam


On 3/2/07, Cecilia Alm <flickita at gmail.com> wrote:
> I know that there are several ways to execute a string which represents a
> piece of python code.
>  Out of curiosity, is it only eval which returns a value? (as below, where
> the string corresponds to a defined function).
>
>  >>> def addone(val):
>  ...     return val + 1
>  ...
>  >>> res = eval('addone(10)')
>
> Thanks!
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>

From David.Barton at nottingham.ac.uk  Mon Mar  5 10:19:40 2007
From: David.Barton at nottingham.ac.uk (Barton David)
Date: Mon, 5 Mar 2007 09:19:40 -0000
Subject: [Tutor] using tarfile on strings or filelike objects
Message-ID: <BAA2EE790D828F4E8B262F17B3B0A7A30363D386@VUIEXCH1.ad.nottingham.ac.uk>

Thanks Kent,

But.. I've actually found that that doesn't work (raises a ReadError),
and neither does..
>>>tf=tarfile.open(mode="r|*",fileobj=filelike)
..which raises "AttributeError: _Stream instance has no attribute
'dbuf'"

However if I explicitly state the compression type.. e.g.
>>>tf=tarfile.open(mode="r|bz2",fileobj=filelike)
..then I can indeed go on to..
>>>print tf.getnames()
>>>assert archive_member_name in tf.getnames()
..and it works ok. Having to explicitly state the compression type isn't
exactly ideal, but I guess it'll do me for now.

Unfortunately, I'm still having trouble actually reading the contents of
'archive_member'.
i.e. ..
>>>tf_filelike=tf.extractfile(archive_member_name)
>>>print tf_filelike.read()
..raises..
File "C:\Python24\lib\tarfile.py", line 551, in _readnormal
    self.fileobj.seek(self.offset + self.pos)
File "C:\Python24\lib\tarfile.py", line 420, in seek
    raise StreamError, "seeking backwards is not allowed"

And I get the same error if I instead try..
>>>tf_infoobject=tf.getmember(archive_member_name)
>>>tf_filelike=tf.extractfile(tf_infoobject)
>>>print tf_filelike.read()

In fact I'm getting this even if I open the archive by passing the path
name (rather than using fileobj) so I guess this isn't the problem I
initially thought it was. I just don't get it.

Regards,
Dave

-----Original Message-----
From: Kent Johnson [mailto:kent37 at tds.net] 
Sent: 03 March 2007 22:26
To: Barton David
Cc: tutor at python.org
Subject: Re: [Tutor] using tarfile on strings or filelike objects

Barton David wrote:
> I like that I can access the contents of a zip archive that's stored 
> in memory (rather than on disk) by packing the archive contents into a

> StringIO or cStringIO object and feeding that to ZipFile...
>  
> i.e.
>  
> filelike=cStringIO.StringIO(archive_as_string)
> zf=zipfile.ZipFile(filelike)
> content=zf.read(archive_member_name)
> zf.close()
> filelike.close()
>  
> but I can't get the same thing to work with TarFile. Is there any way 
> to do this? (Other than first saving the archive data to disk and then

> passing the path to TarFile.open?) The tarfile module documentation 
> talks about an optional fileobj flag but this doesn't seem to work.

Just from reading the docs I would try
filelike = cStringIO...
tf = tarfile.open(mode='r|', fileobj=filelike)

This is based on the example in the docs of reading from stdin.

Kent


This message has been checked for viruses but the contents of an attachment
may still contain software viruses, which could damage your computer system:
you are advised to perform your own checks. Email communications with the
University of Nottingham may be monitored as permitted by UK legislation.


From vasile.filat at gmail.com  Mon Mar  5 06:25:50 2007
From: vasile.filat at gmail.com (Vasile Filat)
Date: Mon, 5 Mar 2007 08:25:50 +0300
Subject: [Tutor] help me to do my exercise
Message-ID: <66372466.20070305082550@gmail.com>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070305/8fd26317/attachment.htm 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: image/jpeg
Size: 173763 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20070305/8fd26317/attachment-0001.jpe 

From kent37 at tds.net  Mon Mar  5 13:44:10 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 05 Mar 2007 07:44:10 -0500
Subject: [Tutor] using tarfile on strings or filelike objects
In-Reply-To: <BAA2EE790D828F4E8B262F17B3B0A7A30363D386@VUIEXCH1.ad.nottingham.ac.uk>
References: <BAA2EE790D828F4E8B262F17B3B0A7A30363D386@VUIEXCH1.ad.nottingham.ac.uk>
Message-ID: <45EC109A.7070004@tds.net>

Barton David wrote:
> Thanks Kent,
> 
> But.. I've actually found that that doesn't work (raises a ReadError),
> and neither does..
>>>> tf=tarfile.open(mode="r|*",fileobj=filelike)
> ..which raises "AttributeError: _Stream instance has no attribute
> 'dbuf'"
> 
> However if I explicitly state the compression type.. e.g.
>>>> tf=tarfile.open(mode="r|bz2",fileobj=filelike)
> ..then I can indeed go on to..
>>>> print tf.getnames()
>>>> assert archive_member_name in tf.getnames()
> ..and it works ok. Having to explicitly state the compression type isn't
> exactly ideal, but I guess it'll do me for now.
> 
> Unfortunately, I'm still having trouble actually reading the contents of
> 'archive_member'.
> i.e. ..
>>>> tf_filelike=tf.extractfile(archive_member_name)
>>>> print tf_filelike.read()
> ..raises..
> File "C:\Python24\lib\tarfile.py", line 551, in _readnormal
>     self.fileobj.seek(self.offset + self.pos)
> File "C:\Python24\lib\tarfile.py", line 420, in seek
>     raise StreamError, "seeking backwards is not allowed"

The docs for the | options say that seeking won't work with them. Maybe 
try just 'r'? A hacky workaround might be to open the file once to get 
the names out and a second time to read the data. Since the file is in 
memory that should be pretty quick.
> 
> And I get the same error if I instead try..
>>>> tf_infoobject=tf.getmember(archive_member_name)
>>>> tf_filelike=tf.extractfile(tf_infoobject)
>>>> print tf_filelike.read()
> 
> In fact I'm getting this even if I open the archive by passing the path
> name (rather than using fileobj) so I guess this isn't the problem I
> initially thought it was. I just don't get it.

What if you try exactly the code shown in the tarfile examples for 
reading from stdin, with your StringIO file substituted for stdin?

You might want to ask about this on comp.lang.python as no one here 
seems to know the answer. This thread is slightly related:
http://tinyurl.com/2hrffs

Kent

> 
> Regards,
> Dave

From rikard.bosnjakovic at gmail.com  Mon Mar  5 14:02:07 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Mon, 5 Mar 2007 14:02:07 +0100
Subject: [Tutor] help me to do my exercise
In-Reply-To: <66372466.20070305082550@gmail.com>
References: <66372466.20070305082550@gmail.com>
Message-ID: <d9e88eaf0703050502s69d4c0ebyedef10e0550354ad@mail.gmail.com>

On 3/5/07, Vasile Filat <vasile.filat at gmail.com> wrote:

> I just started learning Python from a book translated intro Russian. It is my first exercise from the book and I don't know why it is not working. Help me please to correct my code which I will include below.

You need to tell us why it's not working. Do you get any error
messages? Unexpected output? Loops never exiting?


-- 
- Rikard.

From David.Barton at nottingham.ac.uk  Mon Mar  5 15:06:28 2007
From: David.Barton at nottingham.ac.uk (Barton David)
Date: Mon, 5 Mar 2007 14:06:28 -0000
Subject: [Tutor] using tarfile on strings or filelike objects
Message-ID: <BAA2EE790D828F4E8B262F17B3B0A7A30363D6F1@VUIEXCH1.ad.nottingham.ac.uk>

Thanks Kent,

I think I've hacked my way around this but it's a little weird.
Simplest to demonstrate with code (assuming cStringIO and tarfile are
imported and my_tarfile_string & archive_member_name are specified):
__

#approach 1
filelike=cStringIO.StringIO(my_tarfile_string)
tar = tarfile.open(mode="r|bz2", fileobj=filelike)

for tarinfo in tar:
	if tarinfo.name==archive_member_name:
		tfl=tar.extractfile(tarinfo)
		print tfl.read()
		tfl.close()

tar.close()
filelike.close()

#This works. Hooray.
#However, if mode=="r" the following error occurs: "AttributeError:
'NoneType' object has no attribute 'rfind'"
#and if mode=="r|" the following error occurs: "ReadError: empty,
unreadable or compressed file"
#and if mode=="r|*" the following error occurs: "AttributeError: _Stream
instance has no attribute 'dbuf'"
#I only understand the second of those error messages, to be honest.

#approach 2
filelike=cStringIO.StringIO(my_tarfile_string)
tar = tarfile.open(mode="r|bz2", fileobj=filelike)

tfl=tar.extractfile(archive_member_name)
print tfl.read()
tfl.close()

tar.close()
filelike.close()

#approach 3
filelike=cStringIO.StringIO(my_tarfile_string)
tar = tarfile.open(mode="r|bz2", fileobj=filelike)

tarinfo=tar.getmember(archive_member_name)
tfl=tar.extractfile(tarinfo)
print tfl.read()
tfl.close()

tar.close()
filelike.close()

#These DON'T work, and produce the following error: "StreamError:
seeking backwards is not allowed"
#Maybe this is just some wacky bug?


__
At any rate, in the 'slightly related' thread you linked to, the
statement that..
>"bzip2 compressed files cannot be read from a "fake" (StringIO) file
object, only from real files"
..doesn't seem to be the case after all, so that's something. 

Regards
Dave

P.S. I'm very sorry but whenever I post replies to Tutor (I'm using
Outlook and hitting Reply All in response to a tutor's direct reply) it
doesn't seem to add my message to the bottom of the existing thread. If
somebody can tell me what I'm doing wrong, I'd appreciate it.



-----Original Message-----
From: Kent Johnson [mailto:kent37 at tds.net] 
Sent: 05 March 2007 12:44
To: Barton David
Cc: tutor at python.org
Subject: Re: [Tutor] using tarfile on strings or filelike objects

Barton David wrote:
> Thanks Kent,
> 
> But.. I've actually found that that doesn't work (raises a ReadError),

> and neither does..
>>>> tf=tarfile.open(mode="r|*",fileobj=filelike)
> ..which raises "AttributeError: _Stream instance has no attribute 
> 'dbuf'"
> 
> However if I explicitly state the compression type.. e.g.
>>>> tf=tarfile.open(mode="r|bz2",fileobj=filelike)
> ..then I can indeed go on to..
>>>> print tf.getnames()
>>>> assert archive_member_name in tf.getnames()
> ..and it works ok. Having to explicitly state the compression type 
> isn't exactly ideal, but I guess it'll do me for now.
> 
> Unfortunately, I'm still having trouble actually reading the contents 
> of 'archive_member'.
> i.e. ..
>>>> tf_filelike=tf.extractfile(archive_member_name)
>>>> print tf_filelike.read()
> ..raises..
> File "C:\Python24\lib\tarfile.py", line 551, in _readnormal
>     self.fileobj.seek(self.offset + self.pos) File 
> "C:\Python24\lib\tarfile.py", line 420, in seek
>     raise StreamError, "seeking backwards is not allowed"

The docs for the | options say that seeking won't work with them. Maybe
try just 'r'? A hacky workaround might be to open the file once to get
the names out and a second time to read the data. Since the file is in
memory that should be pretty quick.
> 
> And I get the same error if I instead try..
>>>> tf_infoobject=tf.getmember(archive_member_name)
>>>> tf_filelike=tf.extractfile(tf_infoobject)
>>>> print tf_filelike.read()
> 
> In fact I'm getting this even if I open the archive by passing the 
> path name (rather than using fileobj) so I guess this isn't the 
> problem I initially thought it was. I just don't get it.

What if you try exactly the code shown in the tarfile examples for
reading from stdin, with your StringIO file substituted for stdin?

You might want to ask about this on comp.lang.python as no one here
seems to know the answer. This thread is slightly related:
http://tinyurl.com/2hrffs

Kent

> 
> Regards,
> Dave

This message has been checked for viruses but the contents of an attachment
may still contain software viruses, which could damage your computer system:
you are advised to perform your own checks. Email communications with the
University of Nottingham may be monitored as permitted by UK legislation.


From chris.arndt at web.de  Mon Mar  5 15:09:54 2007
From: chris.arndt at web.de (Christopher Arndt)
Date: Mon, 05 Mar 2007 15:09:54 +0100
Subject: [Tutor] help me to do my exercise
In-Reply-To: <66372466.20070305082550@gmail.com>
References: <66372466.20070305082550@gmail.com>
Message-ID: <45EC24B2.1090909@web.de>

Vasile Filat schrieb:
> Help me please to correct my code which I will include below.

It is customary to include code examples either inline in your message or
attach them as a plain text source code file. Some mailing list frown on
attachments in general (but this one doesn't, to my knowledge), but binary
attachments, like the image you sent, should be avoided. If you want to show us
longer code examples, use a pasting bin [1]

One reason why it's not a good idea to show us your code as a screenshot from
your editor is that we have to type it up again, if we want to refer to it in
our replies. Would you want to make this (unnecessary) effort?

Chris


[1] http://en.wikipedia.org/wiki/Pastebin

From ebbaalm at uiuc.edu  Mon Mar  5 15:37:21 2007
From: ebbaalm at uiuc.edu (Cecilia Alm)
Date: Mon, 5 Mar 2007 08:37:21 -0600
Subject: [Tutor] Fwd:  executing a string representing python code
In-Reply-To: <7a4620dc0703050636q35123a5ao44cf5b0d49b927b3@mail.gmail.com>
References: <7a4620dc0703020632q615c53b6me8a187685406dbbd@mail.gmail.com>
	<f989e6210703050015g3cca2364l991d87ec028b58e4@mail.gmail.com>
	<7a4620dc0703050636q35123a5ao44cf5b0d49b927b3@mail.gmail.com>
Message-ID: <7a4620dc0703050637r254fcbb7t9e2520c5a901b4bd@mail.gmail.com>

Thanks, Adam. I guess the exec would be exec("some_func").
The result seems pretty similar to eval(), allthough eval() seems more
straight-forward if the aim is to assign the returned value ("Done") to a
variable.

>>> eval('some_func("wasn\'t that cool")')
Hello World wasn't that cool
'Done'

in other words

>>> s = eval('some_func("wasn\'t that cool")')
Hello World wasn't that cool
>>> s
'Done'


2007/3/5, Adam Pridgen <atpridgen at mail.utexas.edu>:
>
> here's the magic you are looking for:
>
> func_str = \
> '''
> def some_func(value):
> # youwould check value instance here and do something to it
>     print "Hello World", value
>     return "Done"
> '''
> exec(func_str)
> f = locals()["some_func"]
> print f("wasn't that cool!")
>
> When you exec the str, it will create a function object, and then you
> can obtain the object by accessing the object by kwd in the locals()
> dictionary.  Guess it's not really magic, but I think it is still
> pretty cool ;)  There also several variations to this method, but this
> is the most readable IMHO.
>
> Cheers,
>
> Adam
>
>
> On 3/2/07, Cecilia Alm < flickita at gmail.com> wrote:
> > I know that there are several ways to execute a string which represents
> a
> > piece of python code.
> >  Out of curiosity, is it only eval which returns a value? (as below,
> where
> > the string corresponds to a defined function).
> >
> >  >>> def addone(val):
> >  ...     return val + 1
> >  ...
> >  >>> res = eval('addone(10)')
> >
> > Thanks!
> >
> >
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
>



-- 
E. Cecilia Alm
Graduate student, Dept. of Linguistics, UIUC
Office: 2013 Beckman Institute

-- 
E. Cecilia Alm
Graduate student, Dept. of Linguistics, UIUC
Office: 2013 Beckman Institute
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070305/a6b984ec/attachment.htm 

From learner404 at gmail.com  Mon Mar  5 16:51:42 2007
From: learner404 at gmail.com (learner404)
Date: Mon, 5 Mar 2007 16:51:42 +0100
Subject: [Tutor] Hiding/Killing a DOS window (from a previous os.system call)
Message-ID: <13a83ca10703050751k17310476x506b163e66ea2e3c@mail.gmail.com>

Hello,

I'm launching an external app through an os.system() or os.popen() but I
don't want the resulting DOS window to hang-on there forever (my python
script is launched with pythonw):
I use a sys.exit() to kill the script who launched the external
app.Thepython script is killed, the app is launched, but the resulting
DOS window
is still there (I have the same result if I use the DOS tskill or taskkill
command to kill the script with his PID).

How could I hide/kill the resulting DOS window  from an os.sytem /
os.popenwith Python ?

Also is there a way to launch an external app. but without os.system and
os.popen to wait there but immediately continue to the next python line (to
avoid this I'm using a thread for now).

As an example I'm using this so far.
If I use pythonw to launch the script, notepad is launched, the script is
killed but the DOS window stay there.

####

import os,sys,time
from thread import start_new_thread

def launchApp():
    os.system("notepad.exe")

try:
    start_new_thread(launchApp,())
except:
    print "Something went wrong => do somenthing"

time.sleep(2)

print "And now going out"
sys.exit()

----

Thanks
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070305/e9edbdf7/attachment.html 

From eric at ericwalstad.com  Mon Mar  5 17:39:26 2007
From: eric at ericwalstad.com (Eric Walstad)
Date: Mon, 5 Mar 2007 08:39:26 -0800
Subject: [Tutor] help me to do my exercise
In-Reply-To: <66372466.20070305082550@gmail.com>
References: <66372466.20070305082550@gmail.com>
Message-ID: <200703050839.26442.eric@ericwalstad.com>

In addition to what the others have said, you have a syntax error on line 7 of 
your leap.py file.  The 'for' loop will want an iterable to loop over.  The 
syntax error relates to the list you are trying to use, a slice of sys.argv.  
Remember, lists are denoted by square brackets '[' and ']'.

<http://diveintopython.org/native_data_types/lists.html>

From alan.gauld at btinternet.com  Mon Mar  5 18:14:28 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 5 Mar 2007 17:14:28 -0000
Subject: [Tutor] executing a string representing python code
References: <7a4620dc0703020632q615c53b6me8a187685406dbbd@mail.gmail.com><f989e6210703050015g3cca2364l991d87ec028b58e4@mail.gmail.com><7a4620dc0703050636q35123a5ao44cf5b0d49b927b3@mail.gmail.com>
	<7a4620dc0703050637r254fcbb7t9e2520c5a901b4bd@mail.gmail.com>
Message-ID: <eshj1t$g1s$1@sea.gmane.org>

"Cecilia Alm" <ebbaalm at uiuc.edu> wrote

> Thanks, Adam. I guess the exec would be exec("some_func").
> The result seems pretty similar to eval(), allthough eval() seems 
> more
> straight-forward if the aim is to assign the returned value ("Done") 
> to a
> variable.

>>>> s = eval('some_func("wasn\'t that cool")')
> Hello World wasn't that cool
>>>> s
> 'Done'

You should be able to just do:

>>> s = some_func("wasn't that cool")

The whole point of the exec is that the function now exists in
your local namespace. You can execute it as any other function.

>> func_str = \
>> '''
>> def some_func(value):
>> # youwould check value instance here and do something to it
>>     print "Hello World", value
>>     return "Done"
>> '''
>> exec(func_str)

This creates the function

>> f = locals()["some_func"]
>> print f("wasn't that cool!")

There should be no need for this trickery.

HTH,

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



From alan.gauld at btinternet.com  Mon Mar  5 18:24:17 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 5 Mar 2007 17:24:17 -0000
Subject: [Tutor] help me to do my exercise
References: <66372466.20070305082550@gmail.com>
Message-ID: <eshjka$igv$1@sea.gmane.org>

"Vasile Filat" <vasile.filat at gmail.com> wrote

> I just started learning Python from a book translated intro
> Russian. It is my first exercise from the book and I don't
> know why it is not working.

OK, First please send the code as text rather than as an image.
It makes it much easier to comment when we can cut n paste
sections into email.

Secondly please send along any error messages.

OK, Now looking at you code. Thee are several syntax errors
which python should be complaining about. The first I see is:

>  for i in sys.argvj 1:]:

I suspect the j should be a [

Next you have no indentation after the except:

also you have a colon after the continue plus a block of code.
continue just makes the loop go round again...

Next your test for y*100 == 0 will only pass if y is zero!

You only print the Gregorian result if y % 4 is zero, but
not if y%400 is zero...


That should be enough to keep you busy.
Please post text next time.

HTH,

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

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


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



From alan.gauld at btinternet.com  Mon Mar  5 18:38:46 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 5 Mar 2007 17:38:46 -0000
Subject: [Tutor] Hiding/Killing a DOS window (from a previous os.system
	call)
References: <13a83ca10703050751k17310476x506b163e66ea2e3c@mail.gmail.com>
Message-ID: <eshkfg$m45$1@sea.gmane.org>


"learner404" <learner404 at gmail.com> wrote

> I'm launching an external app through an os.system() or os.popen() 
> but I
> don't want the resulting DOS window to hang-on there forever

Try using os.spawnl() instead:

>>> pid = os.spawnl(os.P_NOWAIT,r'C:\Windows\System32\notepad.exe')
>>> print pid
2834

The P_NOWAIT makes it return immediately, and no DOS box
is created.

Note that the spawn family of processes are deprecated and the
subprocess module provides equivalent functionality.

Using subprocess it looks like:

>>> pid = Popen([r'C:\Windows\System32\notepad.exe', ""]).pid

HTH,

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



From learner404 at gmail.com  Mon Mar  5 19:16:10 2007
From: learner404 at gmail.com (learner404)
Date: Mon, 5 Mar 2007 19:16:10 +0100
Subject: [Tutor] Hiding/Killing a DOS window (from a previous os.system
	call)
In-Reply-To: <eshkfg$m45$1@sea.gmane.org>
References: <13a83ca10703050751k17310476x506b163e66ea2e3c@mail.gmail.com>
	<eshkfg$m45$1@sea.gmane.org>
Message-ID: <13a83ca10703051016q5600fedbl5c3af6646faf0359@mail.gmail.com>

Thanks a lot Alan !  both solutions work like a charm :)


On 3/5/07, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
>
> "learner404" <learner404 at gmail.com> wrote
>
> > I'm launching an external app through an os.system() or os.popen()
> > but I
> > don't want the resulting DOS window to hang-on there forever
>
> Try using os.spawnl() instead:
>
> >>> pid = os.spawnl(os.P_NOWAIT,r'C:\Windows\System32\notepad.exe')
> >>> print pid
> 2834
>
> The P_NOWAIT makes it return immediately, and no DOS box
> is created.
>
> Note that the spawn family of processes are deprecated and the
> subprocess module provides equivalent functionality.
>
> Using subprocess it looks like:
>
> >>> pid = Popen([r'C:\Windows\System32\notepad.exe', ""]).pid
>
> HTH,
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070305/f796df14/attachment.html 

From ebbaalm at uiuc.edu  Mon Mar  5 19:21:30 2007
From: ebbaalm at uiuc.edu (Cecilia Alm)
Date: Mon, 5 Mar 2007 12:21:30 -0600
Subject: [Tutor] executing a string representing python code
In-Reply-To: <eshj1t$g1s$1@sea.gmane.org>
References: <7a4620dc0703020632q615c53b6me8a187685406dbbd@mail.gmail.com>
	<f989e6210703050015g3cca2364l991d87ec028b58e4@mail.gmail.com>
	<7a4620dc0703050636q35123a5ao44cf5b0d49b927b3@mail.gmail.com>
	<7a4620dc0703050637r254fcbb7t9e2520c5a901b4bd@mail.gmail.com>
	<eshj1t$g1s$1@sea.gmane.org>
Message-ID: <7a4620dc0703051021m6afc701es45c00deedd250389@mail.gmail.com>

That's neat. When just the function call is the string, eval() seems
appropriate. (For example, if reading what function to call from a file.)

>>> def some_func(val):
    return val

>>> s = eval('some_func("that\'s also pretty cool")')
>>> s
"that's also pretty cool"

At any rate, thanks for the responses,
Cecilia



> You should be able to just do:
>
> >>> s = some_func("wasn't that cool")
>
> The whole point of the exec is that the function now exists in
> your local namespace. You can execute it as any other function.
>
> >> func_str = \
> >> '''
> >> def some_func(value):
> >> # youwould check value instance here and do something to it
> >>     print "Hello World", value
> >>     return "Done"
> >> '''
> >> exec(func_str)
>
> This creates the function
>
> >> f = locals()["some_func"]
> >> print f("wasn't that cool!")
>
> There should be no need for this trickery.
>
> HTH,
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
E. Cecilia Alm
Graduate student, Dept. of Linguistics, UIUC
Office: 2013 Beckman Institute
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070305/8f972d00/attachment.htm 

From cappy2112 at gmail.com  Mon Mar  5 20:43:01 2007
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Mon, 5 Mar 2007 11:43:01 -0800
Subject: [Tutor] Tutor Digest, Vol 37, Issue 15
In-Reply-To: <mailman.14878.1173112759.32030.tutor@python.org>
References: <mailman.14878.1173112759.32030.tutor@python.org>
Message-ID: <8249c4ac0703051143t13c0ccabi4858b779f2c37de4@mail.gmail.com>

Rename your file from .py to .pyw.
This will prevent the DOS window from appearing

Message: 6
Date: Mon, 5 Mar 2007 16:51:42 +0100
From: learner404 <learner404 at gmail.com>
Subject: [Tutor] Hiding/Killing a DOS window (from a previous
       os.system call)
To: "Tutor Python" <tutor at python.org>
Message-ID:
       <13a83ca10703050751k17310476x506b163e66ea2e3c at mail.gmail.com>
Content-Type: text/plain; charset="iso-8859-1"

Hello,

I'm launching an external app through an os.system() or os.popen() but I
don't want the resulting DOS window to hang-on there forever (my python
script is launched with pythonw):
I use a sys.exit() to kill the script who launched the external
app.Thepython script is killed, the app is launched, but the resulting
DOS window
is still there (I have the same result if I use the DOS tskill or taskkill
command to kill the script with his PID).

How could I hide/kill the resulting DOS window  from an os.sytem /
os.popenwith Python ?

Also is there a way to launch an external app. but without os.system and
os.popen to wait there but immediately continue to the next python line (to
avoid this I'm using a thread for now).

As an example I'm using this so far.
If I use pythonw to launch the script, notepad is launched, the script is
killed but the DOS window stay there.

From alan.gauld at btinternet.com  Mon Mar  5 21:01:24 2007
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Mon, 5 Mar 2007 20:01:24 +0000 (GMT)
Subject: [Tutor] executing a string representing python code
Message-ID: <123193.22132.qm@web86110.mail.ird.yahoo.com>

> That's neat. When just the function call is the string, 
> eval() seems appropriate. (For example, if reading what 
> function to call from a file.)

Its conventient but incredibly dangerous.
Its much better in that case to create a dictionary of allowed
(ie safe!) functions that can vbe read and then look that up 
from the file input.

Otherwise anyone who can access the file (legitimately or 
otherwise) can start calling any of the standard Python functions, 
including os.unlink() to delete files, or even os.system(), to do 
just about anything - howsabout formatting your disk?

ok_funks = {
      'some_func' : some_func,
      'another_func': another_func,
      'some_fancy_name': sys.exit
}

func = raw_input('type a function name>')
try: ok_funks[func']()
except: print 'Thats not a valid function'

eval and exec are seductively powerful but they are immensely 
dangerous in a world of crackers and virus makers. They should 
only ever be used in strictly controlled scebnarios and even then 
as a last resort.

HTH,

Alan G.





		
___________________________________________________________ 
What kind of emailer are you? Find out today - get a free analysis of your email personality. Take the quiz at the Yahoo! Mail Championship. 
http://uk.rd.yahoo.com/evt=44106/*http://mail.yahoo.net/uk 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070305/dc22ba96/attachment.html 

From learner404 at gmail.com  Mon Mar  5 21:07:36 2007
From: learner404 at gmail.com (learner404)
Date: Mon, 5 Mar 2007 21:07:36 +0100
Subject: [Tutor] Tutor Digest, Vol 37, Issue 15
In-Reply-To: <8249c4ac0703051143t13c0ccabi4858b779f2c37de4@mail.gmail.com>
References: <mailman.14878.1173112759.32030.tutor@python.org>
	<8249c4ac0703051143t13c0ccabi4858b779f2c37de4@mail.gmail.com>
Message-ID: <13a83ca10703051207v6e53e4b5uecb6e0a7536559b1@mail.gmail.com>

On 3/5/07, Tony Cappellini <cappy2112 at gmail.com> wrote:
>
> Rename your file from .py to .pyw.
> This will prevent the DOS window from appearing


It's not the DOS window from the Python script I was talking about  (in my
mail I said "my python
script is launched with pythonw") but the one resulting from the os.systemor
os.popen commands.

The two solutions that Alan gave are perfect for these :)

Message: 6
> Date: Mon, 5 Mar 2007 16:51:42 +0100
> From: learner404 <learner404 at gmail.com>
> Subject: [Tutor] Hiding/Killing a DOS window (from a previous
>        os.system call)
> To: "Tutor Python" <tutor at python.org>
> Message-ID:
>        <13a83ca10703050751k17310476x506b163e66ea2e3c at mail.gmail.com>
> Content-Type: text/plain; charset="iso-8859-1"
>
> Hello,
>
> I'm launching an external app through an os.system() or os.popen() but I
> don't want the resulting DOS window to hang-on there forever (my python
> script is launched with pythonw):
> I use a sys.exit() to kill the script who launched the external
> app.Thepython script is killed, the app is launched, but the resulting
> DOS window
> is still there (I have the same result if I use the DOS tskill or taskkill
> command to kill the script with his PID).
>
> How could I hide/kill the resulting DOS window  from an os.sytem /
> os.popenwith Python ?
>
> Also is there a way to launch an external app. but without os.system and
> os.popen to wait there but immediately continue to the next python line
> (to
> avoid this I'm using a thread for now).
>
> As an example I'm using this so far.
> If I use pythonw to launch the script, notepad is launched, the script is
> killed but the DOS window stay there.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070305/6755cc6c/attachment-0001.htm 

From zannah.m at gmail.com  Tue Mar  6 00:04:24 2007
From: zannah.m at gmail.com (zannah marsh)
Date: Mon, 5 Mar 2007 18:04:24 -0500
Subject: [Tutor] trouble with function-- trying to check differences btwn 2
	strings
Message-ID: <c19e69be0703051504t3088e2fche73c80a1b8735b37@mail.gmail.com>

I am very new to Python (I've been learning it for about 2 weeks, in a
class). I wrote this function ( as part of a larger program, for my
homework) which is supposed to step through two given strings and check for
differences between the strings. It returns a list of the indices at which
the characters are different. Here it is:

def getDiff(word1,word2):
    #this function takes two words and returns a list containing the index
of each point of difference in the words
    difList = [] #creates empty list to hold index (location) of differences
in words
    index = 0 #sets variable index to 0 to start
    for item in word1: #steps throug string
        if item == item in word2: #checks characters against each other
            print "there is a match at index ", index
            print word1[index]
            print word2[index]
            index += 1 #increments index

        else:
            print "they are not the same at index ", index
            print word1[index]
            print word2[index]
            difList.append(index) #adds index value to list
            index += 1 # increments index
    return difList

It works, but only sometimes-- in some cases, it evaluates letters that are
different as being the same. Seems to be happening after a run of a few
matching letters? It also works for "carpet" "carrot", but not for "carrot"
"carpet". I think it must be something wrong with the structure of the
loop-- or how i am using it-- but I can't see it. Does anyone have any
suggestions? Here is output from some sample runs:

>>> getDiff("desk","foot") # works fine
they are not the same at index  0
d
f
they are not the same at index  1
e
o
they are not the same at index  2
s
o
they are not the same at index  3
k
t
[0, 1, 2, 3]
>>> getDiff("beep","bees") # works fine
there is a match at index  0
b
b
there is a match at index  1
e
e
there is a match at index  2
e
e
they are not the same at index  3
p
s
[3]
>>> getDiff("freeze","fresia")  # this one did not work!
there is a match at index  0
f
f
there is a match at index  1
r
r
there is a match at index  2
e
e
there is a match at index  3
e
s
they are not the same at index  4
z
i
there is a match at index  5
e
a
[4]
>>> getDiff("carrot","carpet") # this one did not work!
there is a match at index  0
c
c
there is a match at index  1
a
a
there is a match at index  2
r
r
there is a match at index  3
r
p
they are not the same at index  4
o
e
there is a match at index  5
t
t
[4]
>>> getDiff("carpet","carrot") #but this does work (inverted order from
above)
there is a match at index  0
c
c
there is a match at index  1
a
a
there is a match at index  2
r
r
they are not the same at index  3
p
r
they are not the same at index  4
e
o
there is a match at index  5
t
t
[3, 4]
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070305/9b629546/attachment.html 

From rikard.bosnjakovic at gmail.com  Tue Mar  6 00:13:59 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Tue, 6 Mar 2007 00:13:59 +0100
Subject: [Tutor] trouble with function-- trying to check differences
	btwn 2 strings
In-Reply-To: <c19e69be0703051504t3088e2fche73c80a1b8735b37@mail.gmail.com>
References: <c19e69be0703051504t3088e2fche73c80a1b8735b37@mail.gmail.com>
Message-ID: <d9e88eaf0703051513waec605cr77659f208409c550@mail.gmail.com>

On 3/6/07, zannah marsh <zannah.m at gmail.com> wrote:

>         if item == item in word2: #checks characters against each other

Here's the error.

Loop variable "item" contains the actual character in word1. The
syntax "item in word2" checks if this character is _anywhere_ in
word2. What you want to do is rewriting this loop so it checks
character per character. Since it's for homework, I don't want to ruin
your grades by giving you a solution. Try it yourself first.

To see what I mean, try running getDiff("abcd", "dcba").


-- 
- Rikard.

From rikard.bosnjakovic at gmail.com  Tue Mar  6 00:27:23 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Tue, 6 Mar 2007 00:27:23 +0100
Subject: [Tutor] trouble with function-- trying to check differences
	btwn 2 strings
In-Reply-To: <c19e69be0703051524k7477dcfbp232f1bf0abcfe05f@mail.gmail.com>
References: <c19e69be0703051504t3088e2fche73c80a1b8735b37@mail.gmail.com>
	<d9e88eaf0703051513waec605cr77659f208409c550@mail.gmail.com>
	<c19e69be0703051524k7477dcfbp232f1bf0abcfe05f@mail.gmail.com>
Message-ID: <d9e88eaf0703051527p46a52ce1ma645686da611d2b8@mail.gmail.com>

On 3/6/07, zannah marsh <zannah.m at gmail.com> wrote:
> thanks Rikard, that makes sense.

No problems, but please post answers to the list and not to my mail adress.

This list is braindead that doesn't use a reply-to-tag for the posts,
but we've had that debate already so there's no need for another.


-- 
- Rikard.

From rikard.bosnjakovic at gmail.com  Tue Mar  6 00:41:23 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Tue, 6 Mar 2007 00:41:23 +0100
Subject: [Tutor] trouble with function-- trying to check differences
	btwn 2 strings
In-Reply-To: <c19e69be0703051538s7d660a89k618b3cff1cba1467@mail.gmail.com>
References: <c19e69be0703051504t3088e2fche73c80a1b8735b37@mail.gmail.com>
	<d9e88eaf0703051513waec605cr77659f208409c550@mail.gmail.com>
	<c19e69be0703051524k7477dcfbp232f1bf0abcfe05f@mail.gmail.com>
	<c19e69be0703051538s7d660a89k618b3cff1cba1467@mail.gmail.com>
Message-ID: <d9e88eaf0703051541h71abbb29u6e1bed61f2b07b25@mail.gmail.com>

On 3/6/07, zannah marsh <zannah.m at gmail.com> wrote:

> step through them as you would in an array or list. so i had this:
>  for i in word1
>      if word1[i] == word2[i]...

For this construction to work in Python, you use the range()-function.

for index in range(len(word1)):
    ....

Say word1 is "parrot", len(word1) == 6, range(len(word1)) = 0,1,2,3,4,5.


-- 
- Rikard.

From ashokn at luma-pictures.com  Tue Mar  6 02:02:33 2007
From: ashokn at luma-pictures.com (Ashok Nayar)
Date: Mon, 5 Mar 2007 17:02:33 -0800
Subject: [Tutor] Quicktime in python
Message-ID: <C934AEF2-551D-40D2-9B29-8E6E7E4DB2DB@luma-pictures.com>

I need a little help. I'm trying to learn how to manipulate  
Quicktimes through python. I want to be able to set up a grid of   
quicktime movies and be able to resize them all to a consistent width  
and height so it's all neat and tidy. I have found very little  
documentation regarding quicktime modules for python. Can anyone help  
me out?

Thanks! 

From alan.gauld at btinternet.com  Tue Mar  6 05:41:12 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 6 Mar 2007 04:41:12 -0000
Subject: [Tutor] Quicktime in python
References: <C934AEF2-551D-40D2-9B29-8E6E7E4DB2DB@luma-pictures.com>
Message-ID: <esir9h$f2q$1@sea.gmane.org>


"Ashok Nayar" <ashokn at luma-pictures.com> wrote 

>I need a little help. I'm trying to learn how to manipulate  
> Quicktimes through python. 

Are you on a Mac? If so MacPyhon includes bindings 
for manipulating QT media. They are pretty low level
and I've never used them so I can't tell you much more 
than that.

If you are not on a Mac then I don't know whats available...

Alan g.



From deliberatus at verizon.net  Tue Mar  6 06:50:39 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Tue, 06 Mar 2007 00:50:39 -0500
Subject: [Tutor] installers and more
Message-ID: <45ED012F.2060100@verizon.net>

1. Installers. Apps which are hard to install do not get installed. 
MiniWiki is now fit for public display and use, but it still takes the 
geek nature to install it. I need to become expert with one of the free 
installers to turn it into something a business executive would be 
willing to download and fire off as an isntaller.

2. It takes python being in the laptop so it can be used. As I do not 
own it, I hesitate to bundle it in. What's the legal aspect of providing 
the language the app needs so it will run?


-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From kent37 at tds.net  Tue Mar  6 09:06:59 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 06 Mar 2007 03:06:59 -0500
Subject: [Tutor] installers and more
In-Reply-To: <45ED012F.2060100@verizon.net>
References: <45ED012F.2060100@verizon.net>
Message-ID: <45ED2123.9090306@tds.net>

Kirk Bailey wrote:
> 2. It takes python being in the laptop so it can be used. As I do not 
> own it, I hesitate to bundle it in. What's the legal aspect of providing 
> the language the app needs so it will run?

This is not a problem, you can distribute a package that includes Python.
http://www.python.org/psf/license/

Kent

From dperlman at wisc.edu  Tue Mar  6 14:21:59 2007
From: dperlman at wisc.edu (David Perlman)
Date: Tue, 06 Mar 2007 07:21:59 -0600
Subject: [Tutor] trouble with function-- trying to check
 differences	btwn 2 strings
In-Reply-To: <d9e88eaf0703051513waec605cr77659f208409c550@mail.gmail.com>
References: <c19e69be0703051504t3088e2fche73c80a1b8735b37@mail.gmail.com>
	<d9e88eaf0703051513waec605cr77659f208409c550@mail.gmail.com>
Message-ID: <5139B26D-F189-4A62-90FE-012E779BEB62@wisc.edu>

OK, I'm new to python too so I don't assume I know what I'm talking  
about yet, but this looks like a mess to me.  What exactly does "item  
== item in word2" evaluate to?  Does "in" or "==" have higher  
precedence?

I can't figure out how this would ever work at all.  It seems like  
it's either checking to see whether boolean TRUE is in word2, or else  
it's checking to see whether item is equal to boolean TRUE or FALSE,  
and neither of those should ever be true.  And yet it seems to be  
working out the same as "item in word2".  So what exactly is python  
doing here?

On Mar 5, 2007, at 5:13 PM, Rikard Bosnjakovic wrote:

> On 3/6/07, zannah marsh <zannah.m at gmail.com> wrote:
>
>>         if item == item in word2: #checks characters against each  
>> other
>
> Here's the error.
>
> Loop variable "item" contains the actual character in word1. The
> syntax "item in word2" checks if this character is _anywhere_ in
> word2. What you want to do is rewriting this loop so it checks
> character per character. Since it's for homework, I don't want to ruin
> your grades by giving you a solution. Try it yourself first.
>
> To see what I mean, try running getDiff("abcd", "dcba").
>
>
> -- 
> - Rikard.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

--
-dave----------------------------------------------------------------
After all, it is not *that* inexpressible.
-H.H. The Dalai Lama




From rabidpoobear at gmail.com  Tue Mar  6 15:18:42 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Tue, 06 Mar 2007 08:18:42 -0600
Subject: [Tutor] trouble with function-- trying to check
 differences	btwn 2 strings
In-Reply-To: <5139B26D-F189-4A62-90FE-012E779BEB62@wisc.edu>
References: <c19e69be0703051504t3088e2fche73c80a1b8735b37@mail.gmail.com>	<d9e88eaf0703051513waec605cr77659f208409c550@mail.gmail.com>
	<5139B26D-F189-4A62-90FE-012E779BEB62@wisc.edu>
Message-ID: <45ED7842.2020101@gmail.com>

David Perlman wrote:
> OK, I'm new to python too so I don't assume I know what I'm talking  
> about yet, but this looks like a mess to me.  What exactly does "item  
> == item in word2" evaluate to?  Does "in" or "==" have higher  
> precedence?
>
> I can't figure out how this would ever work at all.  It seems like  
> it's either checking to see whether boolean TRUE is in word2, or else  
> it's checking to see whether item is equal to boolean TRUE or FALSE,  
> and neither of those should ever be true.  
I'm not really sure what's happening, but check this out.
 >>> word2 = [1,2,3,4]
 >>> print 555 == 555 in word2
False
 >>> print 1 == 1 in word2
True
 >>> print 0 == 0 in word2
False
 >>> word2.append(0)
 >>> print 0 == 0 in word2
True
 >>>
> And yet it seems to be  
> working out the same as "item in word2".
Yeah, it is working the same. 
It appears the == has higher precedence, or the operations are evaluated 
left-to-right.
 >>> print 0 in word2
True
 >>> 0 == True
False

Which suggests what's really happening is
 >>> (0 == 0) in word2
True

So it's searching the list for anything that makes the condition true.
But that's not actually true.
 >>> (555 == 555) in word2
True
 >>> 555 == 555 in word2
False

So It appears to work differently depending on the circumstances.  In 
any event, it's not what the OP wanted.

Hope that wasn't confusing, and maybe helped.
-Luke

From alan.gauld at btinternet.com  Tue Mar  6 18:03:11 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 6 Mar 2007 17:03:11 -0000
Subject: [Tutor] trouble with function-- trying to check
	differences	btwn 2 strings
References: <c19e69be0703051504t3088e2fche73c80a1b8735b37@mail.gmail.com><d9e88eaf0703051513waec605cr77659f208409c550@mail.gmail.com>
	<5139B26D-F189-4A62-90FE-012E779BEB62@wisc.edu>
Message-ID: <esk6op$fmc$1@sea.gmane.org>


"David Perlman" <dperlman at wisc.edu> wrote

> I can't figure out how this would ever work at all.  It seems like
> it's either checking to see whether boolean TRUE is in word2, or 
> else
> it's checking to see whether item is equal to boolean TRUE or FALSE,
> and neither of those should ever be true.

It's doing the latter and since anything that's not 'empty' in
Python evaluates to true we wind up checking whether
true == (item in word)

So if the item is in word we get true == true which is true.

HTH,


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



From zebra05 at gmail.com  Tue Mar  6 18:15:56 2007
From: zebra05 at gmail.com (OkaMthembo)
Date: Tue, 6 Mar 2007 19:15:56 +0200
Subject: [Tutor] PYTHON MOBILE WEB DEVELOPMENT
Message-ID: <c7c6f3bc0703060915j178a2278xd7bd277d733c8332@mail.gmail.com>

Hello All,

I am keen to find out if there are any frameworks for Python mobile web
development out there.
Does anyone know of a major/popular mobile web app written in python?
Moreover, if i wrote a mobile web app
with standard HTML for presentation and Python as a server-side language,
would there be any catches relating to phone compatibility etc?
I know next to nothing about WAP, so can i use HTTP for a mobile app?

Quite a mouthful, i know :-). I would really appreciate any advice.

With Thanks,

Lloyd

-- 
"The Stupidry Foundry"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070306/6597c27e/attachment.htm 

From deliberatus at verizon.net  Tue Mar  6 18:29:59 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Tue, 06 Mar 2007 12:29:59 -0500
Subject: [Tutor] installers and more
In-Reply-To: <45ED2123.9090306@tds.net>
References: <45ED012F.2060100@verizon.net> <45ED2123.9090306@tds.net>
Message-ID: <45EDA517.7020802@verizon.net>

OK, so now I need to pick a freeware installer to bundle it all up and 
install it real easy for the non technical minded, and fire off the 
python self installer I include with it.

So let's refine this tread to INSTALLER discussion. Recomendations, 
comments, criticisms, links to webpages, etc.


Kent Johnson wrote:
> Kirk Bailey wrote:
>> 2. It takes python being in the laptop so it can be used. As I do not 
>> own it, I hesitate to bundle it in. What's the legal aspect of 
>> providing the language the app needs so it will run?
> 
> This is not a problem, you can distribute a package that includes Python.
> http://www.python.org/psf/license/
> 
> Kent
> 
> 

-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From zannah.m at gmail.com  Tue Mar  6 18:39:51 2007
From: zannah.m at gmail.com (zannah marsh)
Date: Tue, 6 Mar 2007 12:39:51 -0500
Subject: [Tutor] trouble with function-- trying to check differences
	btwn 2 strings
In-Reply-To: <esk6op$fmc$1@sea.gmane.org>
References: <c19e69be0703051504t3088e2fche73c80a1b8735b37@mail.gmail.com>
	<d9e88eaf0703051513waec605cr77659f208409c550@mail.gmail.com>
	<5139B26D-F189-4A62-90FE-012E779BEB62@wisc.edu>
	<esk6op$fmc$1@sea.gmane.org>
Message-ID: <c19e69be0703060939y54a22802g1fc5e4971ae9b974@mail.gmail.com>

what I was trying to do with that loop is check each character in the string
against the corresponding character at the same position in the second
string. rikart pointed out that my loop was actually checking if that
character exists anywhere in the second string.
basically, in pseudocode:

for thing in bunch of things
    check to see if thing  from bunch of things is present in second bunch
of things

so "thing" here (called item in my original code) does not represent the
index. it's just a counter for things.
in java (which is the only language i am even kind of familar with) loops
and iterators are different, and everything has to be defined...

rikart pointed out that you need to use a range to get to the indicies of
the items in the string.

for item in range(len(string))...
     if word1[item] == word2[item]


and that's the fix. whether i am doing something totally weird, or that
could be done a better way in python, i don't know...


zannah



On 3/6/07, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
>
> "David Perlman" <dperlman at wisc.edu> wrote
>
> > I can't figure out how this would ever work at all.  It seems like
> > it's either checking to see whether boolean TRUE is in word2, or
> > else
> > it's checking to see whether item is equal to boolean TRUE or FALSE,
> > and neither of those should ever be true.
>
> It's doing the latter and since anything that's not 'empty' in
> Python evaluates to true we wind up checking whether
> true == (item in word)
>
> So if the item is in word we get true == true which is true.
>
> HTH,
>
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
> _______________________________________________
> Tutor maillist  -   Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070306/16f56f5b/attachment.htm 

From zebra05 at gmail.com  Tue Mar  6 18:49:12 2007
From: zebra05 at gmail.com (OkaMthembo)
Date: Tue, 6 Mar 2007 19:49:12 +0200
Subject: [Tutor] Python Mobile Web Development
Message-ID: <c7c6f3bc0703060949vbcc4be0yf7fbb8cfe68f5429@mail.gmail.com>

Hello All,

I am keen to find out if there are any frameworks for Python mobile web
development out there.
Does anyone know of a major/popular mobile web app written in python?
Moreover, if i wrote a mobile web app
with standard HTML for presentation and Python as a server-side language,
would there be any catches relating to phone compatibility etc?
I know next to nothing about WAP, so can i use HTTP for a mobile app?

Quite a mouthful, i know :-). I would really appreciate any advice.

With Thanks,

Lloyd

-- 
"The Stupidry Foundry"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070306/e923224c/attachment.htm 

From rabidpoobear at gmail.com  Tue Mar  6 18:50:33 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Tue, 06 Mar 2007 11:50:33 -0600
Subject: [Tutor] trouble with function-- trying to check
 differences	btwn 2 strings
In-Reply-To: <c19e69be0703060939y54a22802g1fc5e4971ae9b974@mail.gmail.com>
References: <c19e69be0703051504t3088e2fche73c80a1b8735b37@mail.gmail.com>	<d9e88eaf0703051513waec605cr77659f208409c550@mail.gmail.com>	<5139B26D-F189-4A62-90FE-012E779BEB62@wisc.edu>	<esk6op$fmc$1@sea.gmane.org>
	<c19e69be0703060939y54a22802g1fc5e4971ae9b974@mail.gmail.com>
Message-ID: <45EDA9E9.7040603@gmail.com>

zannah marsh wrote:
> what I was trying to do with that loop is check each character in the 
> string against the corresponding character at the same position in the 
> second string. rikart pointed out that my loop was actually checking 
> if that character exists anywhere in the second string.
[snip the fix]
>
> and that's the fix. whether i am doing something totally weird, or 
> that could be done a better way in python, i don't know... 
The way you're doing it now is correct.
The function could be shortened to a single line, though, if you wanted to.
def stringdiff(string1,string2):
    return [i for i in range(len(string1)) if string1[i] != string2[i]]

but I doubt your professor has covered list comprehensions yet, so the 
way you solved the problem is most likely what he was looking for.
-Luke

From alan.gauld at btinternet.com  Tue Mar  6 19:14:55 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 6 Mar 2007 18:14:55 -0000
Subject: [Tutor] trouble with function-- trying to check differencesbtwn
	2 strings
References: <c19e69be0703051504t3088e2fche73c80a1b8735b37@mail.gmail.com><d9e88eaf0703051513waec605cr77659f208409c550@mail.gmail.com><5139B26D-F189-4A62-90FE-012E779BEB62@wisc.edu><esk6op$fmc$1@sea.gmane.org>
	<c19e69be0703060939y54a22802g1fc5e4971ae9b974@mail.gmail.com>
Message-ID: <eskav9$2o6$1@sea.gmane.org>

"zannah marsh" <zannah.m at gmail.com> wrote

> rikart pointed out that you need to use a range to get to the 
> indicies of
> the items in the string.
>
> for item in range(len(string))...
>     if word1[item] == word2[item]
>

There is another way which is to use enumerate which
returns both the item and its index.

>>> for i,c in enumerate('abcd'):
>>>     print c, 'at', i
a at 0
b at 1
c at 2
d at 3

But range() works just as well in this case.

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



From alan.gauld at btinternet.com  Tue Mar  6 19:18:27 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 6 Mar 2007 18:18:27 -0000
Subject: [Tutor] PYTHON MOBILE WEB DEVELOPMENT
References: <c7c6f3bc0703060915j178a2278xd7bd277d733c8332@mail.gmail.com>
Message-ID: <eskb5s$3im$1@sea.gmane.org>


"OkaMthembo" <zebra05 at gmail.com> wrote 

> I am keen to find out if there are any frameworks 
> for Python mobile web development out there.

If you mean WAP applications then so far as I'm 
aware there is nothing different at the server end 
except they serve up some specific XML style 
documents.

In other words any web framework should work, 
especially if the templating system can generate 
XML rather than HTML. But since most of them 
seem to use XHTML nowadays that shouldn't be 
a problem.

But I've never tried it...

Alan G.


From rdm at rcblue.com  Tue Mar  6 20:00:20 2007
From: rdm at rcblue.com (Dick Moores)
Date: Tue, 06 Mar 2007 11:00:20 -0800
Subject: [Tutor] What/Why this Cookbook recipe?
Message-ID: <20070306190932.592D51E400D@bag.python.org>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070306/bcf124ab/attachment.html 

From ebbaalm at uiuc.edu  Tue Mar  6 20:14:04 2007
From: ebbaalm at uiuc.edu (Cecilia Alm)
Date: Tue, 6 Mar 2007 13:14:04 -0600
Subject: [Tutor] executing a string representing python code
In-Reply-To: <123193.22132.qm@web86110.mail.ird.yahoo.com>
References: <123193.22132.qm@web86110.mail.ird.yahoo.com>
Message-ID: <7a4620dc0703061114l5af0e1a5r4e04e5abb7c18bdd@mail.gmail.com>

Hm, I'm not sure I see your point. Could an evil hacker not just as easily
change the dictionary in the python code (or somewhere else in the code) to
perform such evil operations?

--C

2007/3/5, ALAN GAULD <alan.gauld at btinternet.com>:
>
> > That's neat. When just the function call is the string,
> > eval() seems appropriate. (For example, if reading what
> > function to call from a file.)
>
> Its conventient but incredibly dangerous.
> Its much better in that case to create a dictionary of allowed
> (ie safe!) functions that can vbe read and then look that up
> from the file input.
>
> Otherwise anyone who can access the file (legitimately or
> otherwise) can start calling any of the standard Python functions,
> including os.unlink() to delete files, or even os.system(), to do
> just about anything - howsabout formatting your disk?
>
> ok_funks = {
>       'some_func' : some_func,
>       'another_func': another_func,
>       'some_fancy_name': sys.exit
> }
>
> func = raw_input('type a function name>')
> try: ok_funks[func']()
> except: print 'Thats not a valid function'
>
> eval and exec are seductively powerful but they are immensely
> dangerous in a world of crackers and virus makers. They should
> only ever be used in strictly controlled scebnarios and even then
> as a last resort.
>
> HTH,
>
> Alan G.
>
> ------------------------------
> The all-new Yahoo! Mail<http://us.rd.yahoo.com/mail/uk/taglines/default/nowyoucan/free_from_isp/*http://us.rd.yahoo.com/evt=40565/*http://uk.docs.yahoo.com/nowyoucan.html>goes wherever you go - free your email address from your Internet provider.
>



-- 
E. Cecilia Alm
Graduate student, Dept. of Linguistics, UIUC
Office: 2013 Beckman Institute
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070306/7e43fb6b/attachment.htm 

From rabidpoobear at gmail.com  Tue Mar  6 20:22:53 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Tue, 06 Mar 2007 13:22:53 -0600
Subject: [Tutor] executing a string representing python code
In-Reply-To: <7a4620dc0703061114l5af0e1a5r4e04e5abb7c18bdd@mail.gmail.com>
References: <123193.22132.qm@web86110.mail.ird.yahoo.com>
	<7a4620dc0703061114l5af0e1a5r4e04e5abb7c18bdd@mail.gmail.com>
Message-ID: <45EDBF8D.6050908@gmail.com>

Cecilia Alm wrote:
> Hm, I'm not sure I see your point. Could an evil hacker not just as 
> easily change the dictionary in the python code (or somewhere else in 
> the code) to perform such evil operations?
Not too easily, if the code were distributed as .pycs.  However, running 
code you read in from a plain text file, they could change easily.
HTH,
-Luke
>
> --C
>
> 2007/3/5, ALAN GAULD <alan.gauld at btinternet.com 
> <mailto:alan.gauld at btinternet.com>>:
>
>     > That's neat. When just the function call is the string,
>     > eval() seems appropriate. (For example, if reading what
>     > function to call from a file.)
>
>     Its conventient but incredibly dangerous.
>     Its much better in that case to create a dictionary of allowed
>     (ie safe!) functions that can vbe read and then look that up
>     from the file input.
>
>     Otherwise anyone who can access the file (legitimately or
>     otherwise) can start calling any of the standard Python functions,
>     including os.unlink() to delete files, or even os.system(), to do
>     just about anything - howsabout formatting your disk?
>
>     ok_funks = {
>           'some_func' : some_func,
>           'another_func': another_func,
>           'some_fancy_name': sys.exit
>     }
>
>     func = raw_input('type a function name>')
>     try: ok_funks[func']()
>     except: print 'Thats not a valid function'
>
>     eval and exec are seductively powerful but they are immensely
>     dangerous in a world of crackers and virus makers. They should
>     only ever be used in strictly controlled scebnarios and even then
>     as a last resort.
>
>     HTH,
>
>     Alan G.
>
>     ------------------------------------------------------------------------
>     The all-new Yahoo! Mail
>     <http://us.rd.yahoo.com/mail/uk/taglines/default/nowyoucan/free_from_isp/*http://us.rd.yahoo.com/evt=40565/*http://uk.docs.yahoo.com/nowyoucan.html>
>     goes wherever you go - free your email address from your Internet
>     provider.
>
>
>
>
> -- 
> E. Cecilia Alm
> Graduate student, Dept. of Linguistics, UIUC
> Office: 2013 Beckman Institute
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From project5 at redrival.net  Tue Mar  6 20:43:34 2007
From: project5 at redrival.net (Andrei)
Date: Tue, 06 Mar 2007 20:43:34 +0100
Subject: [Tutor] What/Why this Cookbook recipe?
In-Reply-To: <20070306190932.592D51E400D@bag.python.org>
References: <20070306190932.592D51E400D@bag.python.org>
Message-ID: <eskg90$qss$1@sea.gmane.org>

Dick Moores wrote:
> I've been trying to learn new things from the Cookbook, but here's a 
> recipe the utility of which I don't understand at all. Why interpolation 
> (whether the ruby way or not)? Maybe a better example than the couple 
> given would help me? 
<snip>

Normal string formatting in Python works by including in the string a 
sort of type definition (e.g. '%s' means 'insert a string here', '%d' is 
  'insert an integer here', etc.). You have to supply the arguments 
after the format string, in a tuple. For example:

   >>> print 'Name: %s\nAge: %d' % (username, userage)
   Name: John Doe
   Age: 39

With the recipe provided, you can put the variables you want inserted 
directly in the format string - it's no longer necessary to append them 
in a tuple. So for the example above, it would become:

   >>> print interp('Name: #{username}\nAge: #{userage}')

As you see, it's slightly shorter and more ad-hoc - or it would be, if 
it were built into the language and you didn't have to call the interp 
function. It also has the advantage that you don't have to make sure you 
provide the right number (and type) of arguments in the tuple - it's 
easy to e.g. decide to no longer print the age and forget to update the 
tuple, like this:

   >>> print 'Name: %s' % (username, userage)
   Traceback <snip>
   TypeError: not all arguments converted during string formatting

That's a particularly annoying source of errors that isn't caught even 
in (most? all?) machine-code compiled languages. The opposite may also 
occur, that you e.g. decide to also print a phone number, include that 
in the format string, yet forget to include it in the tuple as well.

The recipe has some disadvantages:

- you have put your variable names in a string. This is bad practice - 
if you rename variables, it's easy to overlook them in strings.

- format strings can be used to translate an application. You just give 
the translator your 'Name: %s' string and he gives you 'Borkbork: %s' or 
whatever. The translation doesn't need to be modified if you decide to 
make a user class and get rid of the username and userage vars.

- format strings give you more control, so you can e.g. specify how many 
digits a float should have when formatted.


-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info:
''.join([''.join(s) for s in zip(
"poet at aao.l pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
"rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])


From alan.gauld at btinternet.com  Tue Mar  6 22:03:59 2007
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Tue, 6 Mar 2007 21:03:59 +0000 (GMT)
Subject: [Tutor] executing a string representing python code
Message-ID: <816230.76528.qm@web86110.mail.ird.yahoo.com>

> Hm, I'm not sure I see your point. Could an evil hacker not just 
> as
easily change the dictionary in the python code 
> (or somewhere else in
the code) to perform such evil operations?

If they have access to the source code you are right of course.
But typically the source will be in a secure folder somewhere 
whereas the 'data' files will be more public. In the kind of applications 
that need to do this it tends to be the nature of the beast that the 
data files are either hand crafted by someone other than the original 
programmer (after all he/she would just write code, its far easier!)
or they are auto generated from a database or from web input.

So if the data files aand source code are both well protected then 
there is no problem. If both are publicly avbailable then there's a 
problem either way but in the common scenario where the data 
files are 'public' and the source is hidden/secured then we have 
the problem I described.


Hope that clarifies things,

Alan G.






		
___________________________________________________________ 
Copy addresses and emails from any email account to Yahoo! Mail - quick, easy and free. http://uk.docs.yahoo.com/trueswitch2.html
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070306/21e4a753/attachment.htm 

From ebbaalm at uiuc.edu  Tue Mar  6 22:39:05 2007
From: ebbaalm at uiuc.edu (Cecilia Alm)
Date: Tue, 6 Mar 2007 15:39:05 -0600
Subject: [Tutor] executing a string representing python code
In-Reply-To: <816230.76528.qm@web86110.mail.ird.yahoo.com>
References: <816230.76528.qm@web86110.mail.ird.yahoo.com>
Message-ID: <7a4620dc0703061339w34af8b53qc636479b97f01a26@mail.gmail.com>

Thanks, Alan. I really appreciate the discussion.

--C

2007/3/6, ALAN GAULD <alan.gauld at btinternet.com>:
>
> > Hm, I'm not sure I see your point. Could an evil hacker not just
> > as easily change the dictionary in the python code
> > (or somewhere else in the code) to perform such evil operations?
>
> If they have access to the source code you are right of course.
> But typically the source will be in a secure folder somewhere
> whereas the 'data' files will be more public. In the kind of applications
> that need to do this it tends to be the nature of the beast that the
> data files are either hand crafted by someone other than the original
> programmer (after all he/she would just write code, its far easier!)
> or they are auto generated from a database or from web input.
>
> So if the data files aand source code are both well protected then
> there is no problem. If both are publicly avbailable then there's a
> problem either way but in the common scenario where the data
> files are 'public' and the source is hidden/secured then we have
> the problem I described.
>
> Hope that clarifies things,
>
> Alan G.
>
>
> ------------------------------
> All New Yahoo! Mail<http://us.rd.yahoo.com/mail/uk/taglines/default/nowyoucan/spamguard/*http://us.rd.yahoo.com/evt=40565/*http://uk.docs.yahoo.com/nowyoucan.html>? Tired of unwanted email come-ons? Let our SpamGuard protect you.
>



-- 
E. Cecilia Alm
Graduate student, Dept. of Linguistics, UIUC
Office: 2013 Beckman Institute
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070306/7c5a8148/attachment.htm 

From rabidpoobear at gmail.com  Tue Mar  6 22:41:18 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Tue, 06 Mar 2007 15:41:18 -0600
Subject: [Tutor] What/Why this Cookbook recipe?
In-Reply-To: <eskg90$qss$1@sea.gmane.org>
References: <20070306190932.592D51E400D@bag.python.org>
	<eskg90$qss$1@sea.gmane.org>
Message-ID: <45EDDFFE.4050207@gmail.com>

Andrei wrote:
> Dick Moores wrote:
>   
>> I've been trying to learn new things from the Cookbook, but here's a 
>> recipe the utility of which I don't understand at all. Why interpolation 
>> (whether the ruby way or not)? Maybe a better example than the couple 
>> given would help me? 
>>     
> <snip>
>
> Normal string formatting in Python works by including in the string a 
> sort of type definition (e.g. '%s' means 'insert a string here', '%d' is 
>   'insert an integer here', etc.). You have to supply the arguments 
> after the format string, in a tuple. For example:
>
>    >>> print 'Name: %s\nAge: %d' % (username, userage)
>    Name: John Doe
>    Age: 39
>
> With the recipe provided, you can put the variables you want inserted 
> directly in the format string - it's no longer necessary to append them 
> in a tuple. So for the example above, it would become:
>
>    >>> print interp('Name: #{username}\nAge: #{userage}')
>   
This accomplishes nearly the same thing:
 >>> d = {'username':'bob','userage':23}
 >>> print "Name: %(username)s, Age: %(userage)s" % d
Name: bob, Age: 23

The only difference is that the items have to be keys in the dictionary, 
instead of just variables,
but that's not necessarily a disadvantage.
But I understand they're trying to emulate it exactly as it operates in 
other languages.

>
> The recipe has some disadvantages:
>
> - you have put your variable names in a string. This is bad practice - 
> if you rename variables, it's easy to overlook them in strings.
>   
This is a disadvantage in the dictionary method too, it seems.
> - format strings can be used to translate an application. You just give 
> the translator your 'Name: %s' string and he gives you 'Borkbork: %s' or 
> whatever. The translation doesn't need to be modified if you decide to 
> make a user class and get rid of the username and userage vars.
>   
I don't see what you mean here.  The string in the example,

interp('Name: #{username}\nAge: #{userage}')


could be translated too.

> - format strings give you more control, so you can e.g. specify how many 
> digits a float should have when formatted.
The dictionary method would allow you this control.

HTH,
-Luke

From rdm at rcblue.com  Tue Mar  6 22:42:01 2007
From: rdm at rcblue.com (Dick Moores)
Date: Tue, 06 Mar 2007 13:42:01 -0800
Subject: [Tutor] path to use for setting the environment variable PYTHONDOCS?
Message-ID: <20070306214206.B0E9F1E400E@bag.python.org>

=======================================
 >>>help('assert')

Sorry, topic and keyword documentation is not available because the Python
HTML documentation files could not be found.  If you have installed them,
please set the environment variable PYTHONDOCS to indicate their location.
========================================

I have Python 2.5. Where are the HTML documentation files?

Thanks,

Dick Moores


From dperlman at wisc.edu  Tue Mar  6 23:09:02 2007
From: dperlman at wisc.edu (David Perlman)
Date: Tue, 06 Mar 2007 16:09:02 -0600
Subject: [Tutor] trouble with function-- trying to
 check	differences	btwn 2 strings
In-Reply-To: <esk6op$fmc$1@sea.gmane.org>
References: <c19e69be0703051504t3088e2fche73c80a1b8735b37@mail.gmail.com>
	<d9e88eaf0703051513waec605cr77659f208409c550@mail.gmail.com>
	<5139B26D-F189-4A62-90FE-012E779BEB62@wisc.edu>
	<esk6op$fmc$1@sea.gmane.org>
Message-ID: <7756D1F3-E91F-4A23-922B-4C74981A811F@wisc.edu>

On Mar 6, 2007, at 11:03 AM, Alan Gauld wrote:
> It's doing the latter and since anything that's not 'empty' in
> Python evaluates to true we wind up checking whether
> true == (item in word)
>
> So if the item is in word we get true == true which is true.
>
> HTH,

Sorry, but this still doesn't make sense to me.

 >>> x=('i' in 'i')
 >>> x
True
 >>> y='i'
 >>> x==y
False

I understand that anything that's not 'empty' or zero evaluates to  
True *when cast as a Boolean* by the operation in question:

 >>> if y: print "It's True!"
...
It's True!

But the == operator doesn't cast its operands as Booleans; it merely  
*returns* a Boolean.

Or is the point that in the original case the == operator *is*  
casting item to Boolean because it's comparing it with another  
Boolean?  That's kind of strange, especially considering that in my  
example above, it *didn't* do that.

I still don't understand what's going on.  :)

--
-dave----------------------------------------------------------------
Science arose from poetry... when times change the two can meet again
on a higher level as friends. -G?the



From wescpy at gmail.com  Tue Mar  6 23:28:48 2007
From: wescpy at gmail.com (wesley chun)
Date: Tue, 6 Mar 2007 14:28:48 -0800
Subject: [Tutor] trouble with function-- trying to check differences
	btwn 2 strings
In-Reply-To: <7756D1F3-E91F-4A23-922B-4C74981A811F@wisc.edu>
References: <c19e69be0703051504t3088e2fche73c80a1b8735b37@mail.gmail.com>
	<d9e88eaf0703051513waec605cr77659f208409c550@mail.gmail.com>
	<5139B26D-F189-4A62-90FE-012E779BEB62@wisc.edu>
	<esk6op$fmc$1@sea.gmane.org>
	<7756D1F3-E91F-4A23-922B-4C74981A811F@wisc.edu>
Message-ID: <78b3a9580703061428l210c5eb8t2522ce50d7071f33@mail.gmail.com>

>  >>> x=('i' in 'i')
>  >>> x
> True
>  >>> y='i'
>  >>> x==y
> False

you're right when you talk about "casting" altho that's not what
python does.  it merely performs an object value comparison when you
use '=='.  for example, change your code above to:

>>> True == 'i'    # because this is what you're really doing with x==y
False

so the reason why you get a false is that those 2 values *are*
different from each other, even if their boolean truthfulness may be
the same:

>>> bool(True) == bool('i')
True

how's *that* for casting?  :-)

just remember that the interpreter compares *values* and not boolean
truthfulness, and you'll be ok.  if you really want the latter, then
use bool().

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com

From rob.andrews at gmail.com  Tue Mar  6 23:31:54 2007
From: rob.andrews at gmail.com (Rob Andrews)
Date: Tue, 6 Mar 2007 16:31:54 -0600
Subject: [Tutor] sorting question
Message-ID: <8d757d2e0703061431s678c6ceeib1c5ccda6c65b00f@mail.gmail.com>

I'm trying to think of the best way to go about this one, as the files
I have to sort are *big*.

They're ASCII files with each row consisting of a series of
fixed-length fields, each of which has a corresponding format file.
(To be specific, these files are FirstLogic compatible.)

I'm looking to sort files such that I can produce the 50,000 records
with the highest "score" in a certain field.

A grossly over-simplified example is:

"JohnDoe   3.14123 Anywhere St."
"MarySmith11.03One Jackson Pl. "

------------------------------------------------------------
>>> for x in people: # substituting 'people' for a file of records
	print x[9:14]
	
 3.14
11.03
------------------------------------------------------------

With this in mind, I'm trying to sort the file by the value of the
number in the field represented by x[9:14] in the example here.

I haven't yet figured out a way to apply sort() to this problem,
although I'm certain the failing is my own.

-Rob A.

From alan.gauld at btinternet.com  Tue Mar  6 23:37:31 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 6 Mar 2007 22:37:31 -0000
Subject: [Tutor] trouble with function-- trying to
	check	differences	btwn 2 strings
References: <c19e69be0703051504t3088e2fche73c80a1b8735b37@mail.gmail.com><d9e88eaf0703051513waec605cr77659f208409c550@mail.gmail.com><5139B26D-F189-4A62-90FE-012E779BEB62@wisc.edu><esk6op$fmc$1@sea.gmane.org>
	<7756D1F3-E91F-4A23-922B-4C74981A811F@wisc.edu>
Message-ID: <eskqbl$qt$1@sea.gmane.org>

"David Perlman" <dperlman at wisc.edu> wrote

> Sorry, but this still doesn't make sense to me.
>
 >>> x=('i' in 'i')
 >>> x
True
 >>> y='i'
 >>> x==y
False

> But the == operator doesn't cast its operands as Booleans; 

Good catch!

I don't understand it now either.

But I've been up since 4:30am and am too tired to try 
figuring it out just now, so maybe someone else will 
explain! :-)

>>> for c in 'abcd':
...    print (c == c in 'crab')
...
True
True
True
False

It definitely seems to work as I explained it but how it works is 
defeating my befuddled brain right now. I suspect it needs 
a read of the reference manual...

Alan G.


From alan.gauld at btinternet.com  Tue Mar  6 23:41:43 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 6 Mar 2007 22:41:43 -0000
Subject: [Tutor] path to use for setting the environment variable
	PYTHONDOCS?
References: <20070306214206.B0E9F1E400E@bag.python.org>
Message-ID: <eskqjg$1kb$1@sea.gmane.org>


"Dick Moores" <rdm at rcblue.com> wrote

> Sorry, topic and keyword documentation is not available because the 
> Python
> HTML documentation files could not be found.  If you have installed 
> them,
> please set the environment variable PYTHONDOCS to indicate their 
> location.
> ========================================
>
> I have Python 2.5. Where are the HTML documentation files?

No idea, but I suspect the answer will be platform specific.
Which platform are you using?

Alan G. 



From dperlman at wisc.edu  Tue Mar  6 23:41:16 2007
From: dperlman at wisc.edu (David Perlman)
Date: Tue, 06 Mar 2007 16:41:16 -0600
Subject: [Tutor] trouble with function-- trying to check differences
 btwn 2 strings
In-Reply-To: <78b3a9580703061428l210c5eb8t2522ce50d7071f33@mail.gmail.com>
References: <c19e69be0703051504t3088e2fche73c80a1b8735b37@mail.gmail.com>
	<d9e88eaf0703051513waec605cr77659f208409c550@mail.gmail.com>
	<5139B26D-F189-4A62-90FE-012E779BEB62@wisc.edu>
	<esk6op$fmc$1@sea.gmane.org>
	<7756D1F3-E91F-4A23-922B-4C74981A811F@wisc.edu>
	<78b3a9580703061428l210c5eb8t2522ce50d7071f33@mail.gmail.com>
Message-ID: <BF97082C-299F-40FA-8F22-3E63905516D8@wisc.edu>


On Mar 6, 2007, at 4:28 PM, wesley chun wrote:

>>  >>> x=('i' in 'i')
>>  >>> x
>> True
>>  >>> y='i'
>>  >>> x==y
>> False
>
> you're right when you talk about "casting" altho that's not what
> python does.  it merely performs an object value comparison when you
> use '=='.  for example, change your code above to:
>
>>>> True == 'i'    # because this is what you're really doing with x==y
> False
>
> so the reason why you get a false is that those 2 values *are*
> different from each other, even if their boolean truthfulness may be
> the same:
>
>>>> bool(True) == bool('i')
> True
>
> how's *that* for casting?  :-)
>
> just remember that the interpreter compares *values* and not boolean
> truthfulness, and you'll be ok.  if you really want the latter, then
> use bool().
>
> hope this helps!
> -- wesley

This helps convince me that I still don't understand why the original  
code snippet worked at all.  :)

These code examples make perfect sense.  This one doesn't, and  
appears to be an inconsistency:

 >>> word2 = 'hello'
 >>> item = 'e'
 >>> item in word2
True
 >>> item == item in word2
True
 >>> (item == item) in word2
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
TypeError: 'in <string>' requires string as left operand
 >>> item in word2
True
 >>> item == True
False
 >>> item == (item in word2)
False

Notice that forcing the precedence of "in" and "==" using parentheses  
gives either False or an error, but without parentheses, it's True.   
So what's going on?


--
-dave----------------------------------------------------------------
Science arose from poetry... when times change the two can meet again
on a higher level as friends. -G?the



From john at fouhy.net  Tue Mar  6 23:44:08 2007
From: john at fouhy.net (John Fouhy)
Date: Wed, 7 Mar 2007 11:44:08 +1300
Subject: [Tutor] trouble with function-- trying to check differences
	btwn 2 strings
In-Reply-To: <7756D1F3-E91F-4A23-922B-4C74981A811F@wisc.edu>
References: <c19e69be0703051504t3088e2fche73c80a1b8735b37@mail.gmail.com>
	<d9e88eaf0703051513waec605cr77659f208409c550@mail.gmail.com>
	<5139B26D-F189-4A62-90FE-012E779BEB62@wisc.edu>
	<esk6op$fmc$1@sea.gmane.org>
	<7756D1F3-E91F-4A23-922B-4C74981A811F@wisc.edu>
Message-ID: <5e58f2e40703061444h712c4d3fga165db7ce96fc79a@mail.gmail.com>

On 07/03/07, David Perlman <dperlman at wisc.edu> wrote:
> On Mar 6, 2007, at 11:03 AM, Alan Gauld wrote:
> > It's doing the latter and since anything that's not 'empty' in
> > Python evaluates to true we wind up checking whether
> > true == (item in word)
> >
> > So if the item is in word we get true == true which is true.
> Sorry, but this still doesn't make sense to me.

Hmm, ok, colour me confused as well.  Let's try creating the
conditions in the original poster's code.

Python 2.4.3 (#1, Mar 30 2006, 11:02:16)
[GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> item = 'b'
>>> word2 = 'bees'

The test is "item == item in word2".

>>> item == item in word2
True

Let's see how we can group this:

>>> item == (item in word2)
False

That makes sense.  It's not True though.

>>> (item == item) in word2
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: 'in <string>' requires string as left operand

That also makes sense..

>>> if (item == item) in word2:
...  print 'foo'
...
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: 'in <string>' requires string as left operand

>>> if item == item in word2:
...  print 'foo'
...
foo


So ... hmm.  Not sure what's going on here.

I also notice that, according to
http://docs.python.org/ref/summary.html, '==' has higher precedence
than 'in'.  Which means that

'foo == bar in baz' should group as '(foo == bar) in baz'.  But Luke's
example contradicts this:

>>> lst = [1,2,3,4]
>>> 555 == 555 in lst
False
>>> (555 == 555) in lst
True
>>> 1 == 1 in lst
True

(this works because 1 == True)

-- 
John.

From john at fouhy.net  Tue Mar  6 23:59:59 2007
From: john at fouhy.net (John Fouhy)
Date: Wed, 7 Mar 2007 11:59:59 +1300
Subject: [Tutor] sorting question
In-Reply-To: <8d757d2e0703061431s678c6ceeib1c5ccda6c65b00f@mail.gmail.com>
References: <8d757d2e0703061431s678c6ceeib1c5ccda6c65b00f@mail.gmail.com>
Message-ID: <5e58f2e40703061459s4efb90b0h78e1c0014f3e990a@mail.gmail.com>

On 07/03/07, Rob Andrews <rob.andrews at gmail.com> wrote:
> I'm trying to think of the best way to go about this one, as the files
> I have to sort are *big*.
[...]
> I haven't yet figured out a way to apply sort() to this problem,
> although I'm certain the failing is my own.

To use sort(), you'll have to read the entire file or files into
memory first.  If you can do that, your procedure would be:
 1. Read into memory, splitting each file into a tuple.
 2. Use sort(key=operator.itemgetter(1))  (or whatever field you are sorting on)

If it's not practical to read the file into memory, perhaps you could
use a database?  You could download pysqlite, which is an embeddable
relational database.  Your procedure would then be:
 1. Create database, table, possibly indices on columns you're
interested in sorting by
 2. Read and parse files line by line, insert into database
 3. Run query 'select blah from foo order by whatever limit 50000'.

-- 
John.

From dperlman at wisc.edu  Wed Mar  7 00:41:53 2007
From: dperlman at wisc.edu (David Perlman)
Date: Tue, 06 Mar 2007 17:41:53 -0600
Subject: [Tutor] trouble with function-- trying to check differences
 btwn 2 strings
In-Reply-To: <5e58f2e40703061444h712c4d3fga165db7ce96fc79a@mail.gmail.com>
References: <c19e69be0703051504t3088e2fche73c80a1b8735b37@mail.gmail.com>
	<d9e88eaf0703051513waec605cr77659f208409c550@mail.gmail.com>
	<5139B26D-F189-4A62-90FE-012E779BEB62@wisc.edu>
	<esk6op$fmc$1@sea.gmane.org>
	<7756D1F3-E91F-4A23-922B-4C74981A811F@wisc.edu>
	<5e58f2e40703061444h712c4d3fga165db7ce96fc79a@mail.gmail.com>
Message-ID: <7B5D4190-B265-417C-8470-1A4EFF8DA1EF@wisc.edu>

I think it's a little strange and possibly problematic that type(1)  
is 'int' and type(True) is 'bool' but
1 == True
specifically evaluates to True even though anything else, even if it  
evaluates to True when cast as a boolean, is not == True.

 >>> 1 == True
True
 >>> 2 == True
False
 >>> 0 == False
True
 >>> 2 == False
False

I guess I just need to remember to always look on the bright side of  
life.

On Mar 6, 2007, at 4:44 PM, John Fouhy wrote:

> 'foo == bar in baz' should group as '(foo == bar) in baz'.  But Luke's
> example contradicts this:
>
>>>> lst = [1,2,3,4]
>>>> 555 == 555 in lst
> False
>>>> (555 == 555) in lst
> True
>>>> 1 == 1 in lst
> True
>
> (this works because 1 == True)

--
-dave----------------------------------------------------------------
Science arose from poetry... when times change the two can meet again
on a higher level as friends. -G?the



From kent37 at tds.net  Wed Mar  7 02:13:41 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 06 Mar 2007 20:13:41 -0500
Subject: [Tutor] trouble with function-- trying to check differences
 btwn 2 strings
In-Reply-To: <BF97082C-299F-40FA-8F22-3E63905516D8@wisc.edu>
References: <c19e69be0703051504t3088e2fche73c80a1b8735b37@mail.gmail.com>	<d9e88eaf0703051513waec605cr77659f208409c550@mail.gmail.com>	<5139B26D-F189-4A62-90FE-012E779BEB62@wisc.edu>	<esk6op$fmc$1@sea.gmane.org>	<7756D1F3-E91F-4A23-922B-4C74981A811F@wisc.edu>	<78b3a9580703061428l210c5eb8t2522ce50d7071f33@mail.gmail.com>
	<BF97082C-299F-40FA-8F22-3E63905516D8@wisc.edu>
Message-ID: <45EE11C5.2090900@tds.net>

David Perlman wrote:
> This helps convince me that I still don't understand why the original  
> code snippet worked at all.  :)
> 
> These code examples make perfect sense.  This one doesn't, and  
> appears to be an inconsistency:
> 
>  >>> word2 = 'hello'
>  >>> item = 'e'
>  >>> item in word2
> True
>  >>> item == item in word2
> True
>  >>> (item == item) in word2
> Traceback (most recent call last):
>    File "<stdin>", line 1, in ?
> TypeError: 'in <string>' requires string as left operand
>  >>> item in word2
> True
>  >>> item == True
> False
>  >>> item == (item in word2)
> False
> 
> Notice that forcing the precedence of "in" and "==" using parentheses  
> gives either False or an error, but without parentheses, it's True.   
> So what's going on?

'==' and 'in' are both comparison operators and they have equal 
precedence. Python semantics for comparison operators have a wrinkle 
that usually makes sense but in this case is confusing.

In general, if op1 and op2 are comparison operators,
   a op1 b op2 c
means the same as
   a op1 b and b op2 c

This is handy in the case, for example, of
   a < b < c
which has its conventional meaning of
   a < b and b < c

but for the current question
   item == item in word
this is the same as
   item == item and item in word
which is not what you would expect.

http://docs.python.org/ref/comparisons.html

Kent

From bgailer at alum.rpi.edu  Wed Mar  7 02:16:37 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Tue, 06 Mar 2007 17:16:37 -0800
Subject: [Tutor] trouble with function-- trying to check differences
 btwn 2 strings
In-Reply-To: <BF97082C-299F-40FA-8F22-3E63905516D8@wisc.edu>
References: <c19e69be0703051504t3088e2fche73c80a1b8735b37@mail.gmail.com>	<d9e88eaf0703051513waec605cr77659f208409c550@mail.gmail.com>	<5139B26D-F189-4A62-90FE-012E779BEB62@wisc.edu>	<esk6op$fmc$1@sea.gmane.org>	<7756D1F3-E91F-4A23-922B-4C74981A811F@wisc.edu>	<78b3a9580703061428l210c5eb8t2522ce50d7071f33@mail.gmail.com>
	<BF97082C-299F-40FA-8F22-3E63905516D8@wisc.edu>
Message-ID: <45EE1275.9040902@alum.rpi.edu>

David Perlman wrote:
> On Mar 6, 2007, at 4:28 PM, wesley chun wrote:
>
>   
>>>  >>> x=('i' in 'i')
>>>  >>> x
>>> True
>>>  >>> y='i'
>>>  >>> x==y
>>> False
>>>       
>> you're right when you talk about "casting" altho that's not what
>> python does.  it merely performs an object value comparison when you
>> use '=='.  for example, change your code above to:
>>
>>     
>>>>> True == 'i'    # because this is what you're really doing with x==y
>>>>>           
>> False
>>
>> so the reason why you get a false is that those 2 values *are*
>> different from each other, even if their boolean truthfulness may be
>> the same:
>>
>>     
>>>>> bool(True) == bool('i')
>>>>>           
>> True
>>
>> how's *that* for casting?  :-)
>>
>> just remember that the interpreter compares *values* and not boolean
>> truthfulness, and you'll be ok.  if you really want the latter, then
>> use bool().
>>
>> hope this helps!
>> -- wesley
>>     
>
> This helps convince me that I still don't understand why the original  
> code snippet worked at all.  :)
>
> These code examples make perfect sense.  This one doesn't, and  
> appears to be an inconsistency:
>
>  >>> word2 = 'hello'
>  >>> item = 'e'
>  >>> item in word2
> True
>  >>> item == item in word2
> True
>   
Take a look in 5.9 Comparisons in the Language Reference:

"Comparisons can be chained arbitrarily, e.g., |x < y <= z| is 
equivalent to |x < y and y <= z|, except that |y| is evaluated only once 
(but in both cases |z| is not evaluated at all when |x < y| is found to 
be false)."

Applying this to

item == item in word2

yields:

(item == item) and (item in word2)

 
Take it from there...

-- 
Bob Gailer
510-978-4454


From kent37 at tds.net  Wed Mar  7 02:17:38 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 06 Mar 2007 20:17:38 -0500
Subject: [Tutor] sorting question
In-Reply-To: <8d757d2e0703061431s678c6ceeib1c5ccda6c65b00f@mail.gmail.com>
References: <8d757d2e0703061431s678c6ceeib1c5ccda6c65b00f@mail.gmail.com>
Message-ID: <45EE12B2.3020505@tds.net>

Rob Andrews wrote:
> I'm trying to think of the best way to go about this one, as the files
> I have to sort are *big*.
> 
> They're ASCII files with each row consisting of a series of
> fixed-length fields, each of which has a corresponding format file.
> (To be specific, these files are FirstLogic compatible.)
> 
> I'm looking to sort files such that I can produce the 50,000 records
> with the highest "score" in a certain field.
> 
> A grossly over-simplified example is:
> 
> "JohnDoe   3.14123 Anywhere St."
> "MarySmith11.03One Jackson Pl. "
> 
> ------------------------------------------------------------
>>>> for x in people: # substituting 'people' for a file of records
> 	print x[9:14]
> 	
>  3.14
> 11.03
> ------------------------------------------------------------
> 
> With this in mind, I'm trying to sort the file by the value of the
> number in the field represented by x[9:14] in the example here.

If the files fit in memory you can define a function that returns the 
key value and use it for the sort.

If lines is a list of strings in the above format,
def myKey(line):
   return float(line[9:14])

lines.sort(key=myKey)

Or you can use John's suggestion of splitting the lines but that may not 
be needed in this case.

Kent

From kent37 at tds.net  Wed Mar  7 04:09:01 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 06 Mar 2007 22:09:01 -0500
Subject: [Tutor] Yet another list comprehension question
In-Reply-To: <45E97C8B.1060205@tds.net>
References: <288A3B43F7B2224D9C8441C9FC5D6A02012E34B1@EXCHMAIL01.corp.medplus.com>	<es9hcb$34q$1@sea.gmane.org>
	<45E97C8B.1060205@tds.net>
Message-ID: <45EE2CCD.6010502@tds.net>

Kent Johnson wrote:
> This is a popular question. It comes up frequently on comp.lang.python 
> and there are many recipes in the online cookbook.

Here is a good starting point if you want to see a variety of ways to 
uniquify (?) sequences:
http://tinyurl.com/3cqnj5

Make sure you look at the referenced recipe and the recipes it references...

Like I said, this is a popular problem :-)

Kent

From rdm at rcblue.com  Wed Mar  7 07:18:55 2007
From: rdm at rcblue.com (Dick Moores)
Date: Tue, 06 Mar 2007 22:18:55 -0800
Subject: [Tutor] path to use for setting the environment variable
 PYTHONDOCS?
In-Reply-To: <eskqjg$1kb$1@sea.gmane.org>
References: <20070306214206.B0E9F1E400E@bag.python.org>
	<eskqjg$1kb$1@sea.gmane.org>
Message-ID: <20070307061859.D09801E4003@bag.python.org>

At 02:41 PM 3/6/2007, Alan Gauld wrote:

>"Dick Moores" <rdm at rcblue.com> wrote
>
> > Sorry, topic and keyword documentation is not available because the
> > Python
> > HTML documentation files could not be found.  If you have installed
> > them,
> > please set the environment variable PYTHONDOCS to indicate their
> > location.
> > ========================================
> >
> > I have Python 2.5. Where are the HTML documentation files?
>
>No idea, but I suspect the answer will be platform specific.
>Which platform are you using?

Sorry, Win XP.

Dick


From danielle.davout at gmail.com  Wed Mar  7 10:38:29 2007
From: danielle.davout at gmail.com (danielle davout)
Date: Wed, 7 Mar 2007 10:38:29 +0100
Subject: [Tutor] trouble understanding the python environment in OSX
In-Reply-To: <781164cc0703030550i509e79e5waa2f2c3a4950faad@mail.gmail.com>
References: <781164cc0703030550i509e79e5waa2f2c3a4950faad@mail.gmail.com>
Message-ID: <1364309c0703070138qe29da82l2d06f78b5f032c1a@mail.gmail.com>

probably it is not the same issue but ...
I've got a problem with BeautifulSoup that I've never encounter before
( I've got a new computer and a brand new installation Python 2.5
(r25:51908, Sep, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 )

When I run BeautifulSoupTests.py ( If I am not mistaken, the
BeautifulSoup installer also run this test and it's why I think that
Clay's Unicode problem is somehow related ..)

I obtain the following message :
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright Microsoft Corp.

C:\programmes\python25\Lib\site-packages>BeautifulSoupTests.py
.................................C:\programmes\python25\Lib\site-packages\Beauti
fulSoup.py:1654: UnicodeWarning: Unicode equal comparison failed to convert both
 arguments to Unicode - interpreting them as being unequal
 elif data[:3] == '\xef\xbb\xbf':
C:\programmes\python25\Lib\site-packages\BeautifulSoup.py:1657: UnicodeWarning:
Unicode equal comparison failed to convert both arguments to Unicode - interpret
ing them as being unequal
 elif data[:4] == '\x00\x00\xfe\xff':
C:\programmes\python25\Lib\site-packages\BeautifulSoup.py:1660: UnicodeWarning:
Unicode equal comparison failed to convert both arguments to Unicode - interpret
ing them as being unequal
 elif data[:4] == '\xff\xfe\x00\x00':
.......F...........
======================================================================
FAIL: testQuotedAttributeValues (__main__.QuoteMeOnThat)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "C:\programmes\python25\Lib\site-packages\BeautifulSoupTests.py", line 38
2, in testQuotedAttributeValues
   '<this is="r&#101;ally messed up &amp; stuff"></this>')
 File "C:\programmes\python25\Lib\site-packages\BeautifulSoupTests.py", line 19
, in assertSoupEquals
   self.assertEqual(str(c(toParse, convertEntities=convertEntities)), rep)
 File "C:\programmes\python25\Lib\site-packages\unittest.py", line 273, in fail
UnlessEqual
   raise self.failureException, (msg or '%s != %s' % (first, second))
AssertionError: <this is="really messed up &amp; stuff"></this> != <this is="r&#
101;ally messed up &amp; stuff"></this>
----------------------------------------------------------------------
Ran 52 tests in 0.300s

FAILED (failures=1)

but I am not sure that this failure come  from a Python installation problem
as a matter of fact when I installed Emule, I did receive a strange warning
emule has detected that your current code page "1252 (ANSI-Latin I )"
is not the same as your system's code page "1252 (ANSI-Latin I )". For
converting non-Unicode data to Unicode, you need to specify which code
page to use

emule's code contains
(http://www.koders.com/cpp/fid558EFC295DED6419B3F3DEA41F94A2BAFE2470DE.aspx)
#ifdef _UNICODE
	if (theApp.GetProfileInt(_T("eMule"), _T("SetLanguageACP"), 0) != 0)
		return true;
	int iSetSysACP = theApp.GetProfileInt(_T("eMule"), _T("SetSystemACP"), -1);
	if (iSetSysACP != -1)
		return true;
	iSetSysACP = 0;

	LCID lcidSystem = GetSystemDefaultLCID();	// Installation, or altered
by user in control panel (WinXP)
	LCID lcidUser = GetUserDefaultLCID();		// Installation, or altered by
user in control panel (WinXP)

	// get the ANSI codepage which is to be used for all non-Unicode conversions.
	LANGID lidSystem = LANGIDFROMLCID(lcidSystem);

	// get user's sorting preferences
	//UINT uSortIdUser = SORTIDFROMLCID(lcidUser);
	//UINT uSortVerUser = SORTVERSIONFROMLCID(lcidUser);
	// we can't use the same sorting paramters for 2 different Languages..
	UINT uSortIdUser = SORT_DEFAULT;
	UINT uSortVerUser = 0;

	// create a thread locale which gives full backward compability for
users which had run ANSI emule on
	// a system where the system's code page did not match the user's language..
	LCID lcid = MAKESORTLCID(lidSystem, uSortIdUser, uSortVerUser);
	LCID lcidThread = GetThreadLocale();
	if (lcidThread != lcid)
	{
		CString str =
			_T("eMule has detected that your system's codepage is not the same
as eMule's current codepage. Do you want eMule to use your system's
codepage for converting non-Unicode data to Unicode?\r\n")
			_T("\r\n")
			_T("If you want eMule to use your system's codepage for converting
non-Unicode data, click 'Yes'. (This will give you more backward
compatibility when reading older *.met files created with non-Unicode
eMule versions.)\r\n")
			_T("\r\n")
			_T("If you want eMule to use the current codepage for converting
non-Unicode data, click 'No'. (If you are using eMule the first time
or if you don't care about this issue at all, chose this option. This
is recommended.)\r\n")
			_T("\r\n")
			_T("If you want to cancel and create backup of all your config
files or visit our forum to learn more about this issue, click
'Cancel'.\r\n");
		int iAnswer = AfxMessageBox(str, MB_ICONSTOP | MB_YESNOCANCEL |
MB_DEFBUTTON2);
		if (iAnswer == IDCANCEL)
			return false;
		if (iAnswer == IDYES)
			iSetSysACP = 1;
	}
	theApp.WriteProfileInt(_T("eMule"), _T("SetSystemACP"), iSetSysACP);
#endif

My regional settings is French
But in the "Regional and Languages Options" panel (advanced tab), I could read

Language for non-Unicode programs
this system setting enables non-Unicode programs to display menus and
dialogs in their native language. It does not affect Unicode programs,
but it does apply to all users of this computer
Select a language to match the language version of the non-Unicode
programs you want to use: ...

it was fixed by default to English(United States)
I changed to French(France) and after the necessary reboot, I've no
more warning from Emule but the problem with BeautifulSoup remains
my active code page have changed from 437 to 850 Multilingual (Latin
I) (as told by DOS command line chcp)
I try :
import locale
loc = locale.getlocale(locale.LC_ALL)
I get  (None, None) !
I run the test code: (Localization - set to default on Windows:
http://www.mail-archive.com/python-list at python.org/msg118811.html)

import locale
# Get default
print locale.getdefaultlocale('LANG')
# Get actual
print locale.getlocale(locale.LC_ALL)
# Get default to "loc"
loc, enc = locale.getdefaultlocale('LANG')
try:
    # Try to set
    locale.setlocale(locale.LC_ALL, loc)
except Exception, msg:
    # An error
    print msg
# Get actual
print locale.getlocale(locale.LC_ALL)
# Set manually
locale.setlocale(locale.LC_ALL, "HU")
# Get the actual locale
print locale.getlocale(locale.LC_ALL)
print locale.getdefaultlocale('LANG')

and get
>>> ('fr_FR', 'cp1252')
(None, None)
unsupported locale setting
(None, None)
('fr_FR', 'cp1252')
('fr_FR', 'cp1252')
==================
>>> sys.getfilesystemencoding()
'mbcs'
>>> sys.getdefaultencoding()
'ascii'
==================
I run autotest.py : I've got one test failure reported (test_uuid with a
    WARNING: uuid.getnode is unreliable on many platforms.)
but a "failure" was not reported at the end of the execution :
test_unicode_file
C:\programmes\python25\lib\test\test_unicode_file.py:103:
UnicodeWarning: Unicode equal comparison failed to convert both
arguments to Unicode - interpreting them as being unequal
  filename1==filename2
C:\programmes\python25\lib\shutil.py:36: UnicodeWarning: Unicode equal
comparison failed to convert both arguments to Unicode - interpreting
them as being unequal
  os.path.normcase(os.path.abspath(dst)))

one thing that's clear in all this is that I badly need help !
thanks






>>> ('fr_FR', 'cp1252')
(None, None)
unsupported locale setting
(None, None)
('fr_FR', 'cp1252')
('fr_FR', 'cp1252')
2007/3/3, Kent Johnson <kent37 at tds.net>:
- Afficher le texte des messages pr?c?dents -
> Clay Wiedemann wrote:
>
> > I am running the latest OSX (10.4.8) and know a little about moving
> > about in the terminal. But the world of paths, etc. has me a little
> > confused. And now it is getting in my way. I was wondering if I could
> > get a little help with some things.
> >
> > - Can anyone point me to a well-regarded and pithy tutorial regarding
> > the UNIX underpinnings of OSX, especially anything that would help
> > with Python. (e.g., I can navigate to Python.framework and versions
> > but see 2.5 and Current, which confuses me since 2.5 is the current
> > version.) I would love to know what the structure of the Python
> > installation means.
>
> Current is an alias for 2.5, which is the current install.
> >
> > - I am having trouble installing the BeautifulSoup package. The
> > installer stumbles on a unicode issue (that the Soup developer says is
> > a problem with my Python installation) -- so what is the best way to
> > manually install this? And does the 2.5 / Current divide matter?
>
> What is the error you get in the installer?
>
> The installer is not really needed in this case. You should be able to
> just download the single file and put it in
> .../Current/lib/python2.5/site-packages
>
> Kent
> >
> >
> >
> > Thanks in advance for any help with these basic issues.
> >
> > Good morning from Brooklyn,
> > Clay
> >
> >
> > * Any experience with coding webpages is not helping here
> >
> >
> >
> > - - - - - - -
> >
> > Clay S. Wiedemann
> >
> > aim: khlav
> > wii:
> > twitter: seastokes
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


2007/3/3, Clay Wiedemann <clay.wiedemann at gmail.com>:
> Hi,
>
> I am not only new to Python, but new to programming in an environment
> like this, where knowing a little of how the underpinning work is
> essential.*
>
> I am running the latest OSX (10.4.8) and know a little about moving
> about in the terminal. But the world of paths, etc. has me a little
> confused. And now it is getting in my way. I was wondering if I could
> get a little help with some things.
>
> - Can anyone point me to a well-regarded and pithy tutorial regarding
> the UNIX underpinnings of OSX, especially anything that would help
> with Python. (e.g., I can navigate to Python.framework and versions
> but see 2.5 and Current, which confuses me since 2.5 is the current
> version.) I would love to know what the structure of the Python
> installation means.
>
> - I am having trouble installing the BeautifulSoup package. The
> installer stumbles on a unicode issue (that the Soup developer says is
> a problem with my Python installation) -- so what is the best way to
> manually install this? And does the 2.5 / Current divide matter?
>
>
>
> Thanks in advance for any help with these basic issues.
>
> Good morning from Brooklyn,
> Clay
>
>
> * Any experience with coding webpages is not helping here
>
>
>
> - - - - - - -
>
> Clay S. Wiedemann
>
> aim: khlav
> wii:
> twitter: seastokes
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From kent37 at tds.net  Wed Mar  7 12:15:57 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 07 Mar 2007 06:15:57 -0500
Subject: [Tutor] path to use for setting the environment variable
	PYTHONDOCS?
In-Reply-To: <20070307061859.D09801E4003@bag.python.org>
References: <20070306214206.B0E9F1E400E@bag.python.org>	<eskqjg$1kb$1@sea.gmane.org>
	<20070307061859.D09801E4003@bag.python.org>
Message-ID: <45EE9EED.7090201@tds.net>

Dick Moores wrote:
> At 02:41 PM 3/6/2007, Alan Gauld wrote:
> 
>> "Dick Moores" <rdm at rcblue.com> wrote
>>
>>> Sorry, topic and keyword documentation is not available because the
>>> Python
>>> HTML documentation files could not be found.  If you have installed
>>> them,
>>> please set the environment variable PYTHONDOCS to indicate their
>>> location.
>>> ========================================
>>>
>>> I have Python 2.5. Where are the HTML documentation files?
>> No idea, but I suspect the answer will be platform specific.
>> Which platform are you using?
> 
> Sorry, Win XP.

I don't think the Windows installer for Python includes the HTML docs. 
You can download them from here:
http://docs.python.org/download.html

Kent

From rdm at rcblue.com  Wed Mar  7 14:16:29 2007
From: rdm at rcblue.com (Dick Moores)
Date: Wed, 07 Mar 2007 05:16:29 -0800
Subject: [Tutor] path to use for setting the environment variable
 PYTHONDOCS?
In-Reply-To: <45EE9EED.7090201@tds.net>
References: <20070306214206.B0E9F1E400E@bag.python.org>
	<eskqjg$1kb$1@sea.gmane.org>
	<20070307061859.D09801E4003@bag.python.org>
	<45EE9EED.7090201@tds.net>
Message-ID: <20070307131634.452711E4003@bag.python.org>

At 03:15 AM 3/7/2007, Kent Johnson wrote:
>Dick Moores wrote:
> > At 02:41 PM 3/6/2007, Alan Gauld wrote:
> >
> >> "Dick Moores" <rdm at rcblue.com> wrote
> >>
> >>> Sorry, topic and keyword documentation is not available because the
> >>> Python
> >>> HTML documentation files could not be found.  If you have installed
> >>> them,
> >>> please set the environment variable PYTHONDOCS to indicate their
> >>> location.
> >>> ========================================
> >>>
> >>> I have Python 2.5. Where are the HTML documentation files?
> >> No idea, but I suspect the answer will be platform specific.
> >> Which platform are you using?
> >
> > Sorry, Win XP.
>
>I don't think the Windows installer for Python includes the HTML docs.
>You can download them from here:
>http://docs.python.org/download.html

Thanks, Kent. Got 'em and installed 'em.

Dick



From kent37 at tds.net  Wed Mar  7 14:56:09 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 07 Mar 2007 08:56:09 -0500
Subject: [Tutor] BeautifulSoup and Python 2.5
In-Reply-To: <1364309c0703070138qe29da82l2d06f78b5f032c1a@mail.gmail.com>
References: <781164cc0703030550i509e79e5waa2f2c3a4950faad@mail.gmail.com>
	<1364309c0703070138qe29da82l2d06f78b5f032c1a@mail.gmail.com>
Message-ID: <45EEC479.100@tds.net>

This seems to be a problem with BeautifulSoup and Python 2.5. I spent 
some time looking at it this morning and tracked down one problem. Below 
is the email I sent to the BeautifulSoup maintainer.

I doubt that either of these problems will actually be a problem in 
practice. I suggest you install it by copying the .py file to 
site-packages and go ahead and use it.

Kent

==========================================================

Hi,

BeautifulSoup has a few problems with Python 2.5. Running the tests 
gives this output:

................................./Users/kent/Desktop/Downloads/BeautifulSoup-3.0.3/BeautifulSoup.py:1654: 
UnicodeWarning: Unicode equal comparison failed to convert both 
arguments to Unicode - interpreting them as being unequal
   elif data[:3] == '\xef\xbb\xbf':
/Users/kent/Desktop/Downloads/BeautifulSoup-3.0.3/BeautifulSoup.py:1657: 
UnicodeWarning: Unicode equal comparison failed to convert both 
arguments to Unicode - interpreting them as being unequal
   elif data[:4] == '\x00\x00\xfe\xff':
/Users/kent/Desktop/Downloads/BeautifulSoup-3.0.3/BeautifulSoup.py:1660: 
UnicodeWarning: Unicode equal comparison failed to convert both 
arguments to Unicode - interpreting them as being unequal
   elif data[:4] == '\xff\xfe\x00\x00':
.......F...........
======================================================================
FAIL: testQuotedAttributeValues (__main__.QuoteMeOnThat)
----------------------------------------------------------------------
Traceback (most recent call last):
   File "BeautifulSoupTests.py", line 382, in testQuotedAttributeValues
     '<this is="r&#101;ally messed up &amp; stuff"></this>')
   File "BeautifulSoupTests.py", line 19, in assertSoupEquals
     self.assertEqual(str(c(toParse, convertEntities=convertEntities)), rep)
AssertionError: '<this is="really messed up &amp; stuff"></this>' != 
'<this is="r&#101;ally messed up &amp; stuff"></this>'

----------------------------------------------------------------------
Ran 52 tests in 0.208s

FAILED (failures=1)


The UnicodeWarnings seem to be caused by a change in how Python handles 
mixed string comparisons. In Python 2.4, the comparison
   u'' == '\xef\xbb\xbf'
raises
   UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 
0: ordinal not in range(128)

In Python 2.5, the same comparison prints a warning but doesn't raise an 
exception. For more information about this change, see the section 
starting "A new warning, UnicodeWarning," on this page:
http://docs.python.org/whatsnew/other-lang.html

The affected code is in UnicodeDammit._toUnicode(). When BeautifulSoup() 
is called with no text data, as happens a few times in the test suite, 
_toUnicode() is called with an empty unicode string and triggers this 
warning.

One way to fix this is to have UnicodeDammit.__init__() explicitly check 
for an empty string and just return u"". Here is a suggested rewrite of 
the initial portion of UnicodeDammit.__init__():
     def __init__(self, markup, overrideEncodings=[],
                  smartQuotesTo='xml'):
         self.markup, documentEncoding, sniffedEncoding = \
                      self._detectEncoding(markup)
         self.smartQuotesTo = smartQuotesTo
         self.triedEncodings = []
         if markup=="" or isinstance(markup, unicode):
             self.originalEncoding = None
             self.unicode = unicode(markup)
             return

Note that I have also changed the way this works if markup is already 
unicode; the current implementation is incorrect, it returns a value 
which is not allowed in __init__().


I don't know enough about the way BeautifulSoup works to figure out the 
second one...

Best regards,
Kent


From clay.wiedemann at gmail.com  Wed Mar  7 15:59:21 2007
From: clay.wiedemann at gmail.com (Clay Wiedemann)
Date: Wed, 7 Mar 2007 09:59:21 -0500
Subject: [Tutor] trouble with objects, instances, type,
	and None in BeautifulSoup (and in general?)
Message-ID: <781164cc0703070659j2e305501s613fb874ba344a3@mail.gmail.com>

Still learning, please bear with me if my lingo is a little off. But I
think I have a better handle on my problem.

My objective:
1. get a starting point on a web page, walk down the page until
hitting an HR tag
2. Along the way, test for certain markers that allow me to get
various strings and compile them. For example, the name of a speaker
always appear within a B tag. Please don't help me with this one . . .
(yet)

My approach:
- get the series of starting points on a page then use a "for in" loop
- within that loop (and here is where the trouble occurs) look for an
HR in the .name of the current node. at that point go to the next
node.

My trouble:
- the .name and .string methods trip me up:
--- .name can flunk when a Soup returns a NavigableString
--- .string can return None

I've tried "do while" and even recursion and various conditionals but
keep messing up. So if anyone can show me what is wrong with my code
and/or my approach, that would be great. Maybe a simple type
conversion is needed somewhere?
Would love help with this part and then try objective #2 on my own.

Here's some code showing the recursion + ugly conditionals attempt:

- - - - - - -

def findName(start_point):
	"""
	unnecessary use of recursion? perhaps.
	moves down HTML try returning a name
	only when it exists.
	written to avoid NavigableObject.
	"""
	
	print "------- running findName -------"
	if start_point.name:
		if start_point.name == "None":
			print "You got None, baby!"
			nextNode = start_point.next
			print nextNode
			findName(nextNode)
		else:
			print "got a name?"
			return start_point.name
	else:
		print "not a name"
		print "going to next node"
		nextNode = start_point.next
		findName(nextNode)


quotations = quotepage.findAll('a', attrs = {'name' : re.compile("^qt")})


for q in quotations:
	"""
	testing for .next since current position has a name
	I need a failure to challenge the function
	"""
	position = q.next
	my_nextname = findName(position)
	print my_nextname

- - - - - - -

Thanks for any help!
- Clay

From steve at maguire-family.net  Wed Mar  7 16:33:42 2007
From: steve at maguire-family.net (Steve Maguire)
Date: Wed, 7 Mar 2007 09:33:42 -0600
Subject: [Tutor] Printing labels
Message-ID: <cadaed980703070733s554bb7bahc93d1f98b3b44fca@mail.gmail.com>

I am a Python beginner.  For my first task I wanted to fix a program that I
originally wrote in Excel with VBA.  I want to create a mySQL database
holding my DVD collection, edit it in Python, and print labels for the cases
with an index for filing and a catalog of all the titles their indices.

To print the labels the way I want, I will need extended control over the
printer:  positioning the printer precisely and changing fonts, colors, and
background colors.  Is there a public python library that could give me this
level of control?

Thanks
Steve
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070307/e9189ff3/attachment.html 

From mail at timgolden.me.uk  Wed Mar  7 16:48:20 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Wed, 07 Mar 2007 15:48:20 +0000
Subject: [Tutor] Printing labels
In-Reply-To: <cadaed980703070733s554bb7bahc93d1f98b3b44fca@mail.gmail.com>
References: <cadaed980703070733s554bb7bahc93d1f98b3b44fca@mail.gmail.com>
Message-ID: <45EEDEC4.8090002@timgolden.me.uk>

Steve Maguire wrote:
> I am a Python beginner.  For my first task I wanted to fix a program that I
> originally wrote in Excel with VBA.  I want to create a mySQL database
> holding my DVD collection, edit it in Python, and print labels for the 
> cases
> with an index for filing and a catalog of all the titles their indices.
> 
> To print the labels the way I want, I will need extended control over the
> printer:  positioning the printer precisely and changing fonts, colors, and
> background colors.  Is there a public python library that could give me 
> this
> level of control?

Best bet is probably using Reportlab (http://reportlab.org) to generate
PDF. Their platypus layout scheme is very flexible, and you may even
find someone's already done labels as an example.

TJG

From jeffpeery at yahoo.com  Wed Mar  7 18:15:17 2007
From: jeffpeery at yahoo.com (Jeff Peery)
Date: Wed, 7 Mar 2007 09:15:17 -0800 (PST)
Subject: [Tutor] recommendation for good OO book?
Message-ID: <488373.75921.qm@web43135.mail.sp1.yahoo.com>

Hello, I've been using python for a few years now and I really like it. Although i am beginning to realize I really don't utilize this object oriented stuff in a good way. Does anyone have a favorite book regarding the basics/intro to object oriented programming, how to write good OO code??

thanks,
Jeff

 
---------------------------------
Don't get soaked.  Take a quick peek at the forecast 
 with theYahoo! Search weather shortcut.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070307/29e92e08/attachment.htm 

From Mike.Hansen at atmel.com  Wed Mar  7 18:25:43 2007
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Wed, 7 Mar 2007 10:25:43 -0700
Subject: [Tutor] recommendation for good OO book?
References: <488373.75921.qm@web43135.mail.sp1.yahoo.com>
Message-ID: <57B026980605A64F9B23484C5659E32E637BEE@poccso.US.ad.atmel.com>

 

> -----Original Message-----
> From: tutor-bounces+mike.hansen=atmel.com at python.org 
> [mailto:tutor-bounces+mike.hansen=atmel.com at python.org] On 
> Behalf Of Jeff Peery
> Sent: Wednesday, March 07, 2007 10:15 AM
> To: tutor at python.org
> Subject: [Tutor] recommendation for good OO book?
> 
> Hello, I've been using python for a few years now and I 
> really like it. Although i am beginning to realize I really 
> don't utilize this object oriented stuff in a good way. Does 
> anyone have a favorite book regarding the basics/intro to 
> object oriented programming, how to write good OO code??
> 
> thanks,
> Jeff
> 

I liked The Object Oriented Thought Process. It uses Java and C#(I
think) as examples. I then reread the chapters in Learning Python on OO
to get a better understanding of the Python way of doing it.

Mike


From mjeptcer at gmail.com  Wed Mar  7 18:33:46 2007
From: mjeptcer at gmail.com (mastjeptor regli)
Date: Thu, 8 Mar 2007 01:33:46 +0800
Subject: [Tutor] help:find a string in a text and replace it with a another
	string
Message-ID: <c4d9f550703070933u755afc9bgcdceab90ae44cc27@mail.gmail.com>

Hi,folks.
     At first ,I have a question that I want to ask for help,it is how can I
search a specific string in a text (such a in a word document) and replace
it with another string?
     Second,if the text is changed dynamicly,can I use a variable string(has
been assigned a string) to search in the text and replace it with another
variable string.for example, *Regex Substitution:* s/email/e-mail ,if  the
string of "email" and "e-mail" are both changed from time to time,can we
apply
variable string (which has been assigned a value of string type) instead of
constant string of "email" and "e-mail" to construct a regex substitution
expression ?
      Please reply with experience in using  regular expression or python
library functions to find and replace a string in a text to help me.   Thank
you for your attention.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070308/df127917/attachment.html 

From Mike.Hansen at atmel.com  Wed Mar  7 18:42:54 2007
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Wed, 7 Mar 2007 10:42:54 -0700
Subject: [Tutor] help:find a string in a text and replace it with a
	anotherstring
References: <c4d9f550703070933u755afc9bgcdceab90ae44cc27@mail.gmail.com>
Message-ID: <57B026980605A64F9B23484C5659E32E637BF7@poccso.US.ad.atmel.com>

 

> -----Original Message-----
> From: tutor-bounces at python.org 
> [mailto:tutor-bounces at python.org] On Behalf Of mastjeptor regli
> Sent: Wednesday, March 07, 2007 10:34 AM
> To: tutor at python.org
> Subject: [Tutor] help:find a string in a text and replace it 
> with a anotherstring
> 
> Hi,folks.
>      At first ,I have a question that I want to ask for 
> help,it is how can I search a specific string in a text (such 
> a in a word document) and replace it with another string?
>      Second,if the text is changed dynamicly,can I use a 
> variable string(has been assigned a string) to search in the 
> text and replace it with another variable string.for example, 
> Regex Substitution: s/email/e-mail ,if  the string of "email" 
> and "e-mail" are both changed from time to time,can we apply
> variable string (which has been assigned a value of string 
> type) instead of constant string of "email" and "e-mail" to 
> construct a regex substitution expression ?
>       Please reply with experience in using  regular 
> expression or python library functions to find and replace a 
> string in a text to help me.   Thank you for your attention.
> 

You might not need regular expressions. You can use replace method.

In [11]: x = "Bozo"

In [12]: z = "Bozo The Clown"

In [13]: y = "Krusty"

In [14]: z.replace(x,y)
Out[14]: 'Krusty The Clown'

You could probably populate a dictionary of the words you want to
replace and their replacements. Then use the replace method on the
strings.

Note that Word documents are binary gibberish, so you'd need to use
win32 python windows stuff making this more complicated. On plain text
files, it wouldn't be too bad.

Mike 

From steve at maguire-family.net  Wed Mar  7 19:37:42 2007
From: steve at maguire-family.net (Steve Maguire)
Date: Wed, 7 Mar 2007 12:37:42 -0600
Subject: [Tutor] Tutor Digest, Vol 37, Issue 22
In-Reply-To: <mailman.15319.1173288830.32030.tutor@python.org>
References: <mailman.15319.1173288830.32030.tutor@python.org>
Message-ID: <cadaed980703071037t39ee07a9td3b065230295b988@mail.gmail.com>

>
>
> ---------- Forwarded message ----------
> From: Tim Golden <mail at timgolden.me.uk>
> To:
> Date: Wed, 07 Mar 2007 15:48:20 +0000
> Subject: Re: [Tutor] Printing labels
> Steve Maguire wrote:
> > I am a Python beginner.  For my first task I wanted to fix a program
> that I
> > originally wrote in Excel with VBA.  I want to create a mySQL database
> > holding my DVD collection, edit it in Python, and print labels for the
> > cases
> > with an index for filing and a catalog of all the titles their indices.
> >
> > To print the labels the way I want, I will need extended control over
> the
> > printer:  positioning the printer precisely and changing fonts, colors,
> and
> > background colors.  Is there a public python library that could give me
> > this
> > level of control?
>
> Best bet is probably using Reportlab (http://reportlab.org) to generate
> PDF. Their platypus layout scheme is very flexible, and you may even
> find someone's already done labels as an example.
>
> TJG
>
>
Thanks Tim.  I'll check that out right away.
Steve
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070307/188e4078/attachment.html 

From python at wardroper.org  Thu Mar  8 00:55:53 2007
From: python at wardroper.org (Alan Wardroper)
Date: Wed, 07 Mar 2007 15:55:53 -0800
Subject: [Tutor] Passing a list, dict or tuple to MySQLdb?
Message-ID: <45EF5109.3000909@wardroper.org>

I'm parsing some data to feed to a MySQL database, and would like to be
able to pass in a list (a dictionary or a series of tuples) in the
cursor.execute() or cursor.executemany() statement, but everything I've
tried raises errors. I'm sure it's  a matter of correct formatting the
list as a sequence...

CODE:
import sys, MySQLdb
conn = MySQLdb.connect (host = "localhost", user = "user", psswd =
"xxxx" db = "testdb")
cursor = conn.cursor()

infile = open(sys.argv[2], 'r')
list_of_tuples = []
for line in infile:
    tuple = (line.split()[0], line.split()[1])
    list_of_tuples.append(tuple)

cursor.executemany("UPDATE LOW_PRIORITY sometable SET field1 = %s WHERE
field2 = %s", (list_of_tuples)

"""
example data:
ID123445   somestring1
ID223445   somestring2
ID323445   somestring3
ID423445   somestring4
ID523445   somestring5
"""

Naively, I thought this would result in an execute statement like:
cursor.executemany("UPDATE LOW_PRIORITY sometable SET field1 = %s WHERE
field2 = %s", ('ID123445', 'somestring1'), ('ID223445', 'somestring2'),
('ID323445', 'somestring3'), ('ID423445', 'somestring4'), ('ID523445',
'somestring5'))

But what I get are  bunch of errors,  last of which is:
TypeError: not ll arguments converted during string formatting

Or pass in a list of values to use in a SELECT...WHERE...IN (list)
statement:

ids_to_include = ['ID123445', 'ID223445', 'ID323445']
cursor.execute("UPDATE  sometable SET field1 = 'some standard value'
WHERE field2 IN (%s)", (ids_to_include))


I also tried another similar thing, where I tried to pass in the name of
one of the fields as a dictionary key with the value as the
corresponding value, but it also didn't work--it looked like the key was
bounded in quotes before passing to MySQL, so the db didn't recognise
the fieldname:

for key in dict.keys():
    cursor.execute("INSERT INTO sometable (%s) values (%s)", (key,
dict[key]))


Any pointers?

Thanks


From bill at celestial.net  Thu Mar  8 01:05:27 2007
From: bill at celestial.net (Bill Campbell)
Date: Wed, 7 Mar 2007 16:05:27 -0800
Subject: [Tutor] Passing a list, dict or tuple to MySQLdb?
In-Reply-To: <45EF5109.3000909@wardroper.org>
References: <45EF5109.3000909@wardroper.org>
Message-ID: <20070308000527.GA19529@ayn.mi.celestial.com>

On Wed, Mar 07, 2007, Alan Wardroper wrote:
>I'm parsing some data to feed to a MySQL database, and would like to be
>able to pass in a list (a dictionary or a series of tuples) in the
>cursor.execute() or cursor.executemany() statement, but everything I've
>tried raises errors. I'm sure it's  a matter of correct formatting the
>list as a sequence...
>
>CODE:
>import sys, MySQLdb
>conn = MySQLdb.connect (host = "localhost", user = "user", psswd =
>"xxxx" db = "testdb")
>cursor = conn.cursor()
>
>infile = open(sys.argv[2], 'r')
>list_of_tuples = []
>for line in infile:
>    tuple = (line.split()[0], line.split()[1])
>    list_of_tuples.append(tuple)
>
>cursor.executemany("UPDATE LOW_PRIORITY sometable SET field1 = %s WHERE
>field2 = %s", (list_of_tuples)

I think what you want is ...(*list_of_tuples) similar to the syntax used
when calling functions with position arguments from a list.

Bill
--
INTERNET:   bill at Celestial.COM  Bill Campbell; Celestial Software LLC
URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
FAX:            (206) 232-9186  Mercer Island, WA 98040-0820; (206) 236-1676

Few skills are so well rewarded as the ability to convince parasites that
they are victims. -- Thomas Sowell

From tsila.hassine at gmail.com  Thu Mar  8 01:47:21 2007
From: tsila.hassine at gmail.com (Tsila Hassine)
Date: Thu, 8 Mar 2007 01:47:21 +0100
Subject: [Tutor] ssl error when trying to connect to https (also using
	timeoutsocket.py)
Message-ID: <da5291e90703071647p2bb9ec6bx392edc2e44d0b9b7@mail.gmail.com>

Hello all,

in my code i am importing timeoutsocket in order to set the time out of a
connection. When i try to acces an https site I get the error:

"TypeError: ssl() argument 1 must be _socket.socket, not _socketobject"

when I am not using the timeoutsocket module, I don't have any problems. how
can i solve this ? (I still need to be able to set the timeout of a
connection...)

thanks,
Tsila
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070308/7f9fd01d/attachment.html 

From glen20web at yahoo.com.ph  Thu Mar  8 10:40:38 2007
From: glen20web at yahoo.com.ph (Glenfiddich apayart)
Date: Thu, 8 Mar 2007 01:40:38 -0800 (PST)
Subject: [Tutor] about  __std__ zip file
Message-ID: <792981.89099.qm@web56610.mail.re3.yahoo.com>

hi, 

This is my first day and first time i knew about python. i know now how to handle the python GUI. i just have a small question about the __std zip file. i've read about it on danny website. this is the link .Where should i extract the file?

im thinking if i would put it on my  Lib folder.. hoping for your reply. thanks!

brgds,
glen20web

 		
---------------------------------
 Tired of spam? Yahoo! Mail has the best spam protection around
 http://ph.mail.yahoo.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070308/ed2a062f/attachment.htm 

From kent37 at tds.net  Thu Mar  8 11:58:31 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 08 Mar 2007 05:58:31 -0500
Subject: [Tutor] Roman Numeral to Digital
In-Reply-To: <20070308030702.qm4iwqdwcz4g0css@webmail.frontiernet.net>
References: <20070308030702.qm4iwqdwcz4g0css@webmail.frontiernet.net>
Message-ID: <45EFEC57.4000803@tds.net>

Hi Alan,

I am forwarding your question to tutor at python.org which is the correct 
address for the list. tutor-owner at python.org sends questions to the 
*maintainers* of the list, not the list itself.

Kent

Alan Gilfoy wrote:
> I am learning how to program in python as a major component of my 
> school's senior project, and my most recent assignment was to write a 
> program that converts Roman numerals to digital (base-10 Arabic numerals).
> 
> Now, I was told I have to write the program myself, but I was told I was 
> allowed to ask for hints. :)
> 
> As of right now, I've written a user interface (after all, here that's a 
> simple loop-and-prompt setup leading to print statements), but I have 
> "dummy code" in the place where the conversion code needs to be.
> 
> I want to create two separate functions:
> 
> def.toRoman(digital_input)
>     print "Digital - to - Roman conversion (dummy code)"
>     roman_result = "XXX"
>     return roman_result
> 
> def.toDigital(roman_input)
>     print "Roman - to - digital conversion (dummy code)"
>     digital_result = 30
>     return digital_result
> 
> I'm going to set each of those two "inputs" by a prompt asking for what 
> the program user wants to work with.
> 
> #Such as:
> digital_input = int(raw_input("What digital (base-10) number do you wish 
> to convert to Roman numerals?))
> 
> I'm not sure how I would program Python to run the actual conversions.
> 
> PS: I'm familiar with Roman numerals, and I know how to do the 
> conversions manually.
> 
> 
> 
> 
> 
> 


From kent37 at tds.net  Thu Mar  8 12:50:17 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 08 Mar 2007 06:50:17 -0500
Subject: [Tutor] about  __std__ zip file
In-Reply-To: <792981.89099.qm@web56610.mail.re3.yahoo.com>
References: <792981.89099.qm@web56610.mail.re3.yahoo.com>
Message-ID: <45EFF879.5090705@tds.net>

Glenfiddich apayart wrote:
> hi,
> 
> This is my first day and first time i knew about python. i know now how 
> to handle the python GUI. i just have a small question about the __std 
> zip file. i've read about it on danny website. this is the link 
> <http://hkn.eecs.berkeley.edu/%7Edyoo/python/__std__/> .Where should i 
> extract the file?
> 
> im thinking if i would put it on my  Lib folder.. hoping for your reply. 
> thanks!

The normal place for add-on modules and libraries is a site-packages 
folder within the Lib folder.

Kent

From snakepit.rattlesnakes at gmail.com  Thu Mar  8 13:22:06 2007
From: snakepit.rattlesnakes at gmail.com (Joydeep Mitra)
Date: Thu, 8 Mar 2007 17:52:06 +0530
Subject: [Tutor] Best IDE for python?
Message-ID: <972566ff0703080422j53337e0fi487b22561b624156@mail.gmail.com>

Hi all,
I'm a new user of the python programming language.
I would like to know what's the best IDE for python (having all important
IDE features like debug, etc), other than IDLE.
Thanking in advance
Joy
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070308/6d4c54bc/attachment.htm 

From rabidpoobear at gmail.com  Thu Mar  8 13:57:24 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Thu, 08 Mar 2007 06:57:24 -0600
Subject: [Tutor] Best IDE for python?
In-Reply-To: <972566ff0703080422j53337e0fi487b22561b624156@mail.gmail.com>
References: <972566ff0703080422j53337e0fi487b22561b624156@mail.gmail.com>
Message-ID: <45F00834.2060107@gmail.com>

Joydeep Mitra wrote:
> Hi all,
> I'm a new user of the python programming language.
> I would like to know what's the best IDE for python (having all 
> important IDE features like debug, etc), other than IDLE.
> Thanking in advance
Did you read the Tutor FAQ you got when you signed up for the list?
FAQ stands for Frequently Asked Questions, of which yours is one.
Here is your answer.
"
What's the *best* editor/*IDE* for Python?

It's really a matter of preference. There are many features of an
editor or *IDE* such as syntax highlighting, code completion, code
folding, buffers, tabs,  ... Each editor or *IDE* has some or all of
these features, and you'll have to decide which features are important
to you.
See http://wiki.python.org/moin/PythonEditors for a list of editors.
Also http://wiki.python.org/moin/IntegratedDevelopmentEnvironments has
a list of *IDEs*.
This question is asked every few weeks on comp.lang.python so searching
the archives will yield many opinions.
"
HTH,
-Luke

From ton.vanvliet at skynet.be  Thu Mar  8 14:29:09 2007
From: ton.vanvliet at skynet.be (Ton van Vliet)
Date: Thu, 08 Mar 2007 14:29:09 +0100
Subject: [Tutor] Best IDE for python?
In-Reply-To: <972566ff0703080422j53337e0fi487b22561b624156@mail.gmail.com>
References: <972566ff0703080422j53337e0fi487b22561b624156@mail.gmail.com>
Message-ID: <vl30v2dp8i6uk97mcdi3afnui3v47gntod@4ax.com>

On Thu, 8 Mar 2007 17:52:06 +0530, you wrote:

>Hi all,
>I'm a new user of the python programming language.
>I would like to know what's the best IDE for python (having all important
>IDE features like debug, etc), other than IDLE.
>Thanking in advance
>Joy

There are some ShowMeDo videos that could get you started ->
http://blog.showmedo.com/2007/03/08/choosing-a-python-ide/

HTH,
Ton.

From bgailer at alum.rpi.edu  Thu Mar  8 15:12:58 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Thu, 08 Mar 2007 06:12:58 -0800
Subject: [Tutor] Roman Numeral to Digital
In-Reply-To: <45EFEC57.4000803@tds.net>
References: <20070308030702.qm4iwqdwcz4g0css@webmail.frontiernet.net>
	<45EFEC57.4000803@tds.net>
Message-ID: <45F019EA.6020500@alum.rpi.edu>

Kent Johnson wrote:
> Hi Alan,
>
> I am forwarding your question to tutor at python.org which is the correct 
> address for the list. tutor-owner at python.org sends questions to the 
> *maintainers* of the list, not the list itself.
>
> Kent
>
> Alan Gilfoy wrote:
>   
>> I am learning how to program in python as a major component of my 
>> school's senior project, and my most recent assignment was to write a 
>> program that converts Roman numerals to digital (base-10 Arabic numerals).
>>
>> Now, I was told I have to write the program myself, but I was told I was 
>> allowed to ask for hints. :)
>>
>> As of right now, I've written a user interface (after all, here that's a 
>> simple loop-and-prompt setup leading to print statements), but I have 
>> "dummy code" in the place where the conversion code needs to be.
>>
>> I want to create two separate functions:
>>
>> def.toRoman(digital_input)
>>     print "Digital - to - Roman conversion (dummy code)"
>>     roman_result = "XXX"
>>     return roman_result
>>
>> def.toDigital(roman_input)
>>     print "Roman - to - digital conversion (dummy code)"
>>     digital_result = 30
>>     return digital_result
>>
>> I'm going to set each of those two "inputs" by a prompt asking for what 
>> the program user wants to work with.
>>
>> #Such as:
>> digital_input = int(raw_input("What digital (base-10) number do you wish 
>> to convert to Roman numerals?))
>>
>> I'm not sure how I would program Python to run the actual conversions.
>>
>> PS: I'm familiar with Roman numerals, and I know how to do the 
>> conversions manually.
>>     
Step 1:  write down the steps you use "manually"
Step 2:  for each step ask "how do I do this in Python:

Example:
I initialize the digital value to 0
digital_result = 0

I examine each roman numeral character in turn starting at the left (or 
right?):
for rc in roman_input:

I lookup the character's decimal value
(note there are several ways to do this in Python - the "best" is a 
dictionary), an if elif else statement, ....

I add it to the digital_result

etc.

Hope that gets you started. Write all the manual steps. Make sure each 
is one simple operation. Walk thru the steps to verify that you have 
them correct.

-- 
Bob Gailer
510-978-4454


From sanelson at gmail.com  Thu Mar  8 15:40:22 2007
From: sanelson at gmail.com (Stephen Nelson-Smith)
Date: Thu, 8 Mar 2007 14:40:22 +0000
Subject: [Tutor] Parsing Word Docs
Message-ID: <b6131fdc0703080640r31765be3xf6f42a03a1cb0bfe@mail.gmail.com>

Hello all,

I have a directory containing a load of word documents, say 100 or so.
which is updated every hour.

I want a cgi script that effectively does a grep on the word docs, and
returns each doc that matches the search term.

I've had a look at doing this by looking at each binary file and
reimplementing strings(1) to capture useful info.  I've also read that
one can treat a word doc as a COM object.  Am I right in thinking that
I can't do this on python under unix?

What other ways are there?  Or is the binary parsing the way to go?

S.

From learner404 at gmail.com  Thu Mar  8 15:52:52 2007
From: learner404 at gmail.com (learner404)
Date: Thu, 8 Mar 2007 15:52:52 +0100
Subject: [Tutor] White spaces in a path (from a string variable) and
	os.popen on Windows
Message-ID: <13a83ca10703080652q176227b9iea1a6d3b7d879f40@mail.gmail.com>

Hello,

I'm getting crazy with white spaces on Windows. :(

I'm aware of the three paths gotchas on Windows well explained here:
http://www.freenetpages.co.uk/hp/alan.gauld/tutfiles.htm

But my problem is with white spaces in windows paths (very common with
"program files", "documents and settings",etc).
I precise I use os.popen because I need to read the answer from an external
command-line app that I feed with a file or folder path.

When I know exactly the path in advance I use a raw string r' ' and I add
double quotes where necessary to avoid the white spaces syndrome. But I
don't see how to do this "easily" when my path is a string variable given by
my GUI (like C:\Documents and Settings\name\Mes documents)

I've googled this problem but wasn't successful so far. I just seem to find
people who have problems with whitespaces and Python like here:
http://e-scribe.com/news/324

Can you help me to understand how to deal with white spaces in Pyhton (or
SVP point me to any URL or relevant book).  :)

For now I'm trying  to make work a minimal "hello world" example here :

The little script below shows a button (wx) to select a directory.
I print in the console the selected directory (string) and I try to recover
the result of a DOS dir command thought an os.popen.

If I select a folder without a whitespace(s) it works well. If the path has
a whitespace it doesn't (not apparent result).

Can you make this script work in all situation on Windows ? (ie whatever the
folder I select with the GUI) ?

Many, many thanks in advance. :)


# Test with popen and paths containing white spaces

import wx,os,sys

app=wx.App(redirect=False)

class GUI(wx.Frame):
    def __init__(self,parent,title):
        wx.Frame.__init__(self, parent, -1, title,size=(400,100))
        bkg=wx.Panel(self)
        dirButton=wx.Button(bkg,label="Select a directory")
        self.Bind(wx.EVT_BUTTON, self.goPath, dirButton)
    def goPath(self,evt):
        myDir=wx.DirDialog(self)
        myDir.ShowModal()
        dirPath=myDir.GetPath()
        print "GetPath result is",dirPath
        result=os.popen("dir "+dirPath).read()
        print "os.popen result is ",result

win=GUI(None,title="Test")
win.Show()

app.MainLoop()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070308/d240ce4e/attachment.htm 

From malaclypse2 at gmail.com  Thu Mar  8 16:36:56 2007
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Thu, 8 Mar 2007 10:36:56 -0500
Subject: [Tutor] White spaces in a path (from a string variable) and
	os.popen on Windows
In-Reply-To: <13a83ca10703080652q176227b9iea1a6d3b7d879f40@mail.gmail.com>
References: <13a83ca10703080652q176227b9iea1a6d3b7d879f40@mail.gmail.com>
Message-ID: <16651e80703080736o6c6a8ae5x842ec6c6a458c948@mail.gmail.com>

On 3/8/07, learner404 <learner404 at gmail.com> wrote:
> When I know exactly the path in advance I use a raw string r' ' and I add
> double quotes where necessary to avoid the white spaces syndrome. But I
> don't see how to do this "easily" when my path is a string variable given by
> my GUI (like C:\Documents and Settings\name\Mes documents)

You can just choose to always quote the directory name where it might
have spaces in it.  For instance, change this line:
>         result=os.popen("dir "+dirPath).read()
to this:
        result=os.popen('dir "%s"' % dirPath).read()

That worked fine with all the directories I threw at it.

-- 
Jerry

From agilfoy at frontiernet.net  Thu Mar  8 17:01:58 2007
From: agilfoy at frontiernet.net (Alan Gilfoy)
Date: Thu, 08 Mar 2007 16:01:58 +0000
Subject: [Tutor] Roman to digital (pseudocode)
Message-ID: <20070308160158.a365mpgvsa8s4080@webmail.frontiernet.net>

This, I heard, is more difficult than digital-to-Roman, since you have  
to "read" the subtractive cases, with a smaller numeral placed before  
a larger numeral, without simply adding all the numerals' values up

I'm going to use a raw_input prompt to ask the user which Roman  
numeral he/she wants to convert. How do I "screen" for inputs that  
have characters besides "I", "V", "X", "L", "C", "D", or "M"?

Second Python question:

I know there's a way to "find out" the name of the first item in a list
(ListName[0]), but is there a way to find out the first character of a string?

Also, is there a way to "ask" Python what characters are before and  
after the character in the string that you're asking about?

For example, usign the sample string "MCMXVII" (1917):

How would you ask Python:
"What's the 3rd character in this string?" (returns "M")
"What's before that character?" (returns "C")

Pseudocode time:

If character Y is "M":
and the character before character Y is "C",
add 900 to digital_result
and remove that "C" and that "M" from the string.
#How would you do *that*?

and the character before character Y is another "M", or if character Y  
is the first character in the string,
add 1000 to digital_result
and remove that "M" from the string.





From pthanos at gmail.com  Thu Mar  8 17:02:24 2007
From: pthanos at gmail.com (Thanos Panousis)
Date: Thu, 8 Mar 2007 17:02:24 +0100
Subject: [Tutor] building an interactive deamon
Message-ID: <4dcb3660703080802p3e5fb43fl9e76f37542e5dbe1@mail.gmail.com>

So here goes my first question to the list. I can't really describe in
precise words what I need, therefore it is difficult to google for an
answer.

I am building a system that is supposed to run as a daemon. This daemon will
of course depend on some configuration variables that are read during the
initialization of the program. It does something, sleeps for some seconds,
and so on. No, I dont want it to be a scheduled task.

How can I make a daemon that does not need to be restarted every time a
configuration is changed?
 Say a web fronted is used to make changes to some variables of the system,
like how much time it should sleep, etc. Should I make the program intercept
some signal which triggers a re-read of the config files and fills (global)
variables with fresh values? Or is there another way to do it?

As a side question, is there a more elegant way of making something a deamon
other than the ole
while True:
   do_stuff()
   sleep(some_time)

?


Thanks a lot. This language is really spoilling me: being used to all of
Python's elegance, reading Java makes my eyes hurt...:)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070308/1e913744/attachment.html 

From mail at timgolden.me.uk  Thu Mar  8 17:06:17 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Thu, 08 Mar 2007 16:06:17 +0000
Subject: [Tutor] Parsing Word Docs
In-Reply-To: <b6131fdc0703080640r31765be3xf6f42a03a1cb0bfe@mail.gmail.com>
References: <b6131fdc0703080640r31765be3xf6f42a03a1cb0bfe@mail.gmail.com>
Message-ID: <45F03479.9010705@timgolden.me.uk>

Stephen Nelson-Smith wrote:
> Hello all,
> 
> I have a directory containing a load of word documents, say 100 or so.
> which is updated every hour.
> 
> I want a cgi script that effectively does a grep on the word docs, and
> returns each doc that matches the search term.
> 
> I've had a look at doing this by looking at each binary file and
> reimplementing strings(1) to capture useful info.  I've also read that
> one can treat a word doc as a COM object.  Am I right in thinking that
> I can't do this on python under unix?
> 
> What other ways are there?  Or is the binary parsing the way to go?

Simplest thing's probably antiword (http://www.winfield.demon.nl/)
and then whatever text-scanning approach you want.

TJG

From agilfoy at frontiernet.net  Thu Mar  8 16:39:41 2007
From: agilfoy at frontiernet.net (Alan Gilfoy)
Date: Thu, 08 Mar 2007 15:39:41 +0000
Subject: [Tutor] Digital-to- Roman (pseudocode)
In-Reply-To: <45F019EA.6020500@alum.rpi.edu>
References: <20070308030702.qm4iwqdwcz4g0css@webmail.frontiernet.net>
	<45EFEC57.4000803@tds.net> <45F019EA.6020500@alum.rpi.edu>
Message-ID: <20070308153941.vjlxwnexwt80s40w@webmail.frontiernet.net>

Quoting Bob Gailer <bgailer at alum.rpi.edu>:

> Make sure each step
> is one simple operation. Walk thru the steps to verify that you have
> them correct.

Bob, your email did inspire me on how I would express the process in  
computer-processing terms.

Here's how I'd break down the steps, using "pseudocode".
I might also be askign how to convert each bit of pseudocode into actual code.

(For both, I'm going to program in "exceptions" for numbers less than  
0 or greater than 3999, which is MMMCMXCIX in Roman numerals. That is  
the highest number that can be expressed in Roman numerals using  
strings of no morer than 3 of the same letter (standard rule for Roman  
numerals), and using only the symbols I, V, X, L, C, D and M.)
I know there are ways to express a Roman numeral for 5,000 and higher,  
but I'm goign to pgram those in later.

Digital to Roman pseudocode:

1. if digital_input is greater than 1000:
subtract 1000 from it and add "M" to string roman_result
# How do you do that, add one character to the end of an existing string?
# also, how do I modify the digital_input variable (it's an integer)  
several times through the conversion process?

if digital_input is less than 1000:
is it greater than 900? If so, subtract 900 from digital_input and add  
"CM" to string roman_reuslt

is it less than 900?
If it's less than 900, but greater than 500, subtract 500, and add "D"  
to the string.

If it's less than 900, and less than 500, is it greater than 400?
If so, subtract 400 from input and add "CD" to the string.
If it isn't greater than 400, but greater than 100, subtract 100 from  
the input and add "C" to the result string.

is it less than 100?
If it is, but it's greater than 90, subtract 90 and add "XC" to the string.
if it is less than 90, but greater than 50, subtract 50, and add "L"  
to the string.

(and so on, down from 50 to 1)


From Mike.Hansen at atmel.com  Thu Mar  8 17:42:24 2007
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Thu, 8 Mar 2007 09:42:24 -0700
Subject: [Tutor] Digital-to- Roman (pseudocode)
References: <20070308030702.qm4iwqdwcz4g0css@webmail.frontiernet.net><45EFEC57.4000803@tds.net>
	<45F019EA.6020500@alum.rpi.edu>
	<20070308153941.vjlxwnexwt80s40w@webmail.frontiernet.net>
Message-ID: <57B026980605A64F9B23484C5659E32E637CEC@poccso.US.ad.atmel.com>

I think Dive Into Python has examples of digital to Roman and it might
have Roman to digital. Might be worth looking at after you've come up
with a solution.

Mike


From bgailer at alum.rpi.edu  Thu Mar  8 18:10:42 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Thu, 08 Mar 2007 09:10:42 -0800
Subject: [Tutor] Digital-to- Roman (pseudocode)
In-Reply-To: <20070308153941.vjlxwnexwt80s40w@webmail.frontiernet.net>
References: <20070308030702.qm4iwqdwcz4g0css@webmail.frontiernet.net>	<45EFEC57.4000803@tds.net>
	<45F019EA.6020500@alum.rpi.edu>
	<20070308153941.vjlxwnexwt80s40w@webmail.frontiernet.net>
Message-ID: <45F04392.6020406@alum.rpi.edu>

Alan Gilfoy wrote:
> Quoting Bob Gailer <bgailer at alum.rpi.edu>:
>
>   
>> Make sure each step
>> is one simple operation. Walk thru the steps to verify that you have
>> them correct.
>>     
>
> Bob, your email did inspire me on how I would express the process in  
> computer-processing terms.
>
> Here's how I'd break down the steps, using "pseudocode".
> I might also be askign how to convert each bit of pseudocode into actual code.
>
> (For both, I'm going to program in "exceptions" for numbers less than  
> 0 or greater than 3999, which is MMMCMXCIX in Roman numerals. That is  
> the highest number that can be expressed in Roman numerals using  
> strings of no morer than 3 of the same letter (standard rule for Roman  
> numerals), and using only the symbols I, V, X, L, C, D and M.)
> I know there are ways to express a Roman numeral for 5,000 and higher,  
> but I'm goign to pgram those in later.
>
> Digital to Roman pseudocode:
>
> 1. if digital_input is greater than 1000:
> subtract 1000 from it and add "M" to string roman_result
> # How do you do that, add one character to the end of an existing string?
>   
Start with an empty string:

roman_result = ""

To add a character at the end:

roman_result += "M" # Python shorthand for roman_result = roman_result + "M"


> # also, how do I modify the digital_input variable (it's an integer)  
>   
digital_input -= 1000
> several times through the conversion process?
>   
You will be processing the input in a loop (while or for).
> if digital_input is less than 1000:
> is it greater than 900? If so, subtract 900 from digital_input and add  
> "CM" to string roman_reuslt
>
> is it less than 900?
> If it's less than 900, but greater than 500, subtract 500, and add "D"  
> to the string.
>
> If it's less than 900, and less than 500, is it greater than 400?
> If so, subtract 400 from input and add "CD" to the string.
> If it isn't greater than 400, but greater than 100, subtract 100 from  
> the input and add "C" to the result string.
>
> is it less than 100?
> If it is, but it's greater than 90, subtract 90 and add "XC" to the string.
> if it is less than 90, but greater than 50, subtract 50, and add "L"  
> to the string.
>
> (and so on, down from 50 to 1)
>   
That looks good.

As you gain familiarity with Python you will develop ways to separate 
data from logic. I might say more about this later, but right now I'm 
about to drive north a bit.

-- 
Bob Gailer
510-978-4454


From project5 at redrival.net  Thu Mar  8 19:25:54 2007
From: project5 at redrival.net (Andrei)
Date: Thu, 8 Mar 2007 18:25:54 +0000 (UTC)
Subject: [Tutor] What/Why this Cookbook recipe?
References: <20070306190932.592D51E400D@bag.python.org>
	<eskg90$qss$1@sea.gmane.org> <45EDDFFE.4050207@gmail.com>
Message-ID: <loom.20070308T191326-500@post.gmane.org>

> > - format strings can be used to translate an application. You just give 
> > the translator your 'Name: %s' string and he gives you 'Borkbork: %s' or 
> > whatever. The translation doesn't need to be modified if you decide to 
> > make a user class and get rid of the username and userage vars.
> >   
> I don't see what you mean here.  The string in the example,
> 
> interp('Name: #{username}\nAge: #{userage}')
> 
> could be translated too.

Yep, it could. However, it exposes a few dangers that the normal format string
doesn't. Of course there are workarounds possible (like checking the
translations manually or writing a tool for doing it automatically, or having a
very good translation tool), but it's not the optimal solution.

- the translator is more prone to make an error in the translation because of
the relatively complex syntax

- the translator has the power to expose private information by substituting
other variables in there. Worst case behavior due to malevolent translation in
the case of format strings is a simple exception. 

- and then there's the problem of having to manually update who knows how many
translations whenever you decide to rename a variable

On the other hand, having the variable name in there may give the translator
useful information about the way he should translate a string, as the
translation may be influenced by what will be filled in in the blanks. It's
always a trade-off, isn't it.

Yours,

Andrei


From adam.jtm30 at gmail.com  Thu Mar  8 19:40:11 2007
From: adam.jtm30 at gmail.com (Adam Bark)
Date: Thu, 8 Mar 2007 18:40:11 +0000
Subject: [Tutor] Roman to digital (pseudocode)
In-Reply-To: <20070308160158.a365mpgvsa8s4080@webmail.frontiernet.net>
References: <20070308160158.a365mpgvsa8s4080@webmail.frontiernet.net>
Message-ID: <be4fbf920703081040i35f7fd97id55e9b3b9abbf6f3@mail.gmail.com>

On 08/03/07, Alan Gilfoy <agilfoy at frontiernet.net> wrote:
>
> This, I heard, is more difficult than digital-to-Roman, since you have
> to "read" the subtractive cases, with a smaller numeral placed before
> a larger numeral, without simply adding all the numerals' values up
>
> I'm going to use a raw_input prompt to ask the user which Roman
> numeral he/she wants to convert. How do I "screen" for inputs that
> have characters besides "I", "V", "X", "L", "C", "D", or "M"?
>
> Second Python question:
>
> I know there's a way to "find out" the name of the first item in a list
> (ListName[0]), but is there a way to find out the first character of a
> string?
>
> Also, is there a way to "ask" Python what characters are before and
> after the character in the string that you're asking about?
>
> For example, usign the sample string "MCMXVII" (1917):
>
> How would you ask Python:
> "What's the 3rd character in this string?" (returns "M")
> "What's before that character?" (returns "C")
>
> Pseudocode time:
>
> If character Y is "M":
> and the character before character Y is "C",
> add 900 to digital_result
> and remove that "C" and that "M" from the string.
> #How would you do *that*?
>
> and the character before character Y is another "M", or if character Y
> is the first character in the string,
> add 1000 to digital_result
> and remove that "M" from the string.


you can index a string just like a list:
>>> roman_numeral = "MCMXVII"
>>> roman_numeral[2]
'M'
>>> roman_numeral[2-1]
'C'

HTH
Adam
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070308/583c1dea/attachment.html 

From learner404 at gmail.com  Thu Mar  8 22:00:59 2007
From: learner404 at gmail.com (learner404)
Date: Thu, 8 Mar 2007 22:00:59 +0100
Subject: [Tutor] White spaces in a path (from a string variable) and
	os.popen on Windows
In-Reply-To: <16651e80703080736o6c6a8ae5x842ec6c6a458c948@mail.gmail.com>
References: <13a83ca10703080652q176227b9iea1a6d3b7d879f40@mail.gmail.com>
	<16651e80703080736o6c6a8ae5x842ec6c6a458c948@mail.gmail.com>
Message-ID: <13a83ca10703081300s3b91d705k3c218c75884e33e7@mail.gmail.com>

On 3/8/07, Jerry Hill <malaclypse2 at gmail.com> wrote:
>
>
> >         result=os.popen("dir "+dirPath).read()
> to this:
>         result=os.popen('dir "%s"' % dirPath).read()
>
> That worked fine with all the directories I threw at it.


Thanks a lot Jerry ! :)  I didn't think of doing it this way.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070308/f82a5397/attachment-0001.htm 

From agilfoy at frontiernet.net  Thu Mar  8 23:23:09 2007
From: agilfoy at frontiernet.net (Alan Gilfoy)
Date: Thu, 08 Mar 2007 22:23:09 +0000
Subject: [Tutor] Digital-to- Roman (pseudocode)
In-Reply-To: <45F04392.6020406@alum.rpi.edu>
References: <20070308030702.qm4iwqdwcz4g0css@webmail.frontiernet.net>
	<45EFEC57.4000803@tds.net> <45F019EA.6020500@alum.rpi.edu>
	<20070308153941.vjlxwnexwt80s40w@webmail.frontiernet.net>
	<45F04392.6020406@alum.rpi.edu>
Message-ID: <20070308222309.gg7mtnv56txj4084@webmail.frontiernet.net>

Quoting Bob Gailer <bgailer at alum.rpi.edu>:

>>
>> Digital to Roman pseudocode:
>>
>> 1. if digital_input is greater than 1000:
>> subtract 1000 from it and add "M" to string roman_result
>> # How do you do that, add one character to the end of an existing string?
>>
> Start with an empty string:
>
> roman_result = ""
>
> To add a character at the end:
>
> roman_result += "M" # Python shorthand for roman_result = roman_result + "M"
>
roman_result + "M" would also work, right/ I'm just trying to save  
time on typing in the code, right
>
>> # also, how do I modify the digital_input variable (it's an integer)
> digital_input -= 1000

is that somewhat like digital_result = digital result - int(1000)?

>> several times through the conversion process?
>>
> You will be processing the input in a loop (while or for).

running = True and
while running

is how I've tended to set

(my pseudocode)

> As you gain familiarity with Python you will develop ways to separate
> data from logic. I might say more about this later, but right now I'm
> about to drive north a bit.
>
I have already gained some familiary with separating data manipulation  
(data and logic, as a whole) from the code for the user interface,  
that's something that oen of my advisors has been big on.




From rikard.bosnjakovic at gmail.com  Thu Mar  8 23:17:20 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Thu, 8 Mar 2007 23:17:20 +0100
Subject: [Tutor] Best IDE for python?
In-Reply-To: <972566ff0703080422j53337e0fi487b22561b624156@mail.gmail.com>
References: <972566ff0703080422j53337e0fi487b22561b624156@mail.gmail.com>
Message-ID: <d9e88eaf0703081417x4b3f5bccob7a461d0856439d8@mail.gmail.com>

On 3/8/07, Joydeep Mitra <snakepit.rattlesnakes at gmail.com> wrote:

> I would like to know what's the best IDE for python (having all important
> IDE features like debug, etc), other than IDLE.

Which IDE to use is no more than a matter of taste and laziness.
Myself, I use Emacs (as for to everything).


-- 
- Rikard.

From rdm at rcblue.com  Fri Mar  9 03:34:01 2007
From: rdm at rcblue.com (Dick Moores)
Date: Thu, 08 Mar 2007 18:34:01 -0800
Subject: [Tutor] Best IDE for python?
In-Reply-To: <d9e88eaf0703081417x4b3f5bccob7a461d0856439d8@mail.gmail.co
 m>
References: <972566ff0703080422j53337e0fi487b22561b624156@mail.gmail.com>
	<d9e88eaf0703081417x4b3f5bccob7a461d0856439d8@mail.gmail.com>
Message-ID: <20070309023407.C62F21E4002@bag.python.org>

At 02:17 PM 3/8/2007, Rikard Bosnjakovic wrote:
>On 3/8/07, Joydeep Mitra <snakepit.rattlesnakes at gmail.com> wrote:
>
> > I would like to know what's the best IDE for python (having all important
> > IDE features like debug, etc), other than IDLE.
>
>Which IDE to use is no more than a matter of taste and laziness.

Wow! Care to support that statement?

>Myself, I use Emacs (as for to everything).

Dick Moores



From itpro4470 at hushmail.com  Fri Mar  9 05:44:34 2007
From: itpro4470 at hushmail.com (itpro4470 at hushmail.com)
Date: Thu, 08 Mar 2007 20:44:34 -0800
Subject: [Tutor] please unsubscribe me
Message-ID: <20070309044435.19208DA84A@mailserver8.hushmail.com>



On Thu, 08 Mar 2007 03:00:15 -0800 tutor-request at python.org wrote:
>Send Tutor mailing list submissions to
>	tutor at python.org
>
>To subscribe or unsubscribe via the World Wide Web, visit
>	http://mail.python.org/mailman/listinfo/tutor
>or, via email, send a message with subject or body 'help' to
>	tutor-request at python.org
>
>You can reach the person managing the list at
>	tutor-owner at python.org
>
>When replying, please edit your Subject line so it is more 
>specific
>than "Re: Contents of Tutor digest..."
>
>
>Today's Topics:
>
>   1. Re: help:find a string in a text and replace it with a
>      anotherstring (Mike Hansen)
>   2. Re: Tutor Digest, Vol 37, Issue 22 (Steve Maguire)
>   3. Passing a list, dict or tuple to MySQLdb? (Alan Wardroper)
>   4. Re: Passing a list, dict or tuple to MySQLdb? (Bill 
>Campbell)
>   5. ssl error when trying to connect to https (also using
>      timeoutsocket.py) (Tsila Hassine)
>   6. about  __std__ zip file (Glenfiddich apayart)
>   7. Re: Roman Numeral to Digital (Kent Johnson)
>
>
>-------------------------------------------------------------------

>---
>
>Message: 1
>Date: Wed, 7 Mar 2007 10:42:54 -0700
>From: "Mike Hansen" <Mike.Hansen at atmel.com>
>Subject: Re: [Tutor] help:find a string in a text and replace it 
>with
>	a	anotherstring
>To: <tutor at python.org>
>Message-ID:
>	<57B026980605A64F9B23484C5659E32E637BF7 at poccso.US.ad.atmel.com>
>Content-Type: text/plain;	charset="us-ascii"
>
> 
>
>> -----Original Message-----
>> From: tutor-bounces at python.org 
>> [mailto:tutor-bounces at python.org] On Behalf Of mastjeptor regli
>> Sent: Wednesday, March 07, 2007 10:34 AM
>> To: tutor at python.org
>> Subject: [Tutor] help:find a string in a text and replace it 
>> with a anotherstring
>> 
>> Hi,folks.
>>      At first ,I have a question that I want to ask for 
>> help,it is how can I search a specific string in a text (such 
>> a in a word document) and replace it with another string?
>>      Second,if the text is changed dynamicly,can I use a 
>> variable string(has been assigned a string) to search in the 
>> text and replace it with another variable string.for example, 
>> Regex Substitution: s/email/e-mail ,if  the string of "email" 
>> and "e-mail" are both changed from time to time,can we apply
>> variable string (which has been assigned a value of string 
>> type) instead of constant string of "email" and "e-mail" to 
>> construct a regex substitution expression ?
>>       Please reply with experience in using  regular 
>> expression or python library functions to find and replace a 
>> string in a text to help me.   Thank you for your attention.
>> 
>
>You might not need regular expressions. You can use replace 
>method.
>
>In [11]: x = "Bozo"
>
>In [12]: z = "Bozo The Clown"
>
>In [13]: y = "Krusty"
>
>In [14]: z.replace(x,y)
>Out[14]: 'Krusty The Clown'
>
>You could probably populate a dictionary of the words you want to
>replace and their replacements. Then use the replace method on the
>strings.
>
>Note that Word documents are binary gibberish, so you'd need to 
>use
>win32 python windows stuff making this more complicated. On plain 
>text
>files, it wouldn't be too bad.
>
>Mike 
>
>
>------------------------------
>
>Message: 2
>Date: Wed, 7 Mar 2007 12:37:42 -0600
>From: "Steve Maguire" <steve at maguire-family.net>
>Subject: Re: [Tutor] Tutor Digest, Vol 37, Issue 22
>To: tutor at python.org
>Message-ID:
>	<cadaed980703071037t39ee07a9td3b065230295b988 at mail.gmail.com>
>Content-Type: text/plain; charset="iso-8859-1"
>
>>
>>
>> ---------- Forwarded message ----------
>> From: Tim Golden <mail at timgolden.me.uk>
>> To:
>> Date: Wed, 07 Mar 2007 15:48:20 +0000
>> Subject: Re: [Tutor] Printing labels
>> Steve Maguire wrote:
>> > I am a Python beginner.  For my first task I wanted to fix a 
>program
>> that I
>> > originally wrote in Excel with VBA.  I want to create a mySQL 
>database
>> > holding my DVD collection, edit it in Python, and print labels 

>for the
>> > cases
>> > with an index for filing and a catalog of all the titles their 

>indices.
>> >
>> > To print the labels the way I want, I will need extended 
>control over
>> the
>> > printer:  positioning the printer precisely and changing 
>fonts, colors,
>> and
>> > background colors.  Is there a public python library that 
>could give me
>> > this
>> > level of control?
>>
>> Best bet is probably using Reportlab (http://reportlab.org) to 
>generate
>> PDF. Their platypus layout scheme is very flexible, and you may 
>even
>> find someone's already done labels as an example.
>>
>> TJG
>>
>>
>Thanks Tim.  I'll check that out right away.
>Steve
>-------------- next part --------------
>An HTML attachment was scrubbed...
>URL: 
>http://mail.python.org/pipermail/tutor/attachments/20070307/188e407

>8/attachment-0001.html 
>
>------------------------------
>
>Message: 3
>Date: Wed, 07 Mar 2007 15:55:53 -0800
>From: Alan Wardroper <python at wardroper.org>
>Subject: [Tutor] Passing a list, dict or tuple to MySQLdb?
>To: tutor at python.org
>Message-ID: <45EF5109.3000909 at wardroper.org>
>Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
>I'm parsing some data to feed to a MySQL database, and would like 
>to be
>able to pass in a list (a dictionary or a series of tuples) in the
>cursor.execute() or cursor.executemany() statement, but everything 

>I've
>tried raises errors. I'm sure it's  a matter of correct formatting 

>the
>list as a sequence...
>
>CODE:
>import sys, MySQLdb
>conn = MySQLdb.connect (host = "localhost", user = "user", psswd =
>"xxxx" db = "testdb")
>cursor = conn.cursor()
>
>infile = open(sys.argv[2], 'r')
>list_of_tuples = []
>for line in infile:
>    tuple = (line.split()[0], line.split()[1])
>    list_of_tuples.append(tuple)
>
>cursor.executemany("UPDATE LOW_PRIORITY sometable SET field1 = %s 
>WHERE
>field2 = %s", (list_of_tuples)
>
>"""
>example data:
>ID123445   somestring1
>ID223445   somestring2
>ID323445   somestring3
>ID423445   somestring4
>ID523445   somestring5
>"""
>
>Naively, I thought this would result in an execute statement like:
>cursor.executemany("UPDATE LOW_PRIORITY sometable SET field1 = %s 
>WHERE
>field2 = %s", ('ID123445', 'somestring1'), ('ID223445', 
>'somestring2'),
>('ID323445', 'somestring3'), ('ID423445', 'somestring4'), 
>('ID523445',
>'somestring5'))
>
>But what I get are  bunch of errors,  last of which is:
>TypeError: not ll arguments converted during string formatting
>
>Or pass in a list of values to use in a SELECT...WHERE...IN (list)
>statement:
>
>ids_to_include = ['ID123445', 'ID223445', 'ID323445']
>cursor.execute("UPDATE  sometable SET field1 = 'some standard 
>value'
>WHERE field2 IN (%s)", (ids_to_include))
>
>
>I also tried another similar thing, where I tried to pass in the 
>name of
>one of the fields as a dictionary key with the value as the
>corresponding value, but it also didn't work--it looked like the 
>key was
>bounded in quotes before passing to MySQL, so the db didn't 
>recognise
>the fieldname:
>
>for key in dict.keys():
>    cursor.execute("INSERT INTO sometable (%s) values (%s)", (key,
>dict[key]))
>
>
>Any pointers?
>
>Thanks
>
>
>
>------------------------------
>
>Message: 4
>Date: Wed, 7 Mar 2007 16:05:27 -0800
>From: Bill Campbell <bill at celestial.net>
>Subject: Re: [Tutor] Passing a list, dict or tuple to MySQLdb?
>To: tutor at python.org
>Message-ID: <20070308000527.GA19529 at ayn.mi.celestial.com>
>Content-Type: text/plain; charset=us-ascii
>
>On Wed, Mar 07, 2007, Alan Wardroper wrote:
>>I'm parsing some data to feed to a MySQL database, and would like 

>to be
>>able to pass in a list (a dictionary or a series of tuples) in 
>the
>>cursor.execute() or cursor.executemany() statement, but 
>everything I've
>>tried raises errors. I'm sure it's  a matter of correct 
>formatting the
>>list as a sequence...
>>
>>CODE:
>>import sys, MySQLdb
>>conn = MySQLdb.connect (host = "localhost", user = "user", psswd 
>=
>>"xxxx" db = "testdb")
>>cursor = conn.cursor()
>>
>>infile = open(sys.argv[2], 'r')
>>list_of_tuples = []
>>for line in infile:
>>    tuple = (line.split()[0], line.split()[1])
>>    list_of_tuples.append(tuple)
>>
>>cursor.executemany("UPDATE LOW_PRIORITY sometable SET field1 = %s 

>WHERE
>>field2 = %s", (list_of_tuples)
>
>I think what you want is ...(*list_of_tuples) similar to the 
>syntax used
>when calling functions with position arguments from a list.
>
>Bill
>--
>INTERNET:   bill at Celestial.COM  Bill Campbell; Celestial Software 
>LLC
>URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
>FAX:            (206) 232-9186  Mercer Island, WA 98040-0820; 
>(206) 236-1676
>
>Few skills are so well rewarded as the ability to convince 
>parasites that
>they are victims. -- Thomas Sowell
>
>
>------------------------------
>
>Message: 5
>Date: Thu, 8 Mar 2007 01:47:21 +0100
>From: "Tsila Hassine" <tsila.hassine at gmail.com>
>Subject: [Tutor] ssl error when trying to connect to https (also 
>using
>	timeoutsocket.py)
>To: tutor at python.org
>Message-ID:
>	<da5291e90703071647p2bb9ec6bx392edc2e44d0b9b7 at mail.gmail.com>
>Content-Type: text/plain; charset="iso-8859-1"
>
>Hello all,
>
>in my code i am importing timeoutsocket in order to set the time 
>out of a
>connection. When i try to acces an https site I get the error:
>
>"TypeError: ssl() argument 1 must be _socket.socket, not 
>_socketobject"
>
>when I am not using the timeoutsocket module, I don't have any 
>problems. how
>can i solve this ? (I still need to be able to set the timeout of 
>a
>connection...)
>
>thanks,
>Tsila
>-------------- next part --------------
>An HTML attachment was scrubbed...
>URL: 
>http://mail.python.org/pipermail/tutor/attachments/20070308/7f9fd01

>d/attachment.htm 
>
>------------------------------
>
>Message: 6
>Date: Thu, 8 Mar 2007 01:40:38 -0800 (PST)
>From: Glenfiddich apayart <glen20web at yahoo.com.ph>
>Subject: [Tutor] about  __std__ zip file
>To: tutor at python.org
>Message-ID: <792981.89099.qm at web56610.mail.re3.yahoo.com>
>Content-Type: text/plain; charset="utf-8"
>
>hi, 
>
>This is my first day and first time i knew about python. i know 
>now how to handle the python GUI. i just have a small question 
>about the __std zip file. i've read about it on danny website. 
>this is the link .Where should i extract the file?
>
>im thinking if i would put it on my  Lib folder.. hoping for your 
>reply. thanks!
>
>brgds,
>glen20web
>
> 		
>---------------------------------
> Tired of spam? Yahoo! Mail has the best spam protection around
> http://ph.mail.yahoo.com
>-------------- next part --------------
>An HTML attachment was scrubbed...
>URL: 
>http://mail.python.org/pipermail/tutor/attachments/20070308/ed2a062

>f/attachment.html 
>
>------------------------------
>
>Message: 7
>Date: Thu, 08 Mar 2007 05:58:31 -0500
>From: Kent Johnson <kent37 at tds.net>
>Subject: Re: [Tutor] Roman Numeral to Digital
>To: Alan Gilfoy <agilfoy at frontiernet.net>,	tutor-python
>	<tutor at python.org>
>Message-ID: <45EFEC57.4000803 at tds.net>
>Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
>Hi Alan,
>
>I am forwarding your question to tutor at python.org which is the 
>correct 
>address for the list. tutor-owner at python.org sends questions to 
>the 
>*maintainers* of the list, not the list itself.
>
>Kent
>
>Alan Gilfoy wrote:
>> I am learning how to program in python as a major component of 
>my 
>> school's senior project, and my most recent assignment was to 
>write a 
>> program that converts Roman numerals to digital (base-10 Arabic 
>numerals).
>> 
>> Now, I was told I have to write the program myself, but I was 
>told I was 
>> allowed to ask for hints. :)
>> 
>> As of right now, I've written a user interface (after all, here 
>that's a 
>> simple loop-and-prompt setup leading to print statements), but I 

>have 
>> "dummy code" in the place where the conversion code needs to be.
>> 
>> I want to create two separate functions:
>> 
>> def.toRoman(digital_input)
>>     print "Digital - to - Roman conversion (dummy code)"
>>     roman_result = "XXX"
>>     return roman_result
>> 
>> def.toDigital(roman_input)
>>     print "Roman - to - digital conversion (dummy code)"
>>     digital_result = 30
>>     return digital_result
>> 
>> I'm going to set each of those two "inputs" by a prompt asking 
>for what 
>> the program user wants to work with.
>> 
>> #Such as:
>> digital_input = int(raw_input("What digital (base-10) number do 
>you wish 
>> to convert to Roman numerals?))
>> 
>> I'm not sure how I would program Python to run the actual 
>conversions.
>> 
>> PS: I'm familiar with Roman numerals, and I know how to do the 
>> conversions manually.
>> 
>> 
>> 
>> 
>> 
>> 
>
>
>
>------------------------------
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>
>End of Tutor Digest, Vol 37, Issue 23
>*************************************


Click to consolidate debt and lower month expenses
http://tagline.hushmail.com/fc/CAaCXv1QPxYsLwAs4lrOzOWlcGo2zh0g/


From rabidpoobear at gmail.com  Fri Mar  9 09:41:03 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Fri, 09 Mar 2007 02:41:03 -0600
Subject: [Tutor] please unsubscribe me
In-Reply-To: <20070309044435.19208DA84A@mailserver8.hushmail.com>
References: <20070309044435.19208DA84A@mailserver8.hushmail.com>
Message-ID: <45F11D9F.3030006@gmail.com>

Please read the text of what you just posted:
See that part down there that says 'to unsubscribe'?
I bet that's a good starting point.

itpro4470 at hushmail.com wrote:
> On Thu, 08 Mar 2007 03:00:15 -0800 tutor-request at python.org wrote:
>   
>> Send Tutor mailing list submissions to
>> 	tutor at python.org
>>
>> To subscribe or unsubscribe via the World Wide Web, visit
>> 	http://mail.python.org/mailman/listinfo/tutor
>> or, via email, send a message with subject or body 'help' to
>> 	tutor-request at python.org
>>
>> You can reach the person managing the list at
>> 	tutor-owner at python.org
>>
>> When replying, please edit your Subject line so it is more 
>> specific
>> than "Re: Contents of Tutor digest..."


From sanelson at gmail.com  Fri Mar  9 11:42:52 2007
From: sanelson at gmail.com (Stephen Nelson-Smith)
Date: Fri, 9 Mar 2007 10:42:52 +0000
Subject: [Tutor] How do to an svn checkout using the svn module?
Message-ID: <b6131fdc0703090242x1841b10fn8c71a07e30f12be@mail.gmail.com>

Hello,

I want to do a simple svn checkout using the python svn module.  I
haven't been able to find any/much/basic documentation that discusses
such client operations.

This should be very easy, I imagine!

What do I need to do?

S.

From kent37 at tds.net  Fri Mar  9 12:39:07 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 09 Mar 2007 06:39:07 -0500
Subject: [Tutor] How do to an svn checkout using the svn module?
In-Reply-To: <b6131fdc0703090242x1841b10fn8c71a07e30f12be@mail.gmail.com>
References: <b6131fdc0703090242x1841b10fn8c71a07e30f12be@mail.gmail.com>
Message-ID: <45F1475B.8080104@tds.net>

Stephen Nelson-Smith wrote:
> Hello,
> 
> I want to do a simple svn checkout using the python svn module.  I
> haven't been able to find any/much/basic documentation that discusses
> such client operations.

Did you find the pysvn Programmer's Guide that comes with pysvn? It has 
this example:

import pysvn
client = pysvn.Client()
#check out the current version of the pysvn project
client.checkout('http://localhost/example/trunk',
     './examples/pysvn')
#check out revision 11 of the pysvn project
client.checkout('http://localhost/example/trunk',
    './examples/pysvn-11',
    revision=pysvn.Revision(pysvn.opt_revision_kind.number, 11))

Kent

From sanelson at gmail.com  Fri Mar  9 12:43:35 2007
From: sanelson at gmail.com (Stephen Nelson-Smith)
Date: Fri, 9 Mar 2007 11:43:35 +0000
Subject: [Tutor] How do to an svn checkout using the svn module?
In-Reply-To: <45F1475B.8080104@tds.net>
References: <b6131fdc0703090242x1841b10fn8c71a07e30f12be@mail.gmail.com>
	<45F1475B.8080104@tds.net>
Message-ID: <b6131fdc0703090343w12637092k1e228d513867540@mail.gmail.com>

On 3/9/07, Kent Johnson <kent37 at tds.net> wrote:

> Did you find the pysvn Programmer's Guide that comes with pysvn? It has
> this example:

Ah.. no.... I haven't got pysvn installed... but will take a look.

What I do have is:

>>> import sys
>>> import svn.core
>>> import svn.client
>>> import sys
>>> pool = svn.core.svn_pool_create(None)
>>> svn.core.svn_config_ensure( None, pool )
>>> ctx = svn.client.svn_client_ctx_t()
>>> config = svn.core.svn_config_get_config( None, pool )
>>> ctx.config = config
>>> rev = svn.core.svn_opt_revision_t()
>>> rev.kind = svn.core.svn_opt_revision_head
>>> rev.number = 0
>>> ctx.auth_baton = svn.core.svn_auth_open( [], pool )
>>> url = "https://svn.uk.delarue.com/repos/prdrep/prddoc/"
>>> path ="/tmp"
>>> svn.client.svn_client_checkout(url, path, rev, 0, ctx, pool)

Traceback (most recent call last):
  File "<stdin>", line 1, in ?
libsvn._core.SubversionException: ("PROPFIND request failed on
'/repos/prdrep/prddoc'", 175002)

Not sure what I am doing wrong... the url is correct.

> Kent

S.

From sanelson at gmail.com  Fri Mar  9 13:52:39 2007
From: sanelson at gmail.com (Stephen Nelson-Smith)
Date: Fri, 9 Mar 2007 12:52:39 +0000
Subject: [Tutor] Parsing Word Docs
In-Reply-To: <45F03479.9010705@timgolden.me.uk>
References: <b6131fdc0703080640r31765be3xf6f42a03a1cb0bfe@mail.gmail.com>
	<45F03479.9010705@timgolden.me.uk>
Message-ID: <b6131fdc0703090452v1f82f116neb5373ac597b912@mail.gmail.com>

On 3/8/07, Tim Golden <mail at timgolden.me.uk> wrote:

> Simplest thing's probably antiword (http://www.winfield.demon.nl/)
> and then whatever text-scanning approach you want.

I've gone for:

#!/usr/bin/env python

import glob, os

url = "/home/cherp/prddoc"
searchstring = "dxpolbl.p"
worddocs = []

for (dirpath, dirnames, filenames) in os.walk(url):
  for f in filenames:
    if f.endswith(".doc"):
      worddocs.append(os.path.join(dirpath,f))

for d in worddocs:
  for i in glob.glob(d):
    if searchstring in open(i,"r").read():
      print "Found it in: ", i.split('/')[-1]

Now... I want to convert this to a cgi-script... how do I grab
$QUERY_STRING in python?

S.

From kent37 at tds.net  Fri Mar  9 14:14:52 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 09 Mar 2007 08:14:52 -0500
Subject: [Tutor] How do to an svn checkout using the svn module?
In-Reply-To: <b6131fdc0703090343w12637092k1e228d513867540@mail.gmail.com>
References: <b6131fdc0703090242x1841b10fn8c71a07e30f12be@mail.gmail.com>	
	<45F1475B.8080104@tds.net>
	<b6131fdc0703090343w12637092k1e228d513867540@mail.gmail.com>
Message-ID: <45F15DCC.1090000@tds.net>

Stephen Nelson-Smith wrote:
> On 3/9/07, Kent Johnson <kent37 at tds.net> wrote:
> 
>> Did you find the pysvn Programmer's Guide that comes with pysvn? It has
>> this example:
> 
> Ah.. no.... I haven't got pysvn installed... but will take a look.

Seems like a good idea. What package are you using?
 From http://pysvn.tigris.org:
The pysvn project's goal is to enable Tools to be written in Python that 
use Subversion.

Besides the docs it comes with what looks like a complete implementation 
of the svn command-line client written in Python.

Kent

> 
> What I do have is:
> 
>>>> import sys
>>>> import svn.core
>>>> import svn.client
>>>> import sys
>>>> pool = svn.core.svn_pool_create(None)
>>>> svn.core.svn_config_ensure( None, pool )
>>>> ctx = svn.client.svn_client_ctx_t()
>>>> config = svn.core.svn_config_get_config( None, pool )
>>>> ctx.config = config
>>>> rev = svn.core.svn_opt_revision_t()
>>>> rev.kind = svn.core.svn_opt_revision_head
>>>> rev.number = 0
>>>> ctx.auth_baton = svn.core.svn_auth_open( [], pool )
>>>> url = "https://svn.uk.delarue.com/repos/prdrep/prddoc/"
>>>> path ="/tmp"
>>>> svn.client.svn_client_checkout(url, path, rev, 0, ctx, pool)
> 
> Traceback (most recent call last):
>  File "<stdin>", line 1, in ?
> libsvn._core.SubversionException: ("PROPFIND request failed on
> '/repos/prdrep/prddoc'", 175002)
> 
> Not sure what I am doing wrong... the url is correct.
> 
>> Kent
> 
> S.
> 


From alan.gauld at btinternet.com  Fri Mar  9 22:50:48 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 9 Mar 2007 21:50:48 -0000
Subject: [Tutor] recommendation for good OO book?
References: <488373.75921.qm@web43135.mail.sp1.yahoo.com>
Message-ID: <esskvk$m07$1@sea.gmane.org>

"Jeff Peery" <jeffpeery at yahoo.com> wrote

> I really don't utilize this object oriented stuff in a good way.
> Does anyone have a favorite book regarding the basics/intro
> to object oriented programming, how to write good OO code??

There are lots of books tackle this and it depends on your preferred
learning style. My current favourites are:

1) Object oriented software Construction by Meyer
Pros: The best by a mile in terms of pure OO explanations and very 
thorough
Cons: It uses Meyers own Eiffel language and is huge(over 1200 pages).
But if you want a great theoretical and practical text book it can't 
be beaten.

2) OOA & D by Grady Booch
Pros: The classic text on OOD, gives good background on why
and is excellent for those working onl large scale projects
Cons:A little bit dated now(1992?) and very C++ focused
(The first edition if you can find it is better in that it uses 5 
languages)
Also more focused on design rather than code.

3) OOP by Timothy Budd (2nd Ed)
Pros: Very code oriented and targetted at smaller problems than Booch
Its very short!
Cons: I think the latest version only uses Java which in my view 
weakens
its value significantly

4) OOP by Coad and Nicola
Pros: A really really good book on turning a design into code,
with lots of little rules/idioms (eg Be wary of objects called 
'manager')
Cons: A little old and very hard to find

5) Agile Software Development by Martin
(I;'m in two minds about recommending this since it varies between
brilliant and poor)
Pros: The OOP bits are good but Martin is obsessed by interfaces
and is very C++/Java focussed.
Cons: There is a lot of stuff about Agile development which frankly
is not good. It has lots of bad ideas, mistakes and dubious code.
It's not bad for small scale programming but the Agile stuff is very
poor compared to the OO stuff IMHO. But if you can borrow a copy,
read up the OO bits and scan the rest its quite good.

6) Design Patterns by Gamma et al
Very specific treatment of one aspect of OO but an important one.
And if you read and understand how all the various patterns work
you will have a good toolbox of ideas on how to do OOP (as well
as the patterns themselves!) But it won't help with building a project
from scratch or coming up with the initial  list of classes etc.

All my own views, others will no doubt have other ideas,

And, of course, investigate cetus-links.org

Alan G.



From alan.gauld at btinternet.com  Fri Mar  9 23:02:14 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 9 Mar 2007 22:02:14 -0000
Subject: [Tutor] Best IDE for python?
References: <972566ff0703080422j53337e0fi487b22561b624156@mail.gmail.com><d9e88eaf0703081417x4b3f5bccob7a461d0856439d8@mail.gmail.com>
	<d9e88eaf0703081417x4b3f5bccob7a461d0856439d8@mail.gmail.co m>
	<20070309023407.C62F21E4002@bag.python.org>
Message-ID: <essll2$o3k$1@sea.gmane.org>


"Dick Moores" <rdm at rcblue.com> wrote

>>Which IDE to use is no more than a matter of taste and laziness.
>
> Wow! Care to support that statement?

I'd have thought it was pretty self evident.
The lazier you are the more automation and assistance you
want the IDE to provide. But if you are a traditional programmer
you may prefer to keep total control.

Personally I love features like syntax highlighting, am
slightly ambivalent about tips(eg for function parameters)
and hate code completion wizards etc.

I also like automated navigation (as in highlight a function name
and get the IDE find the definition - ala Unix tags), but I hate
integrated project management tools as in Visual Studio etc.

So I like a good editor but avoid most IDEs.

(In practice I use Netbeans/Eclipse for Java, Delphi(*) for hard-core
windows programming but Pythonwin or vim/command prompt
for Python)

But I know of folks who want the IDE to do everything and
want to think as little as possible about the mechanics of
writing code. Its a matter of taste and how much you want
the tool to do the thinking for you.

(*)And I use Delphi v3 because I don't like the latest
versions because The IDE gets in my way too often!

At least I think that's what Rikard meant.

Alan G. 



From alan.gauld at btinternet.com  Fri Mar  9 23:05:53 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 9 Mar 2007 22:05:53 -0000
Subject: [Tutor] Parsing Word Docs
References: <b6131fdc0703080640r31765be3xf6f42a03a1cb0bfe@mail.gmail.com><45F03479.9010705@timgolden.me.uk>
	<b6131fdc0703090452v1f82f116neb5373ac597b912@mail.gmail.com>
Message-ID: <esslru$oo7$1@sea.gmane.org>


"Stephen Nelson-Smith" <sanelson at gmail.com> wrote 

> Now... I want to convert this to a cgi-script... how do I grab
> $QUERY_STRING in python?

Have you looked at the cgi module and the web topic guides?
The examples are fairly complete.

http://wiki.python.org/moin/CgiScripts


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


From alan.gauld at btinternet.com  Fri Mar  9 23:14:47 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 9 Mar 2007 22:14:47 -0000
Subject: [Tutor] building an interactive deamon
References: <4dcb3660703080802p3e5fb43fl9e76f37542e5dbe1@mail.gmail.com>
Message-ID: <essmcj$qgq$1@sea.gmane.org>


"Thanos Panousis" <pthanos at gmail.com> wrote

> How can I make a daemon that does not need to be restarted
> every time a configuration is changed?

There are several ways to do this.
Simplest if you are sleeping for periods is simply to re-read
the config after every wake-up.

Other options incliude using select() I think select will
work for files so if anything changes on the watched file
select will run its code.

> As a side question, is there a more elegant way of making something 
> a deamon
> other than the ole
> while True:
>   do_stuff()
>   sleep(some_time)

select can be used instead of the sleep to only run the code
when an interesting event happens - provided your events are
detectable by select of course!.

The twisted framework should offer some other options too,
but I've never used twisted so am no expert.

Alan G. 



From rdm at rcblue.com  Sat Mar 10 01:11:40 2007
From: rdm at rcblue.com (Dick Moores)
Date: Fri, 09 Mar 2007 16:11:40 -0800
Subject: [Tutor] Best IDE for python?
In-Reply-To: <essll2$o3k$1@sea.gmane.org>
References: <972566ff0703080422j53337e0fi487b22561b624156@mail.gmail.com>
	<d9e88eaf0703081417x4b3f5bccob7a461d0856439d8@mail.gmail.com>
	<d9e88eaf0703081417x4b3f5bccob7a461d0856439d8@mail.gmail.co m>
	<20070309023407.C62F21E4002@bag.python.org>
	<essll2$o3k$1@sea.gmane.org>
Message-ID: <20070310001144.E60731E4002@bag.python.org>

At 02:02 PM 3/9/2007, you wrote:

>"Dick Moores" <rdm at rcblue.com> wrote
>
> >>Which IDE to use is no more than a matter of taste and laziness.
> >
> > Wow! Care to support that statement?
>
>I'd have thought it was pretty self evident.
>The lazier you are the more automation and assistance you
>want the IDE to provide.

Maybe, but watch your logic. Wanting more automation and assistance 
does not imply laziness. Wanting a washing machine for washing 
clothes instead of washing them by hand does not imply laziness. You 
could, for example, want to put the time saved into programming!

Dick Moores 


From rob.andrews at gmail.com  Sat Mar 10 01:22:59 2007
From: rob.andrews at gmail.com (Rob Andrews)
Date: Fri, 9 Mar 2007 18:22:59 -0600
Subject: [Tutor] Best IDE for python?
In-Reply-To: <20070310001144.E60731E4002@bag.python.org>
References: <972566ff0703080422j53337e0fi487b22561b624156@mail.gmail.com>
	<d9e88eaf0703081417x4b3f5bccob7a461d0856439d8@mail.gmail.com>
	<20070309023407.C62F21E4002@bag.python.org>
	<essll2$o3k$1@sea.gmane.org>
	<20070310001144.E60731E4002@bag.python.org>
Message-ID: <8d757d2e0703091622t634e032fhae5d336d88d2e485@mail.gmail.com>

It may be worthwhile to note that "laziness" isn't necessarily a
derogatory term in programming circles. To quote Eric S. Raymond, who
turned me on to Python as much as any other (in _The Art of Unix
Programming_), "Constructive laziness is one of the cardinal virtues
of the master programmer."

-Rob A.

From alan.gauld at btinternet.com  Sat Mar 10 01:22:21 2007
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Sat, 10 Mar 2007 00:22:21 +0000 (GMT)
Subject: [Tutor] Best IDE for python?
Message-ID: <20070310002221.86897.qmail@web86114.mail.ird.yahoo.com>


> >I'd have thought it was pretty self evident.
>> The lazier you are the more automation and assistance you
>> want the IDE to provide.
>
> Maybe, but watch your logic. Wanting more automation and assistance 
> does not imply laziness. Wanting a washing machine for washing 

Ah, but remember that laziness is one of the three virtues of a programmer:

http://www.netropolis.org/hash/perl/virtue.html

Its something to be encouraged. :-)

Alan G.





		
___________________________________________________________ 
The all-new Yahoo! Mail goes wherever you go - free your email address from your Internet provider. http://uk.docs.yahoo.com/nowyoucan.html

From rdm at rcblue.com  Sat Mar 10 02:04:07 2007
From: rdm at rcblue.com (Dick Moores)
Date: Fri, 09 Mar 2007 17:04:07 -0800
Subject: [Tutor] Best IDE for python?
In-Reply-To: <20070310002221.86897.qmail@web86114.mail.ird.yahoo.com>
References: <20070310002221.86897.qmail@web86114.mail.ird.yahoo.com>
Message-ID: <20070310010526.99AF71E4002@bag.python.org>

At 04:22 PM 3/9/2007, ALAN GAULD wrote:
>http://www.netropolis.org/hash/perl/virtue.html

An Alice in Wonderland world of weirdness!

Dick



From rdm at rcblue.com  Sat Mar 10 02:11:44 2007
From: rdm at rcblue.com (Dick Moores)
Date: Fri, 09 Mar 2007 17:11:44 -0800
Subject: [Tutor] Best IDE for python?
In-Reply-To: <20070310010526.99AF71E4002@bag.python.org>
References: <20070310002221.86897.qmail@web86114.mail.ird.yahoo.com>
	<20070310010526.99AF71E4002@bag.python.org>
Message-ID: <20070310011151.6BDE21E4004@bag.python.org>

At 05:04 PM 3/9/2007, Dick Moores wrote:
>At 04:22 PM 3/9/2007, ALAN GAULD wrote:
> >http://www.netropolis.org/hash/perl/virtue.html
>
>An Alice in Wonderland world of weirdness!

Now here's a world I like:

 >>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Dick 


From kent37 at tds.net  Sat Mar 10 15:55:04 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 10 Mar 2007 09:55:04 -0500
Subject: [Tutor] recommendation for good OO book?
In-Reply-To: <esskvk$m07$1@sea.gmane.org>
References: <488373.75921.qm@web43135.mail.sp1.yahoo.com>
	<esskvk$m07$1@sea.gmane.org>
Message-ID: <45F2C6C8.8090101@tds.net>

Alan Gauld wrote:
> 5) Agile Software Development by Martin
> (I;'m in two minds about recommending this since it varies between
> brilliant and poor)
> Pros: The OOP bits are good but Martin is obsessed by interfaces
> and is very C++/Java focussed.
> Cons: There is a lot of stuff about Agile development which frankly
> is not good. It has lots of bad ideas, mistakes and dubious code.
> It's not bad for small scale programming but the Agile stuff is very
> poor compared to the OO stuff IMHO. But if you can borrow a copy,
> read up the OO bits and scan the rest its quite good.

Hmm...once again I think we will have to agree to disagree :-) This is 
one of my all-time favorite software development books and IMO one of 
the few that shows *why* to use OOP and *how* to do it from a practical 
point of view. So many OOP books start with "Identify the nouns in your 
domain. These may correspond to objects in the implementation." Yes, 
but...that is just a starting point. Martin shows how using real 
requirements to drive object-oriented design can lead to an architecture 
that is loosely coupled, cohesive and maintainable.

My experience with agile development in the style of this book is that 
it works fantastically well for small- to medium-sized projects. The 
writing of Robert Martin has been a huge influence in my professional 
development.

I don't have experience with huge projects like Alan works on, so I 
can't say if this style works there. This difference in background 
probably accounts for our differing opinions.

I would say Martin is obsessed by loose coupling and uses interfaces as 
a means to this end. But he is good about designing to meet real 
requirements rather than designing to meet some abstract goal (the way 
much of the Java libraries seem to have been written).

Martin likes to use metrics to evaluate code. I have not found any value 
in this. The rest of his ideas I find very useful.

The book is very Java and C++ focused; Python has a looser style. I read 
this book before I had written a lot of Python so I don't know how well 
it applies there. This is what kept me from recommending it in response 
to the OP. But in 2003 what language would you have used for a book on 
OOP? I remember being thrilled that he used mostly Java vs C++.

Several chapters from this book are available on-line as stand-alone 
essays. Go to
http://objectmentor.com/resources/publishedArticles.html
and click on Robert C. Martin. Scroll down past the "Craftsman" series.

"Agile Process" is basically chapter 1 of the book.

The Bowling Game: An example of test-first pair programming
Inheritance vs. Delegation
Singleton And Monostate
Proxy and Stairway to Heaven
are all book chapters or early versions of chapters, and some of the 
"principles" appear in the book also.

Kent

From alan.gauld at btinternet.com  Sat Mar 10 16:23:14 2007
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Sat, 10 Mar 2007 15:23:14 +0000 (GMT)
Subject: [Tutor] recommendation for good OO book?
Message-ID: <590088.52377.qm@web86111.mail.ird.yahoo.com>

> 5) Agile Software Development by Martin
> Pros: The OOP bits are good but Martin is obsessed by interfaces
> Cons: There is a lot of stuff about Agile development which frankly
> is not good. It has lots of bad ideas, mistakes and dubious code.

> Hmm...once again I think we will have to agree to disagree :-) This is 
> one of my all-time favorite software development books and IMO one of 
> the few that shows *why* to use OOP and *how* to do it from a practical 
> point of view. 

Like I said the OOP bits are good.

> My experience with agile development in the style of this book 
> is that it works fantastically well for small- to medium-sized projects. 

And I agree Agile works great on small mediyum sized stuff. We 
are starting to try to use it on big projects and it has some, errr 
challenges...

> I don't have experience with huge projects like Alan works on, 
> so I can't say if this style works there. 

Intelligent application works well.
User stories are good, TDD works well for components, less well 
for big systems. The biggest problem areas are integration, communication 
(10 minute standups just dont work for 400 developers, even a "scrum of scrums") 
And you really need an end to end design and test team or the overall objective 
can get forgotten, with each component choosing their own set of stories that 
don't join together to deliver the top level stories. (10 half stories do not make 
5 full ones unfortunately!)

> Martin likes to use metrics to evaluate code. I have not found any value 
> in this. The rest of his ideas I find very useful.

Me too. The ideas are good but the effort of capturing and calculating 
the metrics seem to outweigh the benefits.

> to the OP. But in 2003 what language would you have used for 
> a book on OOP? 

Smalltalk, Lisp, Objective C, Object Pascal, C++, Java, Python

were all around and widely used. All but Python and Java were used 
by Booch in his first edition book back in 1991! After all OOP has 
been around since 1967 and 'popular' since 1980, there are no shortage 
of languages in common use. But Martin (and quite sensibly for a 
commercial author) focussed on the 2 languages that were in 
widest use, thus reaching the bigget market.

> The Bowling Game: An example of test-first pair programming

But a very very bad one. I almost thought he was being sarcastic 
when he wrote it until it became obvious he was serious! If you read 
this you come away with the view that pair programming must be 
the most wasteful way of getting to a solution known to man.
(it isn't, its just the way Martin presents it. For a much better view
of it read Kent Beck's XP book)

The 'final code' is buggy (it fails to reset a counter), doesn't 
meet the original spec (although, since it was for himself, he might 
argue that he changed his mind about the requirement), and is 
bloated with several parts not needed, and the critical algorithm 
implemented twice (differently - and faulty in one case).
They only stumbled on the right solution when they wrote the 
"pseoudo code" which most sane programmers do 
first! - even in Agile...

> Inheritance vs. Delegation
> Singleton And Monostate
> Proxy and Stairway to Heaven

The OOP bits are all good!

Alan G.






		
___________________________________________________________ 
The all-new Yahoo! Mail goes wherever you go - free your email address from your Internet provider. http://uk.docs.yahoo.com/nowyoucan.html

From jmutter at uakron.edu  Sat Mar 10 17:10:30 2007
From: jmutter at uakron.edu (Jay Mutter III)
Date: Sat, 10 Mar 2007 11:10:30 -0500
Subject: [Tutor] Should I use python for parsing text
In-Reply-To: <mailman.15741.1173486181.32030.tutor@python.org>
References: <mailman.15741.1173486181.32030.tutor@python.org>
Message-ID: <E25064DB-90B2-4BCE-ABE1-AEBA8279B1CD@uakron.edu>

I am using an intel iMac with OS -X 10.4.8.
It has Python 2.3.5.

My issue is that I have a lot of text ( about 500 pages at the  
moment) that I need to parse so that I can eliminate  info I don't  
need, break the remainder into fields and put in a database/spreadsheet.
See example  next:

A.-C. Manufacturing Company. (See Sebastian, A. A.,
and Capes, assignors.)
A. G. A. Railway Light & Signal Co. (See Meden, Elof
H? assignor.)
A-N Company, The. (See Alexander and Nasb, as-
signors.;
AN Company, The. (See Nash, It. J., and Alexander, as-
signors.)
A/S. Arendal Smelteverk.    (See Kaaten, Einar, assignor.)
A/S. Bjorgums Gevaei'kompani. (See Bjorguni, Nils, as-
signor.)
A/S  Mekano.     (Sec   Schepeler,   Herman  A.,  assignor.)
A/S Myrens Verkstad.    (See Klling, Jens W. A., assignor.)
A/S Stordo Kisgruber. (See Nielsen, C., and Ilelleland,
assignors.)
A-Z Company, The.    'See llanmer, Laurence G., assignor.)
Aagaard, Carl L., Rockford, 111. Hand scraping tool. No.
1,345,058 ; July 6; v. 276 ; p. 05.
Aalborg, Christian, Wllkinsburg, Pa., assignor to Wcst-
inghouse Electric and Manufacturing Company. Trol-
ley.    No. 1,334,943 ; Mar. 30 ; v. 272 ; p. 741.
Aaron, Solomon E., Boston, Mass. Pliers. No. 1,329,155 ;
Jan. 27 ; v. 270 ; p. 554.

For instance, I would like to go to end of line and if last character  
is a comma or semicolon or hyphen then remove the CR.
Then move line by line through the file and delete everything after a  
numerical sequence

  I am wondering if Python would be a good tool and if so where can I  
find information on how to accomplish this or would I be better off  
using something like the unix tool awk or something else??

Thanks

Jay

From jaggojaggo at yahoo.com  Sun Mar 11 15:33:44 2007
From: jaggojaggo at yahoo.com (Jaggo)
Date: Sun, 11 Mar 2007 07:33:44 -0700 (PDT)
Subject: [Tutor] The whole Roman to Dec and vice versa issue
In-Reply-To: <mailman.55.1173438024.9137.tutor@python.org>
Message-ID: <51216.59499.qm@web52515.mail.yahoo.com>

Hey,
I'm a rather new programmer, but it seems to me the digital to roman should be coded:
While Digital_Input > 0:
If Digital_Input > 1000 then: Roman = + M, Digital_Input = - 1000
elif Digital_Input > 900 then: Roman = + C, Digital_Input = - 900
...
Now if someone could please clarify [or forward me to clarifications of-] separation of data from logics I should be very grateful.

[Come to that, if someone could point me to a *simple* gui which I can use in python, keep in mind I did learn a little VB, I should be grateful as well.]

Thank you.
Omer Tabach.



Quoting Bob Gailer :

>>
>> Digital to Roman pseudocode:
>>
>> 1. if digital_input is greater than 1000:
>> subtract 1000 from it and add "M" to string roman_result
>> # How do you do that, add one character to the end of an existing string?
>>
> Start with an empty string:
>
> roman_result = ""
>
> To add a character at the end:
>
> roman_result += "M" # Python shorthand for roman_result = roman_result + "M"
>
roman_result + "M" would also work, right/ I'm just trying to save  
time on typing in the code, right
>
>> # also, how do I modify the digital_input variable (it's an integer)
> digital_input -= 1000

is that somewhat like digital_result = digital result - int(1000)?

>> several times through the conversion process?
>>
> You will be processing the input in a loop (while or for).

running = True and
while running

is how I've tended to set

(my pseudocode)

> As you gain familiarity with Python you will develop ways to separate
> data from logic. I might say more about this later, but right now I'm
> about to drive north a bit.
>
I have already gained some familiary with separating data manipulation  
(data and logic, as a whole) from the code for the user interface,  
that's something that oen of my advisors has been big on.



 
---------------------------------
Now that's room service! Choose from over 150,000 hotels 
in 45,000 destinations on Yahoo! Travel to find your fit.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070311/beb059b4/attachment.htm 

From alan.gauld at btinternet.com  Sun Mar 11 16:32:35 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 11 Mar 2007 15:32:35 -0000
Subject: [Tutor] Should I use python for parsing text
References: <mailman.15741.1173486181.32030.tutor@python.org>
	<E25064DB-90B2-4BCE-ABE1-AEBA8279B1CD@uakron.edu>
Message-ID: <et17ig$mrl$1@sea.gmane.org>


"Jay Mutter III" <jmutter at uakron.edu> wrote

> See example  next:
> A.-C. Manufacturing Company. (See Sebastian, A. A.,
> and Capes, assignors.)
>...
>Aaron, Solomon E., Boston, Mass. Pliers. No. 1,329,155 ;
>Jan. 27 ; v. 270 ; p. 554.
>
> For instance, I would like to go to end of line and if last
> character  is a comma or semicolon or hyphen then
> remove the CR.

It would look something like:

output = open('example.fixed','w')
for line in file('example.txt'):
    if line[-1] in ',;-':            # check last character
      line = line.strip()         # lose the C/R
      output.write(line)        # write to output
    else: output.write(line)  # append the next line complete with C/R
output.close()

> Then move line by line through the file and delete everything
> after a  numerical sequence

Slightly more tricky because you need to use a regular expression.
But if you know regex then only slightly.

>  I am wondering if Python would be a good tool

Absolutely, its one of the areas where Python excels.

> find information on how to accomplish this

You could check  my tutorial on the three topics:

Handling text
Handling files
Regular Expressions.

Also the standard python documentation for the general tutorial
(assuming you've done basic programming in some other language
before) plus the re module

> using something like the unix tool awk or something else??

awk or sed could both be used, but Python is more generally
useful so unless you already know awk I'd take the time to
learn the basics of Python (a few hours maybe) and use that.

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



From alan.gauld at btinternet.com  Sun Mar 11 16:38:48 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 11 Mar 2007 15:38:48 -0000
Subject: [Tutor] The whole Roman to Dec and vice versa issue
References: <mailman.55.1173438024.9137.tutor@python.org>
	<51216.59499.qm@web52515.mail.yahoo.com>
Message-ID: <et17u5$ntl$1@sea.gmane.org>

"Jaggo" <jaggojaggo at yahoo.com> wrote 

> [Come to that, if someone could point me to a *simple* gui which 
> I can use in python, keep in mind I did learn a little VB, 
> I should be grateful as well.]

Tkinter is the standard Python GUI (IDLE is built using it).
Many prefer wxPython, but it's an extra download.

You can see very basic GUI code for both in the GUI topic 
of my tutorial.

Bear in mind that Python doesn't come with a GUI Form 
builder ala VB, although there are a few around. This is 
one of them (based on wxPython):

http://pythoncard.sourceforge.net/

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


From tsila.hassine at gmail.com  Sun Mar 11 18:04:32 2007
From: tsila.hassine at gmail.com (Tsila Hassine)
Date: Sun, 11 Mar 2007 18:04:32 +0100
Subject: [Tutor] problems to install python 2.5
Message-ID: <da5291e90703111004r7515b6e7r4e40a7c12748c39@mail.gmail.com>

Hello all

I downloaded Python 2.5 (final release) from python.org. I am trying to
install it on my Mac 0s 10.4

the current working version i have of python is 2.3 (also built as a
framework)


It goes through the "./configure" part ok, but the "make install" produces
the following errors :



Modules/posixmodule.c:22: warning: ignoring #pragma weak lchown
Modules/posixmodule.c:23: warning: ignoring #pragma weak statvfs
Modules/posixmodule.c:24: warning: ignoring #pragma weak fstatvfs
Modules/posixmodule.c: In function `posix_lchown':
Modules/posixmodule.c:1681: warning: implicit declaration of function
`lchown'
Modules/posixmodule.c: In function `initposix':
Modules/posixmodule.c:8588: error: `fstatvfs' undeclared (first use in this
function)
Modules/posixmodule.c:8588: error: (Each undeclared identifier is reported
only once
Modules/posixmodule.c:8588: error: for each function it appears in.)
Modules/posixmodule.c:8596: error: `statvfs' undeclared (first use in this
function)
Modules/posixmodule.c:8604: error: `lchown' undeclared (first use in this
function)
make: *** [Modules/posixmodule.o] Error 1


I can't find any documentation of such a problem on the net, does anyone
have a clue to what might be the problem ?

thanks!
Tsila
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070311/d63b0008/attachment.htm 

From kent37 at tds.net  Sun Mar 11 18:35:49 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 11 Mar 2007 13:35:49 -0400
Subject: [Tutor] problems to install python 2.5
In-Reply-To: <da5291e90703111004r7515b6e7r4e40a7c12748c39@mail.gmail.com>
References: <da5291e90703111004r7515b6e7r4e40a7c12748c39@mail.gmail.com>
Message-ID: <45F43DF5.3030208@tds.net>

Tsila Hassine wrote:
> Hello all
> 
> I downloaded Python 2.5 (final release) from python.org. I am trying to
> install it on my Mac 0s 10.4
> 
> the current working version i have of python is 2.3 (also built as a
> framework)
> 
> 
> It goes through the "./configure" part ok, but the "make install" produces
> the following errors :

No clue about your errors, but you can download a framework build of 
Python 2.5 from
http://www.pythonmac.org/packages/py25-fat/index.html

You might have better luck with build questions on the python-mac list:
http://www.python.org/community/sigs/current/pythonmac-sig/

Kent

From tsila.hassine at gmail.com  Sun Mar 11 18:57:34 2007
From: tsila.hassine at gmail.com (Tsila Hassine)
Date: Sun, 11 Mar 2007 18:57:34 +0100
Subject: [Tutor] problems to install python 2.5
In-Reply-To: <45F43DF5.3030208@tds.net>
References: <da5291e90703111004r7515b6e7r4e40a7c12748c39@mail.gmail.com>
	<45F43DF5.3030208@tds.net>
Message-ID: <da5291e90703111057r5f49d5d3wd5542ea8ebad44d2@mail.gmail.com>

I also tried that build as well - it says that installation completed
succesfully - and when i try to launch IDLE - it won't open...

On 3/11/07, Kent Johnson <kent37 at tds.net> wrote:
>
> Tsila Hassine wrote:
> > Hello all
> >
> > I downloaded Python 2.5 (final release) from python.org. I am trying to
> > install it on my Mac 0s 10.4
> >
> > the current working version i have of python is 2.3 (also built as a
> > framework)
> >
> >
> > It goes through the "./configure" part ok, but the "make install"
> produces
> > the following errors :
>
> No clue about your errors, but you can download a framework build of
> Python 2.5 from
> http://www.pythonmac.org/packages/py25-fat/index.html
>
> You might have better luck with build questions on the python-mac list:
> http://www.python.org/community/sigs/current/pythonmac-sig/
>
> Kent
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070311/aeaabdbd/attachment-0001.html 

From andre.roberge at gmail.com  Sun Mar 11 19:11:31 2007
From: andre.roberge at gmail.com (Andre Roberge)
Date: Sun, 11 Mar 2007 14:11:31 -0400
Subject: [Tutor] problems to install python 2.5
In-Reply-To: <da5291e90703111057r5f49d5d3wd5542ea8ebad44d2@mail.gmail.com>
References: <da5291e90703111004r7515b6e7r4e40a7c12748c39@mail.gmail.com>
	<45F43DF5.3030208@tds.net>
	<da5291e90703111057r5f49d5d3wd5542ea8ebad44d2@mail.gmail.com>
Message-ID: <7528bcdd0703111111i4b2894e9x28f5299b68994abc@mail.gmail.com>

On 3/11/07, Tsila Hassine <tsila.hassine at gmail.com> wrote:
> I also tried that build as well - it says that installation completed
> succesfully - and when i try to launch IDLE - it won't open...
>

Could it be that the 2.3 version is still around and that you are
trying to launch the 2.3 version of IDLE?  This happened to me once.

> On 3/11/07, Kent Johnson <kent37 at tds.net> wrote:
> > Tsila Hassine wrote:
> > > Hello all
> > >
> > > I downloaded Python 2.5 (final release) from python.org. I am trying to
> > > install it on my Mac 0s 10.4
> > >
> > > the current working version i have of python is 2.3 (also built as a
> > > framework)
> > >
> > >
> > > It goes through the "./configure" part ok, but the "make install"
> produces
> > > the following errors :
> >
> > No clue about your errors, but you can download a framework build of
> > Python 2.5 from
> > http://www.pythonmac.org/packages/py25-fat/index.html
> >
> > You might have better luck with build questions on the python-mac list:
> >
> http://www.python.org/community/sigs/current/pythonmac-sig/
> >
> > Kent
> >
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>

From tsila.hassine at gmail.com  Sun Mar 11 19:40:26 2007
From: tsila.hassine at gmail.com (Tsila Hassine)
Date: Sun, 11 Mar 2007 19:40:26 +0100
Subject: [Tutor] problems to install python 2.5
In-Reply-To: <7528bcdd0703111111i4b2894e9x28f5299b68994abc@mail.gmail.com>
References: <da5291e90703111004r7515b6e7r4e40a7c12748c39@mail.gmail.com>
	<45F43DF5.3030208@tds.net>
	<da5291e90703111057r5f49d5d3wd5542ea8ebad44d2@mail.gmail.com>
	<7528bcdd0703111111i4b2894e9x28f5299b68994abc@mail.gmail.com>
Message-ID: <da5291e90703111140j66c71edetcb29dedec201e974@mail.gmail.com>

2.3 is still around indeed, but i launched the IDLE from the python
2.5folder, so i don't think that was the problem.

on teh other hand - i discovered that when i type "python2.5" in teh
terminal window it launches indeed the python 2.5, but when running  a
script from the command line it goes to the 2.3 version in the Frameworks.
 - so what do i need to do ? add it to the PATH ? how do i do that ?



On 3/11/07, Andre Roberge <andre.roberge at gmail.com> wrote:
>
> On 3/11/07, Tsila Hassine <tsila.hassine at gmail.com> wrote:
> > I also tried that build as well - it says that installation completed
> > succesfully - and when i try to launch IDLE - it won't open...
> >
>
> Could it be that the 2.3 version is still around and that you are
> trying to launch the 2.3 version of IDLE?  This happened to me once.
>
> > On 3/11/07, Kent Johnson <kent37 at tds.net> wrote:
> > > Tsila Hassine wrote:
> > > > Hello all
> > > >
> > > > I downloaded Python 2.5 (final release) from python.org. I am trying
> to
> > > > install it on my Mac 0s 10.4
> > > >
> > > > the current working version i have of python is 2.3 (also built as a
> > > > framework)
> > > >
> > > >
> > > > It goes through the "./configure" part ok, but the "make install"
> > produces
> > > > the following errors :
> > >
> > > No clue about your errors, but you can download a framework build of
> > > Python 2.5 from
> > > http://www.pythonmac.org/packages/py25-fat/index.html
> > >
> > > You might have better luck with build questions on the python-mac
> list:
> > >
> > http://www.python.org/community/sigs/current/pythonmac-sig/
> > >
> > > Kent
> > >
> >
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070311/cd1c5d76/attachment.html 

From clay.wiedemann at gmail.com  Sun Mar 11 20:42:25 2007
From: clay.wiedemann at gmail.com (Clay Wiedemann)
Date: Sun, 11 Mar 2007 15:42:25 -0400
Subject: [Tutor] problems to install python 2.5
In-Reply-To: <da5291e90703111004r7515b6e7r4e40a7c12748c39@mail.gmail.com>
References: <da5291e90703111004r7515b6e7r4e40a7c12748c39@mail.gmail.com>
Message-ID: <781164cc0703111242v685c9ce4v3cec438f0a463c74@mail.gmail.com>

Did you download the MacPython 2.5 distribution? You should find an
"Update shell profile.command" file, which you can run. I believe once
you do that, you will be set up so that IDLE will launch and you will
default to version 2.5.

On 3/11/07, Tsila Hassine <tsila.hassine at gmail.com> wrote:
> Hello all
>
> I downloaded Python 2.5 (final release) from python.org. I am trying to
> install it on my Mac 0s 10.4
>
> the current working version i have of python is 2.3 (also built as a
> framework)
>
>
> It goes through the "./configure" part ok, but the "make install" produces
> the following errors :
>
>
>
> Modules/posixmodule.c:22: warning: ignoring #pragma weak lchown
> Modules/posixmodule.c:23: warning: ignoring #pragma weak statvfs
> Modules/posixmodule.c:24: warning: ignoring #pragma weak fstatvfs
> Modules/posixmodule.c: In function `posix_lchown':
> Modules/posixmodule.c:1681: warning: implicit declaration of function
> `lchown'
> Modules/posixmodule.c: In function `initposix':
> Modules/posixmodule.c:8588: error: `fstatvfs' undeclared (first use in this
> function)
> Modules/posixmodule.c:8588: error: (Each undeclared identifier is reported
> only once
> Modules/posixmodule.c:8588: error: for each function it appears in.)
> Modules/posixmodule.c:8596: error: `statvfs' undeclared (first use in this
> function)
> Modules/posixmodule.c:8604: error: `lchown' undeclared (first use in this
> function)
> make: *** [Modules/posixmodule.o] Error 1
>
>
> I can't find any documentation of such a problem on the net, does anyone
> have a clue to what might be the problem ?
>
> thanks!
> Tsila
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 

- - - - - - -

Clay S. Wiedemann

voice: 718.362.0375
aim: khlav
wii: 3905 4571 6175 2469
twitter: seastokes

From tsila.hassine at gmail.com  Sun Mar 11 23:01:56 2007
From: tsila.hassine at gmail.com (Tsila Hassine)
Date: Sun, 11 Mar 2007 23:01:56 +0100
Subject: [Tutor] problems to install python 2.5
In-Reply-To: <781164cc0703111242v685c9ce4v3cec438f0a463c74@mail.gmail.com>
References: <da5291e90703111004r7515b6e7r4e40a7c12748c39@mail.gmail.com>
	<781164cc0703111242v685c9ce4v3cec438f0a463c74@mail.gmail.com>
Message-ID: <da5291e90703111501n7f98010cqeaff106a551a629f@mail.gmail.com>

yes I did download that, and it went " sorry can't update zshell" (and yes I
have zshell) so i didn't know how to deal with that ....any ideas ? (but
then i guess its a completely different problem then ...)

thanks!
T.

On 3/11/07, Clay Wiedemann <clay.wiedemann at gmail.com> wrote:
>
> Did you download the MacPython 2.5 distribution? You should find an
> "Update shell profile.command" file, which you can run. I believe once
> you do that, you will be set up so that IDLE will launch and you will
> default to version 2.5.
>
> On 3/11/07, Tsila Hassine <tsila.hassine at gmail.com> wrote:
> > Hello all
> >
> > I downloaded Python 2.5 (final release) from python.org. I am trying to
> > install it on my Mac 0s 10.4
> >
> > the current working version i have of python is 2.3 (also built as a
> > framework)
> >
> >
> > It goes through the "./configure" part ok, but the "make install"
> produces
> > the following errors :
> >
> >
> >
> > Modules/posixmodule.c:22: warning: ignoring #pragma weak lchown
> > Modules/posixmodule.c:23: warning: ignoring #pragma weak statvfs
> > Modules/posixmodule.c:24: warning: ignoring #pragma weak fstatvfs
> > Modules/posixmodule.c: In function `posix_lchown':
> > Modules/posixmodule.c:1681: warning: implicit declaration of function
> > `lchown'
> > Modules/posixmodule.c: In function `initposix':
> > Modules/posixmodule.c:8588: error: `fstatvfs' undeclared (first use in
> this
> > function)
> > Modules/posixmodule.c:8588: error: (Each undeclared identifier is
> reported
> > only once
> > Modules/posixmodule.c:8588: error: for each function it appears in.)
> > Modules/posixmodule.c:8596: error: `statvfs' undeclared (first use in
> this
> > function)
> > Modules/posixmodule.c:8604: error: `lchown' undeclared (first use in
> this
> > function)
> > make: *** [Modules/posixmodule.o] Error 1
> >
> >
> > I can't find any documentation of such a problem on the net, does anyone
> > have a clue to what might be the problem ?
> >
> > thanks!
> > Tsila
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
>
>
> --
>
> - - - - - - -
>
> Clay S. Wiedemann
>
> voice: 718.362.0375
> aim: khlav
> wii: 3905 4571 6175 2469
> twitter: seastokes
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070311/bbb77b88/attachment.html 

From clay.wiedemann at gmail.com  Sun Mar 11 23:33:54 2007
From: clay.wiedemann at gmail.com (Clay Wiedemann)
Date: Sun, 11 Mar 2007 18:33:54 -0400
Subject: [Tutor] problems to install python 2.5
In-Reply-To: <da5291e90703111501n7f98010cqeaff106a551a629f@mail.gmail.com>
References: <da5291e90703111004r7515b6e7r4e40a7c12748c39@mail.gmail.com>
	<781164cc0703111242v685c9ce4v3cec438f0a463c74@mail.gmail.com>
	<da5291e90703111501n7f98010cqeaff106a551a629f@mail.gmail.com>
Message-ID: <781164cc0703111533q2e563747k548f5e9e2a00d131@mail.gmail.com>

No ideas there. I wish I could help, but I am new at this.
I did stop using IDLE though in favor of iPython. I don't know if an
end-around would solve all the problems you have been encountering
though.

http://ipython.scipy.org/moin/

-c

On 3/11/07, Tsila Hassine <tsila.hassine at gmail.com> wrote:
> yes I did download that, and it went " sorry can't update zshell" (and yes I
> have zshell) so i didn't know how to deal with that ....any ideas ? (but
> then i guess its a completely different problem then ...)
>
> thanks!
> T.
>
>
> On 3/11/07, Clay Wiedemann <clay.wiedemann at gmail.com> wrote:
> > Did you download the MacPython 2.5 distribution? You should find an
> > "Update shell profile.command" file, which you can run. I believe once
> > you do that, you will be set up so that IDLE will launch and you will
> > default to version 2.5.
> >
> > On 3/11/07, Tsila Hassine <tsila.hassine at gmail.com> wrote:
> > > Hello all
> > >
> > > I downloaded Python 2.5 (final release) from python.org. I am trying to
> > > install it on my Mac 0s 10.4
> > >
> > > the current working version i have of python is 2.3 (also built as a
> > > framework)
> > >
> > >
> > > It goes through the "./configure" part ok, but the "make install"
> produces
> > > the following errors :
> > >
> > >
> > >
> > > Modules/posixmodule.c:22: warning: ignoring #pragma weak lchown
> > > Modules/posixmodule.c:23: warning: ignoring #pragma weak statvfs
> > > Modules/posixmodule.c:24: warning: ignoring #pragma weak fstatvfs
> > > Modules/posixmodule.c: In function `posix_lchown':
> > > Modules/posixmodule.c:1681: warning: implicit declaration of function
> > > `lchown'
> > > Modules/posixmodule.c: In function `initposix':
> > > Modules/posixmodule.c:8588: error: `fstatvfs' undeclared (first use in
> this
> > > function)
> > > Modules/posixmodule.c:8588: error: (Each undeclared identifier is
> reported
> > > only once
> > > Modules/posixmodule.c:8588: error: for each function it appears in.)
> > > Modules/posixmodule.c:8596: error: `statvfs' undeclared (first use in
> this
> > > function)
> > > Modules/posixmodule.c:8604: error: `lchown' undeclared (first use in
> this
> > > function)
> > > make: *** [Modules/posixmodule.o] Error 1
> > >
> > >
> > > I can't find any documentation of such a problem on the net, does anyone
> > > have a clue to what might be the problem ?
> > >
> > > thanks!
> > > Tsila
> > >
> > > _______________________________________________
> > > Tutor maillist  -  Tutor at python.org
> > > http://mail.python.org/mailman/listinfo/tutor
> > >
> > >
> >
> >
> > --
> >
> > - - - - - - -
> >
> > Clay S. Wiedemann
> >
> > voice: 718.362.0375
> > aim: khlav
> > wii: 3905 4571 6175 2469
> > twitter: seastokes
> >
>
>


-- 

- - - - - - -

Clay S. Wiedemann

voice: 718.362.0375
aim: khlav
wii: 3905 4571 6175 2469
twitter: seastokes

From john at fouhy.net  Sun Mar 11 23:35:12 2007
From: john at fouhy.net (John Fouhy)
Date: Mon, 12 Mar 2007 11:35:12 +1300
Subject: [Tutor] The whole Roman to Dec and vice versa issue
In-Reply-To: <51216.59499.qm@web52515.mail.yahoo.com>
References: <mailman.55.1173438024.9137.tutor@python.org>
	<51216.59499.qm@web52515.mail.yahoo.com>
Message-ID: <5e58f2e40703111535k4fc283c1o9ac4e5f6b2951638@mail.gmail.com>

On 12/03/07, Jaggo <jaggojaggo at yahoo.com> wrote:
> Hey,
> I'm a rather new programmer, but it seems to me the digital to roman should
> be coded:
> While Digital_Input > 0:
> If Digital_Input > 1000 then: Roman = + M, Digital_Input = - 1000
> elif Digital_Input > 900 then: Roman = + C, Digital_Input = - 900
> ...
> Now if someone could please clarify [or forward me to clarifications of-]
> separation of data from logics I should be very grateful.

The idea is that our data is the information:
 1000 corresponds to 'M'
 500 corresponds to 'D'
 100 corresponds to 'C'
 etc..

We can represent that in python using a dictionary:

decToRomanData = { 1000:'M', 500:'D', 100:'C', 50:'L', 10:'X', 5:'V', 1:'I' }

Now we need to write some code that will take an integer and use our
data to convert to a Roman numeral.  One way we could do that is:

def decToRoman(dec):
        roman = ''
        while dec > 0:
                next = max(i for i in decToRomanData if dec >= i)
                roman += decToRomanData[next]
                dec -= next
        return roman

Now, if we suddenly remember that the romans used 'Q' to represent
250, we can just edit our dictionary, and the rest of the code will
remain the same.

[note that this code will not produce strings like 'IV' for 4.  OTOH,
as I recall, the Romans didn't do that consistently either..]

-- 
John.

From kent37 at tds.net  Sun Mar 11 23:39:41 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 11 Mar 2007 18:39:41 -0400
Subject: [Tutor] problems to install python 2.5
In-Reply-To: <da5291e90703111501n7f98010cqeaff106a551a629f@mail.gmail.com>
References: <da5291e90703111004r7515b6e7r4e40a7c12748c39@mail.gmail.com>	<781164cc0703111242v685c9ce4v3cec438f0a463c74@mail.gmail.com>
	<da5291e90703111501n7f98010cqeaff106a551a629f@mail.gmail.com>
Message-ID: <45F4852D.7090103@tds.net>

Tsila Hassine wrote:
> yes I did download that, and it went " sorry can't update zshell" (and 
> yes I
> have zshell) so i didn't know how to deal with that ....any ideas ? (but
> then i guess its a completely different problem then ...)

All that program does is make sure that the bin directory included in 
the Python distribution is included in your path. For bash, it edits 
.bash_profile and inserts this line:

export 
PATH="/Library/Frameworks/Python.framework/Versions/Current/bin:${PATH}"

You should do the equivalent for zshell.

Kent

From kent37 at tds.net  Mon Mar 12 00:20:58 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 11 Mar 2007 19:20:58 -0400
Subject: [Tutor] The whole Roman to Dec and vice versa issue
In-Reply-To: <5e58f2e40703111535k4fc283c1o9ac4e5f6b2951638@mail.gmail.com>
References: <mailman.55.1173438024.9137.tutor@python.org>	<51216.59499.qm@web52515.mail.yahoo.com>
	<5e58f2e40703111535k4fc283c1o9ac4e5f6b2951638@mail.gmail.com>
Message-ID: <45F48EDA.1070405@tds.net>

John Fouhy wrote:
> On 12/03/07, Jaggo <jaggojaggo at yahoo.com> wrote:
>> Hey,
>> I'm a rather new programmer, but it seems to me the digital to roman should
>> be coded:
>> While Digital_Input > 0:
>> If Digital_Input > 1000 then: Roman = + M, Digital_Input = - 1000
>> elif Digital_Input > 900 then: Roman = + C, Digital_Input = - 900
>> ...
>> Now if someone could please clarify [or forward me to clarifications of-]
>> separation of data from logics I should be very grateful.
> 
> The idea is that our data is the information:
>  1000 corresponds to 'M'
>  500 corresponds to 'D'
>  100 corresponds to 'C'
>  etc..
> 
> We can represent that in python using a dictionary:
> 
> decToRomanData = { 1000:'M', 500:'D', 100:'C', 50:'L', 10:'X', 5:'V', 1:'I' }

A list would probably work better here because the order is significant 
and random lookup is not.
> 
> Now we need to write some code that will take an integer and use our
> data to convert to a Roman numeral.  One way we could do that is:
> 
> def decToRoman(dec):
>         roman = ''
>         while dec > 0:
>                 next = max(i for i in decToRomanData if dec >= i)
>                 roman += decToRomanData[next]
>                 dec -= next
>         return roman

Remember this thread started as a homework problem...we shouldn't give 
solutions until the OP has one already. Then we can all get clever and 
show how we would have done it :-)
> 
> Now, if we suddenly remember that the romans used 'Q' to represent
> 250, we can just edit our dictionary, and the rest of the code will
> remain the same.
> 
> [note that this code will not produce strings like 'IV' for 4.  OTOH,
> as I recall, the Romans didn't do that consistently either..]

It seems to me that isn't so different from deciding to use 'Q' for 250. 
Maybe you can change the dictionary for this one too.

Kent

From john at fouhy.net  Mon Mar 12 00:50:49 2007
From: john at fouhy.net (John Fouhy)
Date: Mon, 12 Mar 2007 12:50:49 +1300
Subject: [Tutor] The whole Roman to Dec and vice versa issue
In-Reply-To: <45F48EDA.1070405@tds.net>
References: <mailman.55.1173438024.9137.tutor@python.org>
	<51216.59499.qm@web52515.mail.yahoo.com>
	<5e58f2e40703111535k4fc283c1o9ac4e5f6b2951638@mail.gmail.com>
	<45F48EDA.1070405@tds.net>
Message-ID: <5e58f2e40703111650p2567b5e6pb4db4fa52e310ca3@mail.gmail.com>

On 12/03/07, Kent Johnson <kent37 at tds.net> wrote:
> > [note that this code will not produce strings like 'IV' for 4.  OTOH,
> > as I recall, the Romans didn't do that consistently either..]
> It seems to me that isn't so different from deciding to use 'Q' for 250.
> Maybe you can change the dictionary for this one too.

Ahh, good point.  I was thinking in terms of extra logic to figure out
the subtraction rules, but you could just use extra symbols :-)

-- 
John.

From nephish at gmail.com  Mon Mar 12 02:23:26 2007
From: nephish at gmail.com (shawn bright)
Date: Sun, 11 Mar 2007 20:23:26 -0500
Subject: [Tutor] how to send command line args to py script
Message-ID: <384c93600703111823i4ba53abep2158db3c82262483@mail.gmail.com>

lo there all,

i was wondering how to make a python script accept command line arguments.
i mean, i have used python scripts from the command line in linux and
passed something to it and it knows what to do.

like in a function, if i want to do something like this

def add_two_numbers(a, b):
    x = a + b
    return x

x = add_two_numbers(4,5)
print x

how could i do the same from the cli.

like python add_two_numbers.py 4 5
or maybe python add_two_numbers.py 4, 5
or even python add_two_numbers.py -a 4 -b 5

is there an easy way to do this ?

thanks

From agilfoy at frontiernet.net  Mon Mar 12 02:44:28 2007
From: agilfoy at frontiernet.net (Alan Gilfoy)
Date: Mon, 12 Mar 2007 01:44:28 +0000
Subject: [Tutor] Roman Numeral - To - Digital Converter
Message-ID: <20070312014428.j0drdkb42nwc0gwk@webmail.frontiernet.net>

Roman Numeral - To - Digital Converter

So far, I'm coming along OK with the code that runs the conversions,  
assuming the user gives me a proper input. (A string of capital  
letters I, V, X, L, C, D, M)

However, not every input someone gives the function is goign to be  
properly formatted like that.

So:

1. How do I have my function "screen" an input string for characters  
that aren't I,V,X,L,C,D or M?
2. If any of the characters in the string are merely lowercase  
i,v,x,l,c,d, or m, how would I tell Python to capitalize those and go  
on with working the function?
-- 
"Blind faith in bad leadership is not patriotism."

"One of the most horrible features of war is that all the war-propaganda, all
the screaming and lies and hatred, comes invariably from people who are not
fighting."-George Orwell, _Homage to Catalonia






From chaosweevil42 at gmail.com  Mon Mar 12 02:55:41 2007
From: chaosweevil42 at gmail.com (Gordon)
Date: Sun, 11 Mar 2007 18:55:41 -0700
Subject: [Tutor] how to send command line args to py script
In-Reply-To: <384c93600703111823i4ba53abep2158db3c82262483@mail.gmail.com>
References: <384c93600703111823i4ba53abep2158db3c82262483@mail.gmail.com>
Message-ID: <45F4B31D.2060603@gmail.com>

This is my first time replying to the list, so excuse me if this goes 
out wrong.

Anyhow, you're looking for sys.agrv.  sys.agrv is a list of the 
arguments, with sys.agrv[0] being the script name.

Code:
##########
import sys  #sys.argv is part of the sys module
def add_two_numbers(a, b):
    x = a + b
    return x
y = float(sys.argv[1]) #This gets the arguments and converts them to numbers
z = float(sys.argv[2]) #You need to do this because the arguments come 
as strings
x = add_two_numbers(y,z) #Of course, that means if you put in "python 
add.py 1 fish"
print x #you'll get an error.  So a try-except clause would be good here.
##########
Run the above script with the formatting "python (filename).py 1 1", not 
"python (filename).py -1 -1", that'll get you negative numbers.

shawn bright wrote:
> lo there all,
>
> i was wondering how to make a python script accept command line arguments.
> i mean, i have used python scripts from the command line in linux and
> passed something to it and it knows what to do.
>
> like in a function, if i want to do something like this
>
> def add_two_numbers(a, b):
>     x = a + b
>     return x
>
> x = add_two_numbers(4,5)
> print x
>
> how could i do the same from the cli.
>
> like python add_two_numbers.py 4 5
> or maybe python add_two_numbers.py 4, 5
> or even python add_two_numbers.py -a 4 -b 5
>
> is there an easy way to do this ?
>
> thanks
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


From agilfoy at frontiernet.net  Mon Mar 12 03:04:45 2007
From: agilfoy at frontiernet.net (Alan Gilfoy)
Date: Mon, 12 Mar 2007 02:04:45 +0000
Subject: [Tutor] String-manipulation question
Message-ID: <20070312020445.ie0zt53nz1koww8s@webmail.frontiernet.net>

#start of triple-letter processing block
if len(roman_input) > 2 and roman_input[0] + roman_input[1] +  
roman_input[2] == "MMM":
     digital_result += 3000
     roman_input = #something to remove those "M"'s from the string
     continue

-- 
My question here boils down to, "Is there a way to remove certain  
characters from a string?"

Here, I'm trying to set the variable roman_input (the string's name)  
equal to the string minus those characters, the 3 Ms. (being the first  
three characters  of the string, they would be roman_input[0],  
roman_input[1], and roman_input[2].)

Setting the (new) string equal to the (old) string minus those three  
characters will enable calculations on the string to keep running,  
because I have this piece of code, and similar pieces nested in a loop.






From nephish at gmail.com  Mon Mar 12 03:07:41 2007
From: nephish at gmail.com (shawn bright)
Date: Sun, 11 Mar 2007 21:07:41 -0500
Subject: [Tutor] how to send command line args to py script
In-Reply-To: <45F4B31D.2060603@gmail.com>
References: <384c93600703111823i4ba53abep2158db3c82262483@mail.gmail.com>
	<45F4B31D.2060603@gmail.com>
Message-ID: <384c93600703111907n2abcb36an27970a219eb0f946@mail.gmail.com>

Well, for your first response, its great,
thanks a lot.
shawn

On 3/11/07, Gordon <chaosweevil42 at gmail.com> wrote:
> This is my first time replying to the list, so excuse me if this goes
> out wrong.
>
> Anyhow, you're looking for sys.agrv.  sys.agrv is a list of the
> arguments, with sys.agrv[0] being the script name.
>
> Code:
> ##########
> import sys  #sys.argv is part of the sys module
> def add_two_numbers(a, b):
>     x = a + b
>     return x
> y = float(sys.argv[1]) #This gets the arguments and converts them to numbers
> z = float(sys.argv[2]) #You need to do this because the arguments come
> as strings
> x = add_two_numbers(y,z) #Of course, that means if you put in "python
> add.py 1 fish"
> print x #you'll get an error.  So a try-except clause would be good here.
> ##########
> Run the above script with the formatting "python (filename).py 1 1", not
> "python (filename).py -1 -1", that'll get you negative numbers.
>
> shawn bright wrote:
> > lo there all,
> >
> > i was wondering how to make a python script accept command line arguments.
> > i mean, i have used python scripts from the command line in linux and
> > passed something to it and it knows what to do.
> >
> > like in a function, if i want to do something like this
> >
> > def add_two_numbers(a, b):
> >     x = a + b
> >     return x
> >
> > x = add_two_numbers(4,5)
> > print x
> >
> > how could i do the same from the cli.
> >
> > like python add_two_numbers.py 4 5
> > or maybe python add_two_numbers.py 4, 5
> > or even python add_two_numbers.py -a 4 -b 5
> >
> > is there an easy way to do this ?
> >
> > thanks
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From rabidpoobear at gmail.com  Mon Mar 12 03:45:21 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sun, 11 Mar 2007 21:45:21 -0500
Subject: [Tutor] Roman Numeral - To - Digital Converter
In-Reply-To: <20070312014428.j0drdkb42nwc0gwk@webmail.frontiernet.net>
References: <20070312014428.j0drdkb42nwc0gwk@webmail.frontiernet.net>
Message-ID: <45F4BEC1.3030303@gmail.com>

Alan Gilfoy wrote:
> Roman Numeral - To - Digital Converter
>
> So far, I'm coming along OK with the code that runs the conversions,  
> assuming the user gives me a proper input. (A string of capital  
> letters I, V, X, L, C, D, M)
>
> However, not every input someone gives the function is goign to be  
> properly formatted like that.
>
> So:
>
> 1. How do I have my function "screen" an input string for characters  
> that aren't I,V,X,L,C,D or M?
> 2. If any of the characters in the string are merely lowercase  
> i,v,x,l,c,d, or m, how would I tell Python to capitalize those and go  
> on with working the function?
>   
 >>> 'heLlo'.upper()
'HELLO'
 >>> print 'i' in 'hilly'
True
 >>> print 'i' in 'holy'
False

I hope that gives you some clues.
-Luke

From john at fouhy.net  Mon Mar 12 03:52:29 2007
From: john at fouhy.net (John Fouhy)
Date: Mon, 12 Mar 2007 15:52:29 +1300
Subject: [Tutor] String-manipulation question
In-Reply-To: <20070312020445.ie0zt53nz1koww8s@webmail.frontiernet.net>
References: <20070312020445.ie0zt53nz1koww8s@webmail.frontiernet.net>
Message-ID: <5e58f2e40703111952j406f24d1n869c941d3b5cc8d2@mail.gmail.com>

On 12/03/07, Alan Gilfoy <agilfoy at frontiernet.net> wrote:

> My question here boils down to, "Is there a way to remove certain
> characters from a string?"

There are several ways, depending on what exactly you want to achieve.

In this case, it looks like you're after "string slicing".  The
tutorial covers this; look about half-way down the page:
http://docs.python.org/tut/node5.html

HTH!

-- 
John.

From dkuhlman at rexx.com  Mon Mar 12 04:21:12 2007
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Sun, 11 Mar 2007 20:21:12 -0700
Subject: [Tutor] how to send command line args to py script
In-Reply-To: <384c93600703111907n2abcb36an27970a219eb0f946@mail.gmail.com>
References: <384c93600703111823i4ba53abep2158db3c82262483@mail.gmail.com>
	<45F4B31D.2060603@gmail.com>
	<384c93600703111907n2abcb36an27970a219eb0f946@mail.gmail.com>
Message-ID: <20070312032112.GA19626@cutter.rexx.com>

On Sun, Mar 11, 2007 at 09:07:41PM -0500, shawn bright wrote:
> Well, for your first response, its great,
> thanks a lot.
> shawn

And, when you needs to process command line arguments and flags and
options become more complicated, be sure to look at modules getopt
and optparse in the standard library.  optparse is newer and more
powerful than getopt, but also seems a bit more complex.

Dave


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

From nephish at gmail.com  Mon Mar 12 06:17:37 2007
From: nephish at gmail.com (shawn bright)
Date: Mon, 12 Mar 2007 00:17:37 -0500
Subject: [Tutor] how to send command line args to py script
In-Reply-To: <20070312032112.GA19626@cutter.rexx.com>
References: <384c93600703111823i4ba53abep2158db3c82262483@mail.gmail.com>
	<45F4B31D.2060603@gmail.com>
	<384c93600703111907n2abcb36an27970a219eb0f946@mail.gmail.com>
	<20070312032112.GA19626@cutter.rexx.com>
Message-ID: <384c93600703112217m28695aa7i322d6a8c566ac01a@mail.gmail.com>

OK, will do. Looks like my future will involve more of this kind of thing.

thanks
shawn

On 3/11/07, Dave Kuhlman <dkuhlman at rexx.com> wrote:
> On Sun, Mar 11, 2007 at 09:07:41PM -0500, shawn bright wrote:
> > Well, for your first response, its great,
> > thanks a lot.
> > shawn
>
> And, when you needs to process command line arguments and flags and
> options become more complicated, be sure to look at modules getopt
> and optparse in the standard library.  optparse is newer and more
> powerful than getopt, but also seems a bit more complex.
>
> Dave
>
>
> --
> Dave Kuhlman
> http://www.rexx.com/~dkuhlman
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From alan.gauld at btinternet.com  Mon Mar 12 09:32:18 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 12 Mar 2007 08:32:18 -0000
Subject: [Tutor] String-manipulation question
References: <20070312020445.ie0zt53nz1koww8s@webmail.frontiernet.net>
	<5e58f2e40703111952j406f24d1n869c941d3b5cc8d2@mail.gmail.com>
Message-ID: <et33af$va7$1@sea.gmane.org>

"John Fouhy" <john at fouhy.net> wrote in message 
news:5e58f2e40703111952j406f24d1n869c941d3b5cc8d2 at mail.gmail.com...
> On 12/03/07, Alan Gilfoy <agilfoy at frontiernet.net> wrote:
>
>> My question here boils down to, "Is there a way to remove certain
>> characters from a string?"

> In this case, it looks like you're after "string slicing".  The
> tutorial covers this; look about half-way down the page:
> http://docs.python.org/tut/node5.html

And that will also help you extract the first 3 characters too.

Alan G 



From juinsana at yahoo.com  Mon Mar 12 12:52:19 2007
From: juinsana at yahoo.com (J Greg)
Date: Mon, 12 Mar 2007 04:52:19 -0700 (PDT)
Subject: [Tutor] default parameters in classes
Message-ID: <972255.15294.qm@web32110.mail.mud.yahoo.com>

I want my object to create a fresh dictionary if its
not passed one. 

Perhaps I don't understand. In the example below, the
first instance correctly creates a fresh dictionary.
But the second instance seems to inherit the now dirty
dictionary from the first instance. 

What am I missing?


class newobj:
    
    def __init__(self, labl, d = {} ):
        print labl, d, '\n' # print the dictionary as
passed, or freshly created
        
        if d.has_key('obj1'):
            
            d['obj2'] = 'very dirty'
            
        d['obj1'] = 'dirty'

#-----------------------------------------------------------------
       
# Create 4 instances of an object
# If the parent doesn't already have a dictionary,
create one

obj1 = newobj('obj1:')      # ok
obj2 = newobj('obj2:')      # gets the dirty
dictionary from obj1

dd = dict(obj3=True)    
obj3 = newobj('obj3:', dd)  # ok
obj4 = newobj('obj4:')      # get a dirty dictionary
from obj2

"""
Prints this:

obj1: {} 

obj2: {'obj1': 'dirty'} 

obj3: {'obj3': True} 

obj4: {'obj1': 'dirty', 'obj2': 'very dirty'} 

"""



 
____________________________________________________________________________________
It's here! Your new message!  
Get new email alerts with the free Yahoo! Toolbar.
http://tools.search.yahoo.com/toolbar/features/mail/

From kent37 at tds.net  Mon Mar 12 13:29:44 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 12 Mar 2007 08:29:44 -0400
Subject: [Tutor] default parameters in classes
In-Reply-To: <972255.15294.qm@web32110.mail.mud.yahoo.com>
References: <972255.15294.qm@web32110.mail.mud.yahoo.com>
Message-ID: <45F547B8.6090707@tds.net>

J Greg wrote:
> I want my object to create a fresh dictionary if its
> not passed one. 
> 
> Perhaps I don't understand. In the example below, the
> first instance correctly creates a fresh dictionary.
> But the second instance seems to inherit the now dirty
> dictionary from the first instance. 
> 
> What am I missing?

http://www.effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm

Kent

From carroll at tjc.com  Mon Mar 12 19:03:39 2007
From: carroll at tjc.com (Terry Carroll)
Date: Mon, 12 Mar 2007 11:03:39 -0700 (PDT)
Subject: [Tutor] default parameters in classes
In-Reply-To: <972255.15294.qm@web32110.mail.mud.yahoo.com>
Message-ID: <Pine.LNX.4.44.0703121057470.26885-100000@violet.rahul.net>

On Mon, 12 Mar 2007, J Greg wrote:

> Perhaps I don't understand. In the example below, the
> first instance correctly creates a fresh dictionary.
> But the second instance seems to inherit the now dirty
> dictionary from the first instance. 
> 
> What am I missing?

This is a very common Python "gotcha," passing mutable objects as default 
arguments to a function.  If you do a google search on "python gotchas" it 
will show up in pretty much every list of gotchas.

The idiom to get around this is to instead use a default value of None, 
and then, if you actually see None in the function, set it equal to the 
real default argument you want, i.e.:

class newobj:
    def __init__(self, labl, d = None ):   # changed line
        if d is None:                      # added line
            d = {}                         # added line
        print labl, d, '\n'
        # print the dictionary as passed, or freshly created
        if d.has_key('obj1'):
            d['obj2'] = 'very dirty'
        d['obj1'] = 'dirty'

Now your code:

obj1 = newobj('obj1:')      # ok
obj2 = newobj('obj2:')      # gets the dirty dictionary from obj1

dd = dict(obj3=True)
obj3 = newobj('obj3:', dd)  # ok
obj4 = newobj('obj4:')      # get a dirty dictionary from obj2

Gets:

obj1: {}

obj2: {}

obj3: {'obj3': True}

obj4: {}


Is that more what you were expecting?


From jsmith at medplus.com  Mon Mar 12 19:04:51 2007
From: jsmith at medplus.com (Smith, Jeff)
Date: Mon, 12 Mar 2007 14:04:51 -0400
Subject: [Tutor] File locking
Message-ID: <288A3B43F7B2224D9C8441C9FC5D6A0201465B03@EXCHMAIL01.corp.medplus.com>

I'm always disappointed when I find something that Python doesn't handle
in a platform independent way.  It seems to me that file locking is in
that boat.
 
1. I don't see a way to atomically open a file for writing if and only
if it doesn't exist without resorting to os.open and specialized
platform O_XXX flags.
 
2. I don't see a way to atomically open a file for writing and obtain a
lock on the file.
 
3. I don't see a platform independent way to obtain a lock on a file.
You have to do something goofy like
if sys.platform == win32:
    import msvcrt
else:
    import fcntl
and then similar things to call the correct functions with the correct
flags.
 
Please let me know if I'm missing something since they seem like normal
file operations that I would hope Python would abstract away.  If not,
are there any PEPs concerning this for Python3K?
 
Thanks,
Jeff
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070312/8726f726/attachment.html 

From fharms at iowatelecom.net  Tue Mar 13 01:25:12 2007
From: fharms at iowatelecom.net (isaack  harms)
Date: Mon, 12 Mar 2007 18:25:12 -0600
Subject: [Tutor] (no subject)
Message-ID: <002001c76506$10ed8840$640fa8c0@your4f1261a8e5>


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

From geoframer at gmail.com  Tue Mar 13 11:57:14 2007
From: geoframer at gmail.com (Geoframer)
Date: Tue, 13 Mar 2007 11:57:14 +0100
Subject: [Tutor] Finding the minimum value in a multidimensional array
Message-ID: <5d8e35a70703130357k4e2d674bg254c8c42e19d4762@mail.gmail.com>

Hey everyone,

I've been trying to locate a way to find the location of the minimum value
in an n*n array.
For instance suppose we have a 10x10 array.

In [1]: import numpy
In [2]: a = numpy.zeros((10,10))
In [3]: a
Out[3]:
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])

And we set a value in that array to be the smallest just for illustration
purposes.

In [4]: a[9][8] = -1
In [5]: a
Out[5]:
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0., -1.,  0.]])

I can find this minimum using the 'min' function, but is there a way to find
the index to that position?

In [6]: a.min()
Out[6]: -1.0

Any help is appreciated. Please keep in mind that this is only a 'small'
example. What i'm trying to accomplish is to find the location of the
minimum value in a huge n*n array and quickly and efficiently finding the
index to that position.

Regards - Geofram
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070313/0a6b8341/attachment.htm 

From ronaldo at netf2r.com  Tue Mar 13 12:53:53 2007
From: ronaldo at netf2r.com (ronaldo at netf2r.com)
Date: Tue, 13 Mar 2007 08:53:53 -0300
Subject: [Tutor] HTTP file download
Message-ID: <20070313115353.GA1497@fw.netf2r.com>

Hello all,

How can I download a file using HTTP?
For example:
There is a file at: http://www.somesite.com/file. I need to get this file using HTTP from a python script.
I'm not sure but I think httplib could be used to do that.
Can anyone confirm that? or Can anyone suggest me something else?

Thank you? 

-- 
Ronaldo Z. Afonso
Phone: 55+11+82619082
www.netf2r.com

From ja_roush at mminternet.com  Tue Mar 13 13:27:19 2007
From: ja_roush at mminternet.com (Jim Roush)
Date: Tue, 13 Mar 2007 04:27:19 -0800
Subject: [Tutor] Squlite3 problem
Message-ID: <45F698A7.1030003@mminternet.com>

I'm geting the following error message and I'm stumped

Traceback (most recent call last):
  File "C:\markets\source\QuantScan\QuantScan4_3.py", line 1362, in <module>

    db.close()

sqlite3.OperationalError: Unable to close due to unfinalised statements



Here 's the relevant code

    db = sqlite.connect('c:/markets/db/market_2.db')
    cur_stocks = db.cursor()
    cur_quant = db.cursor()
    cur_subind = db.cursor()
       
    # update ROC table in db
    print '\nupdate ROC table in db...\n'
    cur = db.cursor()
    cur.execute("delete from subind_ROC")
   
    for row in range(0, num_of_subinds):
        (subind, si_ROC_10, si_ROC_10_1, si_ROC_10_2, si_ROC_20, 
si_ROC_20_1, \
            si_ROC_20_2, si_ROC_30, si_ROC_30_1, si_ROC_30_2) = si_ROC[row]

        cur.execute("INSERT INTO subind_ROC (subind, ROC_10, ROC_10_1, 
ROC_10_2, ROC_20, ROC_20_1, ROC_20_2, ROC_30, ROC_30_1, ROC_30_2) Values 
(?,?,?,?,?,?,?,?,?,?)", (subind, si_ROC_10, si_ROC_10_1, si_ROC_10_2, 
si_ROC_20, si_ROC_20_1, si_ROC_20_2, si_ROC_30, si_ROC_30_1, si_ROC_30_2))

    cur.close()
    db.commit()
    db.close()


From jason.massey at gmail.com  Tue Mar 13 13:13:54 2007
From: jason.massey at gmail.com (Jason Massey)
Date: Tue, 13 Mar 2007 07:13:54 -0500
Subject: [Tutor] Squlite3 problem
In-Reply-To: <45F698A7.1030003@mminternet.com>
References: <45F698A7.1030003@mminternet.com>
Message-ID: <7e3eab2c0703130513i6161b984gc72f167b4de3256b@mail.gmail.com>

I found a similar discussion on the pysqlite mailing list (
http://lists.initd.org/pipermail/pysqlite/2005-August/000127.html)

Try committing your changes and then closing your cursor.


 db.commit()
 cur.close()
 db.close()

On 3/13/07, Jim Roush <ja_roush at mminternet.com> wrote:
>
> I'm geting the following error message and I'm stumped
>
> Traceback (most recent call last):
>   File "C:\markets\source\QuantScan\QuantScan4_3.py", line 1362, in
> <module>
>
>     db.close()
>
> sqlite3.OperationalError: Unable to close due to unfinalised statements
>
>
>
> Here 's the relevant code
>
>     db = sqlite.connect('c:/markets/db/market_2.db')
>     cur_stocks = db.cursor()
>     cur_quant = db.cursor()
>     cur_subind = db.cursor()
>
>     # update ROC table in db
>     print '\nupdate ROC table in db...\n'
>     cur = db.cursor()
>     cur.execute("delete from subind_ROC")
>
>     for row in range(0, num_of_subinds):
>         (subind, si_ROC_10, si_ROC_10_1, si_ROC_10_2, si_ROC_20,
> si_ROC_20_1, \
>             si_ROC_20_2, si_ROC_30, si_ROC_30_1, si_ROC_30_2) =
> si_ROC[row]
>
>         cur.execute("INSERT INTO subind_ROC (subind, ROC_10, ROC_10_1,
> ROC_10_2, ROC_20, ROC_20_1, ROC_20_2, ROC_30, ROC_30_1, ROC_30_2) Values
> (?,?,?,?,?,?,?,?,?,?)", (subind, si_ROC_10, si_ROC_10_1, si_ROC_10_2,
> si_ROC_20, si_ROC_20_1, si_ROC_20_2, si_ROC_30, si_ROC_30_1, si_ROC_30_2))
>
>     cur.close()
>     db.commit()
>     db.close()
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070313/d0c7db5e/attachment.html 

From yaguarovi at gmail.com  Tue Mar 13 13:23:44 2007
From: yaguarovi at gmail.com (Jean-Philippe Durand)
Date: Tue, 13 Mar 2007 13:23:44 +0100
Subject: [Tutor] HTTP file download
In-Reply-To: <20070313115353.GA1497@fw.netf2r.com>
References: <20070313115353.GA1497@fw.netf2r.com>
Message-ID: <9f6eb18c0703130523q6cae625dj3fba695d585cc847@mail.gmail.com>

Hello Ronaldo,
Try this :

import urllib
mysock = urllib.urlopen("http://www.somesite.com/file")
htmlSource = mysock.read()
mysock.close()
print htmlSource

Regards.
Jean-Philippe DURAND


2007/3/13, ronaldo at netf2r.com <ronaldo at netf2r.com>:
>
> Hello all,
>
> How can I download a file using HTTP?
> For example:
> There is a file at: http://www.somesite.com/file. I need to get this file
> using HTTP from a python script.
> I'm not sure but I think httplib could be used to do that.
> Can anyone confirm that? or Can anyone suggest me something else?
>
> Thank you?
>
> --
> Ronaldo Z. Afonso
> Phone: 55+11+82619082
> www.netf2r.com
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070313/431c5867/attachment.htm 

From rdm at rcblue.com  Tue Mar 13 13:49:10 2007
From: rdm at rcblue.com (Dick Moores)
Date: Tue, 13 Mar 2007 05:49:10 -0700
Subject: [Tutor] number generator
In-Reply-To: <Xns98F26344EE1F3duncanbooth@127.0.0.1>
References: <1173451441.077648.321270@c51g2000cwc.googlegroups.com>
	<7x7itqqxlh.fsf@ruckus.brouhaha.com>
	<1173453432.893222.308610@j27g2000cwj.googlegroups.com>
	<mailman.4897.1173522747.32031.python-list@python.org>
	<pan.2007.03.10.13.38.30.791542@REMOVE.THIS.cybersource.com.au>
	<mailman.5009.1173771590.32031.python-list@python.org>
	<Xns98F26344EE1F3duncanbooth@127.0.0.1>
Message-ID: <20070313125009.22EC21E4003@bag.python.org>

At 02:52 AM 3/13/2007, Duncan Booth wrote:
>Dick Moores <rdm at rcblue.com> wrote:
>
> > But let's say there is one more constraint--that for each n of the N
> > positive integers, there must be an equal chance for n to be any of
> > the integers between 1 and M-N+1, inclusive. Thus for M == 50 and N
> >== 5, the generated list of 5 should be as likely to be [1,46,1,1,1]
> > as [10,10,10,10,10] or [14, 2, 7, 1, 26].
>
>I don't think what you wrote actually works. Any combination including a 46
>must also have four 1s, so the digit 1 has to be at least 4 times as likely
>to appear as the digit 46, and probably a lot more likely than that.

Yes, I see you're right. Thanks.

>On the other hand, making sure that each combination occurs equally often
>(as your example might imply) is doable but still leaves the question
>whether the order of the numbers matters: are [1,46,1,1,1] and [1,1,46,1,1]
>the same or different combinations?

If the added constraint is instead that the probability of generating 
a given list of length N be the same as that of generating any other 
list of length N, then I believe my function does the job. Of course, 
[1,46,1,1,1] and [1,1,46,1,1], as Python lists, are distinct. I ran 
this test for M == 8 and N == 4:
======================================================
def sumRndInt(M, N):
     import random
     while True:
         lst = []
         for x in range(N):
             n = random.randint(1,M-N+1)
             lst.append(n)
         if sum(lst) == M:
             return lst

A = []
B = []
for x in range(100000):
     lst = sumRndInt(8,4)
     if lst not in A:
         A.append(lst)
         B.append(1)
     else:
         i = A.index(lst)
         B[i] += 1

A.sort()
print A
print B
print len(A), len(B)
===========================================================
a typical run produced:
[[1, 1, 1, 5], [1, 1, 2, 4], [1, 1, 3, 3], [1, 1, 4, 2], [1, 1, 5, 
1], [1, 2, 1, 4], [1, 2, 2, 3], [1, 2, 3, 2], [1, 2, 4, 1], [1, 3, 1, 
3], [1, 3, 2, 2], [1, 3, 3, 1], [1, 4, 1, 2], [1, 4, 2, 1], [1, 5, 1, 
1], [2, 1, 1, 4], [2, 1, 2, 3], [2, 1, 3, 2], [2, 1, 4, 1], [2, 2, 1, 
3], [2, 2, 2, 2], [2, 2, 3, 1], [2, 3, 1, 2], [2, 3, 2, 1], [2, 4, 1, 
1], [3, 1, 1, 3], [3, 1, 2, 2], [3, 1, 3, 1], [3, 2, 1, 2], [3, 2, 2, 
1], [3, 3, 1, 1], [4, 1, 1, 2], [4, 1, 2, 1], [4, 2, 1, 1], [5, 1, 1, 1]]

[2929, 2847, 2806, 2873, 2887, 2856, 2854, 2825, 2847, 2926, 2927, 
2816, 2816, 2861, 2919, 2820, 2890, 2848, 2898, 2883, 2820, 2820, 
2829, 2883, 2873, 2874, 2891, 2884, 2837, 2853, 2759, 2761, 2766, 2947, 2875]

35 35

Dick Moores





From rdm at rcblue.com  Tue Mar 13 13:58:40 2007
From: rdm at rcblue.com (Dick Moores)
Date: Tue, 13 Mar 2007 05:58:40 -0700
Subject: [Tutor] number generator
In-Reply-To: <20070313125009.22EC21E4003@bag.python.org>
References: <1173451441.077648.321270@c51g2000cwc.googlegroups.com>
	<7x7itqqxlh.fsf@ruckus.brouhaha.com>
	<1173453432.893222.308610@j27g2000cwj.googlegroups.com>
	<mailman.4897.1173522747.32031.python-list@python.org>
	<pan.2007.03.10.13.38.30.791542@REMOVE.THIS.cybersource.com.au>
	<mailman.5009.1173771590.32031.python-list@python.org>
	<Xns98F26344EE1F3duncanbooth@127.0.0.1>
	<20070313125009.22EC21E4003@bag.python.org>
Message-ID: <20070313125843.54CF11E4015@bag.python.org>

So sorry. I meant this for the python list.

Dick Moores

At 05:49 AM 3/13/2007, Dick Moores wrote:
>At 02:52 AM 3/13/2007, Duncan Booth wrote:
> >Dick Moores <rdm at rcblue.com> wrote:
> >
> > > But let's say there is one more constraint--that for each n of the N
> > > positive integers, there must be an equal chance for n to be any of
> > > the integers between 1 and M-N+1, inclusive. Thus for M == 50 and N
> > >== 5, the generated list of 5 should be as likely to be [1,46,1,1,1]
> > > as [10,10,10,10,10] or [14, 2, 7, 1, 26].
> >
> >I don't think what you wrote actually works. Any combination including a 46
> >must also have four 1s, so the digit 1 has to be at least 4 times as likely
> >to appear as the digit 46, and probably a lot more likely than that.
>
>Yes, I see you're right. Thanks.
>
> >On the other hand, making sure that each combination occurs equally often
> >(as your example might imply) is doable but still leaves the question
> >whether the order of the numbers matters: are [1,46,1,1,1] and [1,1,46,1,1]
> >the same or different combinations?
>
>If the added constraint is instead that the probability of generating
>a given list of length N be the same as that of generating any other
>list of length N, then I believe my function does the job. Of course,
>[1,46,1,1,1] and [1,1,46,1,1], as Python lists, are distinct. I ran
>this test for M == 8 and N == 4:
>======================================================
>def sumRndInt(M, N):
>      import random
>      while True:
>          lst = []
>          for x in range(N):
>              n = random.randint(1,M-N+1)
>              lst.append(n)
>          if sum(lst) == M:
>              return lst
>
>A = []
>B = []
>for x in range(100000):
>      lst = sumRndInt(8,4)
>      if lst not in A:
>          A.append(lst)
>          B.append(1)
>      else:
>          i = A.index(lst)
>          B[i] += 1
>
>A.sort()
>print A
>print B
>print len(A), len(B)
>===========================================================
>a typical run produced:
>[[1, 1, 1, 5], [1, 1, 2, 4], [1, 1, 3, 3], [1, 1, 4, 2], [1, 1, 5,
>1], [1, 2, 1, 4], [1, 2, 2, 3], [1, 2, 3, 2], [1, 2, 4, 1], [1, 3, 1,
>3], [1, 3, 2, 2], [1, 3, 3, 1], [1, 4, 1, 2], [1, 4, 2, 1], [1, 5, 1,
>1], [2, 1, 1, 4], [2, 1, 2, 3], [2, 1, 3, 2], [2, 1, 4, 1], [2, 2, 1,
>3], [2, 2, 2, 2], [2, 2, 3, 1], [2, 3, 1, 2], [2, 3, 2, 1], [2, 4, 1,
>1], [3, 1, 1, 3], [3, 1, 2, 2], [3, 1, 3, 1], [3, 2, 1, 2], [3, 2, 2,
>1], [3, 3, 1, 1], [4, 1, 1, 2], [4, 1, 2, 1], [4, 2, 1, 1], [5, 1, 1, 1]]
>
>[2929, 2847, 2806, 2873, 2887, 2856, 2854, 2825, 2847, 2926, 2927,
>2816, 2816, 2861, 2919, 2820, 2890, 2848, 2898, 2883, 2820, 2820,
>2829, 2883, 2873, 2874, 2891, 2884, 2837, 2853, 2759, 2761, 2766, 2947, 2875]
>
>35 35
>
>Dick Moores
>
>
>
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor


From eike.welk at gmx.net  Tue Mar 13 14:20:50 2007
From: eike.welk at gmx.net (Eike Welk)
Date: Tue, 13 Mar 2007 14:20:50 +0100
Subject: [Tutor] Finding the minimum value in a multidimensional array
In-Reply-To: <5d8e35a70703130357k4e2d674bg254c8c42e19d4762@mail.gmail.com>
References: <5d8e35a70703130357k4e2d674bg254c8c42e19d4762@mail.gmail.com>
Message-ID: <200703131420.50982.eike.welk@gmx.net>

On Tuesday 13 March 2007 11:57, Geoframer wrote:
> Hey everyone,
>
> I've been trying to locate a way to find the location of the
> minimum value in an n*n array.

The 'argmin' function is probably what you are looking for.
See the examples at:

http://www.scipy.org/Numpy_Example_List

Regards Eike.


From geoframer at gmail.com  Tue Mar 13 14:45:07 2007
From: geoframer at gmail.com (Geoframer)
Date: Tue, 13 Mar 2007 14:45:07 +0100
Subject: [Tutor] Finding the minimum value in a multidimensional array
In-Reply-To: <200703131420.50982.eike.welk@gmx.net>
References: <5d8e35a70703130357k4e2d674bg254c8c42e19d4762@mail.gmail.com>
	<200703131420.50982.eike.welk@gmx.net>
Message-ID: <5d8e35a70703130645s7b5f3e4ak7d5e67b1cabc6d72@mail.gmail.com>

I don't see a solution here... It is not conclusive on what's the minimum
for an array.

ln [1]: import numpy
In [2]: a = numpy.array([[1,2,3,0],[2,3,4,5],[6,5,4,3],[-1,2,-4,5]])

In [3]: a
Out[3]:
array([[ 1,  2,  3,  0],
       [ 2,  3,  4,  5],
       [ 6,  5,  4,  3],
       [-1,  2, -4,  5]])

In [4]: a.argmin(0)
Out[4]: array([3, 0, 3, 0])

In [5]: a.argmin(1)
Out[5]: array([3, 0, 3, 2])

a.argmin(0) shows where the minimum is for each row
a.argmin(1) shows whree the minimum is for each column

Which combined gives (row, column) : (0,3), (1,0), (2,3) and (3,2). So
basically 4 values which i still need to compare. In a small array this
might not be a hefty computational effort. In a n*n array this will lead to
N values which need both indexing and comparing.

Perhaps this is the only solution around but i hope not. In either way
thanks for your time and suggestion.

Regards Geofram


On 3/13/07, Eike Welk <eike.welk at gmx.net> wrote:
>
> On Tuesday 13 March 2007 11:57, Geoframer wrote:
> > Hey everyone,
> >
> > I've been trying to locate a way to find the location of the
> > minimum value in an n*n array.
>
> The 'argmin' function is probably what you are looking for.
> See the examples at:
>
> http://www.scipy.org/Numpy_Example_List
>
> Regards Eike.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070313/bae37e40/attachment.htm 

From malaclypse2 at gmail.com  Tue Mar 13 15:00:05 2007
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Tue, 13 Mar 2007 10:00:05 -0400
Subject: [Tutor] Finding the minimum value in a multidimensional array
In-Reply-To: <5d8e35a70703130645s7b5f3e4ak7d5e67b1cabc6d72@mail.gmail.com>
References: <5d8e35a70703130357k4e2d674bg254c8c42e19d4762@mail.gmail.com>
	<200703131420.50982.eike.welk@gmx.net>
	<5d8e35a70703130645s7b5f3e4ak7d5e67b1cabc6d72@mail.gmail.com>
Message-ID: <16651e80703130700j1e83c924y6d060ac7c6a6fe2e@mail.gmail.com>

On 3/13/07, Geoframer <geoframer at gmail.com> wrote:
> I don't see a solution here... It is not conclusive on what's the minimum
> for an array.
>
> ln [1]: import numpy
>  In [2]: a =
> numpy.array([[1,2,3,0],[2,3,4,5],[6,5,4,3],[-1,2,-4,5]])

Well, what exactly is it that you'd like the answer to be?  The
samples page Eike pointed you to show a couple of ways to do it,
depending on exactly what piece of data you're looking for.  Here's a
bit more along the same lines.  If this doesn't help, perhaps you
could show us a bit of sample data and tell us exactly what answer
you'd like to extract.

>>> a = numpy.array([[1,2,3,0],[2,3,4,5],[6,5,4,3],[-1,2,-4,5]])
>>> a.argmin()
14
>>> a.ravel()[14]
-4
>>> divmod(14, 4)
(3, 2)
>>> a[3][2]
-4

-- 
Jerry

From miguel.oliveira.jr at gmail.com  Tue Mar 13 17:33:47 2007
From: miguel.oliveira.jr at gmail.com (Miguel Oliveira, Jr.)
Date: Tue, 13 Mar 2007 16:33:47 +0000
Subject: [Tutor] Quicktime & Python
Message-ID: <9A7F60C8-213D-494A-89DD-D9BC2274B33D@gmail.com>

Hello,

Just wondering: is there a way to play quicktime .mov files from  
python? I am trying to run an experiment and would like to have  
Python to play the .mov files I have in a given sequence (or in  
random), in full screen and to record a log of the files that were  
played, the order and the time. Any help will be very much appreciated.

Thanks,

Miguel

From miguel.oliveira.jr at gmail.com  Tue Mar 13 17:40:21 2007
From: miguel.oliveira.jr at gmail.com (Miguel Oliveira, Jr.)
Date: Tue, 13 Mar 2007 16:40:21 +0000
Subject: [Tutor] Numpy
Message-ID: <7D11B162-725A-497C-9985-C357A914E03D@gmail.com>

Hello,

I've just intalled [manually] numpy into a Mac Intel OS 10.4. I'm  
running Python version 2.5. Whenever I import numpy, I get the  
following message:

Running from numpy source directory

Does anyone know if this is normal? In Python 2.4, no such message  
pops up when numpy is imported. But then there is a nice setup file  
for Python 2.4 that automaticall install numpy in the correct  
directories.

Thanks for any thoughts on this.

Miguel

From hugonz-lists at h-lab.net  Tue Mar 13 18:53:47 2007
From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=)
Date: Tue, 13 Mar 2007 11:53:47 -0600
Subject: [Tutor] Quicktime & Python
In-Reply-To: <9A7F60C8-213D-494A-89DD-D9BC2274B33D@gmail.com>
References: <9A7F60C8-213D-494A-89DD-D9BC2274B33D@gmail.com>
Message-ID: <45F6E52B.2050206@h-lab.net>

Miguel Oliveira, Jr. wrote:
> Hello,
> 
> Just wondering: is there a way to play quicktime .mov files from  
> python? I am trying to run an experiment and would like to have  
> Python to play the .mov files I have in a given sequence (or in  
> random), in full screen and to record a log of the files that were  
> played, the order and the time. Any help will be very much appreciated.
> 

I would use mplayer. You can control mplayer through a simple text 
interface called slave mode and log what you send to it.

I've got some code you could use, using the subprocess module if you 
want it.

Hugo

From carroll at tjc.com  Tue Mar 13 21:01:48 2007
From: carroll at tjc.com (Terry Carroll)
Date: Tue, 13 Mar 2007 13:01:48 -0700 (PDT)
Subject: [Tutor] trouble with function-- trying to check differences
 btwn 2 strings
In-Reply-To: <eskqbl$qt$1@sea.gmane.org>
Message-ID: <Pine.LNX.4.44.0703131257060.20277-100000@violet.rahul.net>

On Tue, 6 Mar 2007, Alan Gauld wrote:

> But I've been up since 4:30am and am too tired to try 
> figuring it out just now, so maybe someone else will 
> explain! :-)
> 
> >>> for c in 'abcd':
> ...    print (c == c in 'crab')
> ...
> True
> True
> True
> False

Trying to understand that, I tried this, which left me even more 
confused:

>>> for c in "abcd":
...    print (c == c in "crab"), (c == (c in "crab"))
...
True False
True False
True False
False False


From bgailer at alum.rpi.edu  Tue Mar 13 22:08:14 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Tue, 13 Mar 2007 14:08:14 -0700
Subject: [Tutor] Roman to digital (pseudocode)
In-Reply-To: <20070308160158.a365mpgvsa8s4080@webmail.frontiernet.net>
References: <20070308160158.a365mpgvsa8s4080@webmail.frontiernet.net>
Message-ID: <45F712BE.60606@alum.rpi.edu>

Deep breath .... and big step back.

The problem is not just how to code this in Python, but how to parse a 
language (in this case Roman Numbers).

I have studied formal language theory but am not an expert. So here's my 
take on an algorithm that would save a lot of stress.

Create a dictionary with
    keys for each roman letter and each "pair" (iv, ix, xl, xc, etc)
    values are the corresponding decimal values.
Starting at the left of the roman_input and repeating until the end of 
the roman_input
  Take the next pair of roman_input.
  If it is in the dictionary
    add the decimal value and step to the next letter.
  Else
    take the leftmost letter of that pair
    If it is in the dictionary
      add the decimal value and step to the next letter.
   Else
     complain about bad letter

-- 
Bob Gailer
510-978-4454


From clay.wiedemann at gmail.com  Tue Mar 13 23:26:43 2007
From: clay.wiedemann at gmail.com (Clay Wiedemann)
Date: Tue, 13 Mar 2007 18:26:43 -0400
Subject: [Tutor] Roman to digital (pseudocode)
In-Reply-To: <45F712BE.60606@alum.rpi.edu>
References: <20070308160158.a365mpgvsa8s4080@webmail.frontiernet.net>
	<45F712BE.60606@alum.rpi.edu>
Message-ID: <781164cc0703131526n2910e3b3s7c624affebaa78f5@mail.gmail.com>

I am new to python and programming, so not sure if I should weigh in
here. Nonetheless . . .

Creating a dictionary seems fair, but I wonder about using pairs
rather than single letters. Roman numerals are constructed from strict
rules other than the allowable letter set -- here is the relevant
wikipedia bit:

Rules regarding Roman numerals often state that a symbol representing
10x may not precede any symbol larger than 10x+1. For example, C
cannot be preceded by I or V, only by X (or, of course, by a symbol
representing a value equal to or larger than C). Thus, one should
represent the number "ninety-nine" as XCIX, not as the "shortcut" IC.
However, these rules are not universally followed.

Although the shortcut may be easier for people, the universal notation
may be easier to define programmatically. I am wondering what would be
the best way to create the rules

 - A dictionary will help you look up values, but not rules. It does
not retain its order and order is essential. Instead, create a tuple
of the roman numerals in ascending order (roman). Create a paired
tuple with the base 10 value (baseten).

Now get an element from the string you want to test -- use the index
value in roman to test the rules -- you will know what is higher,
lower, and the same

Then look for things like the following:

- does the following element have a lower index in roman? if yes, you
know the value (match indexes from the tuples) -- step forward
- what if the follower is the same? then check the one after, if it is
the same (and the following digit is lower) then you have a value. --
step over the last matching digit
- if the following value is higher, it must be by only one unit, if so
you have a value, but also a new rule: the following digit must be
lower than the last digit of the pair.

and so on.
not pseudocode I know, and I am certain there are better ways to do
this, but maybe something here helps.

-c














On 3/13/07, Bob Gailer <bgailer at alum.rpi.edu> wrote:
> Deep breath .... and big step back.
>
> The problem is not just how to code this in Python, but how to parse a
> language (in this case Roman Numbers).
>
> I have studied formal language theory but am not an expert. So here's my
> take on an algorithm that would save a lot of stress.
>
> Create a dictionary with
>     keys for each roman letter and each "pair" (iv, ix, xl, xc, etc)
>     values are the corresponding decimal values.
> Starting at the left of the roman_input and repeating until the end of
> the roman_input
>   Take the next pair of roman_input.
>   If it is in the dictionary
>     add the decimal value and step to the next letter.
>   Else
>     take the leftmost letter of that pair
>     If it is in the dictionary
>       add the decimal value and step to the next letter.
>    Else
>      complain about bad letter
>
> --
> Bob Gailer
> 510-978-4454
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


-- 

- - - - - - -

Clay S. Wiedemann

voice: 718.362.0375
aim: khlav
wii: 3905 4571 6175 2469
twitter: seastokes

From matthew.williams at cancer.org.uk  Tue Mar 13 23:54:05 2007
From: matthew.williams at cancer.org.uk (Matt Williams)
Date: Tue, 13 Mar 2007 22:54:05 +0000
Subject: [Tutor] Lexicographic ordering (or something simpler)
Message-ID: <45F72B8D.9010108@cancer.org.uk>

Dear All,

I'm trying to write something to calculate rule priorities, based on 
their provenance (ultimately I'm after a lexicographic ordering)

I have a set of terms (the provenances) I'm try to sort. I've done it by 
associating each possible set of terms with a dictionary, and then using 
the elements of the set as keys of the dictionary, so that it can look 
up the values. This is (almost certainly) sub-optimal, but ok for now....

Where I get stuck is that each rule is compared pairwise to each other; 
the precedence of the set of rules is then based on that. Since there 
can be ties between the rules, the result of each pairwise comparison 
for two rules a & ) is either 1,0 or -1, where 1 == a beats b, -1 == b 
beats a and 0 == tie.

At the moment I get back a list of results from testing one set of rules 
against the other. I now need to make a decision based on all the 
results. I've tried coding it as if...elif statements, but that all gets 
horrible.

Given a list of the form [1,0,0,1,-1] I need to make decision (in this, 
  it is undecided, so we drop down to the next criteria).

Any ideas/ pointers as to how I implement this?

Thanks,

Matt


-- 
http://acl.icnet.uk/~mw
http://adhominem.blogsome.com/
+44 (0)7834 899570

From kent37 at tds.net  Wed Mar 14 00:51:40 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 13 Mar 2007 19:51:40 -0400
Subject: [Tutor] Roman to digital (pseudocode)
In-Reply-To: <20070308160158.a365mpgvsa8s4080@webmail.frontiernet.net>
References: <20070308160158.a365mpgvsa8s4080@webmail.frontiernet.net>
Message-ID: <45F7390C.1040904@tds.net>

Alan Gilfoy wrote:
> This, I heard, is more difficult than digital-to-Roman, since you have  
> to "read" the subtractive cases, with a smaller numeral placed before  
> a larger numeral, without simply adding all the numerals' values up
> 
> I'm going to use a raw_input prompt to ask the user which Roman  
> numeral he/she wants to convert. How do I "screen" for inputs that  
> have characters besides "I", "V", "X", "L", "C", "D", or "M"?

You could have a string containing all the allowed characters and make 
sure each input character is in the allowed list.
> 
> Second Python question:
> 
> I know there's a way to "find out" the name of the first item in a list
> (ListName[0]), but is there a way to find out the first character of a string?

Lists and strings are both sequences and many of the same operations 
work on both. (All of the immutable sequence operations work on both.) 
So MyString[0] is the first character in a string.
> 
> Also, is there a way to "ask" Python what characters are before and  
> after the character in the string that you're asking about?
> 
> For example, usign the sample string "MCMXVII" (1917):
> 
> How would you ask Python:
> "What's the 3rd character in this string?" (returns "M")
s[2]

> "What's before that character?" (returns "C")
s[1] or maybe s[2-1] if the 2 is actually in a variable.

Kent

From kent37 at tds.net  Wed Mar 14 00:53:35 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 13 Mar 2007 19:53:35 -0400
Subject: [Tutor] Roman to digital (pseudocode)
In-Reply-To: <45F712BE.60606@alum.rpi.edu>
References: <20070308160158.a365mpgvsa8s4080@webmail.frontiernet.net>
	<45F712BE.60606@alum.rpi.edu>
Message-ID: <45F7397F.80702@tds.net>

Bob Gailer wrote:
> Deep breath .... and big step back.
> 
> The problem is not just how to code this in Python, but how to parse a 
> language (in this case Roman Numbers).
> 
> I have studied formal language theory but am not an expert. So here's my 
> take on an algorithm that would save a lot of stress.
> 
> Create a dictionary with
>     keys for each roman letter and each "pair" (iv, ix, xl, xc, etc)
>     values are the corresponding decimal values.
> Starting at the left of the roman_input and repeating until the end of 
> the roman_input
>   Take the next pair of roman_input.
>   If it is in the dictionary
>     add the decimal value and step to the next letter.
>   Else
>     take the leftmost letter of that pair
>     If it is in the dictionary
>       add the decimal value and step to the next letter.
>    Else
>      complain about bad letter

Or make a list of all the pairs and values, followed by all the single 
letters and values, and just find the first match from the list against 
the start of the test string.

Neither of these is really a parser, though; they allow badly formed 
numbers like IICCXM.

Kent

From kent37 at tds.net  Wed Mar 14 00:58:05 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 13 Mar 2007 19:58:05 -0400
Subject: [Tutor] Lexicographic ordering (or something simpler)
In-Reply-To: <45F72B8D.9010108@cancer.org.uk>
References: <45F72B8D.9010108@cancer.org.uk>
Message-ID: <45F73A8D.1090904@tds.net>

Matt Williams wrote:
> Dear All,
> 
> I'm trying to write something to calculate rule priorities, based on 
> their provenance (ultimately I'm after a lexicographic ordering)

I don't understand your problem description at all but maybe this will 
help. If you sort a list of lists or a list of tuples it will be a 
lexicographical sort. And the sort() method takes an optional key= 
parameter which is a function that creates a sort key. So if you can 
create a key off your terms then you can sort off that.
> 
> I have a set of terms (the provenances) I'm try to sort. I've done it by 
> associating each possible set of terms with a dictionary, and then using 
> the elements of the set as keys of the dictionary, so that it can look 
> up the values. This is (almost certainly) sub-optimal, but ok for now....

If you have some working code it would probably be helpful to see it. 
Then we can help you improve it.

Kent

From cappy2112 at gmail.com  Wed Mar 14 01:59:24 2007
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Tue, 13 Mar 2007 17:59:24 -0700
Subject: [Tutor] HTTP file download
Message-ID: <8249c4ac0703131759h6225b720r8d3be4577f6a773d@mail.gmail.com>

How do you handle a binary file?

Message: 4
Date: Tue, 13 Mar 2007 13:23:44 +0100
From: "Jean-Philippe Durand" <yaguarovi at gmail.com>
Subject: Re: [Tutor] HTTP file download
To: "ronaldo at netf2r.com" <ronaldo at netf2r.com>
Cc: tutor at python.org
Message-ID:
       <9f6eb18c0703130523q6cae625dj3fba695d585cc847 at mail.gmail.com>
Content-Type: text/plain; charset="iso-8859-1"

Hello Ronaldo,
Try this :

import urllib
mysock = urllib.urlopen("http://www.somesite.com/file")
htmlSource = mysock.read()
mysock.close()
print htmlSource

Regards.
Jean-Philippe DURAND

From deliberatus at verizon.net  Wed Mar 14 08:23:08 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Wed, 14 Mar 2007 02:23:08 -0500
Subject: [Tutor] declaring decaration on ul list
Message-ID: <45F7A2DC.1090706@verizon.net>

It just occurred to me that when my wiki does a backsearch it is useful 
to list the results with a * for decorating the unordered list results, 
so I can mousecopy it to update the category(foo) page, /the normal 
bullet is mousecopied as a poundsign (#}. How does one specify what to 
render as a item decoration in an unordered list?
-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From hyperneato at gmail.com  Wed Mar 14 08:19:14 2007
From: hyperneato at gmail.com (Isaac)
Date: Wed, 14 Mar 2007 00:19:14 -0700
Subject: [Tutor] trouble with function-- trying to check
Message-ID: <7260654a0703140019m2bb59f65q790425dfe4b95194@mail.gmail.com>

a, b, c are all in crab but d is not.


> >>> for c in 'abcd':
> ...    print (c == c in 'crab')
> ...
> True
> True
> True
> False



>
> Message: 5
> Date: Tue, 13 Mar 2007 13:01:48 -0700 (PDT)
> From: Terry Carroll <carroll at tjc.com>
> Subject: Re: [Tutor] trouble with function-- trying to check
>         differences btwn 2 strings
> To: tutor at python.org
> Message-ID:
>         <Pine.LNX.4.44.0703131257060.20277-100000 at violet.rahul.net>
> Content-Type: TEXT/PLAIN; charset=US-ASCII
>
> On Tue, 6 Mar 2007, Alan Gauld wrote:
>
> > But I've been up since 4:30am and am too tired to try
> > figuring it out just now, so maybe someone else will
> > explain! :-)
> >
> > >>> for c in 'abcd':
> > ...    print (c == c in 'crab')
> > ...
> > True
> > True
> > True
> > False
>
> Trying to understand that, I tried this, which left me even more
> confused:
>
> >>> for c in "abcd":
> ...    print (c == c in "crab"), (c == (c in "crab"))
> ...
> True False
> True False
> True False
> False False
>
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070314/e7ffd4f7/attachment.htm 

From hyperneato at gmail.com  Wed Mar 14 08:43:41 2007
From: hyperneato at gmail.com (Isaac)
Date: Wed, 14 Mar 2007 00:43:41 -0700
Subject: [Tutor] trouble with function-- trying to check
In-Reply-To: <7260654a0703140019m2bb59f65q790425dfe4b95194@mail.gmail.com>
References: <7260654a0703140019m2bb59f65q790425dfe4b95194@mail.gmail.com>
Message-ID: <7260654a0703140043i1fe6bb5ah196485b7c95c9e52@mail.gmail.com>

a, b, c, or d is a type('str') not boolean which is what (c in "crab") is.
The [in] operator takes presedence, the first 3 times (c in "crab") returns
true and the last returns false; but the strings a, b, c, or d do not ==
true or false - therefore the test (c == (c in "crab")) always returns
false.


(I think)

cheers

-Isaac

reference:
http://docs.python.org/ref/summary.html


Terry wrote:

>>> for c in "abcd":
...    print (c == c in "crab"), (c == (c in "crab"))
...
True False
True False
True False
False False
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070314/82f42cae/attachment.html 

From carroll at tjc.com  Wed Mar 14 09:04:08 2007
From: carroll at tjc.com (Terry Carroll)
Date: Wed, 14 Mar 2007 01:04:08 -0700 (PDT)
Subject: [Tutor] trouble with function-- trying to check
In-Reply-To: <7260654a0703140043i1fe6bb5ah196485b7c95c9e52@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0703140058300.2015-100000@violet.rahul.net>

On Wed, 14 Mar 2007, Isaac wrote:

> a, b, c, or d is a type('str') not boolean which is what (c in "crab") is.
> The [in] operator takes presedence, the first 3 times (c in "crab") returns
> true and the last returns false; but the strings a, b, c, or d do not ==
> true or false - therefore the test (c == (c in "crab")) always returns
> false.

The thing is, if the in operator takes precedence than why do 


  (c == c in "crab")

 and 

  (c == (c in "crab"))

return different results?



From hyperneato at gmail.com  Wed Mar 14 09:04:28 2007
From: hyperneato at gmail.com (Isaac)
Date: Wed, 14 Mar 2007 01:04:28 -0700
Subject: [Tutor] trouble with function-- trying to check
In-Reply-To: <7260654a0703140043i1fe6bb5ah196485b7c95c9e52@mail.gmail.com>
References: <7260654a0703140019m2bb59f65q790425dfe4b95194@mail.gmail.com>
	<7260654a0703140043i1fe6bb5ah196485b7c95c9e52@mail.gmail.com>
Message-ID: <7260654a0703140104s4b593e1fu7598cc985c152233@mail.gmail.com>

As far as I can tell:
because (c in "crab") membership is in parentheses it is more binding than
the [==] comparison. That is why it returns true/false first.

I incorrectly wrote before:
" The [in] operator takes precedence"

http://docs.python.org/ref/summary.html


-Isaac


On 3/14/07, Isaac <hyperneato at gmail.com> wrote:
>
> a, b, c, or d is a type('str') not boolean which is what (c in "crab") is.
> The [in] operator takes presedence, the first 3 times (c in "crab") returns
> true and the last returns false; but the strings a, b, c, or d do not ==
> true or false - therefore the test (c == (c in "crab")) always returns
> false.
>
>
> (I think)
>
> cheers
>
> -Isaac
>
> reference:
> http://docs.python.org/ref/summary.html
>
>
> Terry wrote:
>
> >>> for c in "abcd":
> ...    print (c == c in "crab"), (c == (c in "crab"))
> ...
> True False
> True False
> True False
> False False
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070314/57309d83/attachment.htm 

From janos.juhasz at VELUX.com  Wed Mar 14 09:17:09 2007
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Wed, 14 Mar 2007 09:17:09 +0100
Subject: [Tutor] Roman to digital (pseudocode)
In-Reply-To: <mailman.16514.1173830292.32030.tutor@python.org>
Message-ID: <OF62007377.723C0A77-ONC125729E.002BE9E4-C125729E.002D843D@velux.com>

Hi All,


> - A dictionary will help you look up values, but not rules. It does
> not retain its order and order is essential. Instead, create a tuple
> of the roman numerals in ascending order (roman). Create a paired
> tuple with the base 10 value (baseten).

> Now get an element from the string you want to test -- use the index
> value in roman to test the rules -- you will know what is higher,
> lower, and the same

> Then look for things like the following:

> - does the following element have a lower index in roman? if yes, you
> know the value (match indexes from the tuples) -- step forward
> - what if the follower is the same? then check the one after, if it is
> the same (and the following digit is lower) then you have a value. --
> step over the last matching digit
> - if the following value is higher, it must be by only one unit, if so
> you have a value, but also a new rule: the following digit must be
> lower than the last digit of the pair.

> and so on.
> not pseudocode I know, and I am certain there are better ways to do
> this, but maybe something here helps.


#############################
roman_codec = {'M':1000, 'D':500, 'C':100, 'L':50, 'X':10, 'V':5, 'I':1}

original = raw_input('Enter a roman number:')
roman = original.upper()
roman = list(roman) # I would like to use pop instead roman = roman[1:]
roman.reverse() # pop picks from the end, so prepare for it
decimal = [roman_codec[ch] for ch in roman] # turn the chars into decimal

result = 0

while len(decimal):
    act = decimal.pop()
    if len(decimal) and act < max(decimal): act = -act # if there is a 
char with higher score it is minus :)
    result += act

print original, '=', result
############################

Python is nearly pseudocode.
This is the reason we like it so much.


Best regards,
Janos Juhasz

From kent37 at tds.net  Wed Mar 14 11:39:01 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 14 Mar 2007 06:39:01 -0400
Subject: [Tutor] trouble with function-- trying to check
In-Reply-To: <Pine.LNX.4.44.0703140058300.2015-100000@violet.rahul.net>
References: <Pine.LNX.4.44.0703140058300.2015-100000@violet.rahul.net>
Message-ID: <45F7D0C5.3020107@tds.net>

Terry Carroll wrote:
> On Wed, 14 Mar 2007, Isaac wrote:
> 
>> a, b, c, or d is a type('str') not boolean which is what (c in "crab") is.
>> The [in] operator takes presedence, the first 3 times (c in "crab") returns
>> true and the last returns false; but the strings a, b, c, or d do not ==
>> true or false - therefore the test (c == (c in "crab")) always returns
>> false.
> 
> The thing is, if the in operator takes precedence than why do 
> 
> 
>   (c == c in "crab")
> 
>  and 
> 
>   (c == (c in "crab"))
> 
> return different results?

This has already been discussed on this thread. == and 'in' are comparisons.
(c == c in 'crab')
means
(c == c) and (c in 'crab')

http://docs.python.org/ref/comparisons.html

Kent

From ronaldo at netf2r.com  Wed Mar 14 11:56:03 2007
From: ronaldo at netf2r.com (Ronaldo)
Date: Wed, 14 Mar 2007 07:56:03 -0300
Subject: [Tutor] HTTP file download
In-Reply-To: <9f6eb18c0703130523q6cae625dj3fba695d585cc847@mail.gmail.com>
References: <20070313115353.GA1497@fw.netf2r.com>
	<9f6eb18c0703130523q6cae625dj3fba695d585cc847@mail.gmail.com>
Message-ID: <45F7D4C3.1050603@netf2r.com>

  Hi, Jean

  I've alredy tried this, but it seems that this kind of code just works
when "file" in the url (http://www.somesite.com/file) is an html file.
The thing is that "file" in this case is a text file. For example: if I
try to download the file using a web browser, it asks me for a directory
to save the file.
  Do you have any other idea?

  Thanks.

Jean-Philippe Durand wrote:
> Hello Ronaldo,
> Try this :
> import urllib                                       
>
> mysock = urllib.urlopen("http://www.somesite.com/file") 
>
> htmlSource = mysock.read()                            
> mysock.close()                                        
>
> print htmlSource     
> Regards.
> Jean-Philippe DURAND
>
>
> 2007/3/13, ronaldo at netf2r.com <mailto:ronaldo at netf2r.com> 
> <ronaldo at netf2r.com <mailto:ronaldo at netf2r.com>>:
>
>     Hello all,
>
>     How can I download a file using HTTP?
>     For example:
>     There is a file at: http://www.somesite.com/file. I need to get
>     this file using HTTP from a python script.
>     I'm not sure but I think httplib could be used to do that.
>     Can anyone confirm that? or Can anyone suggest me something else?
>
>     Thank you?
>
>     --
>     Ronaldo Z. Afonso
>     Phone: 55+11+82619082
>     www.netf2r.com <http://www.netf2r.com>
>     _______________________________________________
>     Tutor maillist  -  Tutor at python.org <mailto:Tutor at python.org>
>     http://mail.python.org/mailman/listinfo/tutor
>     <http://mail.python.org/mailman/listinfo/tutor>
>
>



From eike.welk at gmx.net  Wed Mar 14 12:01:32 2007
From: eike.welk at gmx.net (Eike Welk)
Date: Wed, 14 Mar 2007 12:01:32 +0100
Subject: [Tutor] Numpy
In-Reply-To: <7D11B162-725A-497C-9985-C357A914E03D@gmail.com>
References: <7D11B162-725A-497C-9985-C357A914E03D@gmail.com>
Message-ID: <200703141201.32737.eike.welk@gmx.net>

Hello Miguel!

You should go to the NumPy mailing list:

http://projects.scipy.org/mailman/listinfo/numpy-discussion

There are also people with Mac knowledge. (I use Linux.)

Regards Eike.


From jason.massey at gmail.com  Wed Mar 14 12:19:20 2007
From: jason.massey at gmail.com (Jason Massey)
Date: Wed, 14 Mar 2007 06:19:20 -0500
Subject: [Tutor] declaring decaration on ul list
In-Reply-To: <45F7A2DC.1090706@verizon.net>
References: <45F7A2DC.1090706@verizon.net>
Message-ID: <7e3eab2c0703140419s2fe6d800q8a54fbf93df6dc93@mail.gmail.com>

You'll need a style sheet.

See: http://alistapart.com/articles/taminglists/

On 3/14/07, Kirk Bailey <deliberatus at verizon.net> wrote:
>
> It just occurred to me that when my wiki does a backsearch it is useful
> to list the results with a * for decorating the unordered list results,
> so I can mousecopy it to update the category(foo) page, /the normal
> bullet is mousecopied as a poundsign (#}. How does one specify what to
> render as a item decoration in an unordered list?
> --
> Salute!
>         -Kirk Bailey
>            Think
>           +-----+
>           | BOX |
>           +-----+
>            knihT
>
> Fnord.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070314/d7d716f4/attachment.html 

From kent37 at tds.net  Wed Mar 14 12:35:55 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 14 Mar 2007 07:35:55 -0400
Subject: [Tutor] HTTP file download
In-Reply-To: <45F7D4C3.1050603@netf2r.com>
References: <20070313115353.GA1497@fw.netf2r.com>	<9f6eb18c0703130523q6cae625dj3fba695d585cc847@mail.gmail.com>
	<45F7D4C3.1050603@netf2r.com>
Message-ID: <45F7DE1B.8060608@tds.net>

Ronaldo wrote:
>   Hi, Jean
> 
>   I've alredy tried this, but it seems that this kind of code just works
> when "file" in the url (http://www.somesite.com/file) is an html file.
> The thing is that "file" in this case is a text file. For example: if I
> try to download the file using a web browser, it asks me for a directory
> to save the file.
>   Do you have any other idea?

The code below should work fine for a text file. Can you show us the 
code that fails and tell us how it fails? If you can include the URL you 
are trying to download that would also help.

Kent
> 
>   Thanks.
> 
> Jean-Philippe Durand wrote:
>> Hello Ronaldo,
>> Try this :
>> import urllib                                       
>>
>> mysock = urllib.urlopen("http://www.somesite.com/file") 
>>
>> htmlSource = mysock.read()                            
>> mysock.close()                                        
>>
>> print htmlSource     
>> Regards.
>> Jean-Philippe DURAND

From jason.massey at gmail.com  Wed Mar 14 12:44:26 2007
From: jason.massey at gmail.com (Jason Massey)
Date: Wed, 14 Mar 2007 06:44:26 -0500
Subject: [Tutor] HTTP file download
In-Reply-To: <45F7D4C3.1050603@netf2r.com>
References: <20070313115353.GA1497@fw.netf2r.com>
	<9f6eb18c0703130523q6cae625dj3fba695d585cc847@mail.gmail.com>
	<45F7D4C3.1050603@netf2r.com>
Message-ID: <7e3eab2c0703140444x78c0bb0cu6524c9c09339346c@mail.gmail.com>

I've tested this on my Apache server setup, it succesfully downloads the gif
file and the text file and saves them.  Even though I used the 'wb' flag
(write binary) for the text file it turned out okay (the difference in 'w'
and 'wb' seemed to be that 'wb' stripped off some of my blank lines).  One
thing to keep in mind is that you if the file you're downloading has spaces
in the filename you'll need to replace the space with '%20' so it'll
download correctly

import urllib

files = ['game_config.txt','apache_pb.gif']

for f in files:
    mysock = urllib.urlopen("http://localhost/%s" % f)
    fileToSave = mysock.read()
    oFile = open(r"c:\python24\%s" % f,'wb')
    oFile.write(fileToSave)
    oFile.close

On 3/14/07, Ronaldo <ronaldo at netf2r.com> wrote:
>
>   Hi, Jean
>
>   I've alredy tried this, but it seems that this kind of code just works
> when "file" in the url (http://www.somesite.com/file) is an html file.
> The thing is that "file" in this case is a text file. For example: if I
> try to download the file using a web browser, it asks me for a directory
> to save the file.
>   Do you have any other idea?
>
>   Thanks.
>
> Jean-Philippe Durand wrote:
> > Hello Ronaldo,
> > Try this :
> > import urllib
> >
> > mysock = urllib.urlopen("http://www.somesite.com/file")
> >
> > htmlSource = mysock.read()
> > mysock.close()
> >
> > print htmlSource
> > Regards.
> > Jean-Philippe DURAND
> >
> >
> > 2007/3/13, ronaldo at netf2r.com <mailto:ronaldo at netf2r.com>
> > <ronaldo at netf2r.com <mailto:ronaldo at netf2r.com>>:
> >
> >     Hello all,
> >
> >     How can I download a file using HTTP?
> >     For example:
> >     There is a file at: http://www.somesite.com/file. I need to get
> >     this file using HTTP from a python script.
> >     I'm not sure but I think httplib could be used to do that.
> >     Can anyone confirm that? or Can anyone suggest me something else?
> >
> >     Thank you?
> >
> >     --
> >     Ronaldo Z. Afonso
> >     Phone: 55+11+82619082
> >     www.netf2r.com <http://www.netf2r.com>
> >     _______________________________________________
> >     Tutor maillist  -  Tutor at python.org <mailto:Tutor at python.org>
> >     http://mail.python.org/mailman/listinfo/tutor
> >     <http://mail.python.org/mailman/listinfo/tutor>
> >
> >
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070314/c04036d8/attachment.htm 

From sonmez_programming at nerdshack.com  Wed Mar 14 13:15:41 2007
From: sonmez_programming at nerdshack.com (=?UTF-8?B?U8O2bm1leiBLYXJ0YWw=?=)
Date: Wed, 14 Mar 2007 14:15:41 +0200
Subject: [Tutor] HTTP file download
In-Reply-To: <45F7D4C3.1050603@netf2r.com>
References: <20070313115353.GA1497@fw.netf2r.com>	<9f6eb18c0703130523q6cae625dj3fba695d585cc847@mail.gmail.com>
	<45F7D4C3.1050603@netf2r.com>
Message-ID: <45F7E76D.6070901@nerdshack.com>

Hi,

Socket downloads the output of given URL. You can get the file's 
extension by URL and save it as a file with it's extension.

S?nmez

Ronaldo wrote:
>   Hi, Jean
> 
>   I've alredy tried this, but it seems that this kind of code just works
> when "file" in the url (http://www.somesite.com/file) is an html file.
> The thing is that "file" in this case is a text file. For example: if I
> try to download the file using a web browser, it asks me for a directory
> to save the file.
>   Do you have any other idea?
> 
>   Thanks.
> 
> Jean-Philippe Durand wrote:
>> Hello Ronaldo,
>> Try this :
>> import urllib                                       
>>
>> mysock = urllib.urlopen("http://www.somesite.com/file") 
>>
>> htmlSource = mysock.read()                            
>> mysock.close()                                        
>>
>> print htmlSource     
>> Regards.
>> Jean-Philippe DURAND
>>
>>
>> 2007/3/13, ronaldo at netf2r.com <mailto:ronaldo at netf2r.com> 
>> <ronaldo at netf2r.com <mailto:ronaldo at netf2r.com>>:
>>
>>     Hello all,
>>
>>     How can I download a file using HTTP?
>>     For example:
>>     There is a file at: http://www.somesite.com/file. I need to get
>>     this file using HTTP from a python script.
>>     I'm not sure but I think httplib could be used to do that.
>>     Can anyone confirm that? or Can anyone suggest me something else?
>>
>>     Thank you?
>>
>>     --
>>     Ronaldo Z. Afonso
>>     Phone: 55+11+82619082
>>     www.netf2r.com <http://www.netf2r.com>
>>     _______________________________________________
>>     Tutor maillist  -  Tutor at python.org <mailto:Tutor at python.org>
>>     http://mail.python.org/mailman/listinfo/tutor
>>     <http://mail.python.org/mailman/listinfo/tutor>
>>
>>
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


From yaguarovi at gmail.com  Wed Mar 14 14:29:53 2007
From: yaguarovi at gmail.com (Jean-Philippe Durand)
Date: Wed, 14 Mar 2007 14:29:53 +0100
Subject: [Tutor] HTTP file download
In-Reply-To: <45F7D4C3.1050603@netf2r.com>
References: <20070313115353.GA1497@fw.netf2r.com>
	<9f6eb18c0703130523q6cae625dj3fba695d585cc847@mail.gmail.com>
	<45F7D4C3.1050603@netf2r.com>
Message-ID: <9f6eb18c0703140629q42a52108s9ea2fe984391b4c5@mail.gmail.com>

Hi Ronaldo,
Yes the first solution works with html files.

This is how to download a file found on the web :

import urllib
urllib.urlretrieve('http://www.somesite.com/file', 'c:/mylocalfile')
Regards.
Jean-Philippe DURAND


2007/3/14, Ronaldo <ronaldo at netf2r.com>:
>   Hi, Jean
>
>   I've alredy tried this, but it seems that this kind of code just works
> when "file" in the url (http://www.somesite.com/file) is an html file.
> The thing is that "file" in this case is a text file. For example: if I
> try to download the file using a web browser, it asks me for a directory
> to save the file.
>   Do you have any other idea?
>
>   Thanks.
>
> Jean-Philippe Durand wrote:
> > Hello Ronaldo,
> > Try this :
> > import urllib
> >
> > mysock = urllib.urlopen("http://www.somesite.com/file")
> >
> > htmlSource = mysock.read()
> > mysock.close()
> >
> > print htmlSource
> > Regards.
> > Jean-Philippe DURAND
> >
> >
> > 2007/3/13, ronaldo at netf2r.com <mailto:ronaldo at netf2r.com>
> > <ronaldo at netf2r.com <mailto:ronaldo at netf2r.com>>:
> >
> >     Hello all,
> >
> >     How can I download a file using HTTP?
> >     For example:
> >     There is a file at: http://www.somesite.com/file. I need to get
> >     this file using HTTP from a python script.
> >     I'm not sure but I think httplib could be used to do that.
> >     Can anyone confirm that? or Can anyone suggest me something else?
> >
> >     Thank you?
> >
> >     --
> >     Ronaldo Z. Afonso
> >     Phone: 55+11+82619082
> >     www.netf2r.com <http://www.netf2r.com>
> >     _______________________________________________
> >     Tutor maillist  -  Tutor at python.org <mailto:Tutor at python.org>
> >     http://mail.python.org/mailman/listinfo/tutor
> >     <http://mail.python.org/mailman/listinfo/tutor>
> >
> >
>
>
>

From earobinson at gmail.com  Wed Mar 14 15:33:01 2007
From: earobinson at gmail.com (Edward A Robinson)
Date: Wed, 14 Mar 2007 10:33:01 -0400
Subject: [Tutor] Working with files with python (gtk)
Message-ID: <4386d5350703140733o3193c812mfd15b7f9f9b7317f@mail.gmail.com>

This is my first time posting to the python tutor so be nice, I have
read the mailing list and cant seem to find and answer there or on
google so I turn to you guys for help. I'm working on a gtk
application and I want to list all the image files in a directory. Now
I know that if I have an image lets say foo.png and I rename that to
foo.txt nautilus (the default gnome browser) still recognizes that
file as an image.

How can I do the same thing? As well as recognizes images I want users
to be able to open up each image with that images default editor. So
foo.png may open with eye of gnome but bar.jpg may open with gimp. (If
those where the settings in nautilus)

Thanks for your time, I hope this is an appropriate query for this mailing list.

-- 
Edward A Robinson

From hyperneato at gmail.com  Wed Mar 14 17:19:25 2007
From: hyperneato at gmail.com (Isaac)
Date: Wed, 14 Mar 2007 09:19:25 -0700
Subject: [Tutor] trouble with function-- trying to check
Message-ID: <7260654a0703140919i650b181fu16194bab710e36de@mail.gmail.com>

Howdy,

> This has already been discussed on this thread. == and 'in' are
comparisons.

I did not get that thread somehow. I thought I looked for the original
thread but maybe I did not go back far enough. This thread is great for me -
I am learning much.

http://docs.python.org/ref/comparisons.html
says

" The operators <, >, ==, >=, <=, and != compare the values of two objects.
The objects need not have the same type. If both are numbers, they are
converted to a common type. Otherwise, objects of different types
*always*compare unequal,"

later on:

" The operators in and not in test for set membership"

>(c == c in 'crab')
>means
>(c == c) and (c in 'crab')

(c == c in 'crab') returns a true/false.
The statement (c == c), and the statement (c in 'crab') also returns
true/false,
but the [ and ] operator that joins (c == c) and (c in 'crab') returns a
value based on the values that precede and follow the [ and ] operator:

" The expression x and y first evaluates x; if x is false, its value is
returned; otherwise, y is evaluated and the resulting value is returned."
http://docs.python.org/ref/Booleans.html

[code]
python >c = 'c'
python >d = 'c'
python >c == d in 'crab'
True
python >(c == d) and 'crab'
'crab'
[/code]

But if I put parentheses around one term like this:

>   (c == (c in "crab"))
c in 'crab' returns a true/false first because parentheses are more binding
than comparisons. Then the outer parentheses is evaluated- c in this case is
a <type 'str'> and it compares this value/type to the statement returned by
the innermost set which previously returned a <type 'bool'>

cheers

-Isaac

Kent wrote:


This has already been discussed on this thread. == and 'in' are comparisons.
(c == c in 'crab')
means
(c == c) and (c in 'crab')

http://docs.python.org/ref/comparisons.html

Kent

Re: [Tutor] trouble with function-- trying to check
To: Terry Carroll <carroll at tjc.com>
Cc: tutor at python.org
Message-ID: <45F7D0C5.3020107 at tds.net>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

Terry Carroll wrote:
> On Wed, 14 Mar 2007, Isaac wrote:
>
>> a, b, c, or d is a type('str') not boolean which is what (c in "crab")
is.
>> The [in] operator takes presedence, the first 3 times (c in "crab")
returns
>> true and the last returns false; but the strings a, b, c, or d do not ==
>> true or false - therefore the test (c == (c in "crab")) always returns
>> false.
>
> The thing is, if the in operator takes precedence than why do
>
>
>   (c == c in "crab")
>
>  and
>
>   (c == (c in "crab"))
>
> return different results?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070314/65bc0d0a/attachment.html 

From carroll at tjc.com  Wed Mar 14 19:15:47 2007
From: carroll at tjc.com (Terry Carroll)
Date: Wed, 14 Mar 2007 11:15:47 -0700 (PDT)
Subject: [Tutor] trouble with function-- trying to check
In-Reply-To: <45F7D0C5.3020107@tds.net>
Message-ID: <Pine.LNX.4.44.0703141108340.10783-100000@violet.rahul.net>

On Wed, 14 Mar 2007, Kent Johnson wrote:

> This has already been discussed on this thread. == and 'in' are comparisons.

Aha.  I did not see this discussion in the thread; the closest thing I
noticed was Alan's note that I was riffing from, which concluded with "It
definitely seems to work as I explained it but how it works is defeating
my befuddled brain right now."  Looking through the archives, I now find
your note.

> (c == c in 'crab')
> means
> (c == c) and (c in 'crab')
> 
> http://docs.python.org/ref/comparisons.html

Thanks.  My take-away from this is that comparisons (including "in", which
would not have intuitively struck me as a comparison) don't have
precedence rules, so that you can chain them.  It just looks odd to chain
an "=="  with an "in", but I guess it's legal.


From ronaldo at netf2r.com  Wed Mar 14 22:19:23 2007
From: ronaldo at netf2r.com (Ronaldo)
Date: Wed, 14 Mar 2007 18:19:23 -0300
Subject: [Tutor] HTTP file download
In-Reply-To: <45F7DE1B.8060608@tds.net>
References: <20070313115353.GA1497@fw.netf2r.com>	<9f6eb18c0703130523q6cae625dj3fba695d585cc847@mail.gmail.com>
	<45F7D4C3.1050603@netf2r.com> <45F7DE1B.8060608@tds.net>
Message-ID: <45F866DB.7020005@netf2r.com>

  Hi Kent,

  You were right. The code worked fine. I was doing some thing wrong 
with some characters in my URL (for example: I had to change "&amp;" to 
"&").
  I'd like to thank you guys for your help.


Kent Johnson wrote:
> Ronaldo wrote:
>>   Hi, Jean
>>
>>   I've alredy tried this, but it seems that this kind of code just works
>> when "file" in the url (http://www.somesite.com/file) is an html file.
>> The thing is that "file" in this case is a text file. For example: if I
>> try to download the file using a web browser, it asks me for a directory
>> to save the file.
>>   Do you have any other idea?
>
> The code below should work fine for a text file. Can you show us the 
> code that fails and tell us how it fails? If you can include the URL 
> you are trying to download that would also help.
>
> Kent
>>
>>   Thanks.
>>
>> Jean-Philippe Durand wrote:
>>> Hello Ronaldo,
>>> Try this :
>>> import urllib                                      
>>> mysock = urllib.urlopen("http://www.somesite.com/file")
>>> htmlSource = mysock.read()                            
>>> mysock.close()                                       
>>> print htmlSource     Regards.
>>> Jean-Philippe DURAND
>


From earobinson at gmail.com  Thu Mar 15 03:53:50 2007
From: earobinson at gmail.com (Edward A Robinson)
Date: Wed, 14 Mar 2007 22:53:50 -0400
Subject: [Tutor] Working with files with python (gtk)
In-Reply-To: <4386d5350703140733o3193c812mfd15b7f9f9b7317f@mail.gmail.com>
References: <4386d5350703140733o3193c812mfd15b7f9f9b7317f@mail.gmail.com>
Message-ID: <4386d5350703141953ud9f20et83a21455cc18f18d@mail.gmail.com>

I guess what Im looking for is a python command that dose what the
file command in the shell would do

On 3/14/07, Edward A Robinson <earobinson at gmail.com> wrote:
> This is my first time posting to the python tutor so be nice, I have
> read the mailing list and cant seem to find and answer there or on
> google so I turn to you guys for help. I'm working on a gtk
> application and I want to list all the image files in a directory. Now
> I know that if I have an image lets say foo.png and I rename that to
> foo.txt nautilus (the default gnome browser) still recognizes that
> file as an image.
>
> How can I do the same thing? As well as recognizes images I want users
> to be able to open up each image with that images default editor. So
> foo.png may open with eye of gnome but bar.jpg may open with gimp. (If
> those where the settings in nautilus)
>
> Thanks for your time, I hope this is an appropriate query for this mailing list.
>
> --
> Edward A Robinson
>


-- 
Edward A Robinson

From hyperneato at gmail.com  Thu Mar 15 08:19:29 2007
From: hyperneato at gmail.com (Isaac)
Date: Thu, 15 Mar 2007 00:19:29 -0700
Subject: [Tutor] trouble with function-- trying to check
Message-ID: <7260654a0703150019v61f0e98jbc5d40e44b7749a8@mail.gmail.com>

Hola,

Pardon me if I am repeating others, I think I have read the whole thread
now.

In 5.9 of the Language Reference it says:

"Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x
< y and y <= z"

So this would mean that

item == item in word2

means:

item == item and item in word2

not

(item == item) and (item in word2)

which would first return each value in parentheses and place each value on
either side of the boolean operator [ and ]

Best regards,

-Isaac


Bob said:

Take a look in 5.9 Comparisons in the Language Reference:

"Comparisons can be chained arbitrarily, e.g., |x < y <= z| is
equivalent to |x < y and y <= z|, except that |y| is evaluated only once
(but in both cases |z| is not evaluated at all when |x < y| is found to
be false)."

Applying this to

item == item in word2

yields:

(item == item) and (item in word2)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070315/5b643c72/attachment.html 

From mail at timgolden.me.uk  Thu Mar 15 11:16:40 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Thu, 15 Mar 2007 10:16:40 +0000
Subject: [Tutor] Working with files with python (gtk)
In-Reply-To: <4386d5350703141953ud9f20et83a21455cc18f18d@mail.gmail.com>
References: <4386d5350703140733o3193c812mfd15b7f9f9b7317f@mail.gmail.com>
	<4386d5350703141953ud9f20et83a21455cc18f18d@mail.gmail.com>
Message-ID: <45F91D08.5010507@timgolden.me.uk>

Edward A Robinson wrote:
> I guess what Im looking for is a python command that dose what the
> file command in the shell would do
> 
> On 3/14/07, Edward A Robinson <earobinson at gmail.com> wrote:
>> This is my first time posting to the python tutor so be nice, I have
>> read the mailing list and cant seem to find and answer there or on
>> google so I turn to you guys for help. I'm working on a gtk
>> application and I want to list all the image files in a directory. Now
>> I know that if I have an image lets say foo.png and I rename that to
>> foo.txt nautilus (the default gnome browser) still recognizes that
>> file as an image.
>>
>> How can I do the same thing? As well as recognizes images I want users
>> to be able to open up each image with that images default editor. So
>> foo.png may open with eye of gnome but bar.jpg may open with gimp. (If
>> those where the settings in nautilus)

I'm a Windows person rather than a Linux one, so treat this
suggestion with the contempt it deserves ;) I seem to remember
that Nautilus has some kind of Python interface which perhaps
could be used here to ask it what it would do with file x.y.
If not, then your next best is to fall back to some system-specific
mime-type lookup but I presume that would work on extensions, not
on contents. Failing that, you could call the "file" system
command (if that's what it's called) which presumably sniffs
the header and returns something useful.

Basically, knowing the file type comes down to extension or
contents. Python has the mimetypes module for the former. If
it's just images you're after then the Python Imaging Library
(http://effbot.org/zone/pil-index.htm) seems to be able to
read image types correctly, regardless of extension, so maybe
that's a way to go.

<dump>
Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on 
win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> import Image
 >>> Image.open ("issue1.jpg").info
{'jfif_version': (1, 1), 'jfif': 257, 'jfif_unit': 0, 'jfif_density': 
(1, 1)}
 >>>
 >>> Image.open ("issue1.xxx").info
{'jfif_version': (1, 1), 'jfif': 257, 'jfif_unit': 0, 'jfif_density': 
(1, 1)}
 >>>
</dump>

TJG

From kent37 at tds.net  Thu Mar 15 11:25:54 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 15 Mar 2007 06:25:54 -0400
Subject: [Tutor] trouble with function-- trying to check
In-Reply-To: <7260654a0703150019v61f0e98jbc5d40e44b7749a8@mail.gmail.com>
References: <7260654a0703150019v61f0e98jbc5d40e44b7749a8@mail.gmail.com>
Message-ID: <45F91F32.5080008@tds.net>

Isaac wrote:
> In 5.9 of the Language Reference it says:
> 
> "Comparisons can be chained arbitrarily, e.g., |x < y <= z| is 
> equivalent to |x < y and y <= z"
> 
> |So this would mean that
> 
> item == item in word2
> 
> means:
> 
> item == item and item in word2
> 
> not
> 
> (item == item) and (item in word2)
> 
> which would first return each value in parentheses and place each value 
> on either side of the boolean operator [ and ]

What do you think your expression does? Since 'and' has a lower 
precedence than == and 'in', the two expressions have the same meaning. 
I added the parentheses for emphasis.

Kent


From eike.welk at gmx.net  Thu Mar 15 12:24:35 2007
From: eike.welk at gmx.net (Eike Welk)
Date: Thu, 15 Mar 2007 12:24:35 +0100
Subject: [Tutor] Working with files with python (gtk)
In-Reply-To: <4386d5350703141953ud9f20et83a21455cc18f18d@mail.gmail.com>
References: <4386d5350703140733o3193c812mfd15b7f9f9b7317f@mail.gmail.com>
	<4386d5350703141953ud9f20et83a21455cc18f18d@mail.gmail.com>
Message-ID: <200703151224.35646.eike.welk@gmx.net>

Hello Edward!

On Thursday 15 March 2007 03:53, Edward A Robinson wrote:
> I guess what Im looking for is a python command that dose what the
> file command in the shell would do

I don't think there is anything like this in Python's standard 
library. Probably Gnome has a library for identifying the file type 
(I've read that KDE has one). 
So you could ask on a Gnome mailing list for that library and use it.

Offcourse you could use the 'file' program and parse the output.

Regards, Eike.  


From clay.wiedemann at gmail.com  Thu Mar 15 15:27:01 2007
From: clay.wiedemann at gmail.com (Clay Wiedemann)
Date: Thu, 15 Mar 2007 10:27:01 -0400
Subject: [Tutor] skipping ahead within a loop
Message-ID: <781164cc0703150727t3ddf6a0bg6ab148b0dbe0dcbe@mail.gmail.com>

If  doing a loop, how can one skip forward a specific amount randomly
determined within the loop?
Below is a boiled down version of what I am trying (HEIGHT and random
come from NodeBox). I imagine a simple solution is out there, my
searches failed me


for y in range(HEIGHT):
	linewidth = random(3, 9)
	# drawlines, etc.
	y += linewidth 	# this is what does not work



Thanks,
Clay

From jorgen.maillist at gmail.com  Thu Mar 15 15:34:49 2007
From: jorgen.maillist at gmail.com (Jorgen Bodde)
Date: Thu, 15 Mar 2007 15:34:49 +0100
Subject: [Tutor] skipping ahead within a loop
In-Reply-To: <781164cc0703150727t3ddf6a0bg6ab148b0dbe0dcbe@mail.gmail.com>
References: <781164cc0703150727t3ddf6a0bg6ab148b0dbe0dcbe@mail.gmail.com>
Message-ID: <11e49df10703150734o58ed75adw262cd2c19d3dc60e@mail.gmail.com>

Maybe use a while loop?

y = 0
while y < HEIGHT:
    linewidth = random(3,9)
    y += linewidth

Regards,
- Jorgen

On 3/15/07, Clay Wiedemann <clay.wiedemann at gmail.com> wrote:
> If  doing a loop, how can one skip forward a specific amount randomly
> determined within the loop?
> Below is a boiled down version of what I am trying (HEIGHT and random
> come from NodeBox). I imagine a simple solution is out there, my
> searches failed me
>
>
> for y in range(HEIGHT):
>         linewidth = random(3, 9)
>         # drawlines, etc.
>         y += linewidth  # this is what does not work
>
>
>
> Thanks,
> Clay
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From rikard.bosnjakovic at gmail.com  Thu Mar 15 15:35:27 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Thu, 15 Mar 2007 15:35:27 +0100
Subject: [Tutor] skipping ahead within a loop
In-Reply-To: <781164cc0703150727t3ddf6a0bg6ab148b0dbe0dcbe@mail.gmail.com>
References: <781164cc0703150727t3ddf6a0bg6ab148b0dbe0dcbe@mail.gmail.com>
Message-ID: <d9e88eaf0703150735t49b5d374kf8b3c9f883479bed@mail.gmail.com>

On 3/15/07, Clay Wiedemann <clay.wiedemann at gmail.com> wrote:
> If  doing a loop, how can one skip forward a specific amount randomly
> determined within the loop?

y = 0
while y < HEIGHT:
  linewidth = random(3, 9)
  # drawlines etc
  y += linewidth

The reason why you cannot alter the for-variable beats me, though.


-- 
- Rikard.

From kent37 at tds.net  Thu Mar 15 17:00:25 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 15 Mar 2007 12:00:25 -0400
Subject: [Tutor] skipping ahead within a loop
In-Reply-To: <d9e88eaf0703150735t49b5d374kf8b3c9f883479bed@mail.gmail.com>
References: <781164cc0703150727t3ddf6a0bg6ab148b0dbe0dcbe@mail.gmail.com>
	<d9e88eaf0703150735t49b5d374kf8b3c9f883479bed@mail.gmail.com>
Message-ID: <45F96D99.7050503@tds.net>

Rikard Bosnjakovic wrote:
> On 3/15/07, Clay Wiedemann <clay.wiedemann at gmail.com> wrote:
>> If  doing a loop, how can one skip forward a specific amount randomly
>> determined within the loop?
> 
> y = 0
> while y < HEIGHT:
>   linewidth = random(3, 9)
>   # drawlines etc
>   y += linewidth
> 
> The reason why you cannot alter the for-variable beats me, though.

Because each time through the loop the variable is assigned to the next 
value from the range.

A Python for loop is not like a C for loop. Python for loops work with 
sequences. The loop variable is assigned to each element of the sequence 
in turn.

range() returns a list which is the sequence the for loop iterates over.

You can manipulate the loop by making the iterator explicit. For example:
 >>> for i in it:
...     print i
...     it.next() # explicitly skip the next item
...
0
2
4
6

Kent

From dkuhlman at rexx.com  Thu Mar 15 17:32:14 2007
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Thu, 15 Mar 2007 09:32:14 -0700
Subject: [Tutor] skipping ahead within a loop
In-Reply-To: <d9e88eaf0703150735t49b5d374kf8b3c9f883479bed@mail.gmail.com>
References: <781164cc0703150727t3ddf6a0bg6ab148b0dbe0dcbe@mail.gmail.com>
	<d9e88eaf0703150735t49b5d374kf8b3c9f883479bed@mail.gmail.com>
Message-ID: <20070315163214.GA87081@cutter.rexx.com>

On Thu, Mar 15, 2007 at 03:35:27PM +0100, Rikard Bosnjakovic wrote:
> On 3/15/07, Clay Wiedemann <clay.wiedemann at gmail.com> wrote:
> > If  doing a loop, how can one skip forward a specific amount randomly
> > determined within the loop?
> 
> y = 0
> while y < HEIGHT:
>   linewidth = random(3, 9)
>   # drawlines etc
>   y += linewidth
> 
> The reason why you cannot alter the for-variable beats me, though.

The while-statement looks like a good solution to me.

Two additional points:

1. You can alter the for-variable, *but* each time you go to the
   top of the for-loop, that variable is set to the next item from
   the iterator, wiping out any alteration.  Because of this, you
   can modify and use that variable within the loop body without
   having to worry about messing up the loop sequence.  What Clay
   wants to do is mess with the sequencing of items in the loop.

2. The reason that modifying the for-variable does not change the
   sequence of objects processed by the loop is that the
   for-statement is generating a sequence of objects from an
   iterator.  In this case the range function creates a list, which
   the for-statement turns into an iterator.

You don't even *want* to give Clay what he is asking for.  He asked
about being able to jump forward in the loop or sequence.  If you
were able to give him that one, he would come back and ask whether
he could jump *backward* in the loop.

For more on iterators, see "Iterator types" at
http://docs.python.org/lib/typeiter.html.  Also see the "iter"
function in "Built-in functions":
http://docs.python.org/lib/built-in-funcs.html.

You can think of the following:

    def test2():
        for item in range(4):
            print item

as syntactic sugar for this:

    def test1():
        myrange = range(4)
        myiter = iter(myrange)
        try:
            while True:
                item = myiter.next()
                print item
        except StopIteration, e:
            pass

Hoping this is not TMI (too much information), but sometimes it
helps to understand what is going on underneath, because the for
statement and iterators are very general, powerful,
and elegant features of Python.

Dave


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

From clay.wiedemann at gmail.com  Thu Mar 15 19:04:22 2007
From: clay.wiedemann at gmail.com (Clay Wiedemann)
Date: Thu, 15 Mar 2007 14:04:22 -0400
Subject: [Tutor] skipping ahead within a loop
In-Reply-To: <20070315163214.GA87081@cutter.rexx.com>
References: <781164cc0703150727t3ddf6a0bg6ab148b0dbe0dcbe@mail.gmail.com>
	<d9e88eaf0703150735t49b5d374kf8b3c9f883479bed@mail.gmail.com>
	<20070315163214.GA87081@cutter.rexx.com>
Message-ID: <781164cc0703151104i112647edi47a6f2acf8d20ad1@mail.gmail.com>

Thanks, this is not too much information at all. I am always happy with depth.

-c

On 3/15/07, Dave Kuhlman <dkuhlman at rexx.com> wrote:
> On Thu, Mar 15, 2007 at 03:35:27PM +0100, Rikard Bosnjakovic wrote:
> > On 3/15/07, Clay Wiedemann <clay.wiedemann at gmail.com> wrote:
> > > If  doing a loop, how can one skip forward a specific amount randomly
> > > determined within the loop?
> >
> > y = 0
> > while y < HEIGHT:
> >   linewidth = random(3, 9)
> >   # drawlines etc
> >   y += linewidth
> >
> > The reason why you cannot alter the for-variable beats me, though.
>
> The while-statement looks like a good solution to me.
>
> Two additional points:
>
> 1. You can alter the for-variable, *but* each time you go to the
>    top of the for-loop, that variable is set to the next item from
>    the iterator, wiping out any alteration.  Because of this, you
>    can modify and use that variable within the loop body without
>    having to worry about messing up the loop sequence.  What Clay
>    wants to do is mess with the sequencing of items in the loop.
>
> 2. The reason that modifying the for-variable does not change the
>    sequence of objects processed by the loop is that the
>    for-statement is generating a sequence of objects from an
>    iterator.  In this case the range function creates a list, which
>    the for-statement turns into an iterator.
>
> You don't even *want* to give Clay what he is asking for.  He asked
> about being able to jump forward in the loop or sequence.  If you
> were able to give him that one, he would come back and ask whether
> he could jump *backward* in the loop.
>
> For more on iterators, see "Iterator types" at
> http://docs.python.org/lib/typeiter.html.  Also see the "iter"
> function in "Built-in functions":
> http://docs.python.org/lib/built-in-funcs.html.
>
> You can think of the following:
>
>     def test2():
>         for item in range(4):
>             print item
>
> as syntactic sugar for this:
>
>     def test1():
>         myrange = range(4)
>         myiter = iter(myrange)
>         try:
>             while True:
>                 item = myiter.next()
>                 print item
>         except StopIteration, e:
>             pass
>
> Hoping this is not TMI (too much information), but sometimes it
> helps to understand what is going on underneath, because the for
> statement and iterators are very general, powerful,
> and elegant features of Python.
>
> Dave
>
>
> --
> Dave Kuhlman
> http://www.rexx.com/~dkuhlman
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


-- 

- - - - - - -

Clay S. Wiedemann

voice: 718.362.0375
aim: khlav
wii: 3905 4571 6175 2469
twitter: seastokes

From hyperneato at gmail.com  Fri Mar 16 02:46:23 2007
From: hyperneato at gmail.com (Isaac)
Date: Thu, 15 Mar 2007 18:46:23 -0700
Subject: [Tutor] trouble with function-- trying to check
In-Reply-To: <45F91F32.5080008@tds.net>
References: <7260654a0703150019v61f0e98jbc5d40e44b7749a8@mail.gmail.com>
	<45F91F32.5080008@tds.net>
Message-ID: <7260654a0703151846v27a3efcfsf8a36db1a09e1195@mail.gmail.com>

I see. Thanks for clarifying that for me.

-Isaac

On 3/15/07, Kent Johnson <kent37 at tds.net> wrote:
>
> Isaac wrote:
> > In 5.9 of the Language Reference it says:
> >
> > "Comparisons can be chained arbitrarily, e.g., |x < y <= z| is
> > equivalent to |x < y and y <= z"
> >
> > |So this would mean that
> >
> > item == item in word2
> >
> > means:
> >
> > item == item and item in word2
> >
> > not
> >
> > (item == item) and (item in word2)
> >
> > which would first return each value in parentheses and place each value
> > on either side of the boolean operator [ and ]
>
> What do you think your expression does? Since 'and' has a lower
> precedence than == and 'in', the two expressions have the same meaning.
> I added the parentheses for emphasis.
>
> Kent
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070315/05759e4e/attachment.htm 

From deliberatus at verizon.net  Fri Mar 16 05:14:08 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Fri, 16 Mar 2007 00:14:08 -0400
Subject: [Tutor] windows file permissions
Message-ID: <45FA1990.9040303@verizon.net>

how do I check file permission in windows environments in python? I am 
modifying an existing editor program in my wiki to refuse to TRY to edit 
a file if it is set to read only. Until very recently, all my system 
stuff was in a un*x environment (well, FreeBSD) which is just not the same.

-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From deliberatus at verizon.net  Fri Mar 16 06:15:58 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Fri, 16 Mar 2007 01:15:58 -0400
Subject: [Tutor] windows file permissions
In-Reply-To: <45FA1990.9040303@verizon.net>
References: <45FA1990.9040303@verizon.net>
Message-ID: <45FA280E.8000502@verizon.net>

I answered my own question digging around and testing stuff. Here is my
solution for a windows environment:

if not os.access(pagename,os.W_OK):
	print 'Sorry, that file is read only,<p>'
	print 'Please consult your system administrator<br>'
	print 'if this file must be modified.<P>'
	print footer()
	sys.exit()

And it works, testing it by manually setting a page in the wiki of my
laptop to read only. it now politely refuses to attempt to edit a read
only file. This lets me set important pages such as the user license to
read only. YES, one may go in and manually turn them over to writable
state if one knows how- ie, one is a geek like us. ordinary consumer
office road warriors do not.

Now to figure out how to best sell the thing to the target market...



Kirk Bailey wrote:
> how do I check file permission in windows environments in python? I am 
> modifying an existing editor program in my wiki to refuse to TRY to edit 
> a file if it is set to read only. Until very recently, all my system 
> stuff was in a un*x environment (well, FreeBSD) which is just not the same.
> 

-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.


From ceasar102 at yahoo.com  Fri Mar 16 07:52:51 2007
From: ceasar102 at yahoo.com (ammar azif)
Date: Thu, 15 Mar 2007 23:52:51 -0700 (PDT)
Subject: [Tutor] Is generator function similar to multi threading?
Message-ID: <694205.16084.qm@web56107.mail.re3.yahoo.com>

Is generator function similar to multi threading?



 
---------------------------------
Don't be flakey. Get Yahoo! Mail for Mobile and 
always stay connected to friends.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070315/b43af078/attachment.htm 

From mail at timgolden.me.uk  Fri Mar 16 10:05:36 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Fri, 16 Mar 2007 09:05:36 +0000
Subject: [Tutor] windows file permissions
In-Reply-To: <45FA280E.8000502@verizon.net>
References: <45FA1990.9040303@verizon.net> <45FA280E.8000502@verizon.net>
Message-ID: <45FA5DE0.5060403@timgolden.me.uk>

Kirk Bailey wrote:
> I answered my own question digging around and testing stuff. 

I can't tell you how glad I am to hear that: I was just
girding my loins (so to speak) to embark on an explanation
of the Win32 ACL model which would have involved seven levels
of explanation at the end of which you would have probably
have been none the wiser :)

TJG

From kent37 at tds.net  Fri Mar 16 11:15:01 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 16 Mar 2007 06:15:01 -0400
Subject: [Tutor] Is generator function similar to multi threading?
In-Reply-To: <694205.16084.qm@web56107.mail.re3.yahoo.com>
References: <694205.16084.qm@web56107.mail.re3.yahoo.com>
Message-ID: <45FA6E25.6040300@tds.net>

ammar azif wrote:
> Is generator function similar to multi threading?

Only in that they can be alternative ways to solve the same problem.

Generator functions are similar to co-routines and can be used to create 
multiple lightweight tasks. SimPy (http://simpy.sourceforge.net/) is an 
example of this.

However generator functions are most commonly used as a convenient way 
to generate a sequence when the generation involves some saved state.

Kent

From ceasar102 at yahoo.com  Fri Mar 16 11:31:04 2007
From: ceasar102 at yahoo.com (ammar azif)
Date: Fri, 16 Mar 2007 03:31:04 -0700 (PDT)
Subject: [Tutor] convert hex number to decimal
Message-ID: <2892.18598.qm@web56102.mail.re3.yahoo.com>

HI,

Is there any built-in function to convert a hex number to a decimal number?

 
---------------------------------
Need Mail bonding?
Go to the Yahoo! Mail Q&A for great tips from Yahoo! Answers users.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070316/24117697/attachment.htm 

From rikard.bosnjakovic at gmail.com  Fri Mar 16 12:11:58 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Fri, 16 Mar 2007 12:11:58 +0100
Subject: [Tutor] convert hex number to decimal
In-Reply-To: <2892.18598.qm@web56102.mail.re3.yahoo.com>
References: <2892.18598.qm@web56102.mail.re3.yahoo.com>
Message-ID: <d9e88eaf0703160411l4388ff2bsd5e345adf8dca76e@mail.gmail.com>

On 3/16/07, ammar azif <ceasar102 at yahoo.com> wrote:

> Is there any built-in function to convert a hex number to a decimal number?

>>> int("ff", 16)
255



-- 
- Rikard.

From ms at cerenity.org  Fri Mar 16 12:25:48 2007
From: ms at cerenity.org (Michael Sparks)
Date: Fri, 16 Mar 2007 11:25:48 +0000
Subject: [Tutor] Is generator function similar to multi threading?
In-Reply-To: <694205.16084.qm@web56107.mail.re3.yahoo.com>
References: <694205.16084.qm@web56107.mail.re3.yahoo.com>
Message-ID: <200703161125.48883.ms@cerenity.org>

On Friday 16 March 2007 06:52, ammar azif wrote:
> Is generator function similar to multi threading?

Yes, however unlike threads they are more general. They can be used in two 
main ways:
   * To generate a sequence of values
   * To achieve something similar to multithreading, but without using
     operating system threads.

For a tutorial on how to do the latter safely, please take a look at this:
   http://kamaelia.sourceforge.net/MiniAxon/

(It's targeted at someone with very basic python skills, since the first 
iteration of that tutorial was written for someone who'd learnt python the 
previous week)

We use the latter form extremely heavily on our project to great effect. One 
of benefits of using a generator over a thread is that you can (as of python 
2.5) kill a generator by sending an exception into it.(though this isn't the 
reason we're using them) 

As a result combining threading and generators makes sense since you can run a 
generator inside a thread, and have a mechanism to kill the thread - you send 
an exception into the generator.

That said, the primary intended use of generators *is* to generate values. The 
fact they're a restricted co-routine however is incredibly handy. (Because 
they can only be single layer, it forces them to be simpler, which in turn 
makes them much more reusable)

Regards,


Michael.
--
http://kamaelia.sourceforge.net/Home
http://yeoldeclue.com/blog

From nebpro at gmail.com  Fri Mar 16 15:47:49 2007
From: nebpro at gmail.com (Ben)
Date: Fri, 16 Mar 2007 10:47:49 -0400
Subject: [Tutor] Hi
Message-ID: <e5f41cb30703160747u30324649s875b5f33f7bcd052@mail.gmail.com>

Hi all,

I am a newbie to Python. I just learned python for two weeks, and I have to
say I feel very comfortable with the language. The stumbling blocks for me
is the development of the GUI. I am currently learning pywin (PythonWin) to
develop a gui. But I found it is very difficult. I have been searching all
over internet on pywin tutorials, manuals or documentations, and I find
nothing good or concise for either tutorials or documentations about pywin.
Is anyone can point me where I can find a good tutorial about pywin for
someone like me? I will really appreciate it. Thank you

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

From nswitanek at stanford.edu  Fri Mar 16 20:31:04 2007
From: nswitanek at stanford.edu (Switanek, Nick)
Date: Fri, 16 Mar 2007 12:31:04 -0700
Subject: [Tutor] fine in interpreter, hangs in batch
In-Reply-To: <mailman.41.1174042822.26678.tutor@python.org>
Message-ID: <21EB45BA6A0A4844B97D46A7721CFDF2034094D2@gsb-exchmb02.stanford.edu>

Hi,

After creating a list of words ('wordlist'), I can run the following
code in the interactive window of PythonWin in about ten seconds. If I
run the script containing the code, the script seems to hang on the
loop. I'd be grateful for help as to why; I often seem to have something
that works in the interpreter, but not when I run the script.

Thanks in advance,
Nick


N = [2,3,4,5]
ngramlist = [wordlist]
for n in N:
    ngrams = [' '.join(wordlist[i:i+n]) for i in
range(len(wordlist)-n+1)]
    "Finished the %d-gram list." % n

From malaclypse2 at gmail.com  Fri Mar 16 20:51:41 2007
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Fri, 16 Mar 2007 15:51:41 -0400
Subject: [Tutor] fine in interpreter, hangs in batch
In-Reply-To: <21EB45BA6A0A4844B97D46A7721CFDF2034094D2@gsb-exchmb02.stanford.edu>
References: <mailman.41.1174042822.26678.tutor@python.org>
	<21EB45BA6A0A4844B97D46A7721CFDF2034094D2@gsb-exchmb02.stanford.edu>
Message-ID: <16651e80703161251m2ed3071dgfff900ce0edabb07@mail.gmail.com>

On 3/16/07, Switanek, Nick <nswitanek at stanford.edu> wrote:
> After creating a list of words ('wordlist'), I can run the following
> code in the interactive window of PythonWin in about ten seconds. If I
> run the script containing the code, the script seems to hang on the
> loop. I'd be grateful for help as to why; I often seem to have something
> that works in the interpreter, but not when I run the script.

I'm not sure what you mean by 'seems to hang'.  The code that you
posted isn't complete enough to run (since you didn't provide a
definition of wordlist), and just generates a NameError exception.

Beyond that, I don't understand what the code is supposed to produce
for output.  As written, you generate a list in your loop and assign
it to the name ngrams, but never do anything with that list.  Since
you're inside a for loop, your ngrams name is overwritten the next
time you run through the loop.  You also generate a string with the
statement "Finished the %d-gram list." % n, but you don't do anything
with it.  You probably want to either print it, or assign it to a
variable to print later.

Something like this:

wordlist = ['apple', 'orange', 'pear', 'banana', 'coconut']
N = [2,3,4,5]
ngramlist = [wordlist]
for n in N:
   ngrams = [' '.join(wordlist[i:i+n]) for i in range(len(wordlist)-n+1)]
   print "Finished the %d-gram list." % n
   print ngrams

produces the following output when run as a script:

Finished the 2-gram list.
['apple orange', 'orange pear', 'pear banana', 'banana coconut']
Finished the 3-gram list.
['apple orange pear', 'orange pear banana', 'pear banana coconut']
Finished the 4-gram list.
['apple orange pear banana', 'orange pear banana coconut']
Finished the 5-gram list.
['apple orange pear banana coconut']

Does that help?

-- 
Jerry

From python at wardroper.org  Fri Mar 16 21:53:26 2007
From: python at wardroper.org (Alan Wardroper)
Date: Fri, 16 Mar 2007 13:53:26 -0700
Subject: [Tutor]  Passing a list, dict or tuple to MySQLdb?
Message-ID: <45FB03C6.6050708@wardroper.org>

 > I think what you want is ...(*list_of_tuples) similar to the syntax used
 > when calling functions with position arguments from a list.

Thanks, that bypasses the "TypeError: not all arguments converted during 
string formatting" error but raises a new error
    
"TypeError: execute() takes at most 3 arguments (5877 given)"

Looks like the elements of the list are being passed in as individual 
arguments rather than a formatted list.
So, for the simplest case...

I tried various versons of that cursor.execute including all variants 
with/without parentheses around %s &&|| list_of_ids:

If I include one %s substitution for each element in the list, it works, 
but that raises the question of how to do it when you don't know the 
size of the list beforehand?

So, for a 5 element list, this works:
CODE:
cursor.execute("SELECT field1, field2 FROM sometable WHERE field1 IN 
(%s, %s, %s, %s, %s)", list_of_ids)

But when the list is generated by a previous select statement...?

I dug through the docs a bit I pulled out executemany(), and so this 
seems to work:

cursor.executemany("SELECT field1, field2 FROM sometable WHERE field1 IN 
(%s)", (list_of_ids))

Thanks

From tim at johnsons-web.com  Fri Mar 16 17:31:42 2007
From: tim at johnsons-web.com (Tim Johnson)
Date: Fri, 16 Mar 2007 16:31:42 +0000
Subject: [Tutor] cookie expiration date format
Message-ID: <200703161631.42787.tim@johnsons-web.com>

Hi:
I want to be able to expire a cookie programmatically.
In other languages, I just set the expiration date to 'yesterday'.
If I look at the documentation at:
http://docs.python.org/lib/node644.html
for the Cookie object, I see the following:
-----------------------------------------------------------
expires
    Integer expiry date in seconds since epoch,
-----------------------------------------------------------
I'm not clear what datatype is needed here.
Can anyone clarify this for me?
Thanks
Tim
-- 
Tim Johnson <tim at johnsons-web.com>
Palmer, Alaska, USA

From ceasar102 at yahoo.com  Sat Mar 17 03:23:09 2007
From: ceasar102 at yahoo.com (ammar azif)
Date: Fri, 16 Mar 2007 19:23:09 -0700 (PDT)
Subject: [Tutor] Built-in function to check a character is ASCII character?
Message-ID: <61953.89895.qm@web56114.mail.re3.yahoo.com>

Is there any Built-in function to check whether  a character is an ASCII character?

I am trying to learn event driven programming in python. Heres my code:

while 1:
    key=msvcrt.getch()
    if key==255:
        continue
    else:
        print "the key is ", key


But the output is:-

the key is  ?
the key is  ?
the key is  ?
the key is  ?
the key is  ?
the key is  ?
the key is  ?
the key is  ?(infinite loop)

Why is this happening ? what is the  ? character?





 
---------------------------------
Now that's room service! Choose from over 150,000 hotels 
in 45,000 destinations on Yahoo! Travel to find your fit.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070316/6d4dd2b7/attachment.html 

From rabidpoobear at gmail.com  Sat Mar 17 03:31:27 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Fri, 16 Mar 2007 21:31:27 -0500
Subject: [Tutor] cookie expiration date format
In-Reply-To: <200703161631.42787.tim@johnsons-web.com>
References: <200703161631.42787.tim@johnsons-web.com>
Message-ID: <45FB52FF.10902@gmail.com>

Tim Johnson wrote:
> Hi:
> I want to be able to expire a cookie programmatically.
> In other languages, I just set the expiration date to 'yesterday'.
> If I look at the documentation at:
> http://docs.python.org/lib/node644.html
> for the Cookie object, I see the following:
> -----------------------------------------------------------
> expires
>     Integer expiry date in seconds since epoch,
> -----------------------------------------------------------
> I'm not clear what datatype is needed here.
> Can anyone clarify this for me?
>   
Sounds like it's an integer or float, such as returned by time.time()
 >>> import time
 >>> time.time()
1174098190.796 #seconds since epoch
 >>> _ / 60
19568303.179933332#minutes since epoch
 >>> _ / 60
326138.3863322222 #hours ..
 >>> _ / 24
13589.099430509259# days
 >>> _ / 365.25
37.204926572236161 #years
 >>> .205 * 1.2
0.24599999999999997  #months ( fractional part of year )
 >>>

So today is 37 years 2.5 months from January 1, 1970.
1970 + 37 = 2007, and January 1 + 2.5 months = March 16.

If you wanted the cookie to expire 24 hours from now,
time.time() + 3600 * 24 #(seconds in a day)

See http://en.wikipedia.org/wiki/Unix_epoch for more info on the epoch.
look into the time and the datetime modules, there should be an easy way 
to find the seconds since epoch for whatever date you want.
HTH,
-Luke

From rabidpoobear at gmail.com  Sat Mar 17 03:37:50 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Fri, 16 Mar 2007 21:37:50 -0500
Subject: [Tutor] Built-in function to check a character is ASCII
	character?
In-Reply-To: <61953.89895.qm@web56114.mail.re3.yahoo.com>
References: <61953.89895.qm@web56114.mail.re3.yahoo.com>
Message-ID: <45FB547E.8050309@gmail.com>

ammar azif wrote:
> Is there any Built-in function to check whether  a character is an 
> ASCII character?
>
> I am trying to learn event driven programming in python. Heres my code:
>
> while 1:
>     key=msvcrt.getch()
>     if key==255:
>         continue
Here's your problem.
 >>> import msvcrt
 >>> msvcrt.getch()
'\xff'
 >>> print '\xff'
?
 >>> '\xff' == 255
False
 >>> ord('\xff')
255
 >>> '\xff' == chr(255)
True

Do you see?
'\xff' is a character, so it's not equal to the integer value 255 (in 
Python, characters are not the same thing as integers, unlike C++)
If you get the ordinal of '\xff' you'll get 255, or if you do chr(255) 
you'll get '\xff'.
You need to use one or the other method in your comparison, or just 
compare to '\xff'.


From johan at accesstel.co.za  Sat Mar 17 08:24:42 2007
From: johan at accesstel.co.za (Johan Geldenhuys)
Date: Sat, 17 Mar 2007 09:24:42 +0200
Subject: [Tutor] convert hex number to decimal
In-Reply-To: <d9e88eaf0703160411l4388ff2bsd5e345adf8dca76e@mail.gmail.com>
Message-ID: <20070317072643.6215850A9B@nlantispam.mtn.co.za>


>>> ord('\x0D')
13 

Johan

-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf
Of Rikard Bosnjakovic
Sent: 16 March 2007 01:12 PM
To: Tutor at python.org
Subject: Re: [Tutor] convert hex number to decimal

On 3/16/07, ammar azif <ceasar102 at yahoo.com> wrote:

> Is there any built-in function to convert a hex number to a decimal
number?

>>> int("ff", 16)
255



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

--
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.5.446 / Virus Database: 268.18.10/720 - Release Date: 2007/03/12
07:19 PM
 

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.446 / Virus Database: 268.18.10/720 - Release Date: 2007/03/12
07:19 PM
 


From rikard.bosnjakovic at gmail.com  Sat Mar 17 08:50:17 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Sat, 17 Mar 2007 08:50:17 +0100
Subject: [Tutor] Hi
In-Reply-To: <e5f41cb30703160747u30324649s875b5f33f7bcd052@mail.gmail.com>
References: <e5f41cb30703160747u30324649s875b5f33f7bcd052@mail.gmail.com>
Message-ID: <d9e88eaf0703170050h90764e2ja87cc6bb0df88b49@mail.gmail.com>

On 3/16/07, Ben <nebpro at gmail.com> wrote:

> Is anyone can point me where I can find a good tutorial about pywin for
> someone like me?

Pywin itself is not a package for making GUIs, it's merely a IDE for
Windows and got the win32all-package included.

For GUIs, you want to look at wxPython, pygtk or similiar packages.
Those will let you do what you are looking for.


-- 
- Rikard.

From ceasar102 at yahoo.com  Sat Mar 17 09:54:56 2007
From: ceasar102 at yahoo.com (ammar azif)
Date: Sat, 17 Mar 2007 01:54:56 -0700 (PDT)
Subject: [Tutor] Is generator function reusable?
Message-ID: <744962.9415.qm@web56101.mail.re3.yahoo.com>

Lets say a generator function instance is created and has finished its iteration.
Can that instance be reused again? can it accept anymore values? or we should discard it and create a new generator instance.

Thanks

 
---------------------------------
Need Mail bonding?
Go to the Yahoo! Mail Q&A for great tips from Yahoo! Answers users.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070317/48609717/attachment.htm 

From kent37 at tds.net  Sat Mar 17 15:28:33 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 17 Mar 2007 10:28:33 -0400
Subject: [Tutor] Is generator function reusable?
In-Reply-To: <744962.9415.qm@web56101.mail.re3.yahoo.com>
References: <744962.9415.qm@web56101.mail.re3.yahoo.com>
Message-ID: <45FBFB11.8030102@tds.net>

ammar azif wrote:
> Lets say a generator function instance is created and has finished its 
> iteration.
> Can that instance be reused again? can it accept anymore values? or we 
> should discard it and create a new generator instance.

In general, no, you can't reuse any iterator, including the generator 
created by calling a generator function. Iterators go through their 
values once, then raise StopIteration on any further accesses.

In Python 2.5 you can pass values into a generator by calling next() 
with a value. You could use this to create a generator that can be 
reset. But more commonly you would just call the generator function 
again and create a new generator instance.

Kent

From tim at johnsons-web.com  Sat Mar 17 09:13:01 2007
From: tim at johnsons-web.com (Tim Johnson)
Date: Sat, 17 Mar 2007 08:13:01 +0000
Subject: [Tutor] cookie expiration date format
In-Reply-To: <45FB52FF.10902@gmail.com>
References: <200703161631.42787.tim@johnsons-web.com>
	<45FB52FF.10902@gmail.com>
Message-ID: <200703170813.01278.tim@johnsons-web.com>

On Saturday 17 March 2007 02:31, Luke Paireepinart wrote:
> Tim Johnson wrote:
 
> > I'm not clear what datatype is needed here.
> > Can anyone clarify this for me?
>
> Sounds like it's an integer or float, such as returned by time.time()
>
 I shouldn't have used the word 'datatype', 'cuz I'm sure that it is a string.
 -having built cookie functions "from scratch" in other languages, according
to RFC 2965.
 I think I found what I am looking for at 
http://pleac.sourceforge.net/pleac_python/cgiprogramming.html
and look for keyword
time_format

I'll try and implement later today and report back on success or failure
Thanks Luke
tim

-- 
Tim Johnson <tim at johnsons-web.com>
Palmer, Alaska, USA

From tim at johnsons-web.com  Sat Mar 17 15:25:04 2007
From: tim at johnsons-web.com (Tim Johnson)
Date: Sat, 17 Mar 2007 14:25:04 +0000
Subject: [Tutor] cookie expiration date format
In-Reply-To: <200703170813.01278.tim@johnsons-web.com>
References: <200703161631.42787.tim@johnsons-web.com>
	<45FB52FF.10902@gmail.com>
	<200703170813.01278.tim@johnsons-web.com>
Message-ID: <200703171425.04484.tim@johnsons-web.com>

On Saturday 17 March 2007 08:13, Tim Johnson wrote:
> On Saturday 17 March 2007 02:31, Luke Paireepinart wrote:
> > Tim Johnson wrote:
> > > I'm not clear what datatype is needed here.
> > > Can anyone clarify this for me?
> >
> > Sounds like it's an integer or float, such as returned by time.time()
>
>  I shouldn't have used the word 'datatype', 'cuz I'm sure that it is a
> string. -having built cookie functions "from scratch" in other languages,
> according to RFC 2965.
>  I think I found what I am looking for at
> http://pleac.sourceforge.net/pleac_python/cgiprogramming.html
> and look for keyword
> time_format
>
> I'll try and implement later today and report back on success or failure
> Thanks Luke
Here we go....
import datetime
time_format = "%a, %d %b %Y"
expires = "%s" % ((datetime.datetime.now()
				+ datetime.timedelta(-1)).strftime(time_format))
#                                                              ^
#       -1 references previous day  -----------|
Thus the cookie directive in toto looks something like this:
note that it should all on one line so I'm delimiting with two lines of 
asterisks
************************************************************************
Set-Cookie: kbcpCookie=" (password|mypwd)(mylogin)"; 
Domain=.linus.johnson.com; expires=Fri, 16 Mar 2007; Path=/cgi-bin/ 
************************************************************************
I don't think the rfc is touchy about spaces following semicolons, but the 
exact format of the date (minutes and seconds optional) is important

Just a comment:
 I've used python for years and am always impressed with the
great amount of resources and the care taken to vet and document libraries, 
but I must say, in the case of the cookies library, module `Cookie', that the
documentation is a bit lacking and could use more, and some examples - as 
well.
MTCW
Tim

-- 
Tim Johnson <tim at johnsons-web.com>
Palmer, Alaska, USA

From pgreisen at gmail.com  Sun Mar 18 11:08:17 2007
From: pgreisen at gmail.com (Per Jr. Greisen)
Date: Sun, 18 Mar 2007 11:08:17 +0100
Subject: [Tutor] Rounding off
Message-ID: <e016526e0703180308o392c2472v1a5c2bcced3b909c@mail.gmail.com>

Hi,

Is there an easy way - a module or method for which you can round off number
such as

2.1345 to 2.135

Any help or advice appreciated?

-- 
Best regards
Per Jr. Greisen
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070318/b2731ebb/attachment.html 

From rdm at rcblue.com  Sun Mar 18 12:59:56 2007
From: rdm at rcblue.com (Dick Moores)
Date: Sun, 18 Mar 2007 04:59:56 -0700
Subject: [Tutor] Rounding off
In-Reply-To: <e016526e0703180308o392c2472v1a5c2bcced3b909c@mail.gmail.co
 m>
References: <e016526e0703180308o392c2472v1a5c2bcced3b909c@mail.gmail.com>
Message-ID: <20070318120000.2A6831E400A@bag.python.org>

At 03:08 AM 3/18/2007, Per Jr. Greisen wrote:
>Hi,
>
>Is there an easy way - a module or method for which you can round 
>off number such as
>
>2.1345 to 2.135

Well, there are

 >>> print "%.3f" % 2.1345
2.135

or

 >>> print round(2.1345, 3)
2.135

Dick Moores



From kent37 at tds.net  Sun Mar 18 13:55:21 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 18 Mar 2007 08:55:21 -0400
Subject: [Tutor] Rounding off
In-Reply-To: <20070318120000.2A6831E400A@bag.python.org>
References: <e016526e0703180308o392c2472v1a5c2bcced3b909c@mail.gmail.com>
	<20070318120000.2A6831E400A@bag.python.org>
Message-ID: <45FD36B9.4070809@tds.net>

Dick Moores wrote:
> At 03:08 AM 3/18/2007, Per Jr. Greisen wrote:
>> Hi,
>>
>> Is there an easy way - a module or method for which you can round 
>> off number such as
>>
>> 2.1345 to 2.135
> 
> Well, there are
> 
>  >>> print "%.3f" % 2.1345
> 2.135
> 
> or
> 
>  >>> print round(2.1345, 3)
> 2.135

The difference between these two is not obvious from the output. The 
result of "%.3f" % 2.1345 is a string; the result of round() is a 
floating-point number. So if your objective is display, use "%.3f" % 
2.1345. If your objective is further calculations, use round().

Kent

From rdm at rcblue.com  Sun Mar 18 14:39:59 2007
From: rdm at rcblue.com (Dick Moores)
Date: Sun, 18 Mar 2007 06:39:59 -0700
Subject: [Tutor] Rounding off
In-Reply-To: <20070318120000.2A6831E400A@bag.python.org>
References: <e016526e0703180308o392c2472v1a5c2bcced3b909c@mail.gmail.com>
	<20070318120000.2A6831E400A@bag.python.org>
Message-ID: <20070318134003.B34811E400A@bag.python.org>

At 04:59 AM 3/18/2007, Dick Moores wrote:
>At 03:08 AM 3/18/2007, Per Jr. Greisen wrote:
> >Hi,
> >
> >Is there an easy way - a module or method for which you can round
> >off number such as
> >
> >2.1345 to 2.135
>
>Well, there are
>
>  >>> print "%.3f" % 2.1345
>2.135
>
>or
>
>  >>> print round(2.1345, 3)
>2.135


 >>> print "%.4g" % 2.1345
2.135

But now I have a question.

 >>> print "%.3f" % 22.1345
22.134

and

 >>> print "%.5g" % 22.1345
22.134

but

 >>> print "%.3f" % 22.1346
22.135

and

 >>> print "%.5g" % 22.1346
22.135

Why the 22.134's?

Dick Moores 


From kent37 at tds.net  Sun Mar 18 14:51:24 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 18 Mar 2007 09:51:24 -0400
Subject: [Tutor] Rounding off
In-Reply-To: <20070318134003.B34811E400A@bag.python.org>
References: <e016526e0703180308o392c2472v1a5c2bcced3b909c@mail.gmail.com>	<20070318120000.2A6831E400A@bag.python.org>
	<20070318134003.B34811E400A@bag.python.org>
Message-ID: <45FD43DC.4020407@tds.net>

Dick Moores wrote:

>>  >>> print round(2.1345, 3)
>> 2.135
> 
> But now I have a question.
> 
>  >>> print "%.3f" % 22.1345
> 22.134
> 
> Why the 22.134's?

Because neither 2.1345 nor 22.1345 can be represented exactly in 
floating point, and the errors are in the opposite direction:

In [4]: repr(22.1345)
Out[4]: '22.134499999999999'
In [5]: repr(2.1345)
Out[5]: '2.1345000000000001'

Kent

From pgreisen at gmail.com  Sun Mar 18 18:45:46 2007
From: pgreisen at gmail.com (Per Jr. Greisen)
Date: Sun, 18 Mar 2007 18:45:46 +0100
Subject: [Tutor] Rounding number
Message-ID: <e016526e0703181045o3e11fa6cga4ad219a28aa9aae@mail.gmail.com>

Hi,

I use the method from math in order to round off the number:

import math

a = 1.39999

b = round(a,3)

which equals gives
b=1.4

is it possible to have the rounding such that
b = 1.400

so it keeps in my case the correct digits?

Any help appreciate. Thanks in advance



-- 
Best regards
Per Jr. Greisen
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070318/4385b159/attachment.htm 

From fharms at iowatelecom.net  Sun Mar 18 18:30:22 2007
From: fharms at iowatelecom.net (isaack  harms)
Date: Sun, 18 Mar 2007 11:30:22 -0600
Subject: [Tutor] call me 712-248-9407
Message-ID: <007101c76983$1d26c1e0$640fa8c0@your4f1261a8e5>


  Hi bady,

  www.ppibiz.com

  My name is Isaack  Harms with The ProfitMasters Team.  It was nice to talk with you this afternoon.  You requested information after watching my movie online at www.profitsfromtheweb.net  I am here to be your guide through this process and I look forward to getting you on the road to six figures.     



  $1,000 and $4,500  (per Sale ) Delivered Right to Your Door!  



  Below are the steps for you to complete your due diligence on this Extraordinary 0pportunity with EPI. Life by Design is the Name of the Game - Are you Ready to Play? 



  First is to listen to a live or recorded call for a complete overview of the program.   

                   

  Live Call              1-617-588-6550  


  Monday - Thursday       3:00 & 9:00 PM EST 

  Friday            3:00 PM EST

  Saturday       1:00 PM EST

  Sunday         9:00 PM EST 

    

  Recorded Call       1-617-588-6550  





                www.ppibiz.com       

  Second go to my director's frequently asked questions site.   This link will show you the product, magazine articles, and much more. 



  www.faq7.com 





  Third get back with me and let me know that you are ready to get started.  Be ready to have your life drastically changed for the better. 





  Simply put ... You CAN'T L0SE! 

  Get Started Today!





  IsaackHarms

  (712) 248-9407--712.272.3072

  fharms at iowatelecom.net

  www.profitsfromtheweb.net

    

    



  "You can have whatever you want in life if you just 
  Help enough Other people get what They want." 
  Zig Ziglar 








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



-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070318/b60ff1e3/attachment.html 

From ceasar102 at yahoo.com  Mon Mar 19 06:41:01 2007
From: ceasar102 at yahoo.com (ammar azif)
Date: Sun, 18 Mar 2007 22:41:01 -0700 (PDT)
Subject: [Tutor] Tkinter-Button class
Message-ID: <251983.19368.qm@web56103.mail.re3.yahoo.com>

Hi,

Thanks for the help guys.


I have tried gui programming using Tkinter and use the Button class which accepts the command argument which is a function object.

The question is how to send arguments if the function accepts arguments.





 
---------------------------------
 Get your own web address.
 Have a HUGE year through Yahoo! Small Business.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070318/0187e3ff/attachment.html 

From rabidpoobear at gmail.com  Mon Mar 19 07:22:49 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 19 Mar 2007 01:22:49 -0500
Subject: [Tutor] Rounding number
In-Reply-To: <e016526e0703181045o3e11fa6cga4ad219a28aa9aae@mail.gmail.com>
References: <e016526e0703181045o3e11fa6cga4ad219a28aa9aae@mail.gmail.com>
Message-ID: <45FE2C39.2060906@gmail.com>

Per Jr. Greisen wrote:
> Hi,
>
> I use the method from math in order to round off the number:
>
> import math
>
> a = 1.39999
>
> b = round(a,3)
>
> which equals gives
> b=1.4
>
> is it possible to have the rounding such that
> b = 1.400
Trailing zeroes aren't significant values so the computer won't store it.
This rounding works when the rounded values don't have trailing zeroes, 
right?
It's possible to add these zeroes using string formatting, when you want 
to display them.
 >>> "%.3f" % 1.4
'1.400'
See http://docs.python.org/lib/typesseq-strings.html for more 
information on string formatting operations.


From rdm at rcblue.com  Mon Mar 19 11:04:03 2007
From: rdm at rcblue.com (Dick Moores)
Date: Mon, 19 Mar 2007 03:04:03 -0700
Subject: [Tutor] The '45' bug in round()
Message-ID: <20070319100407.EFBF81E4003@bag.python.org>

Yesterday I was shocked, SHOCKED, to discover that round() is 
occasionally rounding incorrectly. For example,

 >>> print round(0.19945,4)
0.1994

For rounding of random samples of numbers between 0 and 1 ending in 
'45', the error ratio is about 0.041. Here are a few more examples:

 >>> print round(0.145, 2)
0.14

 >>> print round(0.5045, 3)
0.504

 >>> print round(0.34145, 4)
0.3414

 >>> print round(0.5170845, 6)
0.517084

 >>> print round(0.083400685245, 11)
0.08340068524

It may not be correct to call this a bug, but this is what I'm going 
to use until round() is revised:

def round2(n, digits=0):
     s = str(n)
     if '.' in s and s[-2:] == '45':
         mantissa = s.split('.')[1]
         if len(mantissa) - digits == 1:
             s = s[:-2] + '5'
             return s
         else:
             return round(float(s), digits)
     else:
         return round(float(n), digits)

Comments, Tutors? Am I way out in left field with this?

Dick Moores







0.504
0.505



0.083400685245
0.08340068524
0.08340068525

0.34145
0.3415
0.3414

0.29692817045
0.2969281705
0.2969281704

0.74945
0.7495
0.7494


From kent37 at tds.net  Mon Mar 19 11:19:44 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 19 Mar 2007 06:19:44 -0400
Subject: [Tutor] Tkinter-Button class
In-Reply-To: <251983.19368.qm@web56103.mail.re3.yahoo.com>
References: <251983.19368.qm@web56103.mail.re3.yahoo.com>
Message-ID: <45FE63C0.7090906@tds.net>

ammar azif wrote:
> Hi,
> 
> Thanks for the help guys.
> 
> 
> I have tried gui programming using Tkinter and use the Button class 
> which accepts the command argument which is a function object.
> 
> The question is how to send arguments if the function accepts arguments.

A common way to do this is to use a lambda expression to bind the 
arguments, e.g.
Button(..., command = lambda: func_with_args(1, 2, 3))

For example see
http://www.daniweb.com/code/snippet610.html

You could also define explicit, short helper functions if you don't want 
to use lambdas.

Kent

From kent37 at tds.net  Mon Mar 19 11:29:57 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 19 Mar 2007 06:29:57 -0400
Subject: [Tutor] The '45' bug in round()
In-Reply-To: <20070319100407.EFBF81E4003@bag.python.org>
References: <20070319100407.EFBF81E4003@bag.python.org>
Message-ID: <45FE6625.5020909@tds.net>

Dick Moores wrote:
> Yesterday I was shocked, SHOCKED, to discover that round() is 
> occasionally rounding incorrectly. For example,
> 
>  >>> print round(0.19945,4)
> 0.1994
> 
> For rounding of random samples of numbers between 0 and 1 ending in 
> '45', the error ratio is about 0.041. Here are a few more examples:

As I said yesterday, these are numbers that don't have an exact 
representation as binary floating point numbers. The actual 
representation is slightly less than what you ask for and it is rounded 
correctly. The repr() function will show a decimal approximation of the 
actual binary number:

In [1]: repr(.19945)
Out[1]: '0.19944999999999999'

For example 0.19945 is actually stored as approximately 
0.19944999999999999. What should be the result of
round(0.19944999999999999, 4)

This is an inherent limitation of binary floating point, not a bug. If 
you want exact representation of decimal fractions use the decimal module.
Read more here:
http://docs.python.org/tut/node16.html

> Comments, Tutors? Am I way out in left field with this?

IMO yes.

Kent

From mail at ozzmosis.com  Mon Mar 19 11:28:33 2007
From: mail at ozzmosis.com (andrew clarke)
Date: Mon, 19 Mar 2007 21:28:33 +1100
Subject: [Tutor] The '45' bug in round()
In-Reply-To: <20070319100407.EFBF81E4003@bag.python.org>
References: <20070319100407.EFBF81E4003@bag.python.org>
Message-ID: <20070319102833.GA73392@ozzmosis.com>

On Mon, Mar 19, 2007 at 03:04:03AM -0700, Dick Moores wrote:

> Yesterday I was shocked, SHOCKED, to discover that round() is 
> occasionally rounding incorrectly. For example,

"Garbage In, Garbage Out" :-)

Floating point numbers in Python (and other computer languages) are only
an approximation:

>>> print round(0.145, 2)
0.14
>>> 0.145
0.14499999999999999
>>> print round(0.1450000001, 2)
0.15

http://docs.python.org/tut/node16.html has some more information about
this.

From rdm at rcblue.com  Mon Mar 19 11:56:04 2007
From: rdm at rcblue.com (Dick Moores)
Date: Mon, 19 Mar 2007 03:56:04 -0700
Subject: [Tutor] The '45' bug in round()
In-Reply-To: <45FE6625.5020909@tds.net>
References: <20070319100407.EFBF81E4003@bag.python.org>
	<45FE6625.5020909@tds.net>
Message-ID: <20070319105609.080291E4009@bag.python.org>

At 03:29 AM 3/19/2007, Kent Johnson wrote:
>Dick Moores wrote:
>>Yesterday I was shocked, SHOCKED, to discover that round() is 
>>occasionally rounding incorrectly. For example,
>>  >>> print round(0.19945,4)
>>0.1994
>>For rounding of random samples of numbers between 0 and 1 ending in 
>>'45', the error ratio is about 0.041. Here are a few more examples:
>
>As I said yesterday, these are numbers that don't have an exact 
>representation as binary floating point numbers. The actual 
>representation is slightly less than what you ask for and it is 
>rounded correctly. The repr() function will show a decimal 
>approximation of the actual binary number:
>
>In [1]: repr(.19945)
>Out[1]: '0.19944999999999999'
>
>For example 0.19945 is actually stored as approximately 
>0.19944999999999999. What should be the result of
>round(0.19944999999999999, 4)
>
>This is an inherent limitation of binary floating point, not a bug. 
>If you want exact representation of decimal fractions use the decimal module.
>Read more here:
>http://docs.python.org/tut/node16.html
>
>>Comments, Tutors? Am I way out in left field with this?
>
>IMO yes.

Kent, I did understand the points you made in that earlier thread. 
However, I'm unhappy with

 >>> print round(0.19945,4)
0.1994

Am I the only one unhappy with this kind of rounding?

My function, round2() restores me to happiness.  :)

 >>> print round2(0.19945,4)
0.1995

Is there something wrong with it?

Here it is again:

def round2(n, digits=0):
     s = str(n)
     if '.' in s and s[-2:] == '45':
         mantissa = s.split('.')[1]
         if len(mantissa) - digits == 1:
             s = s[:-2] + '5'
             return s
         else:
             return round(float(s), digits)
     else:
         return round(float(n), digits)

Dick



From kent37 at tds.net  Mon Mar 19 12:13:09 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 19 Mar 2007 07:13:09 -0400
Subject: [Tutor] Tkinter-Button class
In-Reply-To: <169589.82630.qm@web56113.mail.re3.yahoo.com>
References: <169589.82630.qm@web56113.mail.re3.yahoo.com>
Message-ID: <45FE7045.3080000@tds.net>

ammar azif wrote:
> Hi,
> 
> Thanks for answering .. btw what do you mean by explicit , helper 
> function? Can you explain about these functions?

I just mean, define an ordinary function of no arguments that does what 
you want. For example, the calculator program I linked to has this Button:
tk.Button(root,text='1',width=5,relief=tk.RIDGE,
   command=lambda: click('1'))

That could be written as
def click1():
   click('1')
tk.Button(root,text='1',width=5,relief=tk.RIDGE, command=click1)

Notice there are no parentheses after 'click1' in the Button definition; 
you are passing the actual function to the Button.

Kent

PS Please reply on-list.

> 
> */Kent Johnson <kent37 at tds.net>/* wrote:
> 
>     ammar azif wrote:
>      > Hi,
>      >
>      > Thanks for the help guys.
>      >
>      >
>      > I have tried gui programming using Tkinter and use the Button class
>      > which accepts the command argument which is a function object.
>      >
>      > The question is how to send arguments if the function accepts
>     arguments.
> 
>     A common way to do this is to use a lambda expression to bind the
>     arguments, e.g.
>     Button(..., command = lambda: func_with_args(1, 2, 3))
> 
>     For example see
>     http://www.daniweb.com/code/snippet610.html
> 
>     You could also define explicit, short helper functions if you don't
>     want
>     to use lambdas.
> 
>     Kent
> 
> 
> ------------------------------------------------------------------------
> Don't pick lemons.
> See all the new 2007 cars 
> <http://autos.yahoo.com/new_cars.html;_ylc=X3oDMTE0OGRsc3F2BF9TAzk3MTA3MDc2BHNlYwNtYWlsdGFncwRzbGsDbmV3Y2Fycw--> 
> at Yahoo! Autos. 
> <http://autos.yahoo.com/new_cars.html;_ylc=X3oDMTE0OGRsc3F2BF9TAzk3MTA3MDc2BHNlYwNtYWlsdGFncwRzbGsDbmV3Y2Fycw--> 
> 


From kent37 at tds.net  Mon Mar 19 12:24:39 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 19 Mar 2007 07:24:39 -0400
Subject: [Tutor] The '45' bug in round()
In-Reply-To: <20070319105609.080291E4009@bag.python.org>
References: <20070319100407.EFBF81E4003@bag.python.org>	<45FE6625.5020909@tds.net>
	<20070319105609.080291E4009@bag.python.org>
Message-ID: <45FE72F7.7000407@tds.net>

Dick Moores wrote:

> Kent, I did understand the points you made in that earlier thread. 
> However, I'm unhappy with
> 
>  >>> print round(0.19945,4)
> 0.1994
> 
> Am I the only one unhappy with this kind of rounding?

IMO you are chasing a non-problem. In real-world use, you would probably 
not type in a number and then immediately round it. You would round the 
result of some calculation that itself starts with inexact values and 
then introduces more error. To take the result of this calculation and 
second-guess it seems silly to me.

> My function, round2() restores me to happiness.  :)

Well I should leave well enough alone then :-)

>  >>> print round2(0.19945,4)
> 0.1995
> 
> Is there something wrong with it?

If you want exact decimal representations you may be better off using 
the decimal module than trying to patch binary floating point. Though 
decimal has its own representation error...

Kent

From pgreisen at gmail.com  Mon Mar 19 13:11:27 2007
From: pgreisen at gmail.com (Per Jr. Greisen)
Date: Mon, 19 Mar 2007 13:11:27 +0100
Subject: [Tutor] Making table
Message-ID: <e016526e0703190511p26ba30d6qd9bfe14cad95ebf5@mail.gmail.com>

Hi,
I need to generate a table with different x,y,z values and write them to a
file:
10.171  -15.243 -2.558
9.837   -14.511 -1.923
-23.451 -13.870 51.507

I would like to write to the files as columns
 10.171   -15.243   -2.558
   9.837   -14.511   -1.923
-23.451   -13.870  51.507
   0.233      0.453    0.111

so the number are correctly aligned. Does anybody know a function that can
align the numbers.
Any advice or help appreciated. Thanks in advance.
-- 
Best regards
Per
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070319/7f8f6213/attachment.html 

From dkuhlman at rexx.com  Mon Mar 19 16:31:05 2007
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Mon, 19 Mar 2007 08:31:05 -0700
Subject: [Tutor] Making table
In-Reply-To: <e016526e0703190511p26ba30d6qd9bfe14cad95ebf5@mail.gmail.com>
References: <e016526e0703190511p26ba30d6qd9bfe14cad95ebf5@mail.gmail.com>
Message-ID: <20070319153105.GA55460@cutter.rexx.com>

On Mon, Mar 19, 2007 at 01:11:27PM +0100, Per Jr. Greisen wrote:
> Hi,
> I need to generate a table with different x,y,z values and write them to a
> file:
> 10.171  -15.243 -2.558
> 9.837   -14.511 -1.923
> -23.451 -13.870 51.507
> 
> I would like to write to the files as columns
> 10.171   -15.243   -2.558
>   9.837   -14.511   -1.923
> -23.451   -13.870  51.507
>   0.233      0.453    0.111
> 
> so the number are correctly aligned. Does anybody know a function that can
> align the numbers.
> Any advice or help appreciated. Thanks in advance.

Try ljust and rjust.  They are string functions/methods and are
described here: http://docs.python.org/lib/string-methods.html

Something like the following might work for you:

    In [1]: value = 3.45678
    In [2]: ("%0.3f" % value).rjust(10)
    Out[2]: '     3.457'

(using the ipython interactive shell)

Dave


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

From Mike.Hansen at atmel.com  Mon Mar 19 16:33:02 2007
From: Mike.Hansen at atmel.com (Mike Hansen)
Date: Mon, 19 Mar 2007 09:33:02 -0600
Subject: [Tutor] cookie expiration date format
In-Reply-To: <45FB52FF.10902@gmail.com>
References: <200703161631.42787.tim@johnsons-web.com>
	<45FB52FF.10902@gmail.com>
Message-ID: <57B026980605A64F9B23484C5659E32E6C3369@poccso.US.ad.atmel.com>

 

> -----Original Message-----
> From: tutor-bounces at python.org 
> [mailto:tutor-bounces at python.org] On Behalf Of Luke Paireepinart
> Sent: Friday, March 16, 2007 8:31 PM
> To: Tim Johnson
> Cc: tutor at python.org
> Subject: Re: [Tutor] cookie expiration date format
> 
> Tim Johnson wrote:
> > Hi:
> > I want to be able to expire a cookie programmatically.
> > In other languages, I just set the expiration date to 'yesterday'.
> > If I look at the documentation at:
> > http://docs.python.org/lib/node644.html
> > for the Cookie object, I see the following:
> > -----------------------------------------------------------
> > expires
> >     Integer expiry date in seconds since epoch,
> > -----------------------------------------------------------
> > I'm not clear what datatype is needed here.
> > Can anyone clarify this for me?
> >   
> Sounds like it's an integer or float, such as returned by time.time()
>  >>> import time
>  >>> time.time()
> 1174098190.796 #seconds since epoch
>  >>> _ / 60
> 19568303.179933332#minutes since epoch
>  >>> _ / 60
> 326138.3863322222 #hours ..
>  >>> _ / 24
> 13589.099430509259# days
>  >>> _ / 365.25
> 37.204926572236161 #years
>  >>> .205 * 1.2
> 0.24599999999999997  #months ( fractional part of year )
>  >>>
> 
> So today is 37 years 2.5 months from January 1, 1970.
> 1970 + 37 = 2007, and January 1 + 2.5 months = March 16.
> 
> If you wanted the cookie to expire 24 hours from now,
> time.time() + 3600 * 24 #(seconds in a day)
> 
> See http://en.wikipedia.org/wiki/Unix_epoch for more info on 
> the epoch.
> look into the time and the datetime modules, there should be 
> an easy way 
> to find the seconds since epoch for whatever date you want.
> HTH,
> -Luke

Some of the modules in the Python standard library make things a little
more difficult than other languages.(Perl, Ruby, ...) This is a good
example of it. Are there any 3rd party modules that let you set the
expiration date to 'yesterday'? I know I could write a wrapper, but I'd
rather not re-invent the wheel and save some time.

Another example is ftplib. Other language's ftp modules/libraries allow
you do something like sendaciifile(fh) or sendbinaryfile(fh) yet you
need to build your own wrapper functions in Python.
http://effbot.org/librarybook/ftplib.htm 

Mike

From kent37 at tds.net  Mon Mar 19 16:53:06 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 19 Mar 2007 11:53:06 -0400
Subject: [Tutor] Making table
In-Reply-To: <20070319153105.GA55460@cutter.rexx.com>
References: <e016526e0703190511p26ba30d6qd9bfe14cad95ebf5@mail.gmail.com>
	<20070319153105.GA55460@cutter.rexx.com>
Message-ID: <45FEB1E2.1000501@tds.net>

Dave Kuhlman wrote:
> Try ljust and rjust.  They are string functions/methods and are
> described here: http://docs.python.org/lib/string-methods.html
> 
> Something like the following might work for you:
> 
>     In [1]: value = 3.45678
>     In [2]: ("%0.3f" % value).rjust(10)
>     Out[2]: '     3.457'

Most string formatting conversions allow you to specify a width 
directly. For example,
In [61]: value = 3.45678
In [63]: "%10.3f" % value
Out[63]: '     3.457'

Kent

From nswitanek at stanford.edu  Mon Mar 19 17:52:33 2007
From: nswitanek at stanford.edu (Switanek, Nick)
Date: Mon, 19 Mar 2007 09:52:33 -0700
Subject: [Tutor] fine in interpreter, hangs in batch
In-Reply-To: <16651e80703161251m2ed3071dgfff900ce0edabb07@mail.gmail.com>
Message-ID: <21EB45BA6A0A4844B97D46A7721CFDF20340955D@gsb-exchmb02.stanford.edu>

Thanks very much for your help.

I did indeed neglect to put the "print" in the code that I sent to the
list.

It appears that the step that is taking a long time, and that therefore
makes me think that the script is somehow broken, is creating a
dictionary of frequencies from the list of ngrams. To do this, I've
written, for example:

bigramDict = {}
bigrams = [' '.join(wordlist[i:i+2]) for i in range(len(wordlist)-2+1)]
for bigram in bigrams:
	if bigram in bigramDict.keys(): bigramDict[bigram] += 1
	else: bigramDict[bigram] = 1


With around 500,000 bigrams, this is taking over 25 minutes to run (and
I haven't sat around to let it finish) on an XP machine at 3.0GHz and
1.5GB RAM. I bet I'm trying to reinvent the wheel here, and that there
are faster algorithms available in some package. I think possibly an
indexing package like PyLucene would help create frequency dictionaries,
but I can't figure it out from the online material available. Any
suggestions?

Thanks,
Nick



-----Original Message-----
From: Jerry Hill [mailto:malaclypse2 at gmail.com] 
Sent: Friday, March 16, 2007 12:52 PM
To: Switanek, Nick
Cc: tutor at python.org
Subject: Re: [Tutor] fine in interpreter, hangs in batch

On 3/16/07, Switanek, Nick <nswitanek at stanford.edu> wrote:
> After creating a list of words ('wordlist'), I can run the following
> code in the interactive window of PythonWin in about ten seconds. If I
> run the script containing the code, the script seems to hang on the
> loop. I'd be grateful for help as to why; I often seem to have
something
> that works in the interpreter, but not when I run the script.

I'm not sure what you mean by 'seems to hang'.  The code that you
posted isn't complete enough to run (since you didn't provide a
definition of wordlist), and just generates a NameError exception.

Beyond that, I don't understand what the code is supposed to produce
for output.  As written, you generate a list in your loop and assign
it to the name ngrams, but never do anything with that list.  Since
you're inside a for loop, your ngrams name is overwritten the next
time you run through the loop.  You also generate a string with the
statement "Finished the %d-gram list." % n, but you don't do anything
with it.  You probably want to either print it, or assign it to a
variable to print later.

Something like this:

wordlist = ['apple', 'orange', 'pear', 'banana', 'coconut']
N = [2,3,4,5]
ngramlist = [wordlist]
for n in N:
   ngrams = [' '.join(wordlist[i:i+n]) for i in
range(len(wordlist)-n+1)]
   print "Finished the %d-gram list." % n
   print ngrams

produces the following output when run as a script:

Finished the 2-gram list.
['apple orange', 'orange pear', 'pear banana', 'banana coconut']
Finished the 3-gram list.
['apple orange pear', 'orange pear banana', 'pear banana coconut']
Finished the 4-gram list.
['apple orange pear banana', 'orange pear banana coconut']
Finished the 5-gram list.
['apple orange pear banana coconut']

Does that help?

-- 
Jerry

From tim at johnsons-web.com  Mon Mar 19 10:30:43 2007
From: tim at johnsons-web.com (Tim Johnson)
Date: Mon, 19 Mar 2007 09:30:43 +0000
Subject: [Tutor] cookie expiration date format
In-Reply-To: <57B026980605A64F9B23484C5659E32E6C3369@poccso.US.ad.atmel.com>
References: <200703161631.42787.tim@johnsons-web.com>
	<45FB52FF.10902@gmail.com>
	<57B026980605A64F9B23484C5659E32E6C3369@poccso.US.ad.atmel.com>
Message-ID: <200703190930.43031.tim@johnsons-web.com>

On Monday 19 March 2007 15:33, Mike Hansen wrote:
 
 
> Some of the modules in the Python standard library make things a little
> more difficult than other languages.(Perl, Ruby, ...) This is a good
> example of it. Are there any 3rd party modules that let you set the
> expiration date to 'yesterday'? I know I could write a wrapper, but I'd
> rather not re-invent the wheel and save some time.

 I've written my own. The time format function was all I needed to handle
the expiration. Having had to write cookie objects in other languages from
scratch, I knew what I was after, just a matter of finding the right python
module and function to do it. datetime was the key.

> Another example is ftplib. Other language's ftp modules/libraries allow
> you do something like sendaciifile(fh) or sendbinaryfile(fh) yet you
> need to build your own wrapper functions in Python.
> http://effbot.org/librarybook/ftplib.htm

 Wrote my own wrapper for ftplib years ago. with those function included...

 I think it is inevitable that wrappers get written because programmers have
 unique circumstance and needs. In my case, I not only needed to expire a
 cookie, it served my needs to embedded multiple names and values in
 the cookie value.

 another example, I wrote a cgi wrapper so I could make calls like
 cgi["first_name"] ## where __getitem__ gets the value for posted field name

 I think the cookie library is great. Just needs some more docs and examples.
 (IMHO)
 that would make it easier for other programmers to write their own wrappers.

The function looks like this:
	def expire(self,name):
		c = self.get(name) ## retrieve cookie by name
		if c: 
			time_format = "%a, %d %b %Y"
			expires = "%s" % (
				(datetime.datetime.now() ## set the expiration date to yesterday
				+ datetime.timedelta(-1)).strftime(time_format)
				)   ## one second might be good enough!
			self.expires = expires
			self.set(name,c)
I choose not to override del (using __del__) because it would have 
necessitated a second argument to del(), as in del(cookie,cookie_name)
My class handless multiple cookies.

Thanks Mike
tim

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

-- 
Tim Johnson <tim at johnsons-web.com>
Palmer, Alaska, USA

From kent37 at tds.net  Mon Mar 19 18:23:17 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 19 Mar 2007 13:23:17 -0400
Subject: [Tutor] fine in interpreter, hangs in batch
In-Reply-To: <21EB45BA6A0A4844B97D46A7721CFDF20340955D@gsb-exchmb02.stanford.edu>
References: <21EB45BA6A0A4844B97D46A7721CFDF20340955D@gsb-exchmb02.stanford.edu>
Message-ID: <45FEC705.9030704@tds.net>

Switanek, Nick wrote:
> Thanks very much for your help.
> 
> I did indeed neglect to put the "print" in the code that I sent to the
> list.
> 
> It appears that the step that is taking a long time, and that therefore
> makes me think that the script is somehow broken, is creating a
> dictionary of frequencies from the list of ngrams. To do this, I've
> written, for example:
> 
> bigramDict = {}
> bigrams = [' '.join(wordlist[i:i+2]) for i in range(len(wordlist)-2+1)]
> for bigram in bigrams:
> 	if bigram in bigramDict.keys(): bigramDict[bigram] += 1
> 	else: bigramDict[bigram] = 1

Ouch! bigramDict.keys() creates a *new* *list* of all the keys in 
bigramDict. You then search the list - a linear search! - for bigram. 
I'm not surprised that this gets slow.

If you change that line to
   if bigram in bigramDict: bigramDict[bigram] += 1
you should see a dramatic improvement.

Kent

> 
> 
> With around 500,000 bigrams, this is taking over 25 minutes to run (and
> I haven't sat around to let it finish) on an XP machine at 3.0GHz and
> 1.5GB RAM. I bet I'm trying to reinvent the wheel here, and that there
> are faster algorithms available in some package. I think possibly an
> indexing package like PyLucene would help create frequency dictionaries,
> but I can't figure it out from the online material available. Any
> suggestions?
> 
> Thanks,
> Nick


From kent37 at tds.net  Mon Mar 19 19:03:03 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 19 Mar 2007 14:03:03 -0400
Subject: [Tutor] fine in interpreter, hangs in batch
In-Reply-To: <21EB45BA6A0A4844B97D46A7721CFDF20340956C@gsb-exchmb02.stanford.edu>
References: <21EB45BA6A0A4844B97D46A7721CFDF20340956C@gsb-exchmb02.stanford.edu>
Message-ID: <45FED057.2060603@tds.net>

Switanek, Nick wrote:
> Great, Kent, thanks. I thought that I had to check in the .keys() to see
> if the key was there. 
> 
> It seems that the method you suggest will not work if I'm looking for a
> value in the dictionary. If that's correct, is there a fast alternative
> to searching through .values()

Not directly. If you only need to search by values (not keys) consider 
if you can reverse the keys and values. (This probably won't work if you 
can have many keys with the same value.)

Alternately, maintain a set of values in parallel with the dictionary. 
If there are a lot of places where you need to do this, maybe you want 
to make a dict subclass that manages a helper set. A good place to start 
might be this recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/438823

It doesn't do what you want but it is similar and shows which dict 
methods must be overridden.

Hmm, deleting entries could be tricky, you don't know whether to delete 
from the helper. Maybe keep a dict that maps values to a count of how 
many times the value appears in the main dict.

Kent

From jmh at physics.ucdavis.edu  Mon Mar 19 19:00:01 2007
From: jmh at physics.ucdavis.edu (Michael Hannon)
Date: Mon, 19 Mar 2007 11:00:01 -0700
Subject: [Tutor] The '45' bug in round()
In-Reply-To: <20070319100407.EFBF81E4003@bag.python.org>
References: <20070319100407.EFBF81E4003@bag.python.org>
Message-ID: <20070319180001.GA3137@physics.ucdavis.edu>

On Mon, Mar 19, 2007 at 03:04:03AM -0700, Dick Moores wrote:
> Yesterday I was shocked, SHOCKED, to discover that round() is 
> occasionally rounding incorrectly. For example,
> 
>  >>> print round(0.19945,4)
> 0.1994
.
.
.
> Comments, Tutors? Am I way out in left field with this?


I suggest you might want to look at the discussion of unbiased rounding at:

    http://en.wikipedia.org/wiki/Rounding

					- Mike

From Barry.Carroll at psc.com  Mon Mar 19 18:40:31 2007
From: Barry.Carroll at psc.com (Carroll, Barry)
Date: Mon, 19 Mar 2007 10:40:31 -0700
Subject: [Tutor] Making table
In-Reply-To: <mailman.17463.1174325008.32030.tutor@python.org>
Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595B30@eugsrv400.psc.pscnet.com>

> -----Original Message-----
> Date: Mon, 19 Mar 2007 11:53:06 -0400
> From: Kent Johnson <kent37 at tds.net>
> Subject: Re: [Tutor] Making table
> To: tutor at python.org
> Message-ID: <45FEB1E2.1000501 at tds.net>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
> 
> Dave Kuhlman wrote:
> > Try ljust and rjust.  They are string functions/methods and are
> > described here: http://docs.python.org/lib/string-methods.html
> >
> > Something like the following might work for you:
> >
> >     In [1]: value = 3.45678
> >     In [2]: ("%0.3f" % value).rjust(10)
> >     Out[2]: '     3.457'
> 
> Most string formatting conversions allow you to specify a width
> directly. For example,
> In [61]: value = 3.45678
> In [63]: "%10.3f" % value
> Out[63]: '     3.457'
> 
> Kent
> 
What if one wished to align the values in each column at the decimal
point?  Is there a simple means to do this in Python, or would one need
to write a new function?

Regards,
 
Barry
barry.carroll at psc.com
541-302-1107
________________________
We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed



From malaclypse2 at gmail.com  Mon Mar 19 20:52:37 2007
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Mon, 19 Mar 2007 15:52:37 -0400
Subject: [Tutor] fine in interpreter, hangs in batch
In-Reply-To: <21EB45BA6A0A4844B97D46A7721CFDF20340955D@gsb-exchmb02.stanford.edu>
References: <16651e80703161251m2ed3071dgfff900ce0edabb07@mail.gmail.com>
	<21EB45BA6A0A4844B97D46A7721CFDF20340955D@gsb-exchmb02.stanford.edu>
Message-ID: <16651e80703191252i638fcec6v3084a032fb575c7e@mail.gmail.com>

On 3/19/07, Switanek, Nick <nswitanek at stanford.edu> wrote:
> Thanks very much for your help.
>
> It appears that the step that is taking a long time, and that therefore
> makes me think that the script is somehow broken, is creating a
> dictionary of frequencies from the list of ngrams. To do this, I've
> written, for example:

Well, if you're guessing which part of your code is slow, you should
profile your code so you can stop guessing.  Python has some very
useful built in profiling tools, documented here:
http://docs.python.org/lib/profile.html

Take a look at the "Instant User's Manual", which should be enough to
get you started. Once you can see exactly which parts of your code are
taking the longest, then you'll know what the best targets are for
optimization.

-- 
Jerry

From kent37 at tds.net  Mon Mar 19 20:59:29 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 19 Mar 2007 15:59:29 -0400
Subject: [Tutor] Making table
In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A4304595B30@eugsrv400.psc.pscnet.com>
References: <2BBAEE949D384D40A2B851287ADB6A4304595B30@eugsrv400.psc.pscnet.com>
Message-ID: <45FEEBA1.8060307@tds.net>

Carroll, Barry wrote:
>> -----Original Message-----
>> Date: Mon, 19 Mar 2007 11:53:06 -0400
>> From: Kent Johnson <kent37 at tds.net>

>> Most string formatting conversions allow you to specify a width
>> directly. For example,
>> In [61]: value = 3.45678
>> In [63]: "%10.3f" % value
>> Out[63]: '     3.457'
>>
>> Kent
>>
> What if one wished to align the values in each column at the decimal
> point?  Is there a simple means to do this in Python, or would one need
> to write a new function?

If you specify the number of digits after the decimal point, that number 
of digits will always be given, so columns will line up:
In [86]: '%10.3f' % 1.2
Out[86]: '     1.200'
In [87]: '%10.3f' % 1.23456
Out[87]: '     1.235'

If you want something fancier I think you will have to do it yourself.

Kent

From Barry.Carroll at psc.com  Mon Mar 19 23:52:23 2007
From: Barry.Carroll at psc.com (Carroll, Barry)
Date: Mon, 19 Mar 2007 15:52:23 -0700
Subject: [Tutor] Making table
In-Reply-To: <45FEEBA1.8060307@tds.net>
Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595B31@eugsrv400.psc.pscnet.com>

> -----Original Message-----
> From: Kent Johnson [mailto:kent37 at tds.net]
> Sent: Monday, March 19, 2007 12:59 PM
> To: Carroll, Barry
> Cc: tutor at python.org
> Subject: Re: [Tutor] Making table
> 
> Carroll, Barry wrote:
> >> -----Original Message-----
> >> Date: Mon, 19 Mar 2007 11:53:06 -0400
> >> From: Kent Johnson <kent37 at tds.net>
> 
> >> Most string formatting conversions allow you to specify a width
> >> directly. For example,
> >> In [61]: value = 3.45678
> >> In [63]: "%10.3f" % value
> >> Out[63]: '     3.457'
> >>
> >> Kent
> >>
> > What if one wished to align the values in each column at the decimal
> > point?  Is there a simple means to do this in Python, or would one
need
> > to write a new function?
> 
> If you specify the number of digits after the decimal point, that
number
> of digits will always be given, so columns will line up:
> In [86]: '%10.3f' % 1.2
> Out[86]: '     1.200'
> In [87]: '%10.3f' % 1.23456
> Out[87]: '     1.235'
> 
> If you want something fancier I think you will have to do it yourself.
> 
> Kent
Kent:

Thanks for your response.  That method is certainly good enough for
general use.  What about a case where the user needs to keep track of
significant digits? As an example, assume that the following values
(pulled arbitrarily from my head, I admit) are accurate to three
significant digits:

	253.
	77.6
	9.03
	.0210

Using a formatting string of "%10.4f", these would be rendered as:

	'  253.0000'
	'   77.6000
	'    9.0300'
	'    0.0210'

This formatting gives the impression that all values but the last are
more precise than they truly are.  A scientist or statistician would
prefer to see something like this:

	'254.    '
	' 77.6   '
	'  9.03  '
	'  0.0210'

Does numpy or some other math package have that capability?

Thanks again.
 
Barry
barry.carroll at psc.com
541-302-1107
________________________
We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed




From kent37 at tds.net  Tue Mar 20 11:28:24 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 20 Mar 2007 06:28:24 -0400
Subject: [Tutor] Making table
In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A4304595B31@eugsrv400.psc.pscnet.com>
References: <2BBAEE949D384D40A2B851287ADB6A4304595B31@eugsrv400.psc.pscnet.com>
Message-ID: <45FFB748.5080101@tds.net>

Carroll, Barry wrote:
> This formatting gives the impression that all values but the last are
> more precise than they truly are.  A scientist or statistician would
> prefer to see something like this:
> 
> 	'254.    '
> 	' 77.6   '
> 	'  9.03  '
> 	'  0.0210'
> 
> Does numpy or some other math package have that capability?

I don't know, I don't use numpy.

Kent

From rdm at rcblue.com  Tue Mar 20 12:09:49 2007
From: rdm at rcblue.com (Dick Moores)
Date: Tue, 20 Mar 2007 04:09:49 -0700
Subject: [Tutor] The '45' bug in round()
In-Reply-To: <20070319180001.GA3137@physics.ucdavis.edu>
References: <20070319100407.EFBF81E4003@bag.python.org>
	<20070319180001.GA3137@physics.ucdavis.edu>
Message-ID: <20070320111008.19B151E4006@bag.python.org>

At 11:00 AM 3/19/2007, Michael Hannon wrote:
>On Mon, Mar 19, 2007 at 03:04:03AM -0700, Dick Moores wrote:
> > Yesterday I was shocked, SHOCKED, to discover that round() is
> > occasionally rounding incorrectly. For example,
> >
> >  >>> print round(0.19945,4)
> > 0.1994
>.
>.
>.
> > Comments, Tutors? Am I way out in left field with this?
>
>
>I suggest you might want to look at the discussion of unbiased rounding at:
>
>     http://en.wikipedia.org/wiki/Rounding

Thanks. I'm familiar with "unbiased rounding". I'm glad to know about 
that Wikipedia article. Could you tell me what, in particular, you 
wanted me to think about?

Dick



From akap at isd.dp.ua  Tue Mar 20 15:41:26 2007
From: akap at isd.dp.ua (Alexander Kapshuk)
Date: Tue, 20 Mar 2007 16:41:26 +0200
Subject: [Tutor] breaking the 'while' loop
Message-ID: <70831DC71E5D814C9D1FA8A96653215E08CD5534@server.isd.dp.ua>

Dear All,

 

I have been learning computer programming with Python only for a short
while. I have a question to do with breaking the while loop.

 

I have attached the source code of a program called 'Guess my number'
with the while loop running until the right number is guessed.

 

I want to limit the number of tries to 5. To do that, I have tried the
if structure along with the break statement immediately below the 

'tries += 1' line:

 

if tries > 5:

          break

 print "Wrong guess!"

 

Which still did not result in the while loop breaking after attempt No
5.

 

I would appreciate being explained what I am doing wrong.

 

Regards,

 

Alexander Kapshuk

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070320/4fb44c3b/attachment.htm 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: guess_my_number.py
Type: application/octet-stream
Size: 905 bytes
Desc: guess_my_number.py
Url : http://mail.python.org/pipermail/tutor/attachments/20070320/4fb44c3b/attachment.obj 

From andreengels at gmail.com  Tue Mar 20 16:25:59 2007
From: andreengels at gmail.com (Andre Engels)
Date: Tue, 20 Mar 2007 16:25:59 +0100
Subject: [Tutor] breaking the 'while' loop
In-Reply-To: <70831DC71E5D814C9D1FA8A96653215E08CD5534@server.isd.dp.ua>
References: <70831DC71E5D814C9D1FA8A96653215E08CD5534@server.isd.dp.ua>
Message-ID: <6faf39c90703200825r17d4816dwcbd95fbb8bba9083@mail.gmail.com>

2007/3/20, Alexander Kapshuk <akap at isd.dp.ua>:
>
>  Dear All,
>
>
>
> I have been learning computer programming with Python only for a short
> while. I have a question to do with breaking the *while loop*.
>
>
>
> I have attached the source code of a program called 'Guess my number' with
> the *while loop* running until the right number is guessed.
>
>
>
> I want to limit the number of tries to 5. To do that, I have tried the *if
> structure* along with the *break statement* immediately below the
>
> 'tries += 1' line:
>
>
>
> if tries > 5:
>
>           break
>
>  print "Wrong guess!"
>
>
>
> Which still did not result in the *while loop* breaking after attempt No
> 5.
>
>
>
> I would appreciate being explained what I am doing wrong.
>
It would have helped if you had given the code *with* the extra lines in it.
My first guess is that you did a wrong indentation, but without the actual
code I cannot be sure.

-- 
Andre Engels, andreengels at gmail.com
ICQ: 6260644  --  Skype: a_engels
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070320/26d766f2/attachment.html 

From jmh at physics.ucdavis.edu  Tue Mar 20 16:31:17 2007
From: jmh at physics.ucdavis.edu (Michael Hannon)
Date: Tue, 20 Mar 2007 08:31:17 -0700
Subject: [Tutor] The '45' bug in round()
In-Reply-To: <20070320111008.D8C572000252@eatspam.physics.ucdavis.edu>
References: <20070319100407.EFBF81E4003@bag.python.org>
	<20070319180001.GA3137@physics.ucdavis.edu>
	<20070320111008.D8C572000252@eatspam.physics.ucdavis.edu>
Message-ID: <20070320153117.GA30901@physics.ucdavis.edu>

On Tue, Mar 20, 2007 at 04:09:49AM -0700, Dick Moores wrote:
> At 11:00 AM 3/19/2007, Michael Hannon wrote:
> >On Mon, Mar 19, 2007 at 03:04:03AM -0700, Dick Moores wrote:
> >> Yesterday I was shocked, SHOCKED, to discover that round() is
> >> occasionally rounding incorrectly. For example,
> >>
> >>  >>> print round(0.19945,4)
> >> 0.1994
> >.
> >.
> >.
> >> Comments, Tutors? Am I way out in left field with this?
> >
> >
> >I suggest you might want to look at the discussion of unbiased rounding at:
> >
> >    http://en.wikipedia.org/wiki/Rounding
> 
> Thanks. I'm familiar with "unbiased rounding". I'm glad to know about 
> that Wikipedia article. Could you tell me what, in particular, you 
> wanted me to think about?

Well, perhaps this is something for me to think about, but if you had asked
me to round 0.19945 to four decimal places, I would have told you the answer
is 0.1994, i.e., the same answer that Python gives.

					- Mike

From rabidpoobear at gmail.com  Tue Mar 20 16:59:21 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Tue, 20 Mar 2007 10:59:21 -0500
Subject: [Tutor] breaking the 'while' loop
In-Reply-To: <70831DC71E5D814C9D1FA8A96653215E08CD5534@server.isd.dp.ua>
References: <70831DC71E5D814C9D1FA8A96653215E08CD5534@server.isd.dp.ua>
Message-ID: <460004D9.30601@gmail.com>

>
>
> I want to limit the number of tries to 5. To do that, I have tried the 
> /_if structure_/ along with the /_break statement_/ immediately below the
>
> ?tries += 1? line:
>
Or you could just add this condition to the while loop.
while (guess != the_number and tries < 6):
>
> if tries > 5:
>
> break
>
> print ?Wrong guess!?
>
> Which still did not result in the /_while loop_/ breaking after 
> attempt No 5.
>
> I would appreciate being explained what I am doing wrong.
>
You should have included the source that didn't work. It does us no good 
to see working code that doesn't do what you want.

From rdm at rcblue.com  Tue Mar 20 17:03:43 2007
From: rdm at rcblue.com (Dick Moores)
Date: Tue, 20 Mar 2007 09:03:43 -0700
Subject: [Tutor] The '45' bug in round()
In-Reply-To: <20070320153117.GA30901@physics.ucdavis.edu>
References: <20070319100407.EFBF81E4003@bag.python.org>
	<20070319180001.GA3137@physics.ucdavis.edu>
	<20070320111008.D8C572000252@eatspam.physics.ucdavis.edu>
	<20070320153117.GA30901@physics.ucdavis.edu>
Message-ID: <20070320160349.53BD51E4006@bag.python.org>

At 08:31 AM 3/20/2007, you wrote:
>On Tue, Mar 20, 2007 at 04:09:49AM -0700, Dick Moores wrote:
> > At 11:00 AM 3/19/2007, Michael Hannon wrote:
> > >On Mon, Mar 19, 2007 at 03:04:03AM -0700, Dick Moores wrote:
> > >> Yesterday I was shocked, SHOCKED, to discover that round() is
> > >> occasionally rounding incorrectly. For example,
> > >>
> > >>  >>> print round(0.19945,4)
> > >> 0.1994
> > >.
> > >.
> > >.
> > >> Comments, Tutors? Am I way out in left field with this?
> > >
> > >
> > >I suggest you might want to look at the discussion of unbiased 
> rounding at:
> > >
> > >    http://en.wikipedia.org/wiki/Rounding
> >
> > Thanks. I'm familiar with "unbiased rounding". I'm glad to know about
> > that Wikipedia article. Could you tell me what, in particular, you
> > wanted me to think about?
>
>Well, perhaps this is something for me to think about, but if you had asked
>me to round 0.19945 to four decimal places, I would have told you the answer
>is 0.1994, i.e., the same answer that Python gives.

Is this because that rounding conforms to "unbiased rounding"? If so, 
then you won't like

 >>> print round(0.19965, 4)
0.1997

(which rounds up to an odd number, 7)

But after thinking about it, I may revise my round2() function to do 
"unbiased rounding". It appeals to me, even though most of my life 
I've used what the Wikipedia article terms "the common method":

=====================================================
This method is commonly used, for example in accounting. It is the 
one generally taught in basic mathematics classes. This method is 
also known as Symmetric Arithmetic Rounding or Round-Half-Up 
(Symmetric Implementation):

Decide which is the last digit to keep.
Increase it by 1 if the next digit is 5 or more (this is called rounding up)
Leave it the same if the next digit is 4 or less (this is called 
rounding down)
=======================================================

Dick Moores





From jmh at physics.ucdavis.edu  Tue Mar 20 18:17:02 2007
From: jmh at physics.ucdavis.edu (Michael Hannon)
Date: Tue, 20 Mar 2007 10:17:02 -0700
Subject: [Tutor] The '45' bug in round()
In-Reply-To: <20070320160346.73FC8200027C@eatspam.physics.ucdavis.edu>
References: <20070319100407.EFBF81E4003@bag.python.org>
	<20070319180001.GA3137@physics.ucdavis.edu>
	<20070320111008.D8C572000252@eatspam.physics.ucdavis.edu>
	<20070320153117.GA30901@physics.ucdavis.edu>
	<20070320160346.73FC8200027C@eatspam.physics.ucdavis.edu>
Message-ID: <20070320171702.GC1938@physics.ucdavis.edu>

On Tue, Mar 20, 2007 at 09:03:43AM -0700, Dick Moores wrote:
.
.
.
> >Well, perhaps this is something for me to think about, but if you had asked
> >me to round 0.19945 to four decimal places, I would have told you the 
> >answer
> >is 0.1994, i.e., the same answer that Python gives.
> 
> Is this because that rounding conforms to "unbiased rounding"? If so, 
> then you won't like
> 
> >>> print round(0.19965, 4)
> 0.1997
> 
> (which rounds up to an odd number, 7)

Heh.  You're right.  I don't.  If I get some time, I'll try to dig
through the Python source code to see what they're doing.  Thanks.

					- Mike

From nebpro at gmail.com  Tue Mar 20 19:49:50 2007
From: nebpro at gmail.com (Ben)
Date: Tue, 20 Mar 2007 14:49:50 -0400
Subject: [Tutor] threading and gui programming
Message-ID: <e5f41cb30703201149h62446ce7t97bf028100c08503@mail.gmail.com>

Hi all,

I am curious about one thing. I have been doing research on gui programming.
One thing that I don't understand is why there are some examples uses
threading in the gui examples. Is there any benefits or advantages for using
the threading in the gui programming? Thanks.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070320/599f520e/attachment.html 

From kent37 at tds.net  Tue Mar 20 20:05:48 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 20 Mar 2007 15:05:48 -0400
Subject: [Tutor] threading and gui programming
In-Reply-To: <e5f41cb30703201149h62446ce7t97bf028100c08503@mail.gmail.com>
References: <e5f41cb30703201149h62446ce7t97bf028100c08503@mail.gmail.com>
Message-ID: <4600308C.4090003@tds.net>

Ben wrote:
> Hi all,
> 
> I am curious about one thing. I have been doing research on gui 
> programming. One thing that I don't understand is why there are some 
> examples uses threading in the gui examples. Is there any benefits or 
> advantages for using the threading in the gui programming? Thanks.

This is commonly done when a user action starts some kind of processing 
that will take some time. In order for the GUI to remain responsive, the 
long process must be in a different thread. In general, the GUI will not 
respond to new input until the event handler for the user action returns.

Kent

From nebpro at gmail.com  Tue Mar 20 20:13:01 2007
From: nebpro at gmail.com (Ben)
Date: Tue, 20 Mar 2007 15:13:01 -0400
Subject: [Tutor] threading and gui programming
In-Reply-To: <4600308C.4090003@tds.net>
References: <e5f41cb30703201149h62446ce7t97bf028100c08503@mail.gmail.com>
	<4600308C.4090003@tds.net>
Message-ID: <e5f41cb30703201213r59bf47c1v375a5ef04f5a4073@mail.gmail.com>

That makes sense. I am a newbie to python programming. What really confuses
me is that there are so many gui programming options for python (i.e.
pywin32, wxPython, etc). Is this means that all of these available gui
options be able to integrate with threading? Thanks.

On 3/20/07, Kent Johnson <kent37 at tds.net> wrote:
>
> Ben wrote:
> > Hi all,
> >
> > I am curious about one thing. I have been doing research on gui
> > programming. One thing that I don't understand is why there are some
> > examples uses threading in the gui examples. Is there any benefits or
> > advantages for using the threading in the gui programming? Thanks.
>
> This is commonly done when a user action starts some kind of processing
> that will take some time. In order for the GUI to remain responsive, the
> long process must be in a different thread. In general, the GUI will not
> respond to new input until the event handler for the user action returns.
>
> Kent
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070320/e89eb8c9/attachment.htm 

From carroll at tjc.com  Tue Mar 20 22:24:03 2007
From: carroll at tjc.com (Terry Carroll)
Date: Tue, 20 Mar 2007 14:24:03 -0700 (PDT)
Subject: [Tutor] The '45' bug in round()
In-Reply-To: <20070320160349.53BD51E4006@bag.python.org>
Message-ID: <Pine.LNX.4.44.0703201418050.3213-100000@violet.rahul.net>

On Tue, 20 Mar 2007, Dick Moores wrote:

>  >>> print round(0.19965, 4)
> 0.1997
> 
> (which rounds up to an odd number, 7)

Now that's weird.  It should (I say) round to .1996; not because 6 is even
and 7 is not[1], but because 0.19965 is actually closer to 0.1996 than to
0.1997:

>>> 0.19965
0.19964999999999999


[1] The Python rounding rule is to round "away from zero," i.e., to round 
up for positive numbers and down (where "down" means "more negative") for 
negative numbers.


From rdm at rcblue.com  Tue Mar 20 22:37:15 2007
From: rdm at rcblue.com (Dick Moores)
Date: Tue, 20 Mar 2007 14:37:15 -0700
Subject: [Tutor] The '45' bug in round()
In-Reply-To: <Pine.LNX.4.44.0703201418050.3213-100000@violet.rahul.net>
References: <20070320160349.53BD51E4006@bag.python.org>
	<Pine.LNX.4.44.0703201418050.3213-100000@violet.rahul.net>
Message-ID: <20070320213719.716C41E4006@bag.python.org>

At 02:24 PM 3/20/2007, Terry Carroll wrote:
>On Tue, 20 Mar 2007, Dick Moores wrote:
>
> >  >>> print round(0.19965, 4)
> > 0.1997
> >
> > (which rounds up to an odd number, 7)
>
>Now that's weird.  It should (I say) round to .1996; not because 6 is even
>and 7 is not[1], but because 0.19965 is actually closer to 0.1996 than to
>0.1997:
>
> >>> 0.19965
>0.19964999999999999
>
>
>[1] The Python rounding rule is to round "away from zero," i.e., to round
>up for positive numbers and down (where "down" means "more negative") for
>negative numbers.

So you're claiming there's a bug in round()? So was I, the OP, in 
that original post, but a bug of a different sort. ;)

Dick Moores


From carroll at tjc.com  Tue Mar 20 22:43:53 2007
From: carroll at tjc.com (Terry Carroll)
Date: Tue, 20 Mar 2007 14:43:53 -0700 (PDT)
Subject: [Tutor] The '45' bug in round()
In-Reply-To: <20070320213719.716C41E4006@bag.python.org>
Message-ID: <Pine.LNX.4.44.0703201442040.3213-100000@violet.rahul.net>

On Tue, 20 Mar 2007, Dick Moores wrote:

> So you're claiming there's a bug in round()? 

No.  I'm very reluctant to slap the "bug" label on behavior that strikes 
me as anomalous.  I've found a bug or two, but in most cases, it's far 
more likely to be working as designed, and the bug is in my perception!



From janos.juhasz at VELUX.com  Tue Mar 20 22:53:15 2007
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Tue, 20 Mar 2007 22:53:15 +0100
Subject: [Tutor] Making table
Message-ID: <OF6CDC76A3.A1E29388-ONC12572A4.0077642D-C12572A4.00783AB2@velux.com>

Dear Barry,

>>Using a formatting string of "%10.4f", these would be rendered as:
>>
>>               '  253.0000'
>>               '   77.6000
>>               '    9.0300'
>>               '    0.0210'
>>
>>This formatting gives the impression that all values but the last are
>>more precise than they truly are.  A scientist or statistician would
>>prefer to see something like this:
>>
>>               '254.    '
>>               ' 77.6   '
>>               '  9.03  '
>>               '  0.0210'
>>
>>Does numpy or some other math package have that capability?

You can use advanced regexp, called lookaround, lookbehind for this 
purpose.

###############

import re

l = (253., 77.6, 9.03, .0210, 1000, 100.1230)
ending_zero = re.compile('0(?=0*$)') # zero followed with only zeros

for f in l:
    print re.sub(ending_zero, ' ', ('%10.4f' % f))

###############




Yours sincerely,
______________________________
J?nos Juh?sz
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070320/031db67e/attachment.htm 

From rdm at rcblue.com  Wed Mar 21 00:58:59 2007
From: rdm at rcblue.com (Dick Moores)
Date: Tue, 20 Mar 2007 16:58:59 -0700
Subject: [Tutor] The '45' bug in round()
In-Reply-To: <Pine.LNX.4.44.0703201442040.3213-100000@violet.rahul.net>
References: <20070320213719.716C41E4006@bag.python.org>
	<Pine.LNX.4.44.0703201442040.3213-100000@violet.rahul.net>
Message-ID: <20070320235920.A01771E400C@bag.python.org>

At 02:43 PM 3/20/2007, Terry Carroll wrote:
>On Tue, 20 Mar 2007, Dick Moores wrote:
>
> > So you're claiming there's a bug in round()?
>
>No.  I'm very reluctant to slap the "bug" label on behavior that strikes
>me as anomalous.  I've found a bug or two, but in most cases, it's far
>more likely to be working as designed, and the bug is in my perception!

Yeah, you're probably right. See this reply to me from the Tutor I 
respect the most, even if it might not seem so to him sometimes:
<http://mail.python.org/pipermail/tutor/2007-March/053359.html>

Dick



From jmutter at uakron.edu  Wed Mar 21 03:47:40 2007
From: jmutter at uakron.edu (Jay Mutter III)
Date: Tue, 20 Mar 2007 22:47:40 -0400
Subject: [Tutor] Should I use python for parsing text
Message-ID: <2611CDF8-0672-499D-9AA8-FD0755B63B90@uakron.edu>

"Jay Mutter III" <jmutter at uakron.edu> wrote

 > See example  next:
 > A.-C. Manufacturing Company. (See Sebastian, A. A.,
 > and Capes, assignors.)
 >...
 >Aaron, Solomon E., Boston, Mass. Pliers. No. 1,329,155 ;
 >Jan. 27 ; v. 270 ; p. 554.
 >
 > For instance, I would like to go to end of line and if last
 > character  is a comma or semicolon or hyphen then
 > remove the CR.

It would look something like:

output = open('example.fixed','w')
for line in file('example.txt'):
     if line[-1] in ',;-':            # check last character
       line = line.strip()         # lose the C/R
       output.write(line)        # write to output
     else: output.write(line)  # append the next line complete with C/R
output.close()




Working from the above suggestion ( and thank you very much - i did  
enjoy your online tutorial)
I came up with the following:

import os
import sys
import re
import string

# The next 5 lines are so I have an idea of how many lines i started  
with in the file.

in_filename = raw_input('What is the COMPLETE name of the file you  
want to open:    ')
in_file = open(in_filename, 'r')
text = in_file.read()
num_lines = text.count('\n')
print 'There are', num_lines, 'lines in the file', in_filename

output = open("cleandata.txt","a")    # file for writing data to  
after stripping newline character

# read file, copying each line to new file
for line in text:
     if line[:-1] in '-':
         line = line.rstrip()
         output.write(line)
     else: output.write(line)

print "Data written to cleandata.txt."

# close the files
in_file.close()
output.close()

The above ran with no erros, gave me the number of lines in my  
orginal file but then when i opened the cleandata.txt file
I got:

A.-C.?????????????�Company.????� 
Sebastian,??�A.,�and??????�assignors.)�A.??�A.? 
??????�Light?�Signal???�(See????? 
?�Elof�H
assignor.)�A-N????????�The.????� 
Alexander???�Nasb,???�?????????�??� 
Company,????�(See?????�It.???�and???? 
??????�as-�

So what did I do to cause all of the strange characters????
Plus since this goes on it is as if it removed all \n and not just  
the ones after a hyphen which I was using as my test case.

Thanks again.

Jay



 > Then move line by line through the file and delete everything
 > after a  numerical sequence

Slightly more tricky because you need to use a regular expression.
But if you know regex then only slightly.

 >  I am wondering if Python would be a good tool

Absolutely, its one of the areas where Python excels.

 > find information on how to accomplish this

You could check  my tutorial on the three topics:

Handling text
Handling files
Regular Expressions.

Also the standard python documentation for the general tutorial
(assuming you've done basic programming in some other language
before) plus the re module

 > using something like the unix tool awk or something else??

awk or sed could both be used, but Python is more generally
useful so unless you already know awk I'd take the time to
learn the basics of Python (a few hours maybe) and use that.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070320/4f66ab3d/attachment-0001.htm 

From hokkakada at khmeros.info  Wed Mar 21 05:10:47 2007
From: hokkakada at khmeros.info (hok kakada)
Date: Wed, 21 Mar 2007 11:10:47 +0700
Subject: [Tutor] How to set value back to .conf file
Message-ID: <200703211110.48035.hokkakada@khmeros.info>

Hi all,

I just start to use ConfigParser to store the configuration for my 
application.
I surfed the mails related to ConfigParser, however I couldn't found the way 
of how to set value back to the .conf file.

Let say, I have a test.conf file with:
[General]
userName="da"

later on, I wanna add another option:
email="da at aa.info"

I did the following:
import ConfigParser
conf = ConfigParser.ConfigParser()
conf.read('test.conf')

conf.set('General', 'email', 'da at aa.info'

print conf.items('General')
[('username','da'),('email','da at aa.info')]

But when I look into the file test.conf directly, I didn't see the option 
'email' . I don't know what I am missing here?

Or i need to write it to the file using conf.write(fp)?
If so, how can I get this file pointer?

Thanks very much for your input.

da
-- 
Ms.Kakada Hok
Open Source Engineer
KhmerOS project
Open Institute Organization
H/P:(+855-12) 653 155


From john at fouhy.net  Wed Mar 21 05:53:59 2007
From: john at fouhy.net (John Fouhy)
Date: Wed, 21 Mar 2007 16:53:59 +1200
Subject: [Tutor] How to set value back to .conf file
In-Reply-To: <200703211110.48035.hokkakada@khmeros.info>
References: <200703211110.48035.hokkakada@khmeros.info>
Message-ID: <5e58f2e40703202153y519a49c0ha7f9711288297f30@mail.gmail.com>

On 21/03/07, hok kakada <hokkakada at khmeros.info> wrote:
> I just start to use ConfigParser to store the configuration for my
> application.
[...]
> Or i need to write it to the file using conf.write(fp)?
> If so, how can I get this file pointer?

Yes.  You need to create a file-like object open for writing.

To continue your example, you can do this:

f = open('test.conf', 'w')
conf.write(f)
f.close()

-- 
John.

From rabidpoobear at gmail.com  Wed Mar 21 06:41:44 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 21 Mar 2007 00:41:44 -0500
Subject: [Tutor] Should I use python for parsing text
In-Reply-To: <2611CDF8-0672-499D-9AA8-FD0755B63B90@uakron.edu>
References: <2611CDF8-0672-499D-9AA8-FD0755B63B90@uakron.edu>
Message-ID: <4600C598.4030303@gmail.com>


> # The next 5 lines are so I have an idea of how many lines i started 
> with in the file.
>
> in_filename = raw_input('What is the COMPLETE name of the file you 
> want to open:    ')
> in_file = open(in_filename, 'r')
> text = in_file.read()
read() returns a one-dimensional list with all the data, not a 
2-dimensional one with each element a line.
Use readlines() for this functionality.
(Eg. A file with contents 'hello\nhoware\nyou?' would have this string 
returned by read(), but
readlines() would return ['hello\n','howare\n','you?'].)
> num_lines = text.count('\n')
or just len(text) if you're using readlines()
> print 'There are', num_lines, 'lines in the file', in_filename
>
> output = open("cleandata.txt","a")    # file for writing data to after 
> stripping newline character
You might want to open this file in 'write' mode while you're testing, 
so previous test results don't confuse you.
>
> # read file, copying each line to new file
> for line in text:
since read() returns a 1-dimensional list, you're looping over every 
character in the file, not every line.
>     if line[:-1] in '-':
In this case this is the same as "if line == '-':" because your 'line' 
variable only contains characters.
>         line = line.rstrip()
>         output.write(line)
>     else: output.write(line)
>
> print "Data written to cleandata.txt."
>
> # close the files
> in_file.close()
> output.close()
>
> The above ran with no erros, gave me the number of lines in my orginal 
> file but then when i opened the cleandata.txt file
> I got:
>
> A.-C.????????????? ?Company.?????Sebastian,???A.,?and 
> ???????assignors.)?A.???A.??????? ?Light??Signal???? 
> (See???????Elof?H
assignor.)?A-N?????????The.???? 
> ?Alexander????Nasb,?????????????????Company,????? 
> (See??????It.????and???????????as-?
Not sure what caused all of those characters.
HTH,
-Luke

From janos.juhasz at VELUX.com  Wed Mar 21 06:45:54 2007
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Wed, 21 Mar 2007 06:45:54 +0100
Subject: [Tutor] Should I use python for parsing text
Message-ID: <OFF7099544.1C289D30-ONC12572A5.001EDEBC-C12572A5.001FAAC5@velux.com>

Hy Jay,

I just allways wonder how fine this book about text processing with 
python.

Text Processing in Python at http://gnosis.cx/TPiP/

It shows that Python can be as effective as Perl. The question is the how.
Take a look on it.


Yours sincerely,
______________________________
J?nos Juh?sz


From kent37 at tds.net  Wed Mar 21 11:29:58 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 21 Mar 2007 06:29:58 -0400
Subject: [Tutor] Should I use python for parsing text
In-Reply-To: <2611CDF8-0672-499D-9AA8-FD0755B63B90@uakron.edu>
References: <2611CDF8-0672-499D-9AA8-FD0755B63B90@uakron.edu>
Message-ID: <46010926.3030302@tds.net>

Jay Mutter III wrote:
> "Jay Mutter III" <jmutter at uakron.edu 
> <http://mail.python.org/mailman/listinfo/tutor>> wrote
> 
>>/ See example//  //next:/
>>/ A.-C. Manufacturing Company. (See Sebastian, A. A.,/
>>/ and Capes, assignors.)/
>>/.../
>>/Aaron, Solomon E., Boston, Mass. Pliers. No. 1,329,155 ;/
>>/Jan. 27 ; v. 270 ; p. 554./
>>
>>/ For instance, I would like to go to end of line and if last/
>>/ character//  //is a comma or semicolon or hyphen then/
>>/ remove the CR./
> 
> It would look something like:
> 
> output = open('example.fixed','w')
> for line in file('example.txt'):
>     if line[-1] in ',;-':            # check last character

The last character will always be a newline; try
  if len(line) > 1 and line[-2] in ';,-':
instead.

>       line = line.strip()         # lose the C/R

This will also lose any leading or trailing whitespace. line.rstrip() 
would be safer.

>       output.write(line)        # write to output
>     else: output.write(line)  # append the next line complete with C/R
> output.close()
> 
> 
> 
> 
> Working from the above suggestion ( and thank you very much - i did 
> enjoy your online tutorial)
> I came up with the following:
> 
> import os
> import sys
> import re
> import string

You don't need any of the above.
> 
> # The next 5 lines are so I have an idea of how many lines i started 
> with in the file.
> 
> in_filename = raw_input('What is the COMPLETE name of the file you want 
> to open:    ')
> in_file = open(in_filename, 'r')
> text = in_file.read()

As Luke pointed out, you should use readlines() here.

> num_lines = text.count('\n')
> print 'There are', num_lines, 'lines in the file', in_filename
> 
> output = open("cleandata.txt","a")    # file for writing data to after 
> stripping newline character
> 
> # read file, copying each line to new file
> for line in text:
>     if line[:-1] in '-':
>         line = line.rstrip()
>         output.write(line)
>     else: output.write(line)

Since line is a single character, line[:-1] is always an empty string 
and the condition will always be true. What this loop does is strip all 
the whitespace out of your file.
> 
> print "Data written to cleandata.txt."
> 
> # close the files
> in_file.close()
> output.close()
> 
> The above ran with no erros, gave me the number of lines in my orginal 
> file but then when i opened the cleandata.txt file
> I got:
> 
> A.-C.??????????????Company.?????Sebastian,???A.,?and 
> ???????assignors.)?A.???A.????????Light??Signal????(See 
> ???????Elof?H
assignor.)?A-N?????????The.?????Alexander? 
> ???Nasb,?????????????????Company,?????(See??????It. 
> ????and???????????as-?

This is mysterious. What is the original data? What OS are you running 
on? How did you view the file?

Kent
> 
> So what did I do to cause all of the strange characters????
> Plus since this goes on it is as if it removed all \n and not just the 
> ones after a hyphen which I was using as my test case.
> 
> Thanks again.
> 
> Jay
> 
> 
> 
>>/ Then move line by line through the file and delete everything/
>>/ after a//  //numerical sequence/
> 
> Slightly more tricky because you need to use a regular expression.
> But if you know regex then only slightly.
> 
>>/  //I am wondering if Python would be a good tool/
> 
> Absolutely, its one of the areas where Python excels.
> 
>>/ find information on how to accomplish this/
> 
> You could check  my tutorial on the three topics:
> 
> Handling text
> Handling files
> Regular Expressions.
> 
> Also the standard python documentation for the general tutorial
> (assuming you've done basic programming in some other language
> before) plus the re module
> 
>>/ using something like the unix tool awk or something else??/
> 
> awk or sed could both be used, but Python is more generally
> useful so unless you already know awk I'd take the time to
> learn the basics of Python (a few hours maybe) and use that.
> 
> -- 
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


From emilia12 at mail.bg  Wed Mar 21 12:24:02 2007
From: emilia12 at mail.bg (emilia12 at mail.bg)
Date: Wed, 21 Mar 2007 13:24:02 +0200
Subject: [Tutor]  "from X import Y" vs "import X"
Message-ID: <1174476242.d18e3e2218c2a@mail.bg>

Hi list,

In Python books one can read that "from X import Y" is
better than "import X", but some times (IMO) it is not.

for eg. in SciPy,

from numpy import matrix
from scipy.linalg import inv, det, eig
A=matrix([[1,1,1],[4,4,3],[7,8,5]])
print det(A)

crashes with :
RuntimeError: module compiled against version 1000002 of
C-API but this version of numpy is 1000009
RuntimeError: module compiled against version 1000002 of
C-API but this version of numpy is 1000009

BUT next code works fine:

from numpy import matrix
import numpy
A=matrix([[1,1,1],[4,4,3],[7,8,5]])
print numpy.linalg.det(A)

no crashes at all!

i am using: Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC
v.1310 32 bit (Intel)] on win32
and the last version of SciPy ...

my actual question is "is this a rare case related to the
scipy distribution, or something general in python"

regards,
e.












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

SCENA - ???????????? ????????? ???????? ?? ??????? ??????????? ? ??????????.
http://www.bgscena.com/


From rikard.bosnjakovic at gmail.com  Wed Mar 21 12:44:17 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Wed, 21 Mar 2007 12:44:17 +0100
Subject: [Tutor] "from X import Y" vs "import X"
In-Reply-To: <1174476242.d18e3e2218c2a@mail.bg>
References: <1174476242.d18e3e2218c2a@mail.bg>
Message-ID: <d9e88eaf0703210444o20fce364u164da1009e7e9029@mail.gmail.com>

On 3/21/07, emilia12 at mail.bg <emilia12 at mail.bg> wrote:

> my actual question is "is this a rare case related to the
> scipy distribution, or something general in python"

The first.

I've never ever stumbled on an error like yours, and I use from FOO
import BAR alot without any whole module-imports.

-- 
- Rikard - http://bos.hack.org/cv/

From kent37 at tds.net  Wed Mar 21 13:09:19 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 21 Mar 2007 08:09:19 -0400
Subject: [Tutor] "from X import Y" vs "import X"
In-Reply-To: <1174476242.d18e3e2218c2a@mail.bg>
References: <1174476242.d18e3e2218c2a@mail.bg>
Message-ID: <4601206F.7020501@tds.net>

emilia12 at mail.bg wrote:
> Hi list,
> 
> In Python books one can read that "from X import Y" is
> better than "import X", but some times (IMO) it is not.

What book is that? I'm not aware of any general reason to prefer one of 
these forms over another. "from X import *" is discouraged.
> 
> for eg. in SciPy,
> 
> from numpy import matrix
> from scipy.linalg import inv, det, eig
> A=matrix([[1,1,1],[4,4,3],[7,8,5]])
> print det(A)
> 
> crashes with :
> RuntimeError: module compiled against version 1000002 of
> C-API but this version of numpy is 1000009
> RuntimeError: module compiled against version 1000002 of
> C-API but this version of numpy is 1000009
> 
> BUT next code works fine:
> 
> from numpy import matrix
> import numpy
> A=matrix([[1,1,1],[4,4,3],[7,8,5]])
> print numpy.linalg.det(A)
> 
> no crashes at all!
> 
> i am using: Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC
> v.1310 32 bit (Intel)] on win32
> and the last version of SciPy ...
> 
> my actual question is "is this a rare case related to the
> scipy distribution, or something general in python"

In the first code you use scipy.linalg, in the second code you use 
numpy.linalg. I don't think it is the form of import that matters, but 
the different package. It looks like you have an incompatible version of 
scipy - one compiled for a different version of Python or numpy than you 
are using.

Kent

From electricitymen at gmail.com  Wed Mar 21 16:35:18 2007
From: electricitymen at gmail.com (p l)
Date: Wed, 21 Mar 2007 17:35:18 +0200
Subject: [Tutor] help me and ill love u!!! :)
Message-ID: <509ecd760703210835r14d79641w77830274b0a3d843@mail.gmail.com>

 hello tutor!

im a new python programmer and iv been given a task to get as much details
that i can on my system memory...
now, i have allready found how to get the total physical memory and the
avalible memory.. iv also found how to get the virtual mem and a few more
stuff...
but now im stuck!!

i must find a way to find out the amount of memory sticks i have on the
system (if possible how many slots are there and how many slots are being
used)
and also if it is possible the size in mb each one of sticks has...
also i need to know the type of memory (f.e ddr, ddr2)
those 2 are basicly the most important things but the more info i can get
about the memory the better....

thanks!
electricitymen
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070321/170e4343/attachment.htm 

From nebpro at gmail.com  Wed Mar 21 18:42:25 2007
From: nebpro at gmail.com (Ben)
Date: Wed, 21 Mar 2007 13:42:25 -0400
Subject: [Tutor] pywin DoModal vs CreateWindow
Message-ID: <e5f41cb30703211042x24a474c1gf16fdd2a46f25bc5@mail.gmail.com>

Recently my friend ask me for help on pywin32 gui programming. There is one
thing that throw us off (Note. Both of us don't have any mfc background and
we are newbie in python). When the "DoModal" is called, the gui will stay in
loop. It is different when the "CreateWindow" is called. If we run the
program from command prompt, the gui won't stay in loop (or basically just
blink for a moment and disappear). It is different if we run the program
from "PythonWin" program. Can someone explain this for us? It cause a lot of
confusion. And what should we do to make the gui stay in loop if we used
"CreateWindow" and called it from command prompt. We really appreciate for
any help. Thanks in advance.

Below is the snippet code that we used for testing:
Note: Codes credits to Mark Hammond.

import win32ui
import win32con
from pywin.mfc.dialog import Dialog

d = Dialog (win32ui.IDD_SIMPLE_INPUT)

print d
print d._obj_

d.CreateWindow ()
#d.ShowWindow (win32con.SW_SHOWNORMAL)
button = d.GetDlgItem (win32ui.IDC_PROMPT1)
print "button: ", button
button.SetWindowText ("Hello from Python")
d.SetWindowText ("Python is awesome")
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070321/5a994fa0/attachment.html 

From Barry.Carroll at psc.com  Wed Mar 21 18:33:00 2007
From: Barry.Carroll at psc.com (Carroll, Barry)
Date: Wed, 21 Mar 2007 10:33:00 -0700
Subject: [Tutor] Making table
In-Reply-To: <mailman.17736.1174445268.32030.tutor@python.org>
Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595B36@eugsrv400.psc.pscnet.com>

> -----Original Message-----
> Date: Tue, 20 Mar 2007 22:53:15 +0100
> From: J?nos Juh?sz <janos.juhasz at VELUX.com>
> Subject: Re: [Tutor] Making table
> To: tutor at python.org
> Message-ID:
> 	<OF6CDC76A3.A1E29388-ONC12572A4.0077642D-
> C12572A4.00783AB2 at velux.com>
> Content-Type: text/plain; charset="iso-8859-2"
> 
> Dear Barry,
> 
> >>Using a formatting string of "%10.4f", these would be rendered as:
> >>
> >>               '  253.0000'
> >>               '   77.6000
> >>               '    9.0300'
> >>               '    0.0210'
> >>
> >>This formatting gives the impression that all values but the last
are
> >>more precise than they truly are.  A scientist or statistician would
> >>prefer to see something like this:
> >>
> >>               '254.    '
> >>               ' 77.6   '
> >>               '  9.03  '
> >>               '  0.0210'
> >>
> >>Does numpy or some other math package have that capability?
> 
> You can use advanced regexp, called lookaround, lookbehind for this
> purpose.
> 
> ###############
> 
> import re
> 
> l = (253., 77.6, 9.03, .0210, 1000, 100.1230)
> ending_zero = re.compile('0(?=0*$)') # zero followed with only zeros
> 
> for f in l:
>     print re.sub(ending_zero, ' ', ('%10.4f' % f))
> 
> ###############
> 
> 
> 
> 
> Yours sincerely,
> ______________________________
> J?nos Juh?sz

Thanks, J?nos.  Your solution works in almost all cases.  It breaks down
when one or more trailing zeros are significant: 0.0210 should print
unchanged, since the final 0 is significant.  

Still this is a big step forward.  It shouldn't be too hard to add the
additional logic.

Regards,
 
Barry
barry.carroll at psc.com
541-302-1107
________________________
We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed




From alan.gauld at btinternet.com  Thu Mar 22 00:37:01 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 21 Mar 2007 23:37:01 -0000
Subject: [Tutor] threading and gui programming
References: <e5f41cb30703201149h62446ce7t97bf028100c08503@mail.gmail.com><4600308C.4090003@tds.net>
	<e5f41cb30703201213r59bf47c1v375a5ef04f5a4073@mail.gmail.com>
Message-ID: <etsfit$7l1$1@sea.gmane.org>


"Ben" <nebpro at gmail.com> wrote

> What really confuses
> me is that there are so many gui programming options for python 
> (i.e.
> pywin32, wxPython, etc). Is this means that all of these available 
> gui
> options be able to integrate with threading? Thanks.

Yes, they all have the concept of a function/method as an event 
handler.
The threading code goes inside those functions and thus is completely
independant of the GUI toolkit

Alan g. 



From alan.gauld at btinternet.com  Thu Mar 22 00:28:41 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 21 Mar 2007 23:28:41 -0000
Subject: [Tutor] File locking
References: <288A3B43F7B2224D9C8441C9FC5D6A0201465B03@EXCHMAIL01.corp.medplus.com>
Message-ID: <etsf3a$5il$1@sea.gmane.org>

Jeff,

Just catching up after a week on vacation, but nobody
seems to have picked this up so...

> I'm always disappointed when I find something that Python
> doesn't handle in a platform independent way.

That's often because the platforms all do it too differently! :-)

> 1. I don't see a way to atomically open a file for writing if and 
> only
> if it doesn't exist

Doesn't the os.path.exists() function work on all platforms?

> 2. I don't see a way to atomically open a file for writing and 
> obtain a
> lock on the file.

That's usually automatic on filesystems that support it. (And
impossible on those that don't! - eg DOS/FAT)

> 3. I don't see a platform independent way to obtain a lock
> on a file.

Not all platforms support file locking. And some platforms
(eg. Windows) only support it on some filesystems
(FAT32 up)

> You have to do something goofy like
> if sys.platform == win32:
>    import msvcrt
> else:
>     import fcntl
> and then similar things to call the correct functions with the
> correct flags.

You only have to do this on the rare occasions when you want
to lock a file and you are not writing to it. Otherwise the act of
writing should reate a lock, if possible. (Or so I, perhaps niaively,
believe!)

> Please let me know if I'm missing something

Maybe os.path.exists() and maybe automatic locking on writes.

HTH, and if not elicits other replies!


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



From alan.gauld at btinternet.com  Thu Mar 22 00:34:58 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 21 Mar 2007 23:34:58 -0000
Subject: [Tutor] Making table
References: <e016526e0703190511p26ba30d6qd9bfe14cad95ebf5@mail.gmail.com>
Message-ID: <etsff3$73a$1@sea.gmane.org>


"Per Jr. Greisen" <pgreisen at gmail.com> wrote

> I need to generate a table with different x,y,z values and write 
> them to a
> file:
> 10.171  -15.243 -2.558
> 9.837   -14.511 -1.923
> -23.451 -13.870 51.507
>

others have discussed format strings.
One final tip is to put the format string in a variable then use that
in printing/writing the output

eg:

fmt = '%10.3f\t%10.3f\t%10.3f'
print fmt % v1,v2,v3

This has the advantage that you can build the format string
dynamically by examining the data first - eg the maximum
length of an entry.

Also by using a minus sign in the format string you can
change the justification.

HTH,


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



From alan.gauld at btinternet.com  Thu Mar 22 00:45:27 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 21 Mar 2007 23:45:27 -0000
Subject: [Tutor] pywin DoModal vs CreateWindow
References: <e5f41cb30703211042x24a474c1gf16fdd2a46f25bc5@mail.gmail.com>
Message-ID: <etsg2o$9j3$1@sea.gmane.org>


"Ben" <nebpro at gmail.com> wrote

> Recently my friend ask me for help on pywin32 gui programming.

pywin32 is only really a sensible route if you already know MFC
and want to translate some design into Python. Otherwise its
painful. Mainlybecause the underlying windows code is painful.
It is full of ambiguous calls that apprar to do the same thing,
but not quite...

> thing that throw us off (Note. Both of us don't have any mfc 
> background and
> we are newbie in python). When the "DoModal" is called, the gui will 
> stay in
> loop. It is different when the "CreateWindow" is called.

I'm not quite sure what you mean by stay in loop.
Do Modal brings up a modal window (like the Find/replace dialog
in a word processor) which runs in a separate thread.
CreateWindow is usually used to create windows or widgets
in the main thread. ie it creates the main window or widgets
within it)

> program from command prompt,

Don't try MFCV GUI programming from the Python
command prompt >>>. It is likely to cause confusion
between the python interpreter(a windows program),
the DOS command box(a windows program) and
your program(a windows program!) To have 3 windows
programs running in the same screen space is not
a happy experioence for you or the OS.

> blink for a moment and disappear). It is different if we run the 
> program
> from "PythonWin" program. Can someone explain this for us?

Nope, it depends on too many things. But basically Pythonwin
tries to catch most things that can go wrong and turn them into
messages on screen. Most times it works, other times it won't.
But its slightly more reliable that a >>> prompt in a DOS box
for MFC work. But i'd still recommend the old fashioned way
of just using a text editor(maybe Pythonwin) and then running
your program from the dos prompt directly.

HTH,

Alan G. 



From kent37 at tds.net  Thu Mar 22 02:41:55 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 21 Mar 2007 21:41:55 -0400
Subject: [Tutor] Making table
In-Reply-To: <etsff3$73a$1@sea.gmane.org>
References: <e016526e0703190511p26ba30d6qd9bfe14cad95ebf5@mail.gmail.com>
	<etsff3$73a$1@sea.gmane.org>
Message-ID: <4601DEE3.90902@tds.net>

Alan Gauld wrote:
> others have discussed format strings.
> One final tip is to put the format string in a variable then use that
> in printing/writing the output
> 
> eg:
> 
> fmt = '%10.3f\t%10.3f\t%10.3f'
> print fmt % v1,v2,v3
> 
> This has the advantage that you can build the format string
> dynamically by examining the data first - eg the maximum
> length of an entry.

You don't need to build the format string dynamically to get control of 
the maximum width. A neat trick is that if you use '*' for the format 
width, the width will be read from the parameter list:

In [30]: '%*.3f' % (5, 1.2)
Out[30]: '1.200'
In [31]: '%*.3f' % (10, 1.2)
Out[31]: '     1.200'

Kent

From deliberatus at verizon.net  Thu Mar 22 04:13:57 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Wed, 21 Mar 2007 23:13:57 -0400
Subject: [Tutor] MONEY MATTERS
Message-ID: <4601F475.1090500@verizon.net>

ok, SHOULD THIS BE A THREAD OR A SEPERATE LIST?

Many of ius are independants, and write code for the love of it- or to 
promote and sell independantly. So possibly a thread discussing ways to 
  turn useful code into moiney is a useful idea. If the wish of the list 
is a thread here, we can do that, or we can start a seperate list for 
it. What are the wishes of this list?

-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From wescpy at gmail.com  Thu Mar 22 08:33:32 2007
From: wescpy at gmail.com (wesley chun)
Date: Thu, 22 Mar 2007 00:33:32 -0700
Subject: [Tutor] MONEY MATTERS
In-Reply-To: <4601F475.1090500@verizon.net>
References: <4601F475.1090500@verizon.net>
Message-ID: <78b3a9580703220033y77850e1cx70ed0985c9a0589c@mail.gmail.com>

> ok, SHOULD THIS BE A THREAD OR A SEPERATE LIST?
>
> Many of ius are independants, and write code for the love of it- or to
> promote and sell independantly. So possibly a thread discussing ways to
>   turn useful code into moiney is a useful idea. If the wish of the list
> is a thread here, we can do that, or we can start a seperate list for
> it. What are the wishes of this list?


i don't think this is the right forum for such a thread.  the main
Python thread may be a better place, but i'd better *DUCK* before
someone from other there throws anything at me.  :-)  this list is
really meant for those who are either new to programming or new to
Python, or both, to ask questions and get answers.

perhaps an even *better* place would be to place this on your blog,
and let respondents take the thread in any direction, yet have it be
archived for all to read.

cheers,
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com

From alan.gauld at btinternet.com  Thu Mar 22 10:21:40 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 22 Mar 2007 09:21:40 -0000
Subject: [Tutor] Making table
References: <e016526e0703190511p26ba30d6qd9bfe14cad95ebf5@mail.gmail.com><etsff3$73a$1@sea.gmane.org>
	<4601DEE3.90902@tds.net>
Message-ID: <etthr5$31u$1@sea.gmane.org>


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

>> One final tip is to put the format string in a variable then use 
>> that
>> in printing/writing the output ...
>> This has the advantage that you can build the format string
>> dynamically by examining the data first - eg the maximum
>> length of an entry.

> You don't need to build the format string dynamically to get control 
> of
> the maximum width. A neat trick is that if you use '*' for the 
> format
> width, the width will be read from the parameter list:

Good point, I usually forget that one...

However predefined format strings have other advantages too
- consistency for one thing. You can write output in multiple
places and be sure the format is consistent throughout.

Alan G. 



From Steven.Oldner at LA.GOV  Thu Mar 22 12:27:16 2007
From: Steven.Oldner at LA.GOV (Steve Oldner)
Date: Thu, 22 Mar 2007 06:27:16 -0500
Subject: [Tutor] MONEY MATTERS
In-Reply-To: <4601F475.1090500@verizon.net>
References: <4601F475.1090500@verizon.net>
Message-ID: <C782831DF0073A42B3A874C32BEB538D05BF53@MAILBE05.MAIL.LA.GOV>

My 2 cents worth is to set up something separate, it'll just keep the
principles and ideas clearer.  While I have my own ideas about the
"million dollar application", I would like a forum where I can just
listen and learn any type of ideas without having a worry that someone
will 'steal' my idea and beat me to the market.

I work for a state government supporting a SAP HR application, so
anything I learn from this list is not directly applicable to my job.
However, the ideas and logic to solve various PYTHON solutions is a big
benefit in expanding my search for alternative solutions.

And one day, I will have free time to work on my "million dollar app."
(LOL!)

Thanks,

Steve Oldner  

-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On
Behalf Of Kirk Bailey
Sent: Wednesday, March 21, 2007 10:14 PM
To: tutor at python.org
Subject: [Tutor] MONEY MATTERS

ok, SHOULD THIS BE A THREAD OR A SEPERATE LIST?

Many of ius are independants, and write code for the love of it- or to
promote and sell independantly. So possibly a thread discussing ways to
  turn useful code into moiney is a useful idea. If the wish of the list
is a thread here, we can do that, or we can start a seperate list for
it. What are the wishes of this list?

-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

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

From kent37 at tds.net  Thu Mar 22 12:51:27 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 22 Mar 2007 07:51:27 -0400
Subject: [Tutor] Should I use python for parsing text?
In-Reply-To: <63DA79E7-BED7-4E18-A638-547E274EE234@uakron.edu>
References: <63DA79E7-BED7-4E18-A638-547E274EE234@uakron.edu>
Message-ID: <46026DBF.4070201@tds.net>

Jay Mutter III wrote:
> Kent;
> 
> Thanks for the reply on tutor-python.
> 
> My data file which is just a .txt file created under WinXP by an OCR 
> program contains lines like:
> 
> A.-C. Manufacturing Company. (See Sebastian, A. A.,
> and Capes, assignors.)
> A. G. A. Railway Light & Signal Co. (See Meden, Elof
> H? assignor.)
> A-N Company, The. (See Alexander and Nasb, as-
> signors.;
> AN Company, The. (See Nash, It. J., and Alexander, as-
> signors.)
> 
> I use an intel imac running OS x10.4.9 and when I used python to append 
> one file to another I got a file that opened in OS X's
> TexEdit program with characters that looked liked Japanese/Chinese 
> characters.
> 
> When i pasted them into my mail client (OS X's mail) they were then just 
> a sequence of question marks so I am not sure what happened.
> 
> Any thoughts???

For some reason, after you run the Python program, TexEdit thinks the 
file is not ascii data; it seems to think it is utf-8 or a Chinese 
encoding. Your original email was utf-8 which points in that direction 
but is not conclusive.

If you zip up and send me the original file and the cleandata.txt file 
*exactly as it is produced* by the Python program - not edited in any 
way - I will take a look and see if I can guess what is going on.
> 
> And i tried  using the following on the above data:
> 
> in_filename = raw_input('What is the COMPLETE name of the file you want 
> to open:    ')
> in_file = open(in_filename, 'r')

It wouldn't hurt to use universal newlines here since you are working 
cross-platform:
   open(in_filename, 'Ur')

> text = in_file.readlines()
> num_lines = text.count('\n')

Here 'text' is a list of lines, so text.count('\n') is counting the 
number of blank lines (lines containing only a newline) in your file. 
You should use
   num_lines = len(text)

> print 'There are', num_lines, 'lines in the file', in_filename
> 
> output = open("cleandata.txt","a")    # file for writing data to after 
> stripping newline character

I agree with Luke, use 'w' for now to make sure the file has only the 
output of this program. Maybe something already in the file is making it 
look like utf-8...

> 
> # read file, copying each line to new file
> for line in text:
>     if len(line) > 1 and line[-2] in ';,-':
>         line = line.rstrip()
>         output.write(line)
>     else: output.write(line)
> 
> print "Data written to cleandata.txt."
> 
> # close the files
> in_file.close()
> output.close()
> 
> As written above it tells me that there are 0 lines which is surprising 
> because if I run the first part by itself it tells there are 1982 lines 
> ( actually 1983 so i am figuring EOF)
> It copies/writes the data to the cleandata file but it does not strip 
> out CR and put data on one line ( a sample of what i am trying to get is 
> next)
> 
> A.-C. Manufacturing Company. (See Sebastian, A. A., and Capes, assignors.)
> 
> 
> My apologies if i have intruded.

Please reply on-list in the future.

Kent

From kent37 at tds.net  Thu Mar 22 12:55:37 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 22 Mar 2007 07:55:37 -0400
Subject: [Tutor] MONEY MATTERS
In-Reply-To: <4601F475.1090500@verizon.net>
References: <4601F475.1090500@verizon.net>
Message-ID: <46026EB9.8050607@tds.net>

Kirk Bailey wrote:
> ok, SHOULD THIS BE A THREAD OR A SEPERATE LIST?
> 
> Many of ius are independants, and write code for the love of it- or to 
> promote and sell independantly. So possibly a thread discussing ways to 
>   turn useful code into moiney is a useful idea. If the wish of the list 
> is a thread here, we can do that, or we can start a seperate list for 
> it. What are the wishes of this list?

That is definitely not appropriate for this list. This list has a very 
clear purpose which is to provide a place for people to ask and answer 
beginner questions about Python.

My guess is that there are already lists or web sites devoted to your 
idea, have you looked?

Kent


From rabidpoobear at gmail.com  Thu Mar 22 12:59:52 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Thu, 22 Mar 2007 06:59:52 -0500
Subject: [Tutor] Should I use python for parsing text
In-Reply-To: <F916AC88-D0FE-462B-A0AD-7D0193555480@uakron.edu>
References: <2611CDF8-0672-499D-9AA8-FD0755B63B90@uakron.edu>
	<4600C598.4030303@gmail.com>
	<F916AC88-D0FE-462B-A0AD-7D0193555480@uakron.edu>
Message-ID: <46026FB8.4030505@gmail.com>

Jay Mutter III wrote:
> Luke;
I'm a bit pressed for time right now and I can't look over this e-mail.
Please reply on-list in the future using the 'reply-all' feature.  
You're more likely to get a prompt response.
(this e-mail is  carbon copied to the list, so don't worry about sending 
another.)
>
> Actually it did help but the following
>
> for line in text:
>     if len(line) > 1 and line[-2] in ';,-':
>         line = line.rstrip()
>         output.write(line)
>     else: output.write(line)
>
> does not have any apparent effect on my data.
>
> I start with lines
>
>
> A.-C. Manufacturing Company. (See Sebastian, A. A.,
> and Capes, assignors.)
> A. G. A. Railway Light & Signal Co. (See Meden, Elof
> H? assignor.)
> A-N Company, The. (See Alexander and Nasb, as-
> signors.;
> AN Company, The. (See Nash, It. J., and Alexander, as-
> signors.)
> A/S. Arendal Smelteverk.    (See Kaaten, Einar, assignor.)
> A/S. Bjorgums Gevaei'kompani. (See Bjorguni, Nils, as-
> signor.)
> A/S  Mekano.     (Sec   Schepeler,   Herman  A.,  assignor.)
> A/S Myrens Verkstad.    (See Klling, Jens W. A., assignor.)
> A/S Stordo Kisgruber. (See Nielsen, C., and Ilelleland,
> assignors.)
>
> and I end up with the same.
> My goal is to strip out the CR or LF or whatever so that all info for 
> one entity is on 1 line.
>
> Any ideas of where i am going wrong?
>
> Thanks
>
> Jay
>
>
> On Mar 21, 2007, at 1:41 AM, Luke Paireepinart wrote:
>
>>
>>> # The next 5 lines are so I have an idea of how many lines i started 
>>> with in the file.
>>>
>>> in_filename = raw_input('What is the COMPLETE name of the file you 
>>> want to open:    ')
>>> in_file = open(in_filename, 'r')
>>> text = in_file.read()
>> read() returns a one-dimensional list with all the data, not a 
>> 2-dimensional one with each element a line.
>> Use readlines() for this functionality.
>> (Eg. A file with contents 'hello\nhoware\nyou?' would have this 
>> string returned by read(), but
>> readlines() would return ['hello\n','howare\n','you?'].)
>>> num_lines = text.count('\n')
>> or just len(text) if you're using readlines()
>>> print 'There are', num_lines, 'lines in the file', in_filename
>>>
>>> output = open("cleandata.txt","a")    # file for writing data to 
>>> after stripping newline character
>> You might want to open this file in 'write' mode while you're 
>> testing, so previous test results don't confuse you.
>>>
>>> # read file, copying each line to new file
>>> for line in text:
>> since read() returns a 1-dimensional list, you're looping over every 
>> character in the file, not every line.
>>>     if line[:-1] in '-':
>> In this case this is the same as "if line == '-':" because your 
>> 'line' variable only contains characters.
>>>         line = line.rstrip()
>>>         output.write(line)
>>>     else: output.write(line)
>>>
>>> print "Data written to cleandata.txt."
>>>
>>> # close the files
>>> in_file.close()
>>> output.close()
>>>
>>> The above ran with no erros, gave me the number of lines in my 
>>> orginal file but then when i opened the cleandata.txt file
>>> I got:
>>>
>>> A.-C.????????????? ?Company.?????Sebastian,???A., 
>>> ?and ???????assignors.)?A.???A.??????? ?Light??Signal? 
>>> ??? (See???????Elof?H
assignor.)?A-N?????????The.??? 
>>> ? ?Alexander????Nasb,?????????????????Company,??? 
>>> ?? (See??????It.????and???????????as-?
>> Not sure what caused all of those characters.
>> HTH,
>> -Luke
>
>


From deliberatus at verizon.net  Thu Mar 22 15:45:59 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Thu, 22 Mar 2007 10:45:59 -0400
Subject: [Tutor] MONEY MATTERS
In-Reply-To: <C782831DF0073A42B3A874C32BEB538D05BF53@MAILBE05.MAIL.LA.GOV>
References: <4601F475.1090500@verizon.net>
	<C782831DF0073A42B3A874C32BEB538D05BF53@MAILBE05.MAIL.LA.GOV>
Message-ID: <460296A7.3010201@verizon.net>

So be it.

The list now exists, and is called Coding4Cash.

Here is a weblink to it:
http://tech.groups.yahoo.com/group/coding4cash/

And here are email address':
Post message: 	coding4cash at yahoogroups.com
Subscribe: 	coding4cash-subscribe at yahoogroups.com
Unsubscribe: 	coding4cash-unsubscribe at yahoogroups.com
List owner: 	coding4cash-owner at yahoogroups.com

SPAM need not apply. Hackers, hobbyists, pros, guru's and them what know 
better but do it anyway for the hell of it are all welcome.

This thread is ended in peace and respect; let all who wish come forth 
to discuss scratching the itch that our wallet does not yet contain.


Steve Oldner wrote:
> My 2 cents worth is to set up something separate, it'll just keep the
> principles and ideas clearer.  While I have my own ideas about the
> "million dollar application", I would like a forum where I can just
> listen and learn any type of ideas without having a worry that someone
> will 'steal' my idea and beat me to the market.
> 
> I work for a state government supporting a SAP HR application, so
> anything I learn from this list is not directly applicable to my job.
> However, the ideas and logic to solve various PYTHON solutions is a big
> benefit in expanding my search for alternative solutions.
> 
> And one day, I will have free time to work on my "million dollar app."
> (LOL!)
> 
> Thanks,
> 
> Steve Oldner  
> 
> -----Original Message-----
> From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On
> Behalf Of Kirk Bailey
> Sent: Wednesday, March 21, 2007 10:14 PM
> To: tutor at python.org
> Subject: [Tutor] MONEY MATTERS
> 
> ok, SHOULD THIS BE A THREAD OR A SEPERATE LIST?
> 
> Many of ius are independants, and write code for the love of it- or to
> promote and sell independantly. So possibly a thread discussing ways to
>   turn useful code into moiney is a useful idea. If the wish of the list
> is a thread here, we can do that, or we can start a seperate list for
> it. What are the wishes of this list?
> 

-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From jaggojaggo at yahoo.com  Thu Mar 22 17:06:37 2007
From: jaggojaggo at yahoo.com (Jaggo)
Date: Thu, 22 Mar 2007 09:06:37 -0700 (PDT)
Subject: [Tutor] Money Matters
In-Reply-To: <mailman.41.1174561210.21329.tutor@python.org>
Message-ID: <20070322160637.43126.qmail@web52503.mail.re2.yahoo.com>

Hello!

I read this list because I'm new to Python and I really am learning an average of something new I did not know from every digest hitting my inbox.

I have no interest on the matter of money.

Just my .02$.

-Omer Tabach

tutor-request at python.org wrote:
Message: 3
Date: Wed, 21 Mar 2007 23:13:57 -0400
From: Kirk Bailey 
Subject: [Tutor] MONEY MATTERS
To: tutor at python.org
Message-ID: <4601F475.1090500 at verizon.net>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

ok, SHOULD THIS BE A THREAD OR A SEPERATE LIST?

Many of ius are independants, and write code for the love of it- or to 
promote and sell independantly. So possibly a thread discussing ways to 
  turn useful code into moiney is a useful idea. If the wish of the list 
is a thread here, we can do that, or we can start a seperate list for 
it. What are the wishes of this list?

-- 
Salute!
 -Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.


 
---------------------------------
Don't pick lemons.
See all the new 2007 cars at Yahoo! Autos.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070322/7dabd187/attachment.html 

From jeffpeery at yahoo.com  Thu Mar 22 18:59:08 2007
From: jeffpeery at yahoo.com (Jeff Peery)
Date: Thu, 22 Mar 2007 10:59:08 -0700 (PDT)
Subject: [Tutor] sorting data from multiple arrays
Message-ID: <277809.23222.qm@web43143.mail.sp1.yahoo.com>

hello, I typically run into this problem and I'm not always sure of the most efficient way to handle it. I often work with multiple arrays of data, say arrays a, b, and c, and I want to sort the elements of b and c based on a. for example:

a = [3,2,1,4]
b = ['hi', 'my','name', 'is']
c = [5,2,4,2]

I order 'a' from small to large and do the same rearrangement to 'b' and 'c':
a = [1,2,3,4]
 b = ['name', 'my','hi', 'is']
 c = [4,2,5,2]

usually I do some terrible looking for loops and iterate over the whole mess.... is there a clean, efficient way to do this, or is there a nice function that would reorder the elements of b and c based on the soring of a?

thanks

 
---------------------------------
Don't be flakey. Get Yahoo! Mail for Mobile and 
always stay connected to friends.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070322/ddc81056/attachment-0001.html 

From amonroe at columbus.rr.com  Thu Mar 22 20:13:12 2007
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Thu, 22 Mar 2007 14:13:12 -0500
Subject: [Tutor] sorting data from multiple arrays
In-Reply-To: <277809.23222.qm@web43143.mail.sp1.yahoo.com>
References: <277809.23222.qm@web43143.mail.sp1.yahoo.com>
Message-ID: <85848211473.20070322141312@columbus.rr.com>

> hello, I typically run into this problem and I'm not always sure of the most efficient way to handle it. I often work with multiple arrays of data, say arrays a, b, and c, and I want to sort the
> elements of b and c based on a. for example:

> a = [3,2,1,4]
> b = ['hi', 'my','name', 'is']
> c = [5,2,4,2]

> I order 'a' from small to large and do the same rearrangement to 'b' and 'c':
> a = [1,2,3,4]
>  b = ['name', 'my','hi', 'is']
>  c = [4,2,5,2]

> usually I do some terrible looking for loops and iterate over the whole mess.... is there a clean, efficient way to do this, or is there a nice function that would reorder the elements of b and c
> based on the soring of a?

Is switching to a dictionary an option?

mystuff = {3: ('hi', 5),
           2: ('my', 2),
           1: ('name', 4),
           4: ('is', 2)    }

You can get a list of the keys, sort _that_, then fetch from the dict
based on the sorted list.

Alan


From jmutter at uakron.edu  Thu Mar 22 19:30:03 2007
From: jmutter at uakron.edu (Jay Mutter III)
Date: Thu, 22 Mar 2007 14:30:03 -0400
Subject: [Tutor] Why is it...
Message-ID: <0A7441AE-153F-4356-9D81-026017D7AE3E@uakron.edu>

Why is it that when I run the following interactively

f = open('Patents-1920.txt')
line = f.readline()
while line:
     print line,
     line = f.readline()
f.close()

I get an error message

File "<stdin>", line 4
     f.close()
     ^
SyntaxError: invalid syntax

but if i run it in a script there is no error?

Thanks

Jay


From wescpy at gmail.com  Thu Mar 22 19:38:02 2007
From: wescpy at gmail.com (wesley chun)
Date: Thu, 22 Mar 2007 11:38:02 -0700
Subject: [Tutor] [ANN] Python courses this Spring
In-Reply-To: <78b3a9580703221136v15c9b4a9q892a228a32486053@mail.gmail.com>
References: <78b3a9580703221134s14d026ebgd59d1af30fb4f5c5@mail.gmail.com>
	<78b3a9580703221136v15c9b4a9q892a228a32486053@mail.gmail.com>
Message-ID: <78b3a9580703221138g1fa1576dkf4a333325c95b009@mail.gmail.com>

I'll be giving a variety of Python courses this Spring.  Daytime
courses are for visitors and locals who need Python training in the
shortest amount of time possible via consecutive workdays.  Python is
certainly gaining momentum as our February course filled up
completely!  Although I had planned on scheduling the same set to be
taught in November, it is likely that these May daytime sessions are
the last ones of 2007.

In contrast, I'm experimenting with a *weekly evening* course in
Silicon Valley designed mainly for locals.  It represents a viable
alternative to those who cannot take time off during the week as well
as being more budget-friendly, as I am partnering with a local
community college (Foothill) to offer this course.  Class takes place
on the main campus and you must register through the college to
attend.

For more information, such as cost and other course details, see the
corresponding websites below. Contact me privately if you have any
more questions.

cheers,
-wesley

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

DAYTIME
=======
- (Intensive) Introduction to Python (Mon-Wed, May 14-16)
- Advanced Python Programming (Wed-Fri, May 16-18)
- Advanced Python (short course; Thu-Fri, May 17-18)
- Core Python (Intro+Advanced combo; Mon-Fri, May 14-18)

These courses run daily 9a-5p and will take place in San Bruno right
near the San Francisco International Airport at the:

Staybridge Suites - San Francisco Airport
1350 Huntington Ave
San Bruno, CA  94066 USA
http://www.ichotelsgroup.com/h/d/sb/1/en/hd/sfobr

Discounts are available for students and teachers, as well as multiple
registrations from those working at the same company.  For more info
and registration, go to http://cyberwebconsulting.com (click on
"Python Training")

LOCALS: free parking and 101/280/380 access, BART across the street
and CalTrain down the road (San Bruno stations)

VISITORS: free hotel shuttle to/from the San Francisco airport, lots
of free food and wireless, 2-bedroom suites w/private baths and a
common work/living area available for traveling coworkers, and of
course, The City by the Bay
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

EVENING
=======
- Intermediate Python Programming (Tues, Apr 10-Jun 26)

This course will cover the same topics as the advanced course above as
well as critical portions of the intensive introductory course. It
will be held once a week on Tuesday evenings from 6-9:40p.

Foothill College
12345 El Monte Road
Los Altos Hills, CA  94022 USA
(right off 280, just south of Stanford)

http://www.foothill.edu/schedule/schedule.php
search for CIS 68L for Spring Quarter 2007

From kent37 at tds.net  Thu Mar 22 19:52:05 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 22 Mar 2007 14:52:05 -0400
Subject: [Tutor] sorting data from multiple arrays
In-Reply-To: <277809.23222.qm@web43143.mail.sp1.yahoo.com>
References: <277809.23222.qm@web43143.mail.sp1.yahoo.com>
Message-ID: <4602D055.6040908@tds.net>

Jeff Peery wrote:
> hello, I typically run into this problem and I'm not always sure of the 
> most efficient way to handle it. I often work with multiple arrays of 
> data, say arrays a, b, and c, and I want to sort the elements of b and c 
> based on a. for example:
> 
> a = [3,2,1,4]
> b = ['hi', 'my','name', 'is']
> c = [5,2,4,2]
> 
> I order 'a' from small to large and do the same rearrangement to 'b' and 
> 'c':
> a = [1,2,3,4]
> b = ['name', 'my','hi', 'is']
> c = [4,2,5,2]
> 
> usually I do some terrible looking for loops and iterate over the whole 
> mess.... is there a clean, efficient way to do this, or is there a nice 
> function that would reorder the elements of b and c based on the soring 
> of a?

Decorate-sort-undecorate 
(http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52234)
to the rescue:

In [12]: a = [3,2,1,4]
In [13]: b = ['hi', 'my','name', 'is']
In [14]: c = [5,2,4,2]
In [15]: temp = zip(a, b, c)
In [16]: temp
Out[16]: [(3, 'hi', 5), (2, 'my', 2), (1, 'name', 4), (4, 'is', 2)]
In [17]: temp.sort()
In [18]: _, b, c = zip(*temp)
In [19]: b
Out[19]: ('name', 'my', 'hi', 'is')
In [20]: c
Out[20]: (4, 2, 5, 2)

Or, if you are a fan of one-liners:
In [21]: _, b, c = zip(*sorted(zip(a, b, c)))

Methinks there should be a clever way to do this with the key= argument 
to sort, but I can't think of it at the moment...

Kent

From kent37 at tds.net  Thu Mar 22 19:54:34 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 22 Mar 2007 14:54:34 -0400
Subject: [Tutor] Why is it...
In-Reply-To: <0A7441AE-153F-4356-9D81-026017D7AE3E@uakron.edu>
References: <0A7441AE-153F-4356-9D81-026017D7AE3E@uakron.edu>
Message-ID: <4602D0EA.2080102@tds.net>

Jay Mutter III wrote:
> Why is it that when I run the following interactively
> 
> f = open('Patents-1920.txt')
> line = f.readline()
> while line:
>      print line,
>      line = f.readline()
> f.close()
> 
> I get an error message
> 
> File "<stdin>", line 4
>      f.close()
>      ^
> SyntaxError: invalid syntax
> 
> but if i run it in a script there is no error?

Can you copy/paste the actual console transcript?

BTW a better way to write this is
f = open(...)
for line in f:
     print line,
f.close()

Kent

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


From jason.massey at gmail.com  Thu Mar 22 20:05:04 2007
From: jason.massey at gmail.com (Jason Massey)
Date: Thu, 22 Mar 2007 14:05:04 -0500
Subject: [Tutor] Why is it...
In-Reply-To: <4602D0EA.2080102@tds.net>
References: <0A7441AE-153F-4356-9D81-026017D7AE3E@uakron.edu>
	<4602D0EA.2080102@tds.net>
Message-ID: <7e3eab2c0703221205w422a1a40g1a0b8aecaede3da6@mail.gmail.com>

In the interpreter this doesn't work:

>>> f = open(r"c:\python24\image.dat")
>>> line = f.readline()
>>> while line:
...     line = f.readline()
... f.close()
Traceback (  File "<interactive input>", line 3
    f.close()
    ^
SyntaxError: invalid syntax

But this does:

>>> f = open(r"c:\python24\image.dat")
>>> line = f.readline()
>>> while line:
...     line = f.readline()
...
>>> f.close()
>>>

Note the differing placement of the f.close() statement, it's not part of
the while.


On 3/22/07, Kent Johnson <kent37 at tds.net> wrote:
>
> Jay Mutter III wrote:
> > Why is it that when I run the following interactively
> >
> > f = open('Patents-1920.txt')
> > line = f.readline()
> > while line:
> >      print line,
> >      line = f.readline()
> > f.close()
> >
> > I get an error message
> >
> > File "<stdin>", line 4
> >      f.close()
> >      ^
> > SyntaxError: invalid syntax
> >
> > but if i run it in a script there is no error?
>
> Can you copy/paste the actual console transcript?
>
> BTW a better way to write this is
> f = open(...)
> for line in f:
>      print line,
> f.close()
>
> Kent
>
> >
> > Thanks
> >
> > Jay
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070322/28b86dee/attachment.htm 

From jeffpeery at yahoo.com  Thu Mar 22 21:00:10 2007
From: jeffpeery at yahoo.com (Jeff Peery)
Date: Thu, 22 Mar 2007 13:00:10 -0700 (PDT)
Subject: [Tutor] sorting data from multiple arrays
In-Reply-To: <4602D055.6040908@tds.net>
Message-ID: <90184.99678.qm@web43143.mail.sp1.yahoo.com>

Thanks for all the responses, that is a huge help!

Jeff

Kent Johnson <kent37 at tds.net> wrote: Jeff Peery wrote:
> hello, I typically run into this problem and I'm not always sure of the 
> most efficient way to handle it. I often work with multiple arrays of 
> data, say arrays a, b, and c, and I want to sort the elements of b and c 
> based on a. for example:
> 
> a = [3,2,1,4]
> b = ['hi', 'my','name', 'is']
> c = [5,2,4,2]
> 
> I order 'a' from small to large and do the same rearrangement to 'b' and 
> 'c':
> a = [1,2,3,4]
> b = ['name', 'my','hi', 'is']
> c = [4,2,5,2]
> 
> usually I do some terrible looking for loops and iterate over the whole 
> mess.... is there a clean, efficient way to do this, or is there a nice 
> function that would reorder the elements of b and c based on the soring 
> of a?

Decorate-sort-undecorate 
(http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52234)
to the rescue:

In [12]: a = [3,2,1,4]
In [13]: b = ['hi', 'my','name', 'is']
In [14]: c = [5,2,4,2]
In [15]: temp = zip(a, b, c)
In [16]: temp
Out[16]: [(3, 'hi', 5), (2, 'my', 2), (1, 'name', 4), (4, 'is', 2)]
In [17]: temp.sort()
In [18]: _, b, c = zip(*temp)
In [19]: b
Out[19]: ('name', 'my', 'hi', 'is')
In [20]: c
Out[20]: (4, 2, 5, 2)

Or, if you are a fan of one-liners:
In [21]: _, b, c = zip(*sorted(zip(a, b, c)))

Methinks there should be a clever way to do this with the key= argument 
to sort, but I can't think of it at the moment...

Kent


 
---------------------------------
Finding fabulous fares is fun.
Let Yahoo! FareChase search your favorite travel sites to find flight and hotel bargains.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070322/7124dd6c/attachment.html 

From hmm at woolgathering.cx  Thu Mar 22 20:58:09 2007
From: hmm at woolgathering.cx (William O'Higgins Witteman)
Date: Thu, 22 Mar 2007 15:58:09 -0400
Subject: [Tutor] pruning and ordering a list of lists
Message-ID: <20070322195809.GA16108@sillyrabbi.dyndns.org>

I have a list of lists derived from a log file that I want to create a
summary of, but I am not sure of an approach to do what I need.

Here's a sample of the data:

[["user1","18/Mar/2007:07:52:38 -0400"],["user1","18/Mar/2007:07:52:40 -0400"],["user2","18/Mar/2007:07:52:42 -0400"],["user3","18/Mar/2007:07:52:42 -0400"],["user2","18/Mar/2007:07:52:43 -0400"]]

What I want as output is something like this:

[["first user alphabetically","most recent timestamp for this user"],["second user alphabetically","most recent timestamp for this user"], ...]

Can anyone suggest an approach for this?  Thanks.
-- 

yours,

William

From jmutter at uakron.edu  Thu Mar 22 21:44:01 2007
From: jmutter at uakron.edu (Jay Mutter III)
Date: Thu, 22 Mar 2007 16:44:01 -0400
Subject: [Tutor] Another string question
Message-ID: <918A0A67-F392-4779-AF79-62F8E7027B7D@uakron.edu>

I wanted the following to check each line and if it ends in a right  
parentheses then write the entire line to one file and if not then  
write the line to anther.
It wrote all of the ) to one file and the rest of the line (ie minus  
the ) to the other file.


in_filename = raw_input('What is the COMPLETE name of the file you  
would like to process?    ')
in_file = open(in_filename, 'rU')
text = in_file.read()
count = len(text.splitlines())
print "There are ", count, 'lines to process in this file'
out_filename1 = raw_input('What is the COMPLETE name of the file in  
which you would like to save Companies?    ')
companies = open(out_filename1, 'aU')
out_filename2 = raw_input('What is the COMPLETE name of the file in  
which you would like to save Inventors?    ')
patentdata = open(out_filename2, 'aU')
for line in text:
     if line[-1] in ')':
         companies.write(line)
     else:
         patentdata.write(line)
in_file.close()
companies.close()
patentdata.close()

Thanks

jay

From carroll at tjc.com  Thu Mar 22 22:07:55 2007
From: carroll at tjc.com (Terry Carroll)
Date: Thu, 22 Mar 2007 14:07:55 -0700 (PDT)
Subject: [Tutor] Why is it...
In-Reply-To: <7e3eab2c0703221205w422a1a40g1a0b8aecaede3da6@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0703221402380.18514-100000@violet.rahul.net>

On Thu, 22 Mar 2007, Jason Massey wrote:

> In the interpreter this doesn't work:
> 
> >>> f = open(r"c:\python24\image.dat")
> >>> line = f.readline()
> >>> while line:
> ...     line = f.readline()
> ... f.close()
> Traceback (  File "<interactive input>", line 3
>     f.close()
>     ^
> SyntaxError: invalid syntax

The interactive interpreter was expecting a blank line to end the suite of
the compound statement.  Without the blank line, it interpreted the close
statement to be part of the suite;  and since it's not indented as the
suite should be, it's a syntax error.

The blank line requirement is only in interactive sessions:

      Note that a (top-level) compound statement must be followed by a 
      blank line in interactive mode; this is needed to help the parser
      detect the end of the input.

 http://docs.python.org/ref/interactive.html

> But this does:
> 
> >>> f = open(r"c:\python24\image.dat")
> >>> line = f.readline()
> >>> while line:
> ...     line = f.readline()
> ...
> >>> f.close()
> >>>
> 
> Note the differing placement of the f.close() statement, it's not part of
> the while.

The difference is that this time you gave it the blank line to end the 
suite.



From jeffpeery at yahoo.com  Thu Mar 22 22:35:42 2007
From: jeffpeery at yahoo.com (Jeff Peery)
Date: Thu, 22 Mar 2007 14:35:42 -0700 (PDT)
Subject: [Tutor] sorting data from multiple arrays
In-Reply-To: <4602D055.6040908@tds.net>
Message-ID: <810814.27222.qm@web43131.mail.sp1.yahoo.com>

... what is '*' in '*temp'? thanks!
J

Kent Johnson <kent37 at tds.net> wrote: Jeff Peery wrote:
> hello, I typically run into this problem and I'm not always sure of the 
> most efficient way to handle it. I often work with multiple arrays of 
> data, say arrays a, b, and c, and I want to sort the elements of b and c 
> based on a. for example:
> 
> a = [3,2,1,4]
> b = ['hi', 'my','name', 'is']
> c = [5,2,4,2]
> 
> I order 'a' from small to large and do the same rearrangement to 'b' and 
> 'c':
> a = [1,2,3,4]
> b = ['name', 'my','hi', 'is']
> c = [4,2,5,2]
> 
> usually I do some terrible looking for loops and iterate over the whole 
> mess.... is there a clean, efficient way to do this, or is there a nice 
> function that would reorder the elements of b and c based on the soring 
> of a?

Decorate-sort-undecorate 
(http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52234)
to the rescue:

In [12]: a = [3,2,1,4]
In [13]: b = ['hi', 'my','name', 'is']
In [14]: c = [5,2,4,2]
In [15]: temp = zip(a, b, c)
In [16]: temp
Out[16]: [(3, 'hi', 5), (2, 'my', 2), (1, 'name', 4), (4, 'is', 2)]
In [17]: temp.sort()
In [18]: _, b, c = zip(*temp)
In [19]: b
Out[19]: ('name', 'my', 'hi', 'is')
In [20]: c
Out[20]: (4, 2, 5, 2)

Or, if you are a fan of one-liners:
In [21]: _, b, c = zip(*sorted(zip(a, b, c)))

Methinks there should be a clever way to do this with the key= argument 
to sort, but I can't think of it at the moment...

Kent


 
---------------------------------
Need Mail bonding?
Go to the Yahoo! Mail Q&A for great tips from Yahoo! Answers users.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070322/60331f9e/attachment.htm 

From pine508 at hotmail.com  Fri Mar 23 02:50:31 2007
From: pine508 at hotmail.com (Che M)
Date: Thu, 22 Mar 2007 21:50:31 -0400
Subject: [Tutor] basics of passing arguments to make a graph
Message-ID: <BAY18-F1772BC09964C6944016239E06A0@phx.gbl>

Hi, this is some *really* beginner Python stuff, hope you folks could help 
me.

I've been trying to make basic plots (line graphs) using the pyplot module 
(wx.lib.plot) in wxPython.  So far, so good.  To start, I can use a class 
like this (adapted from a demo) to draw a pre-defined graph:

class PlotPanel(wx.lib.plot.PlotCanvas):
    def __init__(self, *args, **kwargs):
        wx.lib.plot.PlotCanvas.__init__(self, *args, **kwargs)     
#PlotCanvas on which I draw graph
        self.Draw(self._drawGraph())                                       
#draw it using the next function

    def _drawGraph(self):                                       #this 
function draws just this one specific graph
        points = [(1,1), (3,4), (5,7), (7,14)]             #just four points 
for a simple little line graph
        m=[]
        m.append(wx.lib.plot.PolyLine(points))                  #uses the 
points to make a line
        m.append(wx.lib.plot.PolyMarker(points))               #uses the 
points to place markers
        return wx.lib.plot.PlotGraphics(m, "Graph Title",      #return the 
whole graph with title, etc.
            "x axis", "y axis")

This makes a nice graph, but the problem is that doing it this way means I 
need a seperate class for every graph I would want to make.  Obviously not 
the way to do it.

What I want instead is a way to have a class that makes my graphs but which 
expects to be passed points from some other place, in my case, due to some 
user choice (in selecting data from a list or whatever).

I get the sense that the idea is to pass a list of points to the drawGraph 
function.  Is that right?  So far I've fooled with it but can't get it to 
work.  Mostly because I don't understand argument passing well at all (like 
the *args, **kwargs stuff is still mysterious to me).  I was hoping this 
could help touch on some good principles for how to do this type of argument 
passing generally.

Thank you,
Che

_________________________________________________________________
It?s tax season, make sure to follow these few simple tips 
http://articles.moneycentral.msn.com/Taxes/PreparationTips/PreparationTips.aspx?icid=HMMartagline


From alan.gauld at btinternet.com  Fri Mar 23 10:14:53 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 23 Mar 2007 09:14:53 -0000
Subject: [Tutor] basics of passing arguments to make a graph
References: <BAY18-F1772BC09964C6944016239E06A0@phx.gbl>
Message-ID: <eu05qe$vsa$1@sea.gmane.org>

"Che M" <pine508 at hotmail.com> wrote

> I've been trying to make basic plots (line graphs)
> using the pyplot module  in wxPython.

> class PlotPanel(wx.lib.plot.PlotCanvas):
>     def __init__(self, *args, **kwargs):
>          wx.lib.plot.PlotCanvas.__init__(self, *args, **kwargs)
>         self.Draw(self._drawGraph())
>
>    def _drawGraph(self):                                       #this
>         points = [(1,1), (3,4), (5,7), (7,14)]             #just 
> four points

This is the critical bit you need to change.
points is only defined inside this method,
you need to move the list into the class so
that you can access it as self.points. Also
you can set the list to a new value, add
new points etc.

To do that you should add new methods
to your class such as addPoints(), removePoints(),
replacePoints() etc. Also you should probably add
a list of points to your init method so you can pass
in an initial list - and set a default value of the
empty list. Like this:

     def __init__(self, points=[], *args, **kwargs):
          wx.lib.plot.PlotCanvas.__init__(self, *args, **kwargs)
         self.points = points
         self.Draw(self._drawGraph())

addPoints will be something very simple like:

     def addPoints(self, points):
          self.points += points

Now you just modify your drawGraph to use self.points:

>         m=[]
>         m.append(wx.lib.plot.PolyLine(points))

           m.append(wx.lib.plot.PolyLine(self.points))
etc.

> I get the sense that the idea is to pass a list of points
> to the drawGraph function.  Is that right?

If we were working with functions the answer would be yes,
but becausese we have a class we can store thelist as an
attribute of the class which allows us to manage the list
internally.

Another approach would be to create a points list class
and pass that to the drawGraph function. But in this case
the thing that cares about the points list is the PlotPanel
so it's reasonable that it should manage the points list.

>  Mostly because I don't understand argument passing
>  well at all (like the *args, **kwargs stuff is still mysterious
>  to me).

If you understand normal parameters/arguments then don't
worry too much about  *args/**kwargs. I've been using Python
for about 10 years and have only used those features in my
own code a couple of times. Most of the time you don't
need them. In this case so long as you keep them at the
end of your parameter list in init you can pretty much ignnore
them - they just pass any options you give to your class on to
the parent class.

In fact, I consider them sufficiently advanced that I don't even
discuss them in my tutor topic on functions. I probably should
introduce them somewhere I guess, but it will be in an
advanced topic somewhere...

HTH,

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



From andreengels at gmail.com  Fri Mar 23 10:30:51 2007
From: andreengels at gmail.com (Andre Engels)
Date: Fri, 23 Mar 2007 10:30:51 +0100
Subject: [Tutor] Another string question
In-Reply-To: <918A0A67-F392-4779-AF79-62F8E7027B7D@uakron.edu>
References: <918A0A67-F392-4779-AF79-62F8E7027B7D@uakron.edu>
Message-ID: <6faf39c90703230230l3bc0099dp4343f9b3526661cf@mail.gmail.com>

2007/3/22, Jay Mutter III <jmutter at uakron.edu>:
>
> I wanted the following to check each line and if it ends in a right
> parentheses then write the entire line to one file and if not then
> write the line to anther.
> It wrote all of the ) to one file and the rest of the line (ie minus
> the ) to the other file.


The line:
     print "There are ", count, 'lines to process in this file'
should give you a hint - don't you think this number was rather high?

The problem is that if you do "for line in text" with text being a string,
it will not loop over the _lines_  in the string, but over the _characters_
in the string.

The easiest solution would be to replace
     text = in_file.read()
by
     text = in_file.readlines()

in_filename = raw_input('What is the COMPLETE name of the file you
> would like to process?    ')
> in_file = open(in_filename, 'rU')
> text = in_file.read()
> count = len(text.splitlines())
> print "There are ", count, 'lines to process in this file'
> out_filename1 = raw_input('What is the COMPLETE name of the file in
> which you would like to save Companies?    ')
> companies = open(out_filename1, 'aU')
> out_filename2 = raw_input('What is the COMPLETE name of the file in
> which you would like to save Inventors?    ')
> patentdata = open(out_filename2, 'aU')
> for line in text:
>      if line[-1] in ')':
>          companies.write(line)
>      else:
>          patentdata.write(line)
> in_file.close()
> companies.close()
> patentdata.close()
>
> Thanks
>
> jay
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Andre Engels, andreengels at gmail.com
ICQ: 6260644  --  Skype: a_engels
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070323/f900c484/attachment.htm 

From osamu118 at gmail.com  Fri Mar 23 04:22:59 2007
From: osamu118 at gmail.com (Carson Wendy)
Date: Fri, 23 Mar 2007 11:22:59 +0800
Subject: [Tutor] a very simple question
Message-ID: <44AB3C27-1DE1-481E-B36C-E15D9FAEEF7D@gmail.com>

ok, i just started python and i'm stuck on this, could use some help :D
a='test'
def f():
     a=a+'gg'


From kent37 at tds.net  Fri Mar 23 11:27:26 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 23 Mar 2007 06:27:26 -0400
Subject: [Tutor] sorting data from multiple arrays
In-Reply-To: <810814.27222.qm@web43131.mail.sp1.yahoo.com>
References: <810814.27222.qm@web43131.mail.sp1.yahoo.com>
Message-ID: <4603AB8E.9090303@tds.net>

Jeff Peery wrote:
> ... what is '*' in '*temp'? thanks!

Say you have a function of 3 arguments:
In [1]: def add(a, b, c):
    ...:     return a+b+c

Normally to call it, you just specify the three arguments:
In [2]: add(1, 2, 3)
Out[2]: 6

Suppose the arguments were already in a list, what would you do? You 
can't just pass the list, that is a single argument and you need three:
In [3]: data=[1, 2, 3]
In [4]: add(data)
------------------------------------------------------------
Traceback (most recent call last):
   File "<ipython console>", line 1, in <module>
<type 'exceptions.TypeError'>: add() takes exactly 3 arguments (1 given)

You could unpack the data yourself:
In [5]: a, b, c = data
In [6]: add(a, b, c)
Out[6]: 6

Or you can use the * notation, which basically means, "treat each 
element of this list as a separate argument", or "use this list as the 
argument list directly":
In [7]: add(*data)
Out[7]: 6

If the length of the argument list (data, in the example above) can 
change, manually unpacking the list won't work and the * syntax is the 
only alternative.

Kent

>     Decorate-sort-undecorate
>     (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52234)
>     to the rescue:
> 
>     In [12]: a = [3,2,1,4]
>     In [13]: b = ['hi', 'my','name', 'is']
>     In [14]: c = [5,2,4,2]
>     In [15]: temp = zip(a, b, c)
>     In [16]: temp
>     Out[16]: [(3, 'hi', 5), (2, 'my', 2), (1, 'name', 4), (4, 'is', 2)]
>     In [17]: temp.sort()
>     In [18]: _, b, c = zip(*temp)
>     In [19]: b
>     Out[19]: ('name', 'my', 'hi', 'is')
>     In [20]: c
>     Out[20]: (4, 2, 5, 2)


From jmutter at uakron.edu  Fri Mar 23 11:34:49 2007
From: jmutter at uakron.edu (Jay Mutter III)
Date: Fri, 23 Mar 2007 06:34:49 -0400
Subject: [Tutor] Another string question
In-Reply-To: <6faf39c90703230230l3bc0099dp4343f9b3526661cf@mail.gmail.com>
References: <918A0A67-F392-4779-AF79-62F8E7027B7D@uakron.edu>
	<6faf39c90703230230l3bc0099dp4343f9b3526661cf@mail.gmail.com>
Message-ID: <7880A725-1A13-4090-9144-91897EF4D65E@uakron.edu>


On Mar 23, 2007, at 5:30 AM, Andre Engels wrote:

> 2007/3/22, Jay Mutter III <jmutter at uakron.edu>:
> I wanted the following to check each line and if it ends in a right
> parentheses then write the entire line to one file and if not then
> write the line to anther.
> It wrote all of the ) to one file and the rest of the line (ie minus
> the ) to the other file.
>
> The line:
>      print "There are ", count, 'lines to process in this file'
> should give you a hint - don't you think this number was rather high?
>
> The problem is that if you do "for line in text" with text being a  
> string, it will not loop over the _lines_  in the string, but over  
> the _characters_ in the string.
>
> The easiest solution would be to replace
>      text = in_file.read()
> by
>      text = in_file.readlines()
>

Thanks for the response
Actually the number of lines this returns is the same number of lines  
given when i put it in a text editor (TextWrangler).
Luke had mentioned the same thing earlier but when I do change read  
to readlines  i get the following


Traceback (most recent call last):
   File "extract_companies.py", line 17, in ?
     count = len(text.splitlines())
AttributeError: 'list' object has no attribute 'splitlines'



> in_filename = raw_input('What is the COMPLETE name of the file you
> would like to process?    ')
> in_file = open(in_filename, 'rU')
> text = in_file.read()
> count = len(text.splitlines())
> print "There are ", count, 'lines to process in this file'
> out_filename1 = raw_input('What is the COMPLETE name of the file in
> which you would like to save Companies?    ')
> companies = open(out_filename1, 'aU')
> out_filename2 = raw_input('What is the COMPLETE name of the file in
> which you would like to save Inventors?    ')
> patentdata = open(out_filename2, 'aU')
> for line in text:
>      if line[-1] in ')':
>          companies.write(line)
>      else:
>          patentdata.write(line)
> in_file.close()
> companies.close()
> patentdata.close()
>
> Thanks
>
> jay
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
> -- 
> Andre Engels, andreengels at gmail.com
> ICQ: 6260644  --  Skype: a_engels

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

From andreengels at gmail.com  Fri Mar 23 11:43:13 2007
From: andreengels at gmail.com (Andre Engels)
Date: Fri, 23 Mar 2007 11:43:13 +0100
Subject: [Tutor] Fwd:  Another string question
In-Reply-To: <6faf39c90703230342s2996f524p4c2e678bda9b589@mail.gmail.com>
References: <918A0A67-F392-4779-AF79-62F8E7027B7D@uakron.edu>
	<6faf39c90703230230l3bc0099dp4343f9b3526661cf@mail.gmail.com>
	<7880A725-1A13-4090-9144-91897EF4D65E@uakron.edu>
	<6faf39c90703230342s2996f524p4c2e678bda9b589@mail.gmail.com>
Message-ID: <6faf39c90703230343o6f3898a1rdf3d3e4a92343f19@mail.gmail.com>

2007/3/23, Jay Mutter III <jmutter at uakron.edu>:
>
>
> On Mar 23, 2007, at 5:30 AM, Andre Engels wrote:
>
> 2007/3/22, Jay Mutter III < jmutter at uakron.edu>:
> >
> > I wanted the following to check each line and if it ends in a right
> > parentheses then write the entire line to one file and if not then
> > write the line to anther.
> > It wrote all of the ) to one file and the rest of the line (ie minus
> > the ) to the other file.
>
>
> The line:
>      print "There are ", count, 'lines to process in this file'
> should give you a hint - don't you think this number was rather high?
>
> The problem is that if you do "for line in text" with text being a string,
> it will not loop over the _lines_  in the string, but over the _characters_
> in the string.
>
> The easiest solution would be to replace
>      text = in_file.read()
> by
>      text = in_file.readlines()
>
>
> Thanks for the response
> Actually the number of lines this returns is the same number of lines
> given when i put it in a text editor (TextWrangler).
> Luke had mentioned the same thing earlier but when I do change read to
> readlines  i get the following
>
>
> Traceback (most recent call last):
>   File "extract_companies.py", line 17, in ?
>     count = len(text.splitlines())
> AttributeError: 'list' object has no attribute 'splitlines'
>


Ah, yes, there you DO split in lines, but later you don't. You'll have to do
the same thing twice, that is either:

text = in_file.readlines()
count = len(text) # (instead of count = len(text.splitlines())

OR

text = in_file.read()
for line in text.splitlines(): # (instead of for line in text:)

in_filename = raw_input('What is the COMPLE
> >
>  TE name of the file you
> > would like to process?    ')
> > in_file = open(in_filename, 'rU')
> > text = in_file.read()
> > count = len(text.splitlines())
> > print "There are ", count, 'lines to process in this file'
> > out_filename1 = raw_input('What is the COMPLETE name of the file in
> > which you would like to save Companies?    ')
> > companies = open(out_filename1, 'aU')
> > out_filename2 = raw_input('What is the COMPLETE name of the file in
> > which you would like to save Inventors?    ')
> > patentdata = open(out_filename2, 'aU')
> > for line in text:
> >      if line[-1] in ')':
> >          companies.write(line)
> >      else:
> >          patentdata.write(line)
> > in_file.close()
> > companies.close ()
> > patentdata.close()
> >
> > Thanks
> >
> > jay
> > _______________________________________________
> > Tutor maillist  -   Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
>
>
> --
> Andre Engels, andreengels at gmail.com
> ICQ: 6260644  --  Skype: a_engels
>
>
>


-- 
Andre Engels, andreengels at gmail.com
ICQ: 6260644  --  Skype: a_engels
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070323/ffe4b1af/attachment.html 

From kent37 at tds.net  Fri Mar 23 11:58:06 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 23 Mar 2007 06:58:06 -0400
Subject: [Tutor] a very simple question
In-Reply-To: <44AB3C27-1DE1-481E-B36C-E15D9FAEEF7D@gmail.com>
References: <44AB3C27-1DE1-481E-B36C-E15D9FAEEF7D@gmail.com>
Message-ID: <4603B2BE.8000801@tds.net>

Carson Wendy wrote:
> ok, i just started python and i'm stuck on this, could use some help :D
> a='test'
> def f():
>      a=a+'gg'

What is your question? What happens when you run this code? What did you 
expect to happen? What are you trying to do?

Kent

From kent37 at tds.net  Fri Mar 23 12:33:05 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 23 Mar 2007 07:33:05 -0400
Subject: [Tutor] Another string question
In-Reply-To: <7880A725-1A13-4090-9144-91897EF4D65E@uakron.edu>
References: <918A0A67-F392-4779-AF79-62F8E7027B7D@uakron.edu>	<6faf39c90703230230l3bc0099dp4343f9b3526661cf@mail.gmail.com>
	<7880A725-1A13-4090-9144-91897EF4D65E@uakron.edu>
Message-ID: <4603BAF1.9070606@tds.net>

Jay Mutter III wrote:
> Thanks for the response
> Actually the number of lines this returns is the same number of lines 
> given when i put it in a text editor (TextWrangler).
> Luke had mentioned the same thing earlier but when I do change read to 
> readlines  i get the following
> 
> 
> Traceback (most recent call last):
>   File "extract_companies.py", line 17, in ?
>     count = len(text.splitlines())
> AttributeError: 'list' object has no attribute 'splitlines'

I think maybe you are confused about the difference between "all the 
text of a file in a single string" and "all the lines of a file in a 
list of strings."

When you open() a file and read() the contents, you get all the text of 
a file in a single string. len() will give you the length of the string 
(the total file size) and iterating over the string gives you one 
character at at time.

Here is an example of a string:
In [1]: s = 'This is text'
In [2]: len(s)
Out[2]: 12
In [3]: for i in s:
    ...:     print i
    ...:
    ...:
T
h
i
s

i
s

t
e
x
t

On the other hand, if you open() the file and then readlines() from the 
file, the result is a list of strings, each of with is the contents of 
one line of the file, up to and including the newline. len() of the list 
is the number of lines in the list, and iterating the list gives each 
line in turn.

Here is an example of a list of strings:
In [4]: l = [ 'line1', 'line2' ]
In [5]: len(l)
Out[5]: 2
In [6]: for i in l:
    ...:     print i
    ...:
    ...:
line1
line2

Notice that s and l are *used* exactly the same way with len() and for, 
but the results are different.

As a further wrinkle, there are two easy ways to get all the lines in a 
file and they give slightly different results.

open(...).readlines() returns a list of lines in the file and each line 
includes the final newline if it was in the file. (The last line will 
not include a newline if the last line of the file did not.)

open(...).read().splitlines() also gives a list of lines in the file, 
but the newlines are not included.

HTH,
Kent

From Senthil_OR at Dell.com  Fri Mar 23 12:45:14 2007
From: Senthil_OR at Dell.com (Senthil_OR at Dell.com)
Date: Fri, 23 Mar 2007 17:15:14 +0530
Subject: [Tutor] a very simple question
In-Reply-To: <44AB3C27-1DE1-481E-B36C-E15D9FAEEF7D@gmail.com>
References: <44AB3C27-1DE1-481E-B36C-E15D9FAEEF7D@gmail.com>
Message-ID: <D6ED7B7268DC0F4C9BF6AF2537BCE5C6BB68FF@blrx3m03.blr.amer.dell.com>

Carson Wendy wrote:
> ok, i just started python and i'm stuck on this, could use some help
> :D 
> a='test'
> def f():
>      a=a+'gg'

Look for the definition of  'global'
And try this:
>>> a = 'test'
>>> def f()
	global a
	a = a + 'gg'
	print a
>>>f()


-- 
Senthil


Dish of the Day: Good evening, madame and gentlemen. I am the main dish
of the day. May I interest you in parts of my body? 

From rikard.bosnjakovic at gmail.com  Fri Mar 23 13:12:20 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Fri, 23 Mar 2007 13:12:20 +0100
Subject: [Tutor] help me and ill love u!!! :)
In-Reply-To: <509ecd760703210835r14d79641w77830274b0a3d843@mail.gmail.com>
References: <509ecd760703210835r14d79641w77830274b0a3d843@mail.gmail.com>
Message-ID: <d9e88eaf0703230512m212486fbo789b64e1242f8c31@mail.gmail.com>

On 3/21/07, p l <electricitymen at gmail.com> wrote:

> im a new python programmer and iv been given a task to get as much details that i can on my system memory...

Since this is very low level hacking, you need to specify which
operating system you use.


-- 
- Rikard - http://bos.hack.org/cv/

From alan.gauld at btinternet.com  Fri Mar 23 14:45:54 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 23 Mar 2007 13:45:54 -0000
Subject: [Tutor] a very simple question
References: <44AB3C27-1DE1-481E-B36C-E15D9FAEEF7D@gmail.com>
Message-ID: <eu0lmk$euc$1@sea.gmane.org>

"Carson Wendy" <osamu118 at gmail.com> wrote in

> ok, i just started python and i'm stuck on this, could use some help 
> :D
> a='test'
> def f():
>     a=a+'gg'

Welcome to the world of Python.

As a rule when you have a problem tell us what the problem is,
we aren't psychic. Specifically, if you get an error message cut
and paste that error into your email.

Usually the answer to your question will be in the error text,
once you know what to look for.

In your case the answer is that you are defining a new variable
 'a' inside your function, but it depends on 'a' for its value. But
since 'a' (in your function) doesn't exist yet, Python can't give 'a'
a value and complains.

Read the 'Whats in a name?' topic in my tutor for more about this
and how to deal with it.

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



From jmutter at uakron.edu  Fri Mar 23 14:51:00 2007
From: jmutter at uakron.edu (Jay Mutter III)
Date: Fri, 23 Mar 2007 09:51:00 -0400
Subject: [Tutor] Should I use python for parsing text?
In-Reply-To: <46026DBF.4070201@tds.net>
References: <63DA79E7-BED7-4E18-A638-547E274EE234@uakron.edu>
	<46026DBF.4070201@tds.net>
Message-ID: <6D2981FD-F57C-4036-B9C1-6E513D0FB11C@uakron.edu>

First thanks for all of the help
I am actually starting to see the light.

On Mar 22, 2007, at 7:51 AM, Kent Johnson wrote:

> Jay Mutter III wrote:
>> Kent;
>> Thanks for the reply on tutor-python.
>> My data file which is just a .txt file created under WinXP by an  
>> OCR program contains lines like:
>> A.-C. Manufacturing Company. (See Sebastian, A. A.,
>> and Capes, assignors.)
>> A. G. A. Railway Light & Signal Co. (See Meden, Elof
>> H? assignor.)
>> A-N Company, The. (See Alexander and Nasb, as-
>> signors.;
>> AN Company, The. (See Nash, It. J., and Alexander, as-
>> signors.)
>> I use an intel imac running OS x10.4.9 and when I used python to  
>> append one file to another I got a file that opened in OS X's
>> TexEdit program with characters that looked liked Japanese/Chinese  
>> characters.
>> When i pasted them into my mail client (OS X's mail) they were  
>> then just a sequence of question marks so I am not sure what  
>> happened.
>> Any thoughts???
>
> For some reason, after you run the Python program, TexEdit thinks  
> the file is not ascii data; it seems to think it is utf-8 or a  
> Chinese encoding. Your original email was utf-8 which points in  
> that direction but is not conclusive.
>
> If you zip up and send me the original file and the cleandata.txt  
> file *exactly as it is produced* by the Python program - not edited  
> in any way - I will take a look and see if I can guess what is  
> going on.
>>

You are correct that it was utf-8
Multiple people were scanning pages and converting to text, some  
saved as ascii and some saved as unicode
The sample used above was utf-8 so after your comment i checked all,  
put everything as ascii, combined all pieces into one file and  
normalized the line endings to unix style


>> And i tried  using the following on the above data:
>> in_filename = raw_input('What is the COMPLETE name of the file you  
>> want to open:    ')
>> in_file = open(in_filename, 'r')
>
> It wouldn't hurt to use universal newlines here since you are  
> working cross-platform:
>   open(in_filename, 'Ur')
>

corrected this

>> text = in_file.readlines()
>> num_lines = text.count('\n')
>
> Here 'text' is a list of lines, so text.count('\n') is counting the  
> number of blank lines (lines containing only a newline) in your  
> file. You should use
>   num_lines = len(text)
>

changed


>> print 'There are', num_lines, 'lines in the file', in_filename
>> output = open("cleandata.txt","a")    # file for writing data to  
>> after stripping newline character
>
> I agree with Luke, use 'w' for now to make sure the file has only  
> the output of this program. Maybe something already in the file is  
> making it look like utf-8...
>
>> # read file, copying each line to new file
>> for line in text:
>>     if len(line) > 1 and line[-2] in ';,-':
>>         line = line.rstrip()
>>         output.write(line)
>>     else: output.write(line)
>> print "Data written to cleandata.txt."
>> # close the files
>> in_file.close()
>> output.close()
>> As written above it tells me that there are 0 lines which is  
>> surprising because if I run the first part by itself it tells  
>> there are 1982 lines ( actually 1983 so i am figuring EOF)
>> It copies/writes the data to the cleandata file but it does not  
>> strip out CR and put data on one line ( a sample of what i am  
>> trying to get is next)
>> A.-C. Manufacturing Company. (See Sebastian, A. A., and Capes,  
>> assignors.)
>> My apologies if i have intruded.
>
> Please reply on-list in the future.
>
> Kent


From lerik at nolink.net  Fri Mar 23 15:55:42 2007
From: lerik at nolink.net (Lars Erik Gullerud)
Date: Fri, 23 Mar 2007 15:55:42 +0100 (CET)
Subject: [Tutor] Invoking a procedure with an uknown number of arguments...
Message-ID: <20070323145720.G442@electra.nolink.net>

Hello list,

I have the following problem; I have a list with an unknown number of 
strings, like so:

   MyList = ['string1', 'string2', 'string3'..'stringN']

Now, I need to call a procedure from a 3rd party module (which is just a 
wrapper around a C library), where each of these strings must be passed 
as a separate argument, i.e.

   MyProc(arg1, arg2, arg3..argN)

So, the question is basically, how can I invoke this procedure and pass 
each of these list elements as separate arguments, when I don't know in 
advance how many elements there will be? Had this been e.g. a case with 3 
elements, I could hardcode it like:

   MyProc(MyList[0], MyList[1], MyList[2])

...however this is obviously not possible when the number of elements is 
not known in advance.

Any tips?

/leg

From kent37 at tds.net  Fri Mar 23 16:19:51 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 23 Mar 2007 11:19:51 -0400
Subject: [Tutor] Invoking a procedure with an uknown number of
	arguments...
In-Reply-To: <20070323145720.G442@electra.nolink.net>
References: <20070323145720.G442@electra.nolink.net>
Message-ID: <4603F017.5050405@tds.net>

Lars Erik Gullerud wrote:
> Hello list,
> 
> I have the following problem; I have a list with an unknown number of 
> strings, like so:
> 
>    MyList = ['string1', 'string2', 'string3'..'stringN']
> 
> Now, I need to call a procedure from a 3rd party module (which is just a 
> wrapper around a C library), where each of these strings must be passed 
> as a separate argument, i.e.
> 
>    MyProc(arg1, arg2, arg3..argN)
> 
> So, the question is basically, how can I invoke this procedure and pass 
> each of these list elements as separate arguments, when I don't know in 
> advance how many elements there will be?

MyProc(*MyList)

More details here:
http://mail.python.org/pipermail/tutor/2007-March/053435.html

Kent

From nebpro at gmail.com  Fri Mar 23 17:20:48 2007
From: nebpro at gmail.com (Ben)
Date: Fri, 23 Mar 2007 12:20:48 -0400
Subject: [Tutor] threading and gui programming
In-Reply-To: <8249c4ac0703222302w2728ce3fjd49f2ad2395738f8@mail.gmail.com>
References: <8249c4ac0703222302w2728ce3fjd49f2ad2395738f8@mail.gmail.com>
Message-ID: <e5f41cb30703230920u74f34075sd8fab9b36737e5f9@mail.gmail.com>

Hi Tony,

Thank you very much for your pointer. I think I understand what are you
explaining to me. Do you mind give me some code examples? I am still trying
to grasp the gui programming overall. And it is really over my head. I
really appreciate your help. Thank you

-Ben

On 3/23/07, Tony Cappellini <cappy2112 at gmail.com> wrote:
>
> Hi Ben,
>
> I've just started gui programming in Python, and my first app needed a
> little threading.
> It's over my head, so a friend gave me an example, and I integrated it.
>
> The reason for threading in my example- is the same as what Kent
> mentioned.
>
> My app is a gui front end to another python program which processes files.
> The file processor outputs text, and my gui displays it in a text box.
> If it were not for threading, my app would freeze until the app that
> I'm calling finished.
>
> Another way to think of it- is using yourself for an example/.
> If you were eating dinner, and someone in the room called your name-
> you would probably turn your head or walk over to them while you were
> chewing a mouthfull :-)
>
> If you didn't respond to them until you were finished eating, they
> could not finish what they were doing either.
>
> Does that make sense?
>
> You may not always need threading in a gui app. It just depends on
> what you ar edoing, and how long it takes.
>
>
>
> Message: 1
> Date: Tue, 20 Mar 2007 14:49:50 -0400
> From: Ben <nebpro at gmail.com>
> Subject: [Tutor] threading and gui programming
> To: tutor at python.org
> Message-ID:
>        <e5f41cb30703201149h62446ce7t97bf028100c08503 at mail.gmail.com>
> Content-Type: text/plain; charset="iso-8859-1"
>
> Hi all,
>
> I am curious about one thing. I have been doing research on gui
> programming.
> One thing that I don't understand is why there are some examples uses
> threading in the gui examples. Is there any benefits or advantages for
> using
> the threading in the gui programming? Thanks.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070323/e0540a9e/attachment-0001.html 

From jmutter at uakron.edu  Fri Mar 23 18:55:28 2007
From: jmutter at uakron.edu (Jay Mutter III)
Date: Fri, 23 Mar 2007 13:55:28 -0400
Subject: [Tutor] Another string question
In-Reply-To: <6faf39c90703230230l3bc0099dp4343f9b3526661cf@mail.gmail.com>
References: <918A0A67-F392-4779-AF79-62F8E7027B7D@uakron.edu>
	<6faf39c90703230230l3bc0099dp4343f9b3526661cf@mail.gmail.com>
Message-ID: <3E3103A6-D5D1-4011-92BA-ABFEAC6DF720@uakron.edu>

Andre;

Thanks again for the assistance.

I have corrected the splitlines error and it works ( well that part  
of anyway) correctly now.

On Mar 23, 2007, at 5:30 AM, Andre Engels wrote:

> 2007/3/22, Jay Mutter III <jmutter at uakron.edu>:
> I wanted the following to check each line and if it ends in a right
> parentheses then write the entire line to one file and if not then
> write the line to anther.
> It wrote all of the ) to one file and the rest of the line (ie minus
> the ) to the other file.
>
> The line:
>      print "There are ", count, 'lines to process in this file'
> should give you a hint - don't you think this number was rather high?
>
> The problem is that if you do "for line in text" with text being a  
> string, it will not loop over the _lines_  in the string, but over  
> the _characters_ in the string.
>
> The easiest solution would be to replace
>      text = in_file.read()
> by
>      text = in_file.readlines()
>
> in_filename = raw_input('What is the COMPLETE name of the file you
> would like to process?    ')
> in_file = open(in_filename, 'rU')
> text = in_file.read()
> count = len(text.splitlines())
> print "There are ", count, 'lines to process in this file'
> out_filename1 = raw_input('What is the COMPLETE name of the file in
> which you would like to save Companies?    ')
> companies = open(out_filename1, 'aU')
> out_filename2 = raw_input('What is the COMPLETE name of the file in
> which you would like to save Inventors?    ')
> patentdata = open(out_filename2, 'aU')
> for line in text:
>      if line[-1] in ')':
>          companies.write(line)
>      else:
>          patentdata.write(line)
> in_file.close()
> companies.close()
> patentdata.close()
>
> Thanks
>
> jay
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
> -- 
> Andre Engels, andreengels at gmail.com
> ICQ: 6260644  --  Skype: a_engels

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

From jmutter at uakron.edu  Fri Mar 23 19:00:55 2007
From: jmutter at uakron.edu (Jay Mutter III)
Date: Fri, 23 Mar 2007 14:00:55 -0400
Subject: [Tutor] Why is it...
In-Reply-To: <7e3eab2c0703221205w422a1a40g1a0b8aecaede3da6@mail.gmail.com>
References: <0A7441AE-153F-4356-9D81-026017D7AE3E@uakron.edu>
	<4602D0EA.2080102@tds.net>
	<7e3eab2c0703221205w422a1a40g1a0b8aecaede3da6@mail.gmail.com>
Message-ID: <DE8F8FA6-D051-42AF-B08F-0F8CD767D7C7@uakron.edu>

Got it - it needs the blank line to signal that code block has ended.
Thanks

On Mar 22, 2007, at 3:05 PM, Jason Massey wrote:

> In the interpreter this doesn't work:
>
> >>> f = open(r"c:\python24\image.dat")
> >>> line = f.readline()
> >>> while line:
> ...     line = f.readline()
> ... f.close()
> Traceback (  File "<interactive input>", line 3
>     f.close()
>     ^
> SyntaxError: invalid syntax
>
> But this does:
>
> >>> f = open(r"c:\python24\image.dat")
> >>> line = f.readline()
> >>> while line:
> ...     line = f.readline()
> ...
> >>> f.close()
> >>>
>
> Note the differing placement of the f.close() statement, it's not  
> part of the while.
>
>
> On 3/22/07, Kent Johnson <kent37 at tds.net> wrote:
> Jay Mutter III wrote:
> > Why is it that when I run the following interactively
> >
> > f = open('Patents-1920.txt')
> > line = f.readline()
> > while line:
> >      print line,
> >      line = f.readline()
> > f.close()
> >
> > I get an error message
> >
> > File "<stdin>", line 4
> >      f.close()
> >      ^
> > SyntaxError: invalid syntax
> >
> > but if i run it in a script there is no error?
>
> Can you copy/paste the actual console transcript?
>
> BTW a better way to write this is
> f = open(...)
> for line in f:
>      print line,
> f.close()
>
> Kent
>
> >
> > Thanks
> >
> > Jay
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070323/0a8b0b4d/attachment.html 

From pine508 at hotmail.com  Fri Mar 23 19:28:00 2007
From: pine508 at hotmail.com (Che M)
Date: Fri, 23 Mar 2007 14:28:00 -0400
Subject: [Tutor] passing arguments to a make a graph
In-Reply-To: <mailman.18204.1174645652.32030.tutor@python.org>
Message-ID: <BAY18-F1787A2FCAF45FF3C3E5DAE06A0@phx.gbl>


Thank you, Alan.   I started by adding a method called addPoints() to my 
class as you recommend.  But now I don't know how to pass a list of points 
to the addPoints() method.  Here's the relevant code, adding in your 
suggestions:

class PlotPanel(wx.lib.plot.PlotCanvas):
    def __init__(self, points=[], *args, **kwargs):
        wx.lib.plot.PlotCanvas.__init__(self, *args, **kwargs)
        self.points = points
        self.Draw(self._drawGraph())
        self.SetEnableDrag(True)
        #self.SetEnableGrid(True)

    def addPoints(self, points):
        self.points += points

    def _drawGraph(self):
        m=[]
        m.append(wx.lib.plot.PolyLine(self.points))
        m.append(wx.lib.plot.PolyMarker(self.points))
        return wx.lib.plot.PlotGraphics(m, "Title)",
            "x axis", "")

#this button tells it to make a graph using "mypoints".

def OnGraphButton(self, event):
    mypoints = [(3,4), (5,6)]                             #these to be used 
in the plot
    PlotPanel.addPoints(PlotPanel,mypoints)
    self.notebook1.AddPage(imageId=-1, page=PlotPanel(self.notebook1), 
select=True,
              text='Weight')


The error I get using it this way is:

TypeError:  unbound method addPoints() must be called with PlotPanel 
instance as first argument (got type instance instead)

I'm lost.  Also, what does "self.points += points" mean?  What is the += 
operator?

Thanks,
Che

_________________________________________________________________
Mortgage refinance is hot 1) Rates near 30-yr lows 2) Good credit get 
intro-rate 4.625%* 
https://www2.nextag.com/goto.jsp?product=100000035&url=%2fst.jsp&tm=y&search=mortgage_text_links_88_h2a5f&s=4056&p=5117&disc=y&vers=743


From alan.gauld at btinternet.com  Fri Mar 23 21:04:12 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 23 Mar 2007 20:04:12 -0000
Subject: [Tutor] passing arguments to a make a graph
References: <mailman.18204.1174645652.32030.tutor@python.org>
	<BAY18-F1787A2FCAF45FF3C3E5DAE06A0@phx.gbl>
Message-ID: <eu1brt$poe$1@sea.gmane.org>


"Che M" <pine508 at hotmail.com> wrote
> Thank you, Alan.   I started by adding a method called addPoints() 
> to my
> class as you recommend.  But now I don't know how to pass a list of 
> points
> to the addPoints() method.

You need to create an instance of a PlotPanel.

> class PlotPanel(wx.lib.plot.PlotCanvas):
>    def __init__(self, points=[], *args, **kwargs):
>    def addPoints(self, points):
>    def _drawGraph(self):

> #this button tells it to make a graph using "mypoints".
>
> def OnGraphButton(self, event):
>    mypoints = [(3,4), (5,6)]   #these to be used
>    PlotPanel.addPoints(PlotPanel,mypoints)

Instead of using the class create an instance(aka object)

       self.plotPanel = PlotPanel(mypoints,self.notebook1)

That creates an instance passing the mypoints list in
to youir init method along with the notebook1 that you
pass when you create an instance later(see below).

>    self.notebook1.AddPage(imageId=-1, 
> page=PlotPanel(self.notebook1),
>                                          select=True, 
> text='Weight')

This should use the plotPanel instance:

     self.notebook1.AddPage(imageId=-1, page=self.plotPanel,
                                          select=True,  text='Weight')

> The error I get using it this way is:
>
> TypeError:  unbound method addPoints() must be called with PlotPanel
> instance as first argument (got type instance instead)

Yep, You gotta have an instance to call the methods.
See my OOP topic for more on classes, objects etc.

> I'm lost.  Also, what does "self.points += points" mean?  What is 
> the +=
> operator?

x += 5

is shorthand for

x = x + 5

The same applies to -/* etc.
See my raw Materials topic for more info on operators.

HTH,


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



From carroll at tjc.com  Fri Mar 23 21:19:13 2007
From: carroll at tjc.com (Terry Carroll)
Date: Fri, 23 Mar 2007 13:19:13 -0700 (PDT)
Subject: [Tutor] Developing a GUI application
Message-ID: <Pine.LNX.4.44.0703231310100.10190-100000@violet.rahul.net>

I'm pretty much just a dabbler in Python.

Up to now I've mostly been doing line-oriented programs, but I have a 
small app I want to write that I think would be a good candidate to write 
as a GUI-based app.

I'd like advice from the more seasoned programmers here: how do you 
approach a GUI-based app?  

I figure one way to do it is to write the nuts and bolts of it using plain
old line oriented techniques; and then write the GUI, calling the
functions already written.

The other way would be to write a GUI shell with all the controls, but 
calling dummy functions; then write the functions to do the tasks.

What's the general wisdom here?

(If it matters: I'm going to use wxPython; and my app is yet another CDROM 
database program; more details available if it matters.)


From jmutter at uakron.edu  Fri Mar 23 22:32:53 2007
From: jmutter at uakron.edu (Jay Mutter III)
Date: Fri, 23 Mar 2007 17:32:53 -0400
Subject: [Tutor] Parsing text file with Python
Message-ID: <62F2BF08-C1FF-4CA0-9E41-7D842E4D91DD@uakron.edu>

Script i have to date is below and
Thanks to your help i can see some daylight  but I still have a few  
questions

1.)  Are there better ways to write this?
2.) As it writes out the one group to the new file for companies it  
is as if it leaves blank lines behind for if I don't have the elif len 
(line) . 1 the
       inventor's file has blank lines in it.
3.) I reopened the inventor's file to get a count of lines but is  
there a better way to do this?

Thanks



in_filename = raw_input('What is the COMPLETE name of the file you  
would like to process?    ')
in_file = open(in_filename, 'rU')
text = in_file.readlines()
count = len(text)
print "There are ", count, 'lines to process in this file'
out_filename1 = raw_input('What is the COMPLETE name of the file in  
which you would like to save Companies?    ')
companies = open(out_filename1, 'aU')
out_filename2 = raw_input('What is the COMPLETE name of the file in  
which you would like to save Inventors?    ')
patentdata = open(out_filename2, 'aU')
for line in text:
     if line.endswith(')\n'):
         companies.write(line)
     elif line.endswith(') \n'):
         companies.write(line)
      elif len(line) > 1:
             patentdata.write(line)
in_file.close()
companies.close()
patentdata.close()
in_filename2 = raw_input('What was the name of the inventor\'s  
file ?    ')
in_file2 = open(in_filename2, 'rU')
text2 = in_file2.readlines()
count = len(text2)
print "There are - well until we clean up more - approximately ",  
count, 'inventor\s in this file'

From rabidpoobear at gmail.com  Fri Mar 23 22:50:41 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Fri, 23 Mar 2007 16:50:41 -0500
Subject: [Tutor] Developing a GUI application
In-Reply-To: <Pine.LNX.4.44.0703231310100.10190-100000@violet.rahul.net>
References: <Pine.LNX.4.44.0703231310100.10190-100000@violet.rahul.net>
Message-ID: <46044BB1.7010805@gmail.com>

Terry Carroll wrote:
> I'm pretty much just a dabbler in Python.
>
> Up to now I've mostly been doing line-oriented programs, but I have a 
> small app I want to write that I think would be a good candidate to write 
> as a GUI-based app.
>
> I'd like advice from the more seasoned programmers here: how do you 
> approach a GUI-based app?  
>
> I figure one way to do it is to write the nuts and bolts of it using plain
> old line oriented techniques; and then write the GUI, calling the
> functions already written.
>
> The other way would be to write a GUI shell with all the controls, but 
> calling dummy functions; then write the functions to do the tasks.
>   
In either case, what you're intending to end up with is a decoupling of 
the GUI code and the program logic.

For example, in a command-line program, something like this:
print  "%i is your number!" % int(raw_input( "Please enter a number to 
be squared! " )) ** 2

Has the display code and the program logic all tangled up.
A much better version would be:
def squareNum(anint):  return anint ** 2

num = int(raw_input("enter a number to be squared, please! "))
print "Your number squared is: " + str(squareNum(num))

Because if later you want to reuse your function in a GUI app, you'd 
just change your value inputs but the functions would remain the same.

So essentially, when you write your GUI app, try to keep all 
calculations in functions with no GUI involvement.  It makes your 
functions more reusable and also it's good practice, as well as easier 
to maintain ( not having to look through GUI code to find where your 
calculations are.)

I'd say that it'd be best to make it a command-line app first, so that 
you can test the functionality of your code.  Essentially, the GUI is 
just an interface to the functions of your program that lets people use 
your program  easier, and there's no reason to write that part first 
(IMHO of course).
It would be a good idea to sketch out your GUI on a sheet of paper, so 
you have ideas of what kind of paramaters your functions will need to 
use before you write them.  For example, you might want function 
DisplayCDInfo to take an artist and an album, and write the function for 
that, then later realize that you wanted your GUI to give them the 
ability to show the track number as well.  It's nice to know (generally) 
what requirements you want before you start writing a program.
> (If it matters: I'm going to use wxPython; and my app is yet another CDROM 
> database program; more details available if it matters.)
Sounds pretty interesting, mind elaborating a bit?  Is it just for 
retrieving the CD info from freecddb and whatnot and display it?

From carroll at tjc.com  Fri Mar 23 23:16:34 2007
From: carroll at tjc.com (Terry Carroll)
Date: Fri, 23 Mar 2007 15:16:34 -0700 (PDT)
Subject: [Tutor] Developing a GUI application
In-Reply-To: <46044BB1.7010805@gmail.com>
Message-ID: <Pine.LNX.4.44.0703231503230.10190-100000@violet.rahul.net>

On Fri, 23 Mar 2007, Luke Paireepinart wrote:

> In either case, what you're intending to end up with is a decoupling of 
> the GUI code and the program logic.

Absolutely.  I try to do that in any case, even in non-GUI.

[other good advice snipped] 

> > (If it matters: I'm going to use wxPython; and my app is yet another CDROM 
> > database program; more details available if it matters.)
>
> Sounds pretty interesting, mind elaborating a bit?  Is it just for 
> retrieving the CD info from freecddb and whatnot and display it?

It's planned to be a database for data CDs, rather than audio ones; the
main advantage over the many DBs I've already encountered is to store an
MD5 checksum of the file, so that I can check to see if a new file I have
is a duplicate of something I already have and have archived off to CDROM, 
without having to find the CDROM.

I've also thought of having a twist here for MP3 files, specifically,
distinguishing between the files' audio frames and identification info
frames, and checksumming only the audio portion; so that two otherwise
identical MP3 files with different ID3 data would nonetheless have the
same audio checksum and show up as identical; but that's an idea for the
future.

I've also thought of, for image files, to store a thumbnail in the
database, too.

In any case, dabbler that I am (and given the fact that I have two
daughters, one 2 years and one only 3 weeks, which substantially cuts into
my hacking time), I'll probably finish this up, oh, sometime in 2008.


From project5 at redrival.net  Fri Mar 23 23:30:02 2007
From: project5 at redrival.net (Andrei)
Date: Fri, 23 Mar 2007 23:30:02 +0100
Subject: [Tutor] Developing a GUI application
In-Reply-To: <Pine.LNX.4.44.0703231310100.10190-100000@violet.rahul.net>
References: <Pine.LNX.4.44.0703231310100.10190-100000@violet.rahul.net>
Message-ID: <eu1kcs$n91$1@sea.gmane.org>

Hi Terry,

Terry Carroll wrote:
> I'd like advice from the more seasoned programmers here: how do you 
> approach a GUI-based app?

Approaches differ in formality and order of execution and opinions at 
any point in time vary - and they vary with time as well. I'm assuming 
this is a hobby-level project with yourself acting as developer and most 
important customer. So I'll suggest an approach that I think will keep 
you motivated and will help avoid getting bogged down in looking for the 
perfect decision at every step.

It helps if you start with some concrete ideas of what you'll want to be 
able to do with the application. It's not necessary to go all PowerPoint 
on it, but writing down some keywords and sketching interface ideas may 
help you explore your goals. You can even do quick real interface 
designs using e.g. wxGlade - it's often motivating to have *something* 
tangible available. These are not supposed to be final, set-in-stone and 
complete designs - just generic sketches.

> I figure one way to do it is to write the nuts and bolts of it using plain
> old line oriented techniques; and then write the GUI, calling the
> functions already written.

Having two interfaces is a way to make sure you don't accidentally 
couple your interface code to your internal model/storage. There's a 
nicer way to help achieving this: unit tests. However, you may not 
appreciate their advantages until you have more experience. Personally I 
have never used the two-interfaces approach.

> The other way would be to write a GUI shell with all the controls, but 

I would choose for a vertical development: implement everything you need 
(interface, storage, logic) to achieve some small part of the 
functionality - e.g. start by having a list of CD-ROM names and burn 
dates. This should work in the GUI, in the model and in your storage 
parts. Once that is tested and OK, add the next bit of functionality, etc.

You will invariably encounter problems due to previous decisions when 
doing this, but all beginners' applications - as well as most 
professionals' applications :) - eventually end up in a state of 
unmaintainable mess anyway. Making mistakes is a very good way of 
learning and even truly dumb and ugly mistakes can usually be worked 
around or refactored away; software is very malleable, particularly if 
you don't have outside constraints.
With a bit of luck, your software will be almost continuously in a 
usable state and using it will give you new ideas all the time, which 
you had not thought of beforehand.

> calling dummy functions; then write the functions to do the tasks.

You should look into objects - if you don't have at least a basic 
understanding of them, GUI development with wxPython will prove 
difficult and confusing. They are also pretty much essential for well 
structured Python programs.

> (If it matters: I'm going to use wxPython; and my app is yet another CDROM 
> database program; more details available if it matters.)

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info:
''.join([''.join(s) for s in zip(
"poet at aao.l pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
"rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])


From pine508 at hotmail.com  Fri Mar 23 23:33:31 2007
From: pine508 at hotmail.com (Che M)
Date: Fri, 23 Mar 2007 18:33:31 -0400
Subject: [Tutor] passing arguments to a make a graph
In-Reply-To: <mailman.18277.1174686646.32030.tutor@python.org>
Message-ID: <BAY18-F25FCF15CE82F347F067DE3E06A0@phx.gbl>



>Instead of using the class create an instance(aka object)
>
>        self.plotPanel = PlotPanel(mypoints,self.notebook1)
>
>That creates an instance passing the mypoints list in
>to youir init method along with the notebook1 that you
>pass when you create an instance later (see below).

This worked great, thanks!  One question:  you mention that in this way it 
is passing in the mypoints list and also the notebook1.  What I am unclear 
is, why are you allowed to pass in the notebook?  If you look at the 
original class PlotPanel():

class PlotPanel(wx.lib.plot.PlotCanvas):
    def __init__(self, points=[], *args, **kwargs):
        wx.lib.plot.PlotCanvas.__init__(self, *args, **kwargs)
        self.points = points

[some methods deleted]

...in the __init__ function, it has parameters for self, points, *args, and 
**kwargs.  But you are passing it the notebook1, so how does it know which 
"slot" of these four parameters notebook1 refers to?

>See my OOP topic for more on classes, objects etc.

I will look at it, and it should make even more sense given this example.

Gracias,
Che

_________________________________________________________________
The average US Credit Score is 675. The cost to see yours: $0 by Experian. 
http://www.freecreditreport.com/pm/default.aspx?sc=660600&bcd=EMAILFOOTERAVERAGE


From pythontut at pusspaws.net  Fri Mar 23 23:31:26 2007
From: pythontut at pusspaws.net (Dave S)
Date: Fri, 23 Mar 2007 22:31:26 +0000
Subject: [Tutor] My Python project - an update
Message-ID: <200703232231.26662.pythontut@pusspaws.net>

Just to say thank you.

Over the last few months I have been asking a lot of dumb questions about 
python (and qt on the qt mailing list) ... anyhow I finished my pet project, 
all 5500 lines of it. I previously explained what it was but to recap ...

I developed a QT Python app that scans both configuration and data collected 
from remote security systems, up to 80,000 data attributes per site.

After scanning it reports any inconsistencies or errors via a GUI giving them 
a severity level and an option to correct the error or acknowledge and enter 
override text.

It generates a certificate PDF with an embedded md5 authentication string when 
the site has been audited.
 
From its analysis of the data it also generates both a detailed user 
reference PDF and a detailed engineer reference PDF specifically for the 
site.

In my field this has never been done before - lots of very impressed people 
after several demonstrations. I released it under the GPL but apparently my 
terms of employment state that it belongs my employer ... who does not want 
it on sourceforge ...

Where is it now ... its being integrated into a proprietary application as a 
groundbreaking audit/commissioning  function (still running my Python code as 
a back end) and apparently I am due some kind of company reward ...

My thoughts on my first Python QT project ... would have been nice if I could 
have given it to the community ... wonder what they will pay me ? ...

Dave






From bgailer at alum.rpi.edu  Sat Mar 24 01:31:51 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Fri, 23 Mar 2007 17:31:51 -0700
Subject: [Tutor] pruning and ordering a list of lists
In-Reply-To: <20070322195809.GA16108@sillyrabbi.dyndns.org>
References: <20070322195809.GA16108@sillyrabbi.dyndns.org>
Message-ID: <46047177.5080702@alum.rpi.edu>

William O'Higgins Witteman wrote:
> I have a list of lists derived from a log file that I want to create a
> summary of, but I am not sure of an approach to do what I need.
>
> Here's a sample of the data:
>
> [["user1","18/Mar/2007:07:52:38 -0400"],["user1","18/Mar/2007:07:52:40 -0400"],["user2","18/Mar/2007:07:52:42 -0400"],["user3","18/Mar/2007:07:52:42 -0400"],["user2","18/Mar/2007:07:52:43 -0400"]]
>
> What I want as output is something like this:
>
> [["first user alphabetically","most recent timestamp for this user"],["second user alphabetically","most recent timestamp for this user"], ...]
>
> Can anyone suggest an approach for this?  Thanks.
>   
# following code is untested
# assume your data is in variable log:
userData = {} # setup a dictionary to collect latest timestamp for each user
for user, timestamp in log:
  if user not in userData or timestamp > userData[user]
    # note that we need a way to compare timestamps
    # the current representation does not support this
    userData[user] = timestamp
userData2 = userData.items().sorted()

-- 
Bob Gailer
510-978-4454


From alan.gauld at btinternet.com  Sat Mar 24 01:32:53 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 24 Mar 2007 00:32:53 -0000
Subject: [Tutor] passing arguments to a make a graph
References: <mailman.18277.1174686646.32030.tutor@python.org>
	<BAY18-F25FCF15CE82F347F067DE3E06A0@phx.gbl>
Message-ID: <eu1rjm$mba$1@sea.gmane.org>

"Che M" <pine508 at hotmail.com> wrote

>>Instead of using the class create an instance(aka object)
>>        self.plotPanel = PlotPanel(mypoints,self.notebook1)

> This worked great, thanks!  One question:  you mention that in this 
> way it
> is passing in the mypoints list and also the notebook1.  What I am 
> unclear
> is, why are you allowed to pass in the notebook?  If you look at the
> original class PlotPanel():
>
> class PlotPanel(wx.lib.plot.PlotCanvas):
>    def __init__(self, points=[], *args, **kwargs):
>        wx.lib.plot.PlotCanvas.__init__(self, *args, **kwargs)

OK, It always amazes me how the same basic topic comes
up all at once in this group. Kent gave a good explanation
of *args/**kwargs earlier this week, look back for it.

But basically what those two magic words do is take all of
the arguments passed in and bundle them up into those two
collections(kw args is keyword arguments and args is the rest(*))
So then when you call PlotCanvas.__init__() you are just passing
on everything that was passed into your init. You don;t know
nor care how many other arguments were gibemn, you just
pass them onto the superclass to deal with.

But you do care about points, so you put that as the first parameter.
Then when your init gets called Python peels off the first value
and puts it in points, the rest get put into args/kwargs.

(*)You recall that if a function has all of its parameters take
default values you can call it using keywords like this:

def f(a=1,b=2,c=3,d=4,e=3,f=2,g=1):
   pass

f(b=7,g=2)
f(c=4,a=0)

etc

Those are the keyword arguments
But I can also call it with plain values provided I use the right 
order:

f(9,8,7)  # a=9,b=8,c=7,d=4,e=3,f=2,g=1

Those are the args
Now I can use both techniques too:

f(7,8,e=0,g=2)  # a=7,b=8,c=3,d=4,e=0,f=2,g=2

Here args is 7,8
kwargs is e=0,g=2

Is that clearer?

> **kwargs.  But you are passing it the notebook1, so how does it know 
> which
> "slot" of these four parameters notebook1 refers to?

It doesn't, it passes notebook1 as the first value in args to the 
superclass init.
It then gets unpacked as the first parameter(after self) of the 
superclass' init.

HTH,


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



From alan.gauld at btinternet.com  Sat Mar 24 01:48:36 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 24 Mar 2007 00:48:36 -0000
Subject: [Tutor] Parsing text file with Python
References: <62F2BF08-C1FF-4CA0-9E41-7D842E4D91DD@uakron.edu>
Message-ID: <eu1sh5$q5m$1@sea.gmane.org>

"Jay Mutter III" <jmutter at uakron.edu> wrote
> 1.)  Are there better ways to write this?

There are always other ways, as to which is better depends
on your judgement criteria. Your way works.

> 2.) As it writes out the one group to the new file for companies it
> is as if it leaves blank lines behind for if I don't have the elif 
> len
> (line) . 1 the
>       inventor's file has blank lines in it.

I'm not sure what you mean here can you elaborate,
maybe with some sample data?

> 3.) I reopened the inventor's file to get a count of lines but is
> there a better way to do this?

You could track the numbers of items being written as you go.
The only disadvantage of your technique is the time invloved
in opening the file and rereading the data then counting it.
On a really big file that could take a long time. But it has
the big advantage of simplicity.

A couple of points:

> in_filename = raw_input('What is the COMPLETE name of the file you
> would like to process?    ')
> in_file = open(in_filename, 'rU')

You might want to put your file opening code inside a try/except
in case the file isn't there or is locked.

> text = in_file.readlines()
> count = len(text)
> print "There are ", count, 'lines to process in this file'

Unless this is really useful info you could simplify by
omitting the readlines and count and just iterating over
the file. If you use enumerate you even get the final
count for free at the end.

for count,line in enumerate(in_file):
     # count is the line number, line the data

> for line in text:
>     if line.endswith(')\n'):
>         companies.write(line)
>     elif line.endswith(') \n'):
>         companies.write(line)

You could use a boolean or to combine these:

     if line.endswith(')\n') or line.endswith(') \n'):
         companies.write(line)

> in_filename2 = raw_input('What was the name of the inventor\'s
> file ?    ')

Given you opened it surely you already know?
It should be stored in patentdata so you don't need
to ask again?

Also you could use flush() and then seek(0) and then readlines()
before closing the file to get the count. but frankly thats being 
picky.


> in_file2 = open(in_filename2, 'rU')
> text2 = in_file2.readlines()
> count = len(text2)

Well done,


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



From alan.gauld at btinternet.com  Sat Mar 24 01:55:52 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 24 Mar 2007 00:55:52 -0000
Subject: [Tutor] Developing a GUI application
References: <Pine.LNX.4.44.0703231310100.10190-100000@violet.rahul.net>
Message-ID: <eu1sup$ro4$1@sea.gmane.org>

"Terry Carroll" <carroll at tjc.com> wrote

> I figure one way to do it is to write the nuts and bolts of it using 
> plain
> old line oriented techniques; and then write the GUI, calling the
> functions already written.

Absolutely, taking care to put the code the GUI will use in separate
functions, ideally in a separate module, with no UI elements (GUI
or otherwise). You might also think about bundling functions and
data into classes at this stage too.

Its much easier to get a command line version working than
to get a GUI vesion right. Once you know the core works
OK then add the GUI gloss.

> The other way would be to write a GUI shell with all the controls, 
> but
> calling dummy functions; then write the functions to do the tasks.

I do this if the GUI is the bulk of the work. That is, if there will 
be
lots of forms and complex navigation between them and the
core processing is just fetching data from a database, say.

But for any significant processing of data I always write a CLI first.

Incidentally the same applies if I'm writing a networked app, first
get it running locally, then add the client/server gloss then finally
recast the client as a GUI, or the server as a web app as needed.

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



From hmm at woolgathering.cx  Sat Mar 24 02:20:10 2007
From: hmm at woolgathering.cx (William O'Higgins Witteman)
Date: Fri, 23 Mar 2007 21:20:10 -0400
Subject: [Tutor] pruning and ordering a list of lists
In-Reply-To: <46047177.5080702@alum.rpi.edu>
References: <20070322195809.GA16108@sillyrabbi.dyndns.org>
	<46047177.5080702@alum.rpi.edu>
Message-ID: <20070324012010.GG16106@sillyrabbi.dyndns.org>

On Fri, Mar 23, 2007 at 05:31:51PM -0700, Bob Gailer wrote:
>William O'Higgins Witteman wrote:
>>I have a list of lists derived from a log file that I want to create a
>>summary of, but I am not sure of an approach to do what I need.
>>
>>Here's a sample of the data:
>>
>>[["user1","18/Mar/2007:07:52:38 -0400"],["user1","18/Mar/2007:07:52:40 
>>-0400"],["user2","18/Mar/2007:07:52:42 
>>-0400"],["user3","18/Mar/2007:07:52:42 
>>-0400"],["user2","18/Mar/2007:07:52:43 -0400"]]
>>
>>What I want as output is something like this:
>>
>>[["first user alphabetically","most recent timestamp for this 
>>user"],["second user alphabetically","most recent timestamp for this 
>>user"], ...]
>>
>>Can anyone suggest an approach for this?  Thanks.
>>  
># following code is untested
># assume your data is in variable log:
>userData = {} # setup a dictionary to collect latest timestamp for each user
>for user, timestamp in log:
> if user not in userData or timestamp > userData[user]
>   # note that we need a way to compare timestamps
>   # the current representation does not support this
>   userData[user] = timestamp
>userData2 = userData.items().sorted()

Thank you.  I found a similar solution myself while waiting.  I was
stuck with thinking about the output being a list of lists, but once I
thought of it as a dictionary the solution came much more easily.
Here's the code, including timestamp conversions:

#!/usr/bin/python

import time

def userlists(usertimepairs):
  
  userandtoptimes = {}
  for line in usertimepairs:
    line[0] = line[0].lower()
    if userandtoptimes.has_key(line[0]):
      a = time.strptime(userandtoptimes[line[0]],"%d/%b/%Y:%H:%M:%S")
      prevtime = time.mktime(a)
      b = time.strptime(line[1],"%d/%b/%Y:%H:%M:%S -0400")
      thistime = time.mktime(b)
      if thistime > prevtime:
        c = time.gmtime(thistime)
        d = time.strftime("%d/%b/%Y:%H:%M:%S",c)
        userandtoptimes[line[0]] = d
      else:
        pass
    else:
      e = time.strptime(line[1],"%d/%b/%Y:%H:%M:%S -0400")
      f = time.strftime("%d/%b/%Y:%H:%M:%S",e)
      userandtoptimes[line[0]] = f

  #debug print(userandtoptimes)

  # Output to CSV file
  for user, timestamp in userandtoptimes.iteritems():
    op.write(user + "," + timestamp + "\n")

The time is not perfect, because of the discarded GMT offset, but it is
good enough, and by converting to seconds since the epoch the
comparisons are much simpler.  Thanks again.
-- 

yours,

William

From amonroe at columbus.rr.com  Sat Mar 24 04:39:36 2007
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Fri, 23 Mar 2007 22:39:36 -0500
Subject: [Tutor] Developing a GUI application
In-Reply-To: <Pine.LNX.4.44.0703231503230.10190-100000@violet.rahul.net>
References: <Pine.LNX.4.44.0703231503230.10190-100000@violet.rahul.net>
Message-ID: <60964995249.20070323223936@columbus.rr.com>

> On Fri, 23 Mar 2007, Luke Paireepinart wrote:

> I've also thought of having a twist here for MP3 files, specifically,
> distinguishing between the files' audio frames and identification info
> frames, and checksumming only the audio portion; so that two otherwise
> identical MP3 files with different ID3 data would nonetheless have the
> same audio checksum and show up as identical; but that's an idea for the
> future.

I suspect this would run into problems if you used a Fraunhoffer
encoder and I used the LAME encoder, for instance, even if we both
ripped from the same cd to start with.

Alan


From rabidpoobear at gmail.com  Sat Mar 24 03:45:44 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Fri, 23 Mar 2007 21:45:44 -0500
Subject: [Tutor] Developing a GUI application
In-Reply-To: <60964995249.20070323223936@columbus.rr.com>
References: <Pine.LNX.4.44.0703231503230.10190-100000@violet.rahul.net>
	<60964995249.20070323223936@columbus.rr.com>
Message-ID: <460490D8.80501@gmail.com>

R. Alan Monroe wrote:
>> On Fri, 23 Mar 2007, Luke Paireepinart wrote:
>>     
>
>   
>> I've also thought of having a twist here for MP3 files, specifically,
>> distinguishing between the files' audio frames and identification info
>> frames, and checksumming only the audio portion; so that two otherwise
>> identical MP3 files with different ID3 data would nonetheless have the
>> same audio checksum and show up as identical; but that's an idea for the
>> future.
>>     
>
> I suspect this would run into problems if you used a Fraunhoffer
> encoder and I used the LAME encoder, for instance, even if we both
> ripped from the same cd to start with.
>   
Yeah, also if it were the same song with a different 
bitrate/frequency/(stereo/mono/dual)/ etc.

I think the point of it was that, if I have a song with messed up tags, 
and I back it up, but later fix the tags,
if it were governed just by the md5 of the whole file, these two 
wouldn't be considered identical.
Remember this program is to help him keep track of backups.

From kent37 at tds.net  Sat Mar 24 04:04:41 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 23 Mar 2007 23:04:41 -0400
Subject: [Tutor] Developing a GUI application
In-Reply-To: <Pine.LNX.4.44.0703231310100.10190-100000@violet.rahul.net>
References: <Pine.LNX.4.44.0703231310100.10190-100000@violet.rahul.net>
Message-ID: <46049549.9000006@tds.net>

Terry Carroll wrote:
> I'm pretty much just a dabbler in Python.
> 
> Up to now I've mostly been doing line-oriented programs, but I have a 
> small app I want to write that I think would be a good candidate to write 
> as a GUI-based app.
> 
> I'd like advice from the more seasoned programmers here: how do you 
> approach a GUI-based app?  
> 
> I figure one way to do it is to write the nuts and bolts of it using plain
> old line oriented techniques; and then write the GUI, calling the
> functions already written.
> 
> The other way would be to write a GUI shell with all the controls, but 
> calling dummy functions; then write the functions to do the tasks.
> 
> What's the general wisdom here?

I usually alternate between writing the functional code and hooking it 
up to a GUI. I will write a bit of code that does something useful and 
write unit tests for it so I am confident that it works. Then I will 
write the GUI to drive that bit of function and test that (by hand, 
usually). Repeat as needed.

Kent

From kent37 at tds.net  Sat Mar 24 04:13:58 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 23 Mar 2007 23:13:58 -0400
Subject: [Tutor] pruning and ordering a list of lists
In-Reply-To: <20070324012010.GG16106@sillyrabbi.dyndns.org>
References: <20070322195809.GA16108@sillyrabbi.dyndns.org>	<46047177.5080702@alum.rpi.edu>
	<20070324012010.GG16106@sillyrabbi.dyndns.org>
Message-ID: <46049776.2030807@tds.net>

William O'Higgins Witteman wrote:
> Thank you.  I found a similar solution myself while waiting.  I was
> stuck with thinking about the output being a list of lists, but once I
> thought of it as a dictionary the solution came much more easily.
> Here's the code, including timestamp conversions:
> 
> #!/usr/bin/python
> 
> import time
> 
> def userlists(usertimepairs):
>   
>   userandtoptimes = {}
>   for line in usertimepairs:

You can say
   for user, timestamp in usertimepairs:
and then refer to user and timestamp instead of line[0] and line[1]; it 
makes the code much more readable.

>     line[0] = line[0].lower()
>     if userandtoptimes.has_key(line[0]):
>       a = time.strptime(userandtoptimes[line[0]],"%d/%b/%Y:%H:%M:%S")
>       prevtime = time.mktime(a)

You might consider keeping prevtime in the dictionary instead of 
converting to and from strings all the time. You can convert them back 
to strings when you write them out. Then the above two lines would just be
   prevtime = userndtoptimes[user]

>       b = time.strptime(line[1],"%d/%b/%Y:%H:%M:%S -0400")
>       thistime = time.mktime(b)
>       if thistime > prevtime:
>         c = time.gmtime(thistime)
>         d = time.strftime("%d/%b/%Y:%H:%M:%S",c)
>         userandtoptimes[line[0]] = d

This could just be
   userandtoptimes[user] = thistime

>       else:
>         pass
>     else:
>       e = time.strptime(line[1],"%d/%b/%Y:%H:%M:%S -0400")
>       f = time.strftime("%d/%b/%Y:%H:%M:%S",e)
>       userandtoptimes[line[0]] = f
> 
>   #debug print(userandtoptimes)
> 
>   # Output to CSV file
>   for user, timestamp in userandtoptimes.iteritems():
>     op.write(user + "," + timestamp + "\n")

Here you would have to convert to a string.

Kent

From rikard.bosnjakovic at gmail.com  Sat Mar 24 18:04:31 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Sat, 24 Mar 2007 18:04:31 +0100
Subject: [Tutor] a very simple question
In-Reply-To: <eu0lmk$euc$1@sea.gmane.org>
References: <44AB3C27-1DE1-481E-B36C-E15D9FAEEF7D@gmail.com>
	<eu0lmk$euc$1@sea.gmane.org>
Message-ID: <d9e88eaf0703241004m6b8bf0edgae078cfc33aca3e@mail.gmail.com>

On 3/23/07, Alan Gauld <alan.gauld at btinternet.com> wrote:

> Read the 'Whats in a name?' topic in my tutor for more about this
> and how to deal with it.

http://www.catb.org/~esr/faqs/smart-questions.html as well.

-- 
- Rikard - http://bos.hack.org/cv/

From jmutter at uakron.edu  Sun Mar 25 00:25:10 2007
From: jmutter at uakron.edu (Jay Mutter III)
Date: Sat, 24 Mar 2007 19:25:10 -0400
Subject: [Tutor] parsing text
Message-ID: <6D8D4200-6D64-4C1D-8466-51F71990F07C@uakron.edu>

Kent thanks for this as I was clearly confused with regards to string  
and list of strings.
I am, however, still having difficulty with how to solve a problem  
involving a related issue.

i have the following text:

Barnett, John B., assignor of one-half to R. N. Tutt, Kansas City,  
Mo.    Automatic display-sign.    No. 1,330 411-Apr. 13 ; v. 273 ; p.  
193.
Barnett,  John  II..  Tettenhall,  England.     Seat  of   
motorcars.    No. 1.353,708; Sept. 21 ; v. 278; p. 487. Barnett, Otto  
R.    (See Scott, John M., assignor.)
Barnett. Otto R.     (See Sponenburg, Hiram H., assignor)
Barnett, William A., Lincoln. Nebr.    Attachment for garment- 
turning   machines.     No.   1,342,937;   June   8 ?   v 270 ; p. 313."
Barnhart, Clarence D., Brooklyn, assignor to W. S. Rockwell Company,  
New York. N. Y.    Conveyer for furnaces No. 1.333.371 ; Mar. 9 ; v.  
272 ; p. 278.
Barnhart, Clarence v., Waynesboro, Pa., assignor to J. K. Hoffman and  
W. M. Raeclitel.  Hagerstowu, Md.     Seed-planter.    No. 1,357.43S:  
Nov. 2; v. 280: p. 45.
Barnhart, John E.    (See Haves, J. P.. and Barnhart )
Barnhart,-Mollie E.    (See Freeman. Alpheus J., assignor) Barnhill,  
E. B., and J. Stone, Indianapolis, Ind.    Auto-tire 477513

1.) when i do readlines and create a list and then print the list it  
adds a blank line between every line of text
2.)in the second line after p.487 there is the beginning of a new  
line of data only it isn't on a newline.
i tried string.replace(s,'p.','\n') in an attempt to put a CR in but  
it just put the characters\n in the string.

ideas?

Thanks again

jay



Jay Mutter III wrote:
 > Thanks for the response
 > Actually the number of lines this returns is the same number of lines
 > given when i put it in a text editor (TextWrangler).
 > Luke had mentioned the same thing earlier but when I do change  
read to
 > readlines  i get the following
 >
 >
 > Traceback (most recent call last):
 >   File "extract_companies.py", line 17, in ?
 >     count = len(text.splitlines())
 > AttributeError: 'list' object has no attribute 'splitlines'

I think maybe you are confused about the difference between "all the
text of a file in a single string" and "all the lines of a file in a
list of strings."

When you open() a file and read() the contents, you get all the text of
a file in a single string. len() will give you the length of the string
(the total file size) and iterating over the string gives you one
character at at time.

Here is an example of a string:
In [1]: s = 'This is text'
In [2]: len(s)
Out[2]: 12
In [3]: for i in s:
     ...:     print i
     ...:
     ...:
T
h
i
s

i
s

t
e
x
t

On the other hand, if you open() the file and then readlines() from the
file, the result is a list of strings, each of with is the contents of
one line of the file, up to and including the newline. len() of the list
is the number of lines in the list, and iterating the list gives each
line in turn.

Here is an example of a list of strings:
In [4]: l = [ 'line1', 'line2' ]
In [5]: len(l)
Out[5]: 2
In [6]: for i in l:
     ...:     print i
     ...:
     ...:
line1
line2

Notice that s and l are *used* exactly the same way with len() and for,
but the results are different.

As a further wrinkle, there are two easy ways to get all the lines in a
file and they give slightly different results.

open(...).readlines() returns a list of lines in the file and each line
includes the final newline if it was in the file. (The last line will
not include a newline if the last line of the file did not.)

open(...).read().splitlines() also gives a list of lines in the file,
but the newlines are not included.

HTH,
Kent



-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070324/55e95a41/attachment-0001.html 

From jaggojaggo at yahoo.com  Sun Mar 25 00:41:22 2007
From: jaggojaggo at yahoo.com (Jaggo)
Date: Sat, 24 Mar 2007 16:41:22 -0700 (PDT)
Subject: [Tutor] Tutor Digest, Vol 37, Issue 62
In-Reply-To: <mailman.18408.1174778716.32030.tutor@python.org>
Message-ID: <20070324234122.86838.qmail@web52504.mail.re2.yahoo.com>

Message: 2
Date: Sat, 24 Mar 2007 19:25:10 -0400
From: Jay Mutter III 
Subject: [Tutor] parsing text
[...]
1.) when i do readlines and create a list and then print the list it  
adds a blank line between every line of text
[...]
ideas?

Thanks again

jay
Well,
regarding your first question:
"print string" automatically breaks a line at the end of string. Use "print string," instead [note that trailin' , .]

[I'm not sure about your n. 2, that's why no answer is included.

 
---------------------------------
TV dinner still cooling?
Check out "Tonight's Picks" on Yahoo! TV.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070324/2d731ac8/attachment.htm 

From alan.gauld at btinternet.com  Sun Mar 25 01:00:29 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 25 Mar 2007 00:00:29 -0000
Subject: [Tutor] parsing text
References: <6D8D4200-6D64-4C1D-8466-51F71990F07C@uakron.edu>
Message-ID: <eu4e2v$o5h$1@sea.gmane.org>

"Jay Mutter III" <jmutter at uakron.edu> wrote

> i have the following text:
>
> Barnett, John B., assignor of one-half to R. N. Tutt, Kansas City,
> Mo.    Automatic display-sign.    No. 1,330 411-Apr. 13 ; v. 273 ; 
> p.
> 193.
> Barnett,  John  II..  Tettenhall,  England.     Seat  of
> motorcars.    No. 1.353,708; Sept. 21 ; v. 278; p. 487. Barnett, 
> Otto
> R.    (See Scott, John M., assignor.)
>
> 1.) when i do readlines and create a list and then print the list it
> adds a blank line between every line of text

I suspect that's because you are reading a newline character
from the file and print adds a newline of its own. You need to
use rstrip() to take out the newline from the file.

> 2.)in the second line after p.487 there is the beginning of a new
> line of data only it isn't on a newline.

I'm not quite sure what you mean here.
It would be helpful if you can show us the problematic output
as well as the input. Also to send us the actual code fragments
that are causing the damage.

> i tried string.replace(s,'p.','\n') in an attempt to put a CR in but
> it just put the characters\n in the string.

Dont use the string module functions. Use the string methods,
so it becomes:

s.replace('p.', '\n')

However that doesn't explain why you are getting the literal
characters! Can you send us the actual code you are using?
And the output showing the error?

HTH,

Alan G. 



From ebbaalm at uiuc.edu  Sun Mar 25 01:32:36 2007
From: ebbaalm at uiuc.edu (Cecilia Alm)
Date: Sat, 24 Mar 2007 19:32:36 -0500
Subject: [Tutor] No need to seed random?
Message-ID: <7a4620dc0703241732m355f23d3m26cfcbe2a06dfad5@mail.gmail.com>

After importing random, there is no need to call random.seed() in a
python program, is there? (unless one wishes to specifically control
what the seed is.)

Thanks!

From erik.kloeppel at forethought.net  Sat Mar 24 05:54:56 2007
From: erik.kloeppel at forethought.net (Lurch)
Date: Fri, 23 Mar 2007 22:54:56 -0600
Subject: [Tutor] nube question...
Message-ID: <4604AF20.10709@forethought.net>

Gentlemen,

I don't consider myself a rank beginner (I did take a shower this week), 
but I've been beating my brains out over this for the past week.

I'm writing this GUI app (Tkinter).  Just about everything is done (all 
the nuts,bolts, and the occasional nail.  Now Im trying to code a simple 
status window to let the dumb user (me) know what's going on behind the 
curtain.  The idea is, the application calls the subroutine, the 
subroutine pops open a frame and print some text in it, then returns 
control back to the  main app - leaving the frame/text visible.  Then, 
the app calls the subroutine and *updates* the frame, so you end up with 
a growing list of notices...(basically, I'm working with a variable set 
of files, and it's convenient to know which is being operated on)

I've ripped code from Mark Lutz's book (3rd edition), from Welch's book 
(also 3rd edition), and from around the net. It seems to me that I'm 
missing something obvious when it comes to self.update.  The subroutine 
works as advertised the first time through, but one the window is open 
and the text displays, the app stops - unless I close the window.  Of 
course, then everything works until the NEXT message is displayed.

Sure, I could add a button and work from that, but I don't *WANT* to - 
the idea is a (more or less) continuous flow of information that I can 
scroll through if need be.

As you can see from the sample code below, I'm using the Text widget 
instead of Message.  I had a reason for that when I started this 
nightmare, but I'm not wedded to it.

Any assistance from anybody would be much appreciated.

Thanks in advance!

Erik

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

from Tkinter import *

data={}
data[4,9]="you are here"
data[4,10]=0
msg=1
x={}

def loop():
    global x
    x[1]=0
    while x[1]<10:
        messages(x)
        print "howdee"
        x[1]=x[1]+1

def messages(msg):
    class MESSAGES(Frame):
        def __init__(self,parent=None,text='', file=None):
            Frame.__init__(self,parent)
            self.pack(expand=YES,fill=BOTH)
            self.makewidgets()
            self.message(text)
            self.update()
   
        def makewidgets(self):
            sbar=Scrollbar(self)
            a=Text(self,relief=RAISED)
            sbar.config(command=a.yview,bg='#fcfcfc')
            a.config(yscrollcommand=sbar.set,bg='#f0f0f0')
            sbar.pack(side=RIGHT,fill=Y)
            a.pack(side=LEFT,expand=YES,fill=BOTH)
            self.a=a
            data[4,10]=1
           
        def message(self,text):
            self.a.insert(END,text)
            self.a.focus()
            return self.a.get('35.2',END+'-1c')

    if __name__=='__main__':
        root=Tk()
        MESSAGES(text=data[4,9]).mainloop()
        return
       
loop()

I've tried this small mod, just now, but it *really* breaks things the 
second time through:


    class MESSAGES(Frame):
        def __init__(self,parent=None,text='', file=None):
            Frame.__init__(self,parent)
            self.pack(expand=YES,fill=BOTH)
            if data[4,10]==0:
                self.makewidgets()
            self.message(text)
            self.update

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

From kent37 at tds.net  Sun Mar 25 04:26:33 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 24 Mar 2007 22:26:33 -0400
Subject: [Tutor] parsing text
In-Reply-To: <eu4e2v$o5h$1@sea.gmane.org>
References: <6D8D4200-6D64-4C1D-8466-51F71990F07C@uakron.edu>
	<eu4e2v$o5h$1@sea.gmane.org>
Message-ID: <4605DDD9.8010808@tds.net>

Alan Gauld wrote:

>> 1.) when i do readlines and create a list and then print the list it
>> adds a blank line between every line of text
> 
> I suspect that's because you are reading a newline character
> from the file and print adds a newline of its own. You need to
> use rstrip() to take out the newline from the file.

or use sys.stdout.write() instead of print, it doesn't add a newline.

Kent

From kent37 at tds.net  Sun Mar 25 04:32:32 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 24 Mar 2007 22:32:32 -0400
Subject: [Tutor] No need to seed random?
In-Reply-To: <7a4620dc0703241732m355f23d3m26cfcbe2a06dfad5@mail.gmail.com>
References: <7a4620dc0703241732m355f23d3m26cfcbe2a06dfad5@mail.gmail.com>
Message-ID: <4605DF40.3090007@tds.net>

Cecilia Alm wrote:
> After importing random, there is no need to call random.seed() in a
> python program, is there? (unless one wishes to specifically control
> what the seed is.)

Right.

Kent

From mc_anjo at tamu.edu  Sun Mar 25 05:23:06 2007
From: mc_anjo at tamu.edu (Chris Smith)
Date: Sat, 24 Mar 2007 22:23:06 -0500
Subject: [Tutor] Pmw BLT help
Message-ID: <eu4puq$ubm$1@sea.gmane.org>

I'm trying to learn how to use Pmw.BLT to have plotting in some GUIs I 
would like to create. I have a book with some examples but when I run 
the code I get this error message which seems to be related to the 
packages I installed and not my code:

Traceback (most recent call last):
   File "C:\Documents and Settings\Chris & Esther\My 
Documents\Python\Books&relatedcode\Python4ComputationalScience\src\py\gui\plotdemo_blt.py", 
line 105, in ?
     blt = BltDemo1(root)
   File "C:\Documents and Settings\Chris & Esther\My 
Documents\Python\Books&relatedcode\Python4ComputationalScience\src\py\gui\plotdemo_blt.py", 
line 16, in __init__
     self.vector_x = Pmw.Blt.Vector()
   File "C:\Python24\lib\site-packages\Pmw\Pmw_1_2\lib\PmwBlt.py", line 
99, in __init__
     self.tk.call(_vectorCommand, 'create', self._name)
TclError: invalid command name "::blt::vector"

I've read over the installation instructions and even reinstalled the 
software and that didn't help any. Could anyone help me out?

C. Smith


From alan.gauld at btinternet.com  Sun Mar 25 10:50:47 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 25 Mar 2007 09:50:47 +0100
Subject: [Tutor] nube question...
References: <4604AF20.10709@forethought.net>
Message-ID: <eu5d59$fvt$1@sea.gmane.org>

"Lurch" <erik.kloeppel at forethought.net> wrote

> the nuts,bolts, and the occasional nail.  Now Im trying to code a 
> simple
> status window to let the dumb user (me) know what's going on behind 
> the
> curtain.  The idea is, the application calls the subroutine, the
> subroutine pops open a frame and print some text in it, then returns
> control back to the  main app - leaving the frame/text visible. 
> Then,
> the app calls the subroutine and *updates* the frame, so you end up 
> with
> a growing list of notices...(basically, I'm working with a variable 
> set
> of files, and it's convenient to know which is being operated on)

> I've ripped code from Mark Lutz's book (3rd edition), from Welch's 
> book
> (also 3rd edition), and from around the net.

One of the problems with ripping code from books is that you
often wind up with a strange mix of styles without really
understanding any of it. And I think that's happening here.

Do you actually understand how this program is supposed to work?
Can you explain why the MESSAGES class definition is inside
the messages() function?
Do you know what sequence of events leads to your window
being created and where the reference to the window is held?

It would be better to structure your Tkinter app in a more
conventional manner - have you read the online Tkinter
tutorial/reference pages?

The reason I ask is that your code calls messages() every time
is goes round the loopp, but messages() only defines the
MESSAGES class, it doesn't do anything with it. Why are
you doing that?

I also don't understand why you are using a dictionary
as a counter? Why not just use a simple variable to hold
the number and avoid all the x[1] stuff?

If you trace what happens when you run this program:
It creates a MESSAGES instance and then calls mainloop.
But you don't hold a refernce to the object nor do you have
any useful event handlers defined in the GUI.
It then processes (standard) events. When the mainloop exits
it then goes on to call your loop() function which creates the
class definition and prints 'howdee' multiple times. It doesn't
make sense! (to me!)

I suggest you sit down, work out what you actually want
to happen and design the straucture of your code to do that.
That means thinking in terms of events and messages.
You see to be trying to mix a non event-driven model
(your loop() function) and an event driven model - your GUI.
That's not a good idea. You need to rethink what you are doing
so that you crewate the GUI then launch your processing
from a GUI event. You can then update the GUI from your
code. If your processing takes a long time as implied in the
message you will either want to put your code in a thread
(see an earlier thread last week) or break it into chunks
controlled by the GUI - maybe via timers.

> missing something obvious when it comes to self.update.  The 
> subroutine
> works as advertised the first time through, but one the window is 
> open
> and the text displays, the app stops - unless I close the window. 
> Of
> course, then everything works until the NEXT message is displayed.

I don't understand this either. What NEXT message?
There is no reference to NEXT in your code? Also your code
prints to the console but also displays a GUI window, which
window are you referring to? The GUI or the console?

As to self.update - you only call that once when you create
the instance. Do you understand OOP and how objects are
created? The difference between classes and instances?

> Sure, I could add a button and work from that, but I don't *WANT* 
> to -
> the idea is a (more or less) continuous flow of information that I 
> can
> scroll through if need be.

Thats not a problem, you don;t need a button but you do need
to reestructure your code so that your function runs (probably
as a thread) within the GUI mainloop().

> As you can see from the sample code below, I'm using the Text widget
> instead of Message.  I had a reason for that when I started this
> nightmare, but I'm not wedded to it.

Text is probably the right thing to use for what you want.

> Any assistance from anybody would be much appreciated.

I'd start again.
First write a GUI class that just contains the Text widget - forget
about scroll bars for now. Then write a method within that class
that does the looping - your loop() function effectively, and call
that at the end of the init(). Instead of printing make the loop
insert text into the TEXT widget.

That should result in a program that does what you want but
doesn't have scroll bars and is totally unresponsive until the
loop finishes. The next tricxk is to make your methoid run in
a thread, but get the basics working first. It should be a really
short program, maybe 10-15 lines.

HTH,


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

> -----------------------
> from Tkinter import *
>
> data={}
> data[4,9]="you are here"
> data[4,10]=0
> msg=1
> x={}
>
> def loop():
>    global x
>    x[1]=0
>    while x[1]<10:
>        messages(x)
>        print "howdee"
>        x[1]=x[1]+1
>
> def messages(msg):
>    class MESSAGES(Frame):
>        def __init__(self,parent=None,text='', file=None):
>            Frame.__init__(self,parent)
>            self.pack(expand=YES,fill=BOTH)
>            self.makewidgets()
>            self.message(text)
>            self.update()
>
>        def makewidgets(self):
>            sbar=Scrollbar(self)
>            a=Text(self,relief=RAISED)
>            sbar.config(command=a.yview,bg='#fcfcfc')
>            a.config(yscrollcommand=sbar.set,bg='#f0f0f0')
>            sbar.pack(side=RIGHT,fill=Y)
>            a.pack(side=LEFT,expand=YES,fill=BOTH)
>            self.a=a
>            data[4,10]=1
>
>        def message(self,text):
>            self.a.insert(END,text)
>            self.a.focus()
>            return self.a.get('35.2',END+'-1c')
>
>    if __name__=='__main__':
>        root=Tk()
>        MESSAGES(text=data[4,9]).mainloop()
>        return
>
> loop()
>



From alan.gauld at btinternet.com  Sun Mar 25 11:37:26 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 25 Mar 2007 10:37:26 +0100
Subject: [Tutor] Pmw BLT help
References: <eu4puq$ubm$1@sea.gmane.org>
Message-ID: <eu5fsn$mi2$1@sea.gmane.org>


"Chris Smith" <mc_anjo at tamu.edu> wrote

> I'm trying to learn how to use Pmw.BLT

> line 16, in __init__
>     self.vector_x = Pmw.Blt.Vector()
>   File "C:\Python24\lib\site-packages\Pmw\Pmw_1_2\lib\PmwBlt.py", 
> line
> 99, in __init__
>     self.tk.call(_vectorCommand, 'create', self._name)
> TclError: invalid command name "::blt::vector"
>
> I've read over the installation instructions and even reinstalled 
> the
> software and that didn't help any. Could anyone help me out?

I don't use PMW but its saying there is no such command as Vector.
Are you sure PMW is installed OK? Have you got any of the
other commands to work? Is the case OK?

Just some ideas,

Alan G.




From jmutter at uakron.edu  Sun Mar 25 13:47:11 2007
From: jmutter at uakron.edu (Jay Mutter III)
Date: Sun, 25 Mar 2007 07:47:11 -0400
Subject: [Tutor] Tutor Digest, Vol 37, Issue 63
In-Reply-To: <mailman.18441.1174812666.32030.tutor@python.org>
References: <mailman.18441.1174812666.32030.tutor@python.org>
Message-ID: <6F465922-16DD-45AA-8438-E3883C5A79B9@uakron.edu>

>
> Message: 1
> Date: Sat, 24 Mar 2007 16:41:22 -0700 (PDT)
> From: Jaggo <jaggojaggo at yahoo.com>
> Subject: Re: [Tutor] Tutor Digest, Vol 37, Issue 62
> To: tutor at python.org
> Message-ID: <20070324234122.86838.qmail at web52504.mail.re2.yahoo.com>
> Content-Type: text/plain; charset="iso-8859-1"
>
> Message: 2
> Date: Sat, 24 Mar 2007 19:25:10 -0400
> From: Jay Mutter III
> Subject: [Tutor] parsing text
> [...]
> 1.) when i do readlines and create a list and then print the list it
> adds a blank line between every line of text
> [...]
> ideas?
>
> Thanks again
>
> jay
> Well,
> regarding your first question:
> "print string" automatically breaks a line at the end of string.  
> Use "print string," instead [note that trailin' , .]
>

yes, thank you for that


> [I'm not sure about your n. 2, that's why no answer is included.
>
>
> ---------------------------------
> TV dinner still cooling?
> Check out "Tonight's Picks" on Yahoo! TV.
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL: http://mail.python.org/pipermail/tutor/attachments/ 
> 20070324/2d731ac8/attachment-0001.htm
>
> ------------------------------
>
> Message: 2
> Date: Sun, 25 Mar 2007 00:00:29 -0000
> From: "Alan Gauld" <alan.gauld at btinternet.com>
> Subject: Re: [Tutor] parsing text
> To: tutor at python.org
> Message-ID: <eu4e2v$o5h$1 at sea.gmane.org>
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
> 	reply-type=original
>
> "Jay Mutter III" <jmutter at uakron.edu> wrote
>
>> i have the following text:
>>
>> Barnett, John B., assignor of one-half to R. N. Tutt, Kansas City,
>> Mo.    Automatic display-sign.    No. 1,330 411-Apr. 13 ; v. 273 ;
>> p.
>> 193.
>> Barnett,  John  II..  Tettenhall,  England.     Seat  of
>> motorcars.    No. 1.353,708; Sept. 21 ; v. 278; p. 487. Barnett,
>> Otto
>> R.    (See Scott, John M., assignor.)
>>
>> 1.) when i do readlines and create a list and then print the list it
>> adds a blank line between every line of text
>
> I suspect that's because you are reading a newline character
> from the file and print adds a newline of its own. You need to
> use rstrip() to take out the newline from the file.
>
>> 2.)in the second line after p.487 there is the beginning of a new
>> line of data only it isn't on a newline.
>
> I'm not quite sure what you mean here.
> It would be helpful if you can show us the problematic output
> as well as the input. Also to send us the actual code fragments
> that are causing the damage.

Yes after i received the reply i realized that i was not very clear.
i have a text file of inventors which should have one inventor on  
each line in alphabetical order but of course the lines
do not break at the end of 'p. xxx.'  (where p.xxx is the relevant  
page number)

I read the data in as a string figuring that I could then replace p.  
xxx with a carriage return, somehow write the data out to a text file
and the problem would be solved. Not quite so simple given my limited  
skill set.
The following is what I put in (interactively) and what I got out.

 >>> ss = open('inp.txt')
 >>> s = ss.read()
 >>> s.replace('p. ','\n')
'Barnett, John B., assignor of one-half to R. N. Tutt, Kansas City,  
Mo. Automatic display-sign.\xc2\xa0 \xc2\xa0 No. 1,330 411-Apr. 13 ;  
v. 273 ;\xc2\xa0\n\n193. Barnett,\xc2\xa0 John\xc2\xa0 II..\xc2\xa0  
Tettenhall,\xc2\xa0 England. \xc2\xa0 \xc2\xa0 Seat\xc2\xa0 of 
\nmotorcars.\xc2\xa0 \xc2\xa0 No. 1.353,708; Sept. 21 ; v. 278;  
\n487. Barnett,\xc2\xa0\nOtto R.\xc2\xa0 \xc2\xa0 (See Scott, John  
M., assignor.)'
 >>>

I though about treating it as a list of lines, stripping carriage  
returns on the basis of some criteria but i have never gotten rstrip  
to work



>
>> i tried string.replace(s,'p.','\n') in an attempt to put a CR in but
>> it just put the characters\n in the string.
>
> Dont use the string module functions. Use the string methods,
> so it becomes:
>
> s.replace('p.', '\n')
>
> However that doesn't explain why you are getting the literal
> characters! Can you send us the actual code you are using?
> And the output showing the error?
>
> HTH,
>
> Alan G.
>
>
>
>
> ------------------------------
>
> Message: 3
> Date: Sat, 24 Mar 2007 19:32:36 -0500
> From: "Cecilia Alm" <ebbaalm at uiuc.edu>
> Subject: [Tutor] No need to seed random?
> To: tutor at python.org
> Message-ID:
> 	<7a4620dc0703241732m355f23d3m26cfcbe2a06dfad5 at mail.gmail.com>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> After importing random, there is no need to call random.seed() in a
> python program, is there? (unless one wishes to specifically control
> what the seed is.)
>
> Thanks!
>
>
> ------------------------------
>
> Message: 4
> Date: Fri, 23 Mar 2007 22:54:56 -0600
> From: Lurch <erik.kloeppel at forethought.net>
> Subject: [Tutor] nube question...
> To: tutor at python.org
> Message-ID: <4604AF20.10709 at forethought.net>
> Content-Type: text/plain; charset="iso-8859-1"
>
> Gentlemen,
>
> I don't consider myself a rank beginner (I did take a shower this  
> week),
> but I've been beating my brains out over this for the past week.
>
> I'm writing this GUI app (Tkinter).  Just about everything is done  
> (all
> the nuts,bolts, and the occasional nail.  Now Im trying to code a  
> simple
> status window to let the dumb user (me) know what's going on behind  
> the
> curtain.  The idea is, the application calls the subroutine, the
> subroutine pops open a frame and print some text in it, then returns
> control back to the  main app - leaving the frame/text visible.  Then,
> the app calls the subroutine and *updates* the frame, so you end up  
> with
> a growing list of notices...(basically, I'm working with a variable  
> set
> of files, and it's convenient to know which is being operated on)
>
> I've ripped code from Mark Lutz's book (3rd edition), from Welch's  
> book
> (also 3rd edition), and from around the net. It seems to me that I'm
> missing something obvious when it comes to self.update.  The  
> subroutine
> works as advertised the first time through, but one the window is open
> and the text displays, the app stops - unless I close the window.  Of
> course, then everything works until the NEXT message is displayed.
>
> Sure, I could add a button and work from that, but I don't *WANT* to -
> the idea is a (more or less) continuous flow of information that I can
> scroll through if need be.
>
> As you can see from the sample code below, I'm using the Text widget
> instead of Message.  I had a reason for that when I started this
> nightmare, but I'm not wedded to it.
>
> Any assistance from anybody would be much appreciated.
>
> Thanks in advance!
>
> Erik
>
> -----------------------
>
> from Tkinter import *
>
> data={}
> data[4,9]="you are here"
> data[4,10]=0
> msg=1
> x={}
>
> def loop():
>     global x
>     x[1]=0
>     while x[1]<10:
>         messages(x)
>         print "howdee"
>         x[1]=x[1]+1
>
> def messages(msg):
>     class MESSAGES(Frame):
>         def __init__(self,parent=None,text='', file=None):
>             Frame.__init__(self,parent)
>             self.pack(expand=YES,fill=BOTH)
>             self.makewidgets()
>             self.message(text)
>             self.update()
>
>         def makewidgets(self):
>             sbar=Scrollbar(self)
>             a=Text(self,relief=RAISED)
>             sbar.config(command=a.yview,bg='#fcfcfc')
>             a.config(yscrollcommand=sbar.set,bg='#f0f0f0')
>             sbar.pack(side=RIGHT,fill=Y)
>             a.pack(side=LEFT,expand=YES,fill=BOTH)
>             self.a=a
>             data[4,10]=1
>
>         def message(self,text):
>             self.a.insert(END,text)
>             self.a.focus()
>             return self.a.get('35.2',END+'-1c')
>
>     if __name__=='__main__':
>         root=Tk()
>         MESSAGES(text=data[4,9]).mainloop()
>         return
>
> loop()
>
> I've tried this small mod, just now, but it *really* breaks things the
> second time through:
>
>
>     class MESSAGES(Frame):
>         def __init__(self,parent=None,text='', file=None):
>             Frame.__init__(self,parent)
>             self.pack(expand=YES,fill=BOTH)
>             if data[4,10]==0:
>                 self.makewidgets()
>             self.message(text)
>             self.update
>
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL: http://mail.python.org/pipermail/tutor/attachments/ 
> 20070323/0c786de6/attachment.html
>
> ------------------------------
>
> Message: 5
> Date: Sat, 24 Mar 2007 22:26:33 -0400
> From: Kent Johnson <kent37 at tds.net>
> Subject: Re: [Tutor] parsing text
> Cc: tutor at python.org
> Message-ID: <4605DDD9.8010808 at tds.net>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> Alan Gauld wrote:
>
>>> 1.) when i do readlines and create a list and then print the list it
>>> adds a blank line between every line of text
>>
>> I suspect that's because you are reading a newline character
>> from the file and print adds a newline of its own. You need to
>> use rstrip() to take out the newline from the file.
>
> or use sys.stdout.write() instead of print, it doesn't add a newline.
>
> Kent
>
>
> ------------------------------
>
> Message: 6
> Date: Sat, 24 Mar 2007 22:32:32 -0400
> From: Kent Johnson <kent37 at tds.net>
> Subject: Re: [Tutor] No need to seed random?
> To: Cecilia Alm <ebbaalm at uiuc.edu>
> Cc: tutor at python.org
> Message-ID: <4605DF40.3090007 at tds.net>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> Cecilia Alm wrote:
>> After importing random, there is no need to call random.seed() in a
>> python program, is there? (unless one wishes to specifically control
>> what the seed is.)
>
> Right.
>
> Kent
>
>
> ------------------------------
>
> Message: 7
> Date: Sat, 24 Mar 2007 22:23:06 -0500
> From: Chris Smith <mc_anjo at tamu.edu>
> Subject: [Tutor] Pmw BLT help
> To: tutor at python.org
> Message-ID: <eu4puq$ubm$1 at sea.gmane.org>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> I'm trying to learn how to use Pmw.BLT to have plotting in some GUIs I
> would like to create. I have a book with some examples but when I run
> the code I get this error message which seems to be related to the
> packages I installed and not my code:
>
> Traceback (most recent call last):
>    File "C:\Documents and Settings\Chris & Esther\My
> Documents\Python\Books&relatedcode\Python4ComputationalScience\src 
> \py\gui\plotdemo_blt.py",
> line 105, in ?
>      blt = BltDemo1(root)
>    File "C:\Documents and Settings\Chris & Esther\My
> Documents\Python\Books&relatedcode\Python4ComputationalScience\src 
> \py\gui\plotdemo_blt.py",
> line 16, in __init__
>      self.vector_x = Pmw.Blt.Vector()
>    File "C:\Python24\lib\site-packages\Pmw\Pmw_1_2\lib\PmwBlt.py",  
> line
> 99, in __init__
>      self.tk.call(_vectorCommand, 'create', self._name)
> TclError: invalid command name "::blt::vector"
>
> I've read over the installation instructions and even reinstalled the
> software and that didn't help any. Could anyone help me out?
>
> C. Smith
>
>
>
> ------------------------------
>
> Message: 8
> Date: Sun, 25 Mar 2007 09:50:47 +0100
> From: "Alan Gauld" <alan.gauld at btinternet.com>
> Subject: Re: [Tutor] nube question...
> To: tutor at python.org
> Message-ID: <eu5d59$fvt$1 at sea.gmane.org>
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
> 	reply-type=original
>
> "Lurch" <erik.kloeppel at forethought.net> wrote
>
>> the nuts,bolts, and the occasional nail.  Now Im trying to code a
>> simple
>> status window to let the dumb user (me) know what's going on behind
>> the
>> curtain.  The idea is, the application calls the subroutine, the
>> subroutine pops open a frame and print some text in it, then returns
>> control back to the  main app - leaving the frame/text visible.
>> Then,
>> the app calls the subroutine and *updates* the frame, so you end up
>> with
>> a growing list of notices...(basically, I'm working with a variable
>> set
>> of files, and it's convenient to know which is being operated on)
>
>> I've ripped code from Mark Lutz's book (3rd edition), from Welch's
>> book
>> (also 3rd edition), and from around the net.
>
> One of the problems with ripping code from books is that you
> often wind up with a strange mix of styles without really
> understanding any of it. And I think that's happening here.
>
> Do you actually understand how this program is supposed to work?
> Can you explain why the MESSAGES class definition is inside
> the messages() function?
> Do you know what sequence of events leads to your window
> being created and where the reference to the window is held?
>
> It would be better to structure your Tkinter app in a more
> conventional manner - have you read the online Tkinter
> tutorial/reference pages?
>
> The reason I ask is that your code calls messages() every time
> is goes round the loopp, but messages() only defines the
> MESSAGES class, it doesn't do anything with it. Why are
> you doing that?
>
> I also don't understand why you are using a dictionary
> as a counter? Why not just use a simple variable to hold
> the number and avoid all the x[1] stuff?
>
> If you trace what happens when you run this program:
> It creates a MESSAGES instance and then calls mainloop.
> But you don't hold a refernce to the object nor do you have
> any useful event handlers defined in the GUI.
> It then processes (standard) events. When the mainloop exits
> it then goes on to call your loop() function which creates the
> class definition and prints 'howdee' multiple times. It doesn't
> make sense! (to me!)
>
> I suggest you sit down, work out what you actually want
> to happen and design the straucture of your code to do that.
> That means thinking in terms of events and messages.
> You see to be trying to mix a non event-driven model
> (your loop() function) and an event driven model - your GUI.
> That's not a good idea. You need to rethink what you are doing
> so that you crewate the GUI then launch your processing
> from a GUI event. You can then update the GUI from your
> code. If your processing takes a long time as implied in the
> message you will either want to put your code in a thread
> (see an earlier thread last week) or break it into chunks
> controlled by the GUI - maybe via timers.
>
>> missing something obvious when it comes to self.update.  The
>> subroutine
>> works as advertised the first time through, but one the window is
>> open
>> and the text displays, the app stops - unless I close the window.
>> Of
>> course, then everything works until the NEXT message is displayed.
>
> I don't understand this either. What NEXT message?
> There is no reference to NEXT in your code? Also your code
> prints to the console but also displays a GUI window, which
> window are you referring to? The GUI or the console?
>
> As to self.update - you only call that once when you create
> the instance. Do you understand OOP and how objects are
> created? The difference between classes and instances?
>
>> Sure, I could add a button and work from that, but I don't *WANT*
>> to -
>> the idea is a (more or less) continuous flow of information that I
>> can
>> scroll through if need be.
>
> Thats not a problem, you don;t need a button but you do need
> to reestructure your code so that your function runs (probably
> as a thread) within the GUI mainloop().
>
>> As you can see from the sample code below, I'm using the Text widget
>> instead of Message.  I had a reason for that when I started this
>> nightmare, but I'm not wedded to it.
>
> Text is probably the right thing to use for what you want.
>
>> Any assistance from anybody would be much appreciated.
>
> I'd start again.
> First write a GUI class that just contains the Text widget - forget
> about scroll bars for now. Then write a method within that class
> that does the looping - your loop() function effectively, and call
> that at the end of the init(). Instead of printing make the loop
> insert text into the TEXT widget.
>
> That should result in a program that does what you want but
> doesn't have scroll bars and is totally unresponsive until the
> loop finishes. The next tricxk is to make your methoid run in
> a thread, but get the basics working first. It should be a really
> short program, maybe 10-15 lines.
>
> HTH,
>
>
> -- 
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>> -----------------------
>> from Tkinter import *
>>
>> data={}
>> data[4,9]="you are here"
>> data[4,10]=0
>> msg=1
>> x={}
>>
>> def loop():
>>    global x
>>    x[1]=0
>>    while x[1]<10:
>>        messages(x)
>>        print "howdee"
>>        x[1]=x[1]+1
>>
>> def messages(msg):
>>    class MESSAGES(Frame):
>>        def __init__(self,parent=None,text='', file=None):
>>            Frame.__init__(self,parent)
>>            self.pack(expand=YES,fill=BOTH)
>>            self.makewidgets()
>>            self.message(text)
>>            self.update()
>>
>>        def makewidgets(self):
>>            sbar=Scrollbar(self)
>>            a=Text(self,relief=RAISED)
>>            sbar.config(command=a.yview,bg='#fcfcfc')
>>            a.config(yscrollcommand=sbar.set,bg='#f0f0f0')
>>            sbar.pack(side=RIGHT,fill=Y)
>>            a.pack(side=LEFT,expand=YES,fill=BOTH)
>>            self.a=a
>>            data[4,10]=1
>>
>>        def message(self,text):
>>            self.a.insert(END,text)
>>            self.a.focus()
>>            return self.a.get('35.2',END+'-1c')
>>
>>    if __name__=='__main__':
>>        root=Tk()
>>        MESSAGES(text=data[4,9]).mainloop()
>>        return
>>
>> loop()
>>
>
>
>
>
> ------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
> End of Tutor Digest, Vol 37, Issue 63
> *************************************


From rikard.bosnjakovic at gmail.com  Sun Mar 25 14:05:17 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Sun, 25 Mar 2007 14:05:17 +0200
Subject: [Tutor] Tutor Digest, Vol 37, Issue 63
In-Reply-To: <6F465922-16DD-45AA-8438-E3883C5A79B9@uakron.edu>
References: <mailman.18441.1174812666.32030.tutor@python.org>
	<6F465922-16DD-45AA-8438-E3883C5A79B9@uakron.edu>
Message-ID: <d9e88eaf0703250505u5e7fbddbr553c24869ec3b704@mail.gmail.com>

On 3/25/07, Jay Mutter III <jmutter at uakron.edu> wrote:

[snip huge post]

92% of the lines in your post contained quotes from earlier posts.
Please try to reduce the amount of quoted lines.


-- 
- Rikard.

From utkarsh.tandon at gmail.com  Sun Mar 25 15:49:05 2007
From: utkarsh.tandon at gmail.com (Utkarsh Tandon)
Date: Sun, 25 Mar 2007 19:19:05 +0530
Subject: [Tutor] Some Strange Behavior
Message-ID: <32a80def0703250649x40a4fecfkc221d2e3d3fe2458@mail.gmail.com>

Umm, hey everyone

I'm a newbie to the world of programming. The best way to learn anything is
to do it. So I was just trying to make a program
that removed comments from a C program. The program worked but a whitespace
came after every character. Can anyone please tell me the reason for thw
whitespace.


Here is C code I was editing :-
/* Comments............. */
/* Some more comments........ */

main()
    {
    printf("/* Hello, World! */");
    /* Some more comments .......................... */
    }



Here is the program
def main(filename):
    text = open(str(filename), 'r')
    realtext = text.read()
    realtext = list(realtext)
    length = len(realtext)
    string = False


    for i in range (0, length):

        try:


            if realtext[i] == '/' and realtext[i + 1] == '*':


                del realtext[i]
                del realtext[i]


                while realtext[i] != '*' and realtext[i+1] != '/':
                    del realtext[i]

                del realtext[i]
                del realtext[i]




        except IndexError:
            break

    filename = str(raw_input('Enter the name of the new file '))

    file = open(str(filename), 'w')
    realtext = str(realtext)

    realtext = realtext.replace('[', "").replace(']', "").replace(',',
"").replace("'", "").replace('\\n', "").replace('\\t', "")
    file.write(realtext)

main(str(raw_input('Enter the filename ')))

Here is it's output, notice the unnecesary whitespace after every
character:-
   m a i n ( )   {   p r i n t f ( " " ) ;     }
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070325/087499a9/attachment.htm 

From rikard.bosnjakovic at gmail.com  Sun Mar 25 16:39:12 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Sun, 25 Mar 2007 16:39:12 +0200
Subject: [Tutor] Some Strange Behavior
In-Reply-To: <32a80def0703250649x40a4fecfkc221d2e3d3fe2458@mail.gmail.com>
References: <32a80def0703250649x40a4fecfkc221d2e3d3fe2458@mail.gmail.com>
Message-ID: <d9e88eaf0703250739p15b5cebg3da32809faa6db69@mail.gmail.com>

On 3/25/07, Utkarsh Tandon <utkarsh.tandon at gmail.com> wrote:

>     realtext = str(realtext)

Here's the problem. Use this instead:

   realtext = "".join(realtext)

>     realtext = realtext.replace('[', "").replace(']', "").replace(',',
> "").replace("'", "").replace('\\n', "").replace('\\t', "")

And delete this one.


-- 
- Rikard - http://bos.hack.org/cv/

From alan.gauld at btinternet.com  Sun Mar 25 17:16:23 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 25 Mar 2007 16:16:23 +0100
Subject: [Tutor] Some Strange Behavior
References: <32a80def0703250649x40a4fecfkc221d2e3d3fe2458@mail.gmail.com>
Message-ID: <eu63o8$rkr$1@sea.gmane.org>

"Utkarsh Tandon" <utkarsh.tandon at gmail.com> wrote

> So I was just trying to make a program that removed
> comments from a C program.
> The program worked but a whitespace came after every
> character. Can anyone please tell me the reason for thw
> whitespace.

See comments below.

But a general observation first.
It is possible to write C code in Python, but its not very effective.
In the same way you wouldn't use low level assembler features
to write to the screen in C but rather use printf or puts so in
Python there are lots of high level functions and libraries that
you can use to do the job more effectively.

But as a learning excercise, heh, its ok...

> Here is the program

> def main(filename):
>    text = open(str(filename), 'r')

You don;t need to convert it to a string, hopefully it already is
and if not converting anything else is always going to be risky.
Better to wrap the open() in a try/except and catch the error
if the name isn't valid.

>    realtext = text.read()
>    realtext = list(realtext)
>    length = len(realtext)

this converts the contents of the file into a list of characters.
But there's no need to do that. Pythons for and len will work
just as well on strings. Strings are just another type of
sequence to Python. You need to do it because of the
way you are deleting the characters but that's an extremely
non Pythonic way of doing things.

>    string = False

??? This doesn't do anything ???

>    for i in range (0, length):
>        try:
>            if realtext[i] == '/' and realtext[i + 1] == '*':
>                del realtext[i]
>                del realtext[i]
>
>                while realtext[i] != '*' and realtext[i+1] != '/':
>                    del realtext[i]

note that you never increment i here so you are relying
on Python shuffling up the list elements. That isn't guaranteed
behaviour, although I suspect it works at least in the standard
Python implementations.

>
>                del realtext[i]
>                del realtext[i]

you can delete slices in Python so you could do this in one statement.

>        except IndexError:
>            break

>    filename = str(raw_input('Enter the name of the new file '))
>
>    file = open(str(filename), 'w')
>    realtext = str(realtext)

You are trying to turn the list of chars back to a string but in
fact you get a string representation of the list - including [] and
commas etc. (Try it at the >>> prompt!)

You need to look at the string join() method.

>    realtext = realtext.replace('[', "").replace(']', 
> "").replace(',',
> "").replace("'", "").replace('\\n', "").replace('\\t', "")

Eek! Now you try to force the list into the right shape...
But you forgot to replace the spaces after the commas I think...

>    file.write(realtext)
>
> main(str(raw_input('Enter the filename ')))

You definitely don't need str here since raw_input always
returns a string.

> Here is it's output, notice the unnecesary whitespace after every
> character:-
>   m a i n ( )   {   p r i n t f ( " " ) ;     }

Thats a very long winded and difficult way to do a fairly simple
Python task. Don't try to write Python like a C programmer.

FWIW Here is my attempt to do what you want using broadly
the same technoque but in a somewhat more pyhonic style:

#####################
fname = raw_input('Whats the C file name? ')
code = open(fname).read()

result = ''
inComment = False
i = 0
while i < len(code):
    if inComment:
        if code[i:i+2] == '*/':
           inComment = False
           i += 1
    elif code[i:i+2] == '/*':
       inComment = True
       i += 1
    else:
       result = result + code[i]
    i += 1

print result # write to an output file if you prefer...
################

There seems to be a slight bug with multiline comments...
But I didn't test it extensively.

HTH, However in practice I'd probably use regular expressions
to solve this particular problem...

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



From mc_anjo at tamu.edu  Sun Mar 25 17:24:26 2007
From: mc_anjo at tamu.edu (Chris Smith)
Date: Sun, 25 Mar 2007 10:24:26 -0500
Subject: [Tutor] Pmw BLT help
In-Reply-To: <eu5fsn$mi2$1@sea.gmane.org>
References: <eu4puq$ubm$1@sea.gmane.org> <eu5fsn$mi2$1@sea.gmane.org>
Message-ID: <eu647a$sum$1@sea.gmane.org>

Alan Gauld wrote:
> "Chris Smith" <mc_anjo at tamu.edu> wrote
> 
> 
>>I'm trying to learn how to use Pmw.BLT
> 
> 
>>line 16, in __init__
>>    self.vector_x = Pmw.Blt.Vector()
>>  File "C:\Python24\lib\site-packages\Pmw\Pmw_1_2\lib\PmwBlt.py", 
>>line
>>99, in __init__
>>    self.tk.call(_vectorCommand, 'create', self._name)
>>TclError: invalid command name "::blt::vector"
>>
>>I've read over the installation instructions and even reinstalled 
>>the
>>software and that didn't help any. Could anyone help me out?
> 
> 
> I don't use PMW but its saying there is no such command as Vector.
> Are you sure PMW is installed OK? Have you got any of the
> other commands to work? Is the case OK?
> 
> Just some ideas,
> 
> Alan G.
I know I've installed Pmw ok since all I do for installation is unpack 
it and put in into the site-packages folder in the python installation. 
I think the problem is when Pmw is trying to reference BLT which is 
supposed to be installed with Tcl (it's an extension of some kind), but 
I can't find any BLT troubleshooting help.

C. Smith


From alan.gauld at btinternet.com  Sun Mar 25 17:27:29 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 25 Mar 2007 16:27:29 +0100
Subject: [Tutor] Tutor Digest, Vol 37, Issue 63
References: <mailman.18441.1174812666.32030.tutor@python.org>
	<6F465922-16DD-45AA-8438-E3883C5A79B9@uakron.edu>
Message-ID: <eu64d2$te7$1@sea.gmane.org>


"Jay Mutter III" <jmutter at uakron.edu> wrote

> The following is what I put in (interactively) and what I got out.
>
> >>> ss = open('inp.txt')
> >>> s = ss.read()
> >>> s.replace('p. ','\n')
> 'Barnett, John B., assignor of one-half to R. N. Tutt, Kansas City,
> Mo. Automatic display-sign.\xc2\xa0 \xc2\xa0 No. 1,330 411-Apr. 13 ;
> v. 273 ;\xc2\xa0\n\n193. Barnett,\xc2\xa0 John\xc2\xa0 II..\xc2\xa0

Try using print s.replace()

You are getting caught with the difference between repr() and str()
Python uses repr when evaluating an expression at the >>> prompt
but uses str() when using print. Try:

>>> print 'here are lines\nof text'
>>> repr ('here are lines\nof text')

> I though about treating it as a list of lines, stripping carriage
> returns on the basis of some criteria but i have never gotten rstrip
> to work

Strange, what happens? rstrip() is pretty simple!

HTH,

Alan G 



From alan.gauld at btinternet.com  Sun Mar 25 21:06:55 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 25 Mar 2007 20:06:55 +0100
Subject: [Tutor] Pmw BLT help
References: <eu4puq$ubm$1@sea.gmane.org> <eu5fsn$mi2$1@sea.gmane.org>
	<eu647a$sum$1@sea.gmane.org>
Message-ID: <eu6h8g$65e$1@sea.gmane.org>


"Chris Smith" <mc_anjo at tamu.edu> wrote

>>>I'm trying to learn how to use Pmw.BLT
> I know I've installed Pmw ok since all I do for installation is 
> unpack
> it and put in into the site-packages folder in the python 
> installation.

I admire your optimism! :-)
Have you actually proved it by getting some of the basics to work?

> I think the problem is when Pmw is trying to reference BLT which is
> supposed to be installed with Tcl (it's an extension of some kind),

Ah! It's that BLT, I didn't know there was a Python port.

The home page of the tcl project is supposed to be:

www.tcltk.com/blt.

According to my Tcl in a Nushell book.

Its an extension that you have to install on top of tcl.
You may have to do that before using it from PMW.

There may be a forum of some sort there that can help.

Alan G.




From rkreuzhuber at hotmail.com  Mon Mar 26 15:00:24 2007
From: rkreuzhuber at hotmail.com (Roman Kreuzhuber)
Date: Mon, 26 Mar 2007 15:00:24 +0200
Subject: [Tutor] Unicode in List Object
Message-ID: <BAY144-F36EE4DC6FE4D148154FF5FA66F0@phx.gbl>

Hello!
I need some help:
I want to store multiple inputs from text fields in a list-object, which 
works as a very small databank. The problem is that this data will contain 
unicode characters as i live in a german-speaking country. I've searched 
through the internet for days but without any success, so I hope that you 
can help me!
Just for the beginning it would be nice if someone had a short code-snippet 
which converts the character to a storeable one, or if this is impossible, 
which makes the list-object hold unicode-data.
thanks in advance
roman

_________________________________________________________________
Sie m?chten Teil der Evolution der Kommunikation werden? 
http://www.communicationevolved.com/de-at/


From mail at timgolden.me.uk  Mon Mar 26 15:38:00 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Mon, 26 Mar 2007 14:38:00 +0100
Subject: [Tutor] Unicode in List Object
In-Reply-To: <BAY144-F36EE4DC6FE4D148154FF5FA66F0@phx.gbl>
References: <BAY144-F36EE4DC6FE4D148154FF5FA66F0@phx.gbl>
Message-ID: <4607CCB8.2000508@timgolden.me.uk>

Roman Kreuzhuber wrote:

> I want to store multiple inputs from text fields in a list-object, which 
> works as a very small databank. The problem is that this data will contain 
> unicode characters 

I'm not sure why you think this is a problem. A Python list can
hold anything, including unicode objects or encoded strings. eg,

['White', u'Wei\u00df', 'Wei\xdf']

This is a list containing an entirely ASCII string,
a unicode object containing a non-ASCII character,
and the same string encoded as iso-8859-1.

Can you post some code which shows what you're trying
to do and how it's failing?

TJG

From rdm at rcblue.com  Mon Mar 26 17:03:19 2007
From: rdm at rcblue.com (Dick Moores)
Date: Mon, 26 Mar 2007 08:03:19 -0700
Subject: [Tutor] 3 recent short essays by Kent Johnson
Message-ID: <20070326150338.7FF701E400B@bag.python.org>

"Python Decorators," "The path module" and "List Comprehensions."
<http://personalpages.tds.net/~kent37/kk/index.html>

Dick Moores


From rkreuzhuber at hotmail.com  Mon Mar 26 17:05:25 2007
From: rkreuzhuber at hotmail.com (Roman Kreuzhuber)
Date: Mon, 26 Mar 2007 17:05:25 +0200
Subject: [Tutor] Unicode in List Object
In-Reply-To: <4607CCB8.2000508@timgolden.me.uk>
Message-ID: <BAY144-F12E6F81C30AD9EA981BFB5A66F0@phx.gbl>

Thanks for the quick response!
I see! Oh I didn't realize that it's not the list which raises an error.
For a test I tried to insert a string containing a unicode character as 
follows:

ListObject = []
ListObject.insert(0,u"M??lasdji")

which raises: "SyntaxError: Non-ASCII character '\xfc' in file C:\python 
proj\lists\main.py on line 48, but no encoding declared; see 
http://www.python.org/peps/pep-0263.html for details"

I then tried:

ListObject = []
ListObject.insert(0,u"M??lasdji".encode('utf-8'))

without success...

So would this error have been raised too if this was an input from a 
GUI-text-object?
I'm sorry for this silly question but I'm more or less completely new to 
python and never encountered similar errors with different languages

roman


>From: Tim Golden <mail at timgolden.me.uk>
>To: Roman Kreuzhuber <rkreuzhuber at hotmail.com>
>CC: tutor at python.org
>Subject: Re: [Tutor] Unicode in List Object
>Date: Mon, 26 Mar 2007 14:38:00 +0100
>
>Roman Kreuzhuber wrote:
>
>>I want to store multiple inputs from text fields in a list-object, which 
>>works as a very small databank. The problem is that this data will contain 
>>unicode characters
>
>I'm not sure why you think this is a problem. A Python list can
>hold anything, including unicode objects or encoded strings. eg,
>
>['White', u'Wei\u00df', 'Wei\xdf']
>
>This is a list containing an entirely ASCII string,
>a unicode object containing a non-ASCII character,
>and the same string encoded as iso-8859-1.
>
>Can you post some code which shows what you're trying
>to do and how it's failing?
>
>TJG

_________________________________________________________________
Sie m?chten Teil der Evolution der Kommunikation werden? 
http://www.communicationevolved.com/de-at/


From andreengels at gmail.com  Mon Mar 26 17:24:15 2007
From: andreengels at gmail.com (Andre Engels)
Date: Mon, 26 Mar 2007 17:24:15 +0200
Subject: [Tutor] Unicode in List Object
In-Reply-To: <BAY144-F12E6F81C30AD9EA981BFB5A66F0@phx.gbl>
References: <4607CCB8.2000508@timgolden.me.uk>
	<BAY144-F12E6F81C30AD9EA981BFB5A66F0@phx.gbl>
Message-ID: <6faf39c90703260824g23989a5bs39540a77b8a3e546@mail.gmail.com>

2007/3/26, Roman Kreuzhuber <rkreuzhuber at hotmail.com>:
>
> Thanks for the quick response!
> I see! Oh I didn't realize that it's not the list which raises an error.
> For a test I tried to insert a string containing a unicode character as
> follows:
>
> ListObject = []
> ListObject.insert(0,u"M??lasdji")
>
> which raises: "SyntaxError: Non-ASCII character '\xfc' in file C:\python
> proj\lists\main.py on line 48, but no encoding declared; see
> http://www.python.org/peps/pep-0263.html for details"


At the top of your Python file, below the line which might be there that
reads

#!/usr/bin/python

but above any other line, add:

# -*- coding: utf-8  -*-

This tells the parser that this file should be read as unicode.

-- 
Andre Engels, andreengels at gmail.com
ICQ: 6260644  --  Skype: a_engels
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070326/31f2449c/attachment.html 

From kent37 at tds.net  Mon Mar 26 17:33:57 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 26 Mar 2007 11:33:57 -0400
Subject: [Tutor] Unicode in List Object
In-Reply-To: <BAY144-F12E6F81C30AD9EA981BFB5A66F0@phx.gbl>
References: <BAY144-F12E6F81C30AD9EA981BFB5A66F0@phx.gbl>
Message-ID: <4607E7E5.4040004@tds.net>

Roman Kreuzhuber wrote:
> Thanks for the quick response!
> I see! Oh I didn't realize that it's not the list which raises an error.
> For a test I tried to insert a string containing a unicode character as 
> follows:
> 
> ListObject = []
> ListObject.insert(0,u"M??lasdji")
> 
> which raises: "SyntaxError: Non-ASCII character '\xfc' in file C:\python 
> proj\lists\main.py on line 48, but no encoding declared; see 
> http://www.python.org/peps/pep-0263.html for details"

Did you look at the link? It's not the easiest reading for a newbie, I 
admit.

Python expects your source file to contain ASCII text unless you tell it 
otherwise. You can tell it what encoding to use with a special comment 
at the top of the file. Try adding
# coding=utf-8

(or whatever the appropriate coding is) to the top of your source file.

> So would this error have been raised too if this was an input from a 
> GUI-text-object?

No, this is a syntax error in your source file.

Kent

From mail at timgolden.me.uk  Mon Mar 26 17:45:18 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Mon, 26 Mar 2007 16:45:18 +0100
Subject: [Tutor] Unicode in List Object
In-Reply-To: <6faf39c90703260824g23989a5bs39540a77b8a3e546@mail.gmail.com>
References: <4607CCB8.2000508@timgolden.me.uk>	<BAY144-F12E6F81C30AD9EA981BFB5A66F0@phx.gbl>
	<6faf39c90703260824g23989a5bs39540a77b8a3e546@mail.gmail.com>
Message-ID: <4607EA8E.6040300@timgolden.me.uk>

Andre Engels wrote:
> 2007/3/26, Roman Kreuzhuber <rkreuzhuber at hotmail.com>:
>>
>> Thanks for the quick response!
>> I see! Oh I didn't realize that it's not the list which raises an error.
>> For a test I tried to insert a string containing a unicode character as
>> follows:
>>
>> ListObject = []
>> ListObject.insert(0,u"M??lasdji")
>>
>> which raises: "SyntaxError: Non-ASCII character '\xfc' in file C:\python
>> proj\lists\main.py on line 48, but no encoding declared; see
>> http://www.python.org/peps/pep-0263.html for details"
> 
> 
> At the top of your Python file, below the line which might be there that
> reads
> 
> #!/usr/bin/python
> 
> but above any other line, add:
> 
> # -*- coding: utf-8  -*-
> 
> This tells the parser that this file should be read as unicode.

Ummm... just to be picky: it tells the parser that the file
was saved (by whatever text editor you use) using the utf-8
encoding and should be converted to unicode on that basis.
Obviously if you use some other encoding, such as iso-8859-1,
it needs to read:

# -*- coding: iso-8859-1  -*-

Roman: there are several Unicode tutorials available for
Python. One recently highlighted was:

   http://boodebr.org/main/python/all-about-python-and-unicode

and there are several listed here:

   http://wiki.python.org/moin/Unicode

TJG

From mail at timgolden.me.uk  Mon Mar 26 18:02:38 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Mon, 26 Mar 2007 17:02:38 +0100
Subject: [Tutor] Unicode in List Object
In-Reply-To: <BAY144-F12E6F81C30AD9EA981BFB5A66F0@phx.gbl>
References: <BAY144-F12E6F81C30AD9EA981BFB5A66F0@phx.gbl>
Message-ID: <4607EE9E.8050302@timgolden.me.uk>

Roman Kreuzhuber wrote:
> Thanks for the quick response!
> I see! Oh I didn't realize that it's not the list which raises an error.
> For a test I tried to insert a string containing a unicode character as 
> follows:
> 
> ListObject = []
> ListObject.insert(0,u"M??lasdji")

By the way, aside from the Unicode-encoding issue, you seem
to be coming from a language background where you have to
declare things. In python, you could do the above as:

l = [u"M??lasdji"]

or, if you have to add several things to the list,
one at a time, say from a text file, you can use
append for the most obvious add-to-end case:

l = []
l.append ("Hello")
l.append ("World")

Obviously, if you do really want to add at the
beginning of the list, you can use insert (0, ...)
as you have, but it might just as good to append
as above, and then to reverse the list, ie:

l = []
l.insert (0, "Hello")
l.insert (0, "World")

is equivalent to:

l = []
l.append ("Hello")
l.append ("World")
l.reverse ()

TJG

From shitizb at yahoo.com  Mon Mar 26 22:46:00 2007
From: shitizb at yahoo.com (Shitiz Bansal)
Date: Mon, 26 Mar 2007 13:46:00 -0700 (PDT)
Subject: [Tutor] Filesystem vs Database vs Lucene
Message-ID: <20070326204600.32881.qmail@web53810.mail.re2.yahoo.com>

Hi,
I need to implement a system which stores Strings(average length 50 chars).
For every input String it would need to tell the user wether that string already exists in the system. It would also need to add that input String to the system if it did not exist. It will also be useful to know the last accessed datetime value of that string.
The number of strings is in millions and i also need persistence so keeping all Strings in memory is not an option.
I was wondering what would be the most efficient(timewise) solution for this riddle.
Would it be wiser to keep these Strings in an indexed column of the DB or would it be better to keep these strings as filenames on the filesystem in a folder hiearchy of some sort. I have no experience of indexers like lucene but i can also consider those if they are a better alternative than the other two.
Please also bear in mind the time required to insert the strings(for eg. i tried using a database but found the insertion time to be very high once i indexed the particular column.
Thanks,
Shitiz

 
---------------------------------
 Get your own web address.
 Have a HUGE year through Yahoo! Small Business.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070326/3fd215d0/attachment.htm 

From chris.arndt at web.de  Mon Mar 26 23:21:31 2007
From: chris.arndt at web.de (Christopher Arndt)
Date: Mon, 26 Mar 2007 23:21:31 +0200
Subject: [Tutor] Filesystem vs Database vs Lucene
In-Reply-To: <20070326204600.32881.qmail@web53810.mail.re2.yahoo.com>
References: <20070326204600.32881.qmail@web53810.mail.re2.yahoo.com>
Message-ID: <4608395B.5090809@web.de>

Shitiz Bansal schrieb:
> I need to implement a system which stores Strings(average length 50 chars).
> I was wondering what would be the most efficient(timewise) solution for
> this riddle.

I'd use pysqlite, a SQL database in a file.

> For every input String it would need to tell the user wether that string
> already exists in the system.

Create the string column as "UNIQUE".

> It would also need to add that input
> String to the system if it did not exist.

Select the string to be inserted, if there is no result, you can insert the new
string.

> It will also be useful to know
> the last accessed datetime value of that string.

Just add a column with type TIMESTAMP and update that accordingly.

> The number of strings is in millions

Should be no problem with SQLite, if the strings are short.


Chris

From alan.gauld at btinternet.com  Mon Mar 26 23:24:01 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 26 Mar 2007 22:24:01 +0100
Subject: [Tutor] Filesystem vs Database vs Lucene
References: <20070326204600.32881.qmail@web53810.mail.re2.yahoo.com>
Message-ID: <eu9dlj$eqo$1@sea.gmane.org>

"Shitiz Bansal" <shitizb at yahoo.com> wrote

> I need to implement a system which stores Strings(average length 50 
> chars).
> For every input String it would need to tell the user wether that 
> string
> already exists in the system. It would also need to add that input
> String to the system if it did not exist.

Sounds like a job for a dictionary, except...

> It will also be useful to know the last accessed datetime value of 
> that string.

That can be done with a bit of effort.

> The number of strings is in millions and i also need persistence
> so keeping all Strings in memory is not an option.

10 million x 50 chars = 500MB. So if you have a Gig of RAM
and not much else running on the machine memory might still
be a valid option... but if not...

This rules out a normal dictionary, but what about a shelf?
Have a look at the shelve module, it makes a file look a lot like
a dictionary. It should solve your problem. And you can store
either a string or a string/date tuple.

I'm not sure how a shelf would perform compared to a database,
but its a lot simpler to manage.

> Would it be wiser to keep these Strings in an indexed column
> of the DB or would it be better to keep these strings as filenames
> on the filesystem in a folder hiearchy of some sort.

I'd definitely go for the database approach if not using shelve.

> Please also bear in mind the time required to insert the
> strings (for eg. i tried using a database but found the insertion
> time to be very high once i indexed the particular column.

That's common, so I'd suggest not indexing. Its the rebuild of the
index that takes the time. Or if you can break the strings into
categories to reduce the size of the tables that would help.
But that depends on how easy it is to categorise the strings
such that you know where to insert/search.

Also consider using the dbm family of moidules, for simple
data access they often out perform a full SQL database.

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



From rdm at rcblue.com  Tue Mar 27 03:23:29 2007
From: rdm at rcblue.com (Dick Moores)
Date: Mon, 26 Mar 2007 18:23:29 -0700
Subject: [Tutor] nube question...
In-Reply-To: <4604AF20.10709@forethought.net>
References: <4604AF20.10709@forethought.net>
Message-ID: <20070327012333.A34511E4006@bag.python.org>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070326/b30e1b20/attachment.htm 

From rdm at rcblue.com  Tue Mar 27 03:49:56 2007
From: rdm at rcblue.com (Dick Moores)
Date: Mon, 26 Mar 2007 18:49:56 -0700
Subject: [Tutor] nube question...
In-Reply-To: <20070327012333.A34511E4006@bag.python.org>
References: <4604AF20.10709@forethought.net>
	<20070327012333.A34511E4006@bag.python.org>
Message-ID: <20070327015000.ACDE31E4006@bag.python.org>

At 06:23 PM 3/26/2007, Dick Moores wrote:
>At 09:54 PM 3/23/2007, Lurch wrote:
>>I've ripped code from Mark Lutz's book (3rd edition),
>
>I suppose you mean < http://tinyurl.com/2shcmj>?
>
>>  from Welch's book (also 3rd edition), and from around the net.
>
>Title, please?

Ah, found it. Practical Programming in Tcl and Tk (3rd Edition). 
<http://tinyurl.com/2kxpg5>

Dick Moores



From python at kapitalisten.no  Tue Mar 27 08:52:21 2007
From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=)
Date: Tue, 27 Mar 2007 08:52:21 +0200 (CEST)
Subject: [Tutor] Webform
Message-ID: <19214.193.71.38.142.1174978341.squirrel@mail.sporck.net>

Hello.

I am trying to fill in a webform, and have tried using
Clientform/mechanize, but cannot seem to get it right. Here is the code:

from urllib2 import urlopen
import ClientForm
from ClientForm import ParseResponse

response =
urlopen("http://www.datateam.no/boc/bocadresse.nsf/wMedlemsoek?OpenForm&Seq=1")
forms = ParseResponse(response, backwards_compat=False)
form = forms[0]
print form

form["QueryField"] = """980213250"""

print urlopen(form.click()).read()

It just gives me feedback that the form is processed, but I can't seem to
get the result I get if I manually enter the value with the browser.

Thanks in advance


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


From utkarsh.tandon at gmail.com  Tue Mar 27 09:42:05 2007
From: utkarsh.tandon at gmail.com (Utkarsh Tandon)
Date: Tue, 27 Mar 2007 13:12:05 +0530
Subject: [Tutor] What kind of approach
Message-ID: <32a80def0703270042h7045765fm85cc84ce11bd6cc0@mail.gmail.com>

Allan Gauld wrote:
> Thats a very long winded and difficult way to do a fairly simple
> Python task. Don't try to write Python like a C programmer.

I'm really new to python. And I don't have much experience in programming either
So umm, what kind of approach should I have when coding programs in Python ?

From akap at isd.dp.ua  Tue Mar 27 12:16:35 2007
From: akap at isd.dp.ua (Alexander Kapshuk)
Date: Tue, 27 Mar 2007 13:16:35 +0300
Subject: [Tutor] guess my number game
Message-ID: <70831DC71E5D814C9D1FA8A96653215E08CD5ACD@server.isd.dp.ua>

I'm working on a program that has the user think of a number between 1
and 100 and then tries to guess that number.

 

I'm having trouble telling the computer to keep on looking for the
correct number, each time narrowing down the search range.

 

Please see the code below.

 

import random

 

print "\tWelcome to 'Guess My Number 1.2'!"

print "\nThink of a number between 1 and 100."

print "The computer will try to guess it in as few attempts as
possible.\n"

 

# set the initial values

user_number = int(raw_input("Think of a number between 1 and 100 and
press Enter: "))

guess = random.randrange(50) + 1

answer = ""

tries = 1

 

# guessing loop

print guess

answer = raw_input("Is the above No '>', '<' or '=' as your No?: ")

while (answer != "="):

    if (answer == ">"):

        print (guess = random.randrange(100) + 51)

    elif (answer == "<"):

        print (guess = random.randrange(49) + 1)

    elif (answer == "="):

        print "Correct! The number was", user_number "And it only took
you", tries " tries!\n"

    else:

        print "Keep on trying!"

 

    tries += 1

 

raw_input("\n\nPress the enter key to exit.")

 

 

 

 

 

Thanking you all in advance.

 

 

Alexander Kapshuk

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070327/4dbfbac1/attachment.html 

From rdm at rcblue.com  Tue Mar 27 13:19:38 2007
From: rdm at rcblue.com (Dick Moores)
Date: Tue, 27 Mar 2007 04:19:38 -0700
Subject: [Tutor] guess my number game
In-Reply-To: <70831DC71E5D814C9D1FA8A96653215E08CD5ACD@server.isd.dp.ua>
References: <70831DC71E5D814C9D1FA8A96653215E08CD5ACD@server.isd.dp.ua>
Message-ID: <20070327111943.F34F21E4006@bag.python.org>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070327/81afa00d/attachment.html 

From kent37 at tds.net  Tue Mar 27 14:04:55 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 27 Mar 2007 08:04:55 -0400
Subject: [Tutor] Webform
In-Reply-To: <19214.193.71.38.142.1174978341.squirrel@mail.sporck.net>
References: <19214.193.71.38.142.1174978341.squirrel@mail.sporck.net>
Message-ID: <46090867.7080704@tds.net>

?yvind wrote:
> I am trying to fill in a webform, and have tried using
> Clientform/mechanize, but cannot seem to get it right.
> 
> It just gives me feedback that the form is processed, but I can't seem to
> get the result I get if I manually enter the value with the browser.

This form is doing some funny stuff with JavaScript. Take a look at the 
page source. The button you click is not the actual submit button, 
clicking it calls _doClick() with a long parameter. This parameter is 
set as the value of the hidden __Click field before submitting the form.

I don't know for sure why this is done, but probably to thwart machine 
harvesting of the data such as you are doing. You should make sure you 
aren't violating the terms of use of the website by automatically 
fetching the data.

Anyway this seems to work:
In [1]: import urllib2
In [2]: from ClientForm import ParseResponse
In [4]: response = 
urllib2.urlopen("http://www.datateam.no/boc/bocadresse.nsf/wMedlemsoek?OpenForm&Seq=1")
In [5]: forms = ParseResponse(response, backwards_compat=False)
In [6]: form = forms[0]
In [10]: click = form.find_control('__Click')
In [11]: click.readonly=False
In [12]: form['__Click'] = 
'41256C7C00368A2B.8b5a45b319030f3ec125728a00788ddb/$Body/0.CB4'
In [13]: form["QueryField"] = """980213250"""
In [20]: print urllib2.urlopen(form.click()).read()

The value for the __Click field doesn't seem to change, but if it does 
you will have to parse it out of the onclick atttribute of the SubmitBtn 
control.

Kent

From uktechportal at yahoo.co.uk  Tue Mar 27 13:19:40 2007
From: uktechportal at yahoo.co.uk (James Rocks)
Date: Tue, 27 Mar 2007 11:19:40 +0000 (GMT)
Subject: [Tutor] POP3 MailBox Access
Message-ID: <20070327111940.55149.qmail@web27701.mail.ukl.yahoo.com>





Hi,


 


I'm new to this list but not new to Python ... I've been on
and off coding in it for years. Still I remain just a hobbyist :)


 


Recently my interest in Python was rekindled when I started
hosting a game I used to play (VGA Planets or VGAP) and, because I was also a
player in the same game (something frowned upon or at least viewed suspiciously
in some VGAP circles) I wanted to host the game as neutrally as possible so I
set about writing an automatic hosting (AutoHost) program. VGAP is a multi-player,
strategic, space-based play-by-email game where the host runs, generates result
(RST) files, these get sent to the players who then create turn (TRN) files, effectively
a list of commands, that they then return to the host for the next run. 


 


The general idea of my program is that AutoHost runs (on a
separate machine, Windows 200 Professional) the host, sends out the RST files to
the players and waits for them to send their TRN files back. Once a specific
time has passed or all the TRN's have come back the host runs again and in
between AutoHost sends status updates and receipts for submitted TRN's. 


 


I have had some problems ... initially I wasn't able to get mail
functioning at all and was forced to rely on three DOS command line programs
which I called by means of Python's sys (os module) function. In addition I had
a number of issues with the receipt of mail (for some reason unknown to me the
command line utility which had been working after a fashion suddenly decided to
receive attached files as uuencoded text) and I was forced to abandon it as a
means of getting the TRN's and I switched to FTP instead. The program ran as a
series of separate instances fired off by means of an external scheduler. 


 


This worked but was unsatisfactory ... broadly speaking I'm
pleased with the result but I've got a bit fired up and want to improve it. Firstly
I wanted to internalise the scheduler and have since done so using a timer
routine I found on the internet and the program now runs permanently with
events being triggered by that timer. Secondly I wanted to send & receive mail
using Python's own routines ... I have been successful with SMTP sending but
receiving mail still eludes me probably because it is via POP3. Part of the
reason may be because my POP3 user isn't a single ID as such but a sub-mailbox
from my family one i.e. the VGAP user has a username of mailbox+vgap and
requires authentication. 


 


I have used the a number of variations on the following code
with no luck, even though I know there are messages in the box I get back
nothing.


 


]     


]     import getpass, poplib


]     


]     M = poplib.POP3('mail.isp.net')


]     M.user(getpass.getuser())


]     M.pass_(getpass.getpass())


]     numMessages = len(M.list()[1])


]     for i in range(numMessages):


]         for j in
M.retr(i+1)[1]:


]             print j


]     


 


So, if anyone can offer any help I'd appreciate it :)


 


Kyu






	
	
		
___________________________________________________________ 
New Yahoo! Mail is the ultimate force in competitive emailing. Find out more at the Yahoo! Mail Championships. Plus: play games and win prizes. 
http://uk.rd.yahoo.com/evt=44106/*http://mail.yahoo.net/uk 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070327/e8c871ff/attachment.html 

From rikard.bosnjakovic at gmail.com  Tue Mar 27 14:20:31 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Tue, 27 Mar 2007 14:20:31 +0200
Subject: [Tutor] POP3 MailBox Access
In-Reply-To: <20070327111940.55149.qmail@web27701.mail.ukl.yahoo.com>
References: <20070327111940.55149.qmail@web27701.mail.ukl.yahoo.com>
Message-ID: <d9e88eaf0703270520m30425b23l36c7d3b5f57f04f@mail.gmail.com>

On 3/27/07, James Rocks <uktechportal at yahoo.co.uk> wrote:

[...]
> So, if anyone can offer any help I'd appreciate it :)

FWIW, your code works fine for me. I tested on my local pop3-server
and I got all the messages on it. Perhaps it's a server issue of
yours.


-- 
- Rikard - http://bos.hack.org/cv/

From uktechportal at yahoo.co.uk  Tue Mar 27 14:34:56 2007
From: uktechportal at yahoo.co.uk (James Rocks)
Date: Tue, 27 Mar 2007 12:34:56 +0000 (GMT)
Subject: [Tutor] POP3 MailBox Access
Message-ID: <20070327123456.26308.qmail@web27710.mail.ukl.yahoo.com>

> Rikard Bosnjakovic Wrote: 
> FWIW, your code works fine for me. I tested on my local pop3-server
> and I got all the messages on it. Perhaps it's a server issue of
> yours.


Thanks
for replying Richard ... it may well be my ISP, perhaps the way they
require us to use "accountname+mailboxname" for our user credentials. 

Kyu





		
___________________________________________________________ 
To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070327/e3bdb6f1/attachment.htm 

From alan.gauld at btinternet.com  Tue Mar 27 19:22:22 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 27 Mar 2007 18:22:22 +0100
Subject: [Tutor] What kind of approach
References: <32a80def0703270042h7045765fm85cc84ce11bd6cc0@mail.gmail.com>
Message-ID: <eubjsg$3ut$1@sea.gmane.org>


"Utkarsh Tandon" <utkarsh.tandon at gmail.com> wrote 
> Alan Gauld wrote:
>> Thats a very long winded and difficult way to do a fairly simple
>> Python task. Don't try to write Python like a C programmer.
> 
> I'm really new to python. And I don't have much experience in 
> programming either 

Ok, My mistake. The code you had was very like the way 
experienced C programmers typically start using Python;
as if it was C. That's not a good way.

> what kind of approach should I have when coding programs 
> in Python ?

Python is often described as coming "with batteries included"
This is because of the 100 plus modules in the standard library 
that provide tools to do most things more easily. The Pythonic 
approach is to leverage those modules, plus the higher level 
data structures within Python to maximum advantage.

The best solution for stripping C comments is probably to 
use a re module's regular expressions. Define a regex that 
matches a C comment, then replace all occurrences of the 
regex with an empty string. Of course defining the regex 
can be a challenge in itself, but it's a different challenge! :-)


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


From rohan.deshpande at gmail.com  Wed Mar 28 11:43:46 2007
From: rohan.deshpande at gmail.com (Rohan Deshpande)
Date: Wed, 28 Mar 2007 10:43:46 +0100
Subject: [Tutor] web app approach
Message-ID: <e5a6f5430703280243yb22f2c2vb63feb12e3d8bd5b@mail.gmail.com>

Hi everyone,

In terms of building a web application, is the preferred method of
development to develop the application as a console app and then migrate it
to a web app?  Also, in my readings people have been saying that python
frameworks are numerous and not as useful as they seem, and that WSGI is the
way to go at the moment.  For a python newbie giving his first go at a  web
app, what do you recommend?

-Rohan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070328/c7ffa078/attachment.html 

From rohan.deshpande at gmail.com  Wed Mar 28 11:50:15 2007
From: rohan.deshpande at gmail.com (Rohan Deshpande)
Date: Wed, 28 Mar 2007 10:50:15 +0100
Subject: [Tutor]  My Python project - an update
In-Reply-To: <e5a6f5430703280249m4fefc5cfm6d3741e24de2cbda@mail.gmail.com>
References: <200703232231.26662.pythontut@pusspaws.net>
	<e5a6f5430703280249m4fefc5cfm6d3741e24de2cbda@mail.gmail.com>
Message-ID: <e5a6f5430703280250m4d17518bpcd38306dba891c99@mail.gmail.com>

Out of curiousity, why md5?  Hasn't it been cracked already?  Would sha1 or
2sum be a better alternative?  I'm a newbie to this so it's just a question.

-Rohan

On 3/23/07, Dave S <pythontut at pusspaws.net> wrote:
>
> Just to say thank you.
>
> Over the last few months I have been asking a lot of dumb questions about
> python (and qt on the qt mailing list) ... anyhow I finished my pet
> project,
> all 5500 lines of it. I previously explained what it was but to recap ...
>
> I developed a QT Python app that scans both configuration and data
> collected
> from remote security systems, up to 80,000 data attributes per site.
>
> After scanning it reports any inconsistencies or errors via a GUI giving
> them
> a severity level and an option to correct the error or acknowledge and
> enter
> override text.
>
> It generates a certificate PDF with an embedded md5 authentication string
> when
> the site has been audited.
>
> >From its analysis of the data it also generates both a detailed user
> reference PDF and a detailed engineer reference PDF specifically for the
> site.
>
> In my field this has never been done before - lots of very impressed
> people
> after several demonstrations. I released it under the GPL but apparently
> my
> terms of employment state that it belongs my employer ... who does not
> want
> it on sourceforge ...
>
> Where is it now ... its being integrated into a proprietary application as
> a
> groundbreaking audit/commissioning  function (still running my Python code
> as
> a back end) and apparently I am due some kind of company reward ...
>
> My thoughts on my first Python QT project ... would have been nice if I
> could
> have given it to the community ... wonder what they will pay me ? ...
>
> Dave
>
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070328/63420f22/attachment.htm 

From uktechportal at yahoo.co.uk  Wed Mar 28 12:57:40 2007
From: uktechportal at yahoo.co.uk (James Rocks)
Date: Wed, 28 Mar 2007 10:57:40 +0000 (GMT)
Subject: [Tutor] hints on uuencoding?
Message-ID: <20070328105740.19169.qmail@web27715.mail.ukl.yahoo.com>

OK ... so I got my mail receipt working (thanks Rikard) but one thing I will be downloading is attached TRN files.

I can download a mail and subsequently put it in a text file but then I want as easy a way as possible (which may or may not involve uudecoding, there may well be a way to simply pull the attached file off for all I know) to get that file from either trhe text file or the mail object: 

Here's my code so far: 

def GetVGAPMail(sServer='', sUser='', sPassword=''):
    import getpass, poplib
    from string import split, strip, upper
    from os import system

    _TRUE_ = 1
    _FALSE_ = 0

    vMail = poplib.POP3(sServer)
    vMail.user(sUser)
    vMail.pass_(sPassword)
    iMessages = len(vMail.list()[1])

    aMail = []
    for iLoop in range(iMessages):
        # print "**** Loop", iLoop
        lDel = _TRUE_
        fWrite = open ("temp.txt", 'w')
        for sLine in vMail.retr(iLoop + 1)[1]:
            fWrite.write ("%s\n" % sLine)
            # print sLine
            sLine = strip(sLine)
            if len(sLine) > 1:
                aLine = split(sLine)
                # print aLine
                if aLine[0] == "Subject:" and len(aLine) > 1:
                    sCommand = upper(aLine[0])
                    aParam = aLine[1:]
                
                if

        fWrite.close()

        if sCommand == "TURN":
            # download file
            print "**** TURN ****"
            lDel = _FALSE_
        elif sCommand == "RESEND":
            # resend RST
            print "**** RESEND ****"
        elif sCommand == "MAIL":
            # change mail address
            print "**** MAIL ****"
        elif sCommand == "PASSWORD":
            # change password
            print "**** PASSWORD ****"
        elif sCommand == "STATUS":
            # change mail game status
            print "**** STATUS ****"
        else: 
            # change send help file
            print "**** HELP ****"

        if lDel:
            # rename file to temp name (will ultimately delete file)
            print "**** Rename temp.txt to del.txt ****"
            system("ren temp.txt del%s.txt" % iLoop)
        else:
            # rename file to PLAYER3.TRN (this is the file with an attachmnet)
            print "**** Rename temp.txt to PLAYER3.TRN ****"
            system("ren temp.txt PLAYER3.TRN")

Any ideas?

Kyu




		
___________________________________________________________ 
Win a BlackBerry device from O2 with Yahoo!. Enter now. http://www.yahoo.co.uk/blackberry
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070328/e299527e/attachment.htm 

From ms at cerenity.org  Wed Mar 28 13:12:45 2007
From: ms at cerenity.org (Michael Sparks)
Date: Wed, 28 Mar 2007 11:12:45 +0000
Subject: [Tutor] My Python project - an update
In-Reply-To: <e5a6f5430703280250m4d17518bpcd38306dba891c99@mail.gmail.com>
References: <200703232231.26662.pythontut@pusspaws.net>
	<e5a6f5430703280249m4fefc5cfm6d3741e24de2cbda@mail.gmail.com>
	<e5a6f5430703280250m4d17518bpcd38306dba891c99@mail.gmail.com>
Message-ID: <200703281212.46363.ms@cerenity.org>

On Wednesday 28 March 2007 10:50, Rohan Deshpande wrote:
> Out of curiousity, why md5?? Hasn't it been cracked already?? Would sha1 or
> 2sum be a better alternative?? I'm a newbie to this so it's just a
> question.

People have indeed shown vulnerabilities in MD5 for this sort of purpose. 
Specifically this includes modification of existing data on a system in a 
manner that preserves the MD5 with a crafted modification text (ie actual 
deliberate change, rather than random text that happens to match).

SHA1 is generally considered a better approach at the moment as a result. This 
isn't to say that MD5 is hideously crippled - for most purposes its still 
very good, but in this particular context it makes less sense. Especially 
given that once this sort of vulnerability is shown first to be possible, 
then demonstrated with a specific attack associated with a repeatable method, 
after that things generally get worse not better.


Michael

From kent37 at tds.net  Wed Mar 28 13:27:22 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 28 Mar 2007 07:27:22 -0400
Subject: [Tutor] web app approach
In-Reply-To: <e5a6f5430703280243yb22f2c2vb63feb12e3d8bd5b@mail.gmail.com>
References: <e5a6f5430703280243yb22f2c2vb63feb12e3d8bd5b@mail.gmail.com>
Message-ID: <460A511A.5090308@tds.net>

Rohan Deshpande wrote:
> Hi everyone,
> 
> In terms of building a web application, is the preferred method of 
> development to develop the application as a console app and then migrate 
> it to a web app? 

That is a good approach but not the only one. I prefer to develop the 
functional bits of the application using unit tests and occasionally 
simple driver applications. I don't go to the trouble of making a full 
command-line program.

We recently had a discussion of this in the context of GUI applications; 
since a web interface is another kind of GUI the advice there applies to 
your situation.
http://mail.python.org/pipermail/tutor/2007-March/053451.html

> Also, in my readings people have been saying that 
> python frameworks are numerous and not as useful as they seem, and that 
> WSGI is the way to go at the moment.  For a python newbie giving his 
> first go at a  web app, what do you recommend?

You should be able to find people happy with many frameworks including 
Django, TurboGears, Pylons, web.py, Karrigell...

I'm using Django at the moment and finding it very powerful and useful. 
WSGI lets you glue together diverse components; you probably don't want 
to use _just_ WSGI, but include other WSGI components. That is the 
approach Pylons takes.

Kent

From kent37 at tds.net  Wed Mar 28 13:36:52 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 28 Mar 2007 07:36:52 -0400
Subject: [Tutor] hints on uuencoding?
In-Reply-To: <20070328105740.19169.qmail@web27715.mail.ukl.yahoo.com>
References: <20070328105740.19169.qmail@web27715.mail.ukl.yahoo.com>
Message-ID: <460A5354.5080704@tds.net>

James Rocks wrote:
> OK ... so I got my mail receipt working (thanks Rikard) but one thing
> I will be downloading is attached TRN files.
> 
> I can download a mail and subsequently put it in a text file but then
> I want as easy a way as possible (which may or may not involve
> uudecoding, there may well be a way to simply pull the attached file
> off for all I know) to get that file from either trhe text file or
> the mail object:

It sounds like you need to use the email package to pull apart a 
multi-part mime message. The last example here may help:
http://docs.python.org/lib/node162.html

Kent

From tedroche at gmail.com  Wed Mar 28 22:29:51 2007
From: tedroche at gmail.com (Ted Roche)
Date: Wed, 28 Mar 2007 16:29:51 -0400
Subject: [Tutor] 3 recent short essays by Kent Johnson
In-Reply-To: <20070326150338.7FF701E400B@bag.python.org>
References: <20070326150338.7FF701E400B@bag.python.org>
Message-ID: <c9415b010703281329p7fb9cea2g3aa46b5243acde4c@mail.gmail.com>

On 3/26/07, Dick Moores <rdm at rcblue.com> wrote:
> "Python Decorators," "The path module" and "List Comprehensions."
> <http://personalpages.tds.net/~kent37/kk/index.html>
>
> Dick Moores

If you're in or near New Hampshire, join the Python SIG
(http://www.pysig.org) and you might get the change to see Kent
deliver these live as the "Kent's Korner" portion of our meetings -
fourth Thursday of the month,  in Manchester, NH. Details:
http://www.pysig.org

-- 
Ted Roche
PySIG Rabble-Rouser

From rabidpoobear at gmail.com  Thu Mar 29 01:19:44 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 28 Mar 2007 18:19:44 -0500
Subject: [Tutor] 3 recent short essays by Kent Johnson
In-Reply-To: <c9415b010703281329p7fb9cea2g3aa46b5243acde4c@mail.gmail.com>
References: <20070326150338.7FF701E400B@bag.python.org>
	<c9415b010703281329p7fb9cea2g3aa46b5243acde4c@mail.gmail.com>
Message-ID: <460AF810.8050003@gmail.com>

Ted Roche wrote:
> On 3/26/07, Dick Moores <rdm at rcblue.com> wrote:
>   
>> "Python Decorators," "The path module" and "List Comprehensions."
>> <http://personalpages.tds.net/~kent37/kk/index.html>
>>
>> Dick Moores
>>     
>
> If you're in or near New Hampshire, join the Python SIG
> (http://www.pysig.org) and you might get the change to see Kent
> deliver these live as the "Kent's Korner" portion of our meetings -
> fourth Thursday of the month,  in Manchester, NH. Details:
> http://www.pysig.org
>   
Ah, never before have I desired more to live in New England ;) .
Wish I could check that out, Kent.  Sounds like great fun.
-Luke


From shitizb at yahoo.com  Thu Mar 29 02:13:29 2007
From: shitizb at yahoo.com (Shitiz Bansal)
Date: Wed, 28 Mar 2007 17:13:29 -0700 (PDT)
Subject: [Tutor] Filesystem vs Database vs Lucene
In-Reply-To: <eu9dlj$eqo$1@sea.gmane.org>
Message-ID: <20070329001329.16533.qmail@web53802.mail.re2.yahoo.com>

Thanks Alan for your reply.
I however have a few more concerns.

Memory is not an option not just because of capacity but also because I desire persistence.
Also I feel that 500 MB of data in a dictionary would typically cross 1 Gigin total used memory.That of course will depend on the Hashing algorithm used and the actual data.Anyway this program is just a module of something quite larger so...

Shelves seem nice but I would like to be sure on how it is implemented. Would it 
seek to a particular point in file and load just the desired data in memory or does it unpickle everything and create a fullblown dictionary in memory?...in which case the memory problem will resurface.

If this is addressed I would definitely opt for shelve over db/dbm as it would be simpler. Also the underlying algorithm being a hash search instead of a b-tree search/insert as in most database indexes, this is bound to outperform them.

It might be blasphemous to say this here but is there an equivalent c library as I am willing to spend an extra amount of time coding for that extra zing in performance.

Alan Gauld <alan.gauld at btinternet.com> wrote: "Shitiz Bansal"  wrote

> I need to implement a system which stores Strings(average length 50 
> chars).
> For every input String it would need to tell the user wether that 
> string
> already exists in the system. It would also need to add that input
> String to the system if it did not exist.

Sounds like a job for a dictionary, except...

> It will also be useful to know the last accessed datetime value of 
> that string.

That can be done with a bit of effort.

> The number of strings is in millions and i also need persistence
> so keeping all Strings in memory is not an option.

10 million x 50 chars = 500MB. So if you have a Gig of RAM
and not much else running on the machine memory might still
be a valid option... but if not...

This rules out a normal dictionary, but what about a shelf?
Have a look at the shelve module, it makes a file look a lot like
a dictionary. It should solve your problem. And you can store
either a string or a string/date tuple.

I'm not sure how a shelf would perform compared to a database,
but its a lot simpler to manage.

> Would it be wiser to keep these Strings in an indexed column
> of the DB or would it be better to keep these strings as filenames
> on the filesystem in a folder hiearchy of some sort.

I'd definitely go for the database approach if not using shelve.

> Please also bear in mind the time required to insert the
> strings (for eg. i tried using a database but found the insertion
> time to be very high once i indexed the particular column.

That's common, so I'd suggest not indexing. Its the rebuild of the
index that takes the time. Or if you can break the strings into
categories to reduce the size of the tables that would help.
But that depends on how easy it is to categorise the strings
such that you know where to insert/search.

Also consider using the dbm family of moidules, for simple
data access they often out perform a full SQL database.

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


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


 
---------------------------------
Don't be flakey. Get Yahoo! Mail for Mobile and 
always stay connected to friends.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070328/97e90487/attachment-0001.htm 

From bgailer at alum.rpi.edu  Thu Mar 29 03:13:39 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Wed, 28 Mar 2007 18:13:39 -0700
Subject: [Tutor] Filesystem vs Database vs Lucene
In-Reply-To: <20070329001329.16533.qmail@web53802.mail.re2.yahoo.com>
References: <20070329001329.16533.qmail@web53802.mail.re2.yahoo.com>
Message-ID: <460B12C3.9060307@alum.rpi.edu>

Shitiz Bansal wrote:
> > I need to implement a system which stores Strings(average length 50> 
> chars).
[snip]
How much greater than 50? 500, 5000, 50,000, ...?

Are these arbitrary text, or do the words come from some predetermined 
domain?

Would you provide some examples?

-- 
Bob Gailer
510-978-4454


From bgailer at alum.rpi.edu  Thu Mar 29 03:27:10 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Wed, 28 Mar 2007 18:27:10 -0700
Subject: [Tutor] Filesystem vs Database vs Lucene OOPS
In-Reply-To: <460B12C3.9060307@alum.rpi.edu>
References: <20070329001329.16533.qmail@web53802.mail.re2.yahoo.com>
	<460B12C3.9060307@alum.rpi.edu>
Message-ID: <460B15EE.7030308@alum.rpi.edu>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070328/12de5e66/attachment.htm 

From rabidpoobear at gmail.com  Thu Mar 29 03:44:50 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 28 Mar 2007 20:44:50 -0500
Subject: [Tutor] Filesystem vs Database vs Lucene OOPS
In-Reply-To: <460B15EE.7030308@alum.rpi.edu>
References: <20070329001329.16533.qmail@web53802.mail.re2.yahoo.com>	<460B12C3.9060307@alum.rpi.edu>
	<460B15EE.7030308@alum.rpi.edu>
Message-ID: <460B1A12.20000@gmail.com>

Bob Gailer wrote:
> Bob Gailer wrote:
>> Shitiz Bansal wrote:
>>   
>>>> I need to implement a system which stores Strings(average length 50> 
>>>>       
>>> chars).
>>>     
>> [snip]
>>   
> I may have read 50> as >50. Please confirm that average length IS 50?
 > I need to implement a system which stores Strings(average length 50
 > chars).
is how it showed up on my computer, so I bet the > sign is really just 
those things e-mail clients add to denote quoted text.

-Luke

From john at fouhy.net  Thu Mar 29 05:04:36 2007
From: john at fouhy.net (John Fouhy)
Date: Thu, 29 Mar 2007 15:04:36 +1200
Subject: [Tutor] Filesystem vs Database vs Lucene
In-Reply-To: <20070329001329.16533.qmail@web53802.mail.re2.yahoo.com>
References: <eu9dlj$eqo$1@sea.gmane.org>
	<20070329001329.16533.qmail@web53802.mail.re2.yahoo.com>
Message-ID: <5e58f2e40703282004s49995658n5a51d66d2abcc310@mail.gmail.com>

On 29/03/07, Shitiz Bansal <shitizb at yahoo.com> wrote:
> Shelves seem nice but I would like to be sure on how it is implemented.
> Would it
> seek to a particular point in file and load just the desired data in memory
> or does it unpickle everything and create a fullblown dictionary in
> memory?...in which case the memory problem will resurface.

One great thing about python is that you have the source code, so you
can go check out shelve.py in your python distribution.

If you do that, you will learn that shelve is basically a dictionary
interface over the top of anydbm, python's dbm-style database
interface.

> It might be blasphemous to say this here but is there an equivalent c
> library as I am willing to spend an extra amount of time coding for that
> extra zing in performance.

Many parts of the standard library are written in C, and if you know
what you're doing, you can write your own python modules in C and
incorporate them into your python programs.

-- 
John.

From agilfoy at frontiernet.net  Fri Mar 30 01:15:24 2007
From: agilfoy at frontiernet.net (Alan Gilfoy)
Date: Thu, 29 Mar 2007 23:15:24 +0000
Subject: [Tutor] A string-manipulation question
Message-ID: <20070329231524.22nwfglx53tc80co@webmail.frontiernet.net>

Hi. I want to learn how to "break down" a string into its component  
words, and then process each word somehow.

Is there a way in Python to separate a string into its component words.

Like this:
"I would like to convert an English string (sentence) into Pig Latin."

The Pig Latin conversion I think I can handle already (if not, I'll  
cross that bridge when I come to it.) However, what I want help on is  
how to make each word of the string a separate value, or at least make  
it able to index the string by word, as opposed to the standard method  
of strings being indexed by character.
-- 
"Computers were the first God-Satan collaboration project."
"Blind faith in bad leadership is not patriotism."

"One of the most horrible features of war is that all the war-propaganda, all
the screaming and lies and hatred, comes invariably from people who are not
fighting."-George Orwell, _Homage to Catalonia






From bgailer at alum.rpi.edu  Fri Mar 30 01:35:16 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Thu, 29 Mar 2007 16:35:16 -0700
Subject: [Tutor] A string-manipulation question
In-Reply-To: <20070329231524.22nwfglx53tc80co@webmail.frontiernet.net>
References: <20070329231524.22nwfglx53tc80co@webmail.frontiernet.net>
Message-ID: <460C4D34.6010102@alum.rpi.edu>

Alan Gilfoy wrote:
> Hi. I want to learn how to "break down" a string into its component  
> words, and then process each word somehow.
>
> Is there a way in Python to separate a string into its component words.
>
> Like this:
> "I would like to convert an English string (sentence) into Pig Latin."
>
> The Pig Latin conversion I think I can handle already (if not, I'll  
> cross that bridge when I come to it.) However, what I want help on is  
> how to make each word of the string a separate value, or at least make  
> it able to index the string by word, as opposed to the standard method  
> of strings being indexed by character.
>   

"I would like to convert an English string (sentence) into Pig Latin.".split()
yields:
["I", "would", "like", "to", "convert", "an", "English", "string", 
"(sentence)", "into", "Pig Latin."]


-- 
Bob Gailer
510-978-4454


From amonroe at columbus.rr.com  Fri Mar 30 02:37:56 2007
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Thu, 29 Mar 2007 19:37:56 -0500
Subject: [Tutor] A string-manipulation question
In-Reply-To: <20070329231524.22nwfglx53tc80co@webmail.frontiernet.net>
References: <20070329231524.22nwfglx53tc80co@webmail.frontiernet.net>
Message-ID: <251472495025.20070329193756@columbus.rr.com>

> Hi. I want to learn how to "break down" a string into its component  
> words, and then process each word somehow.

> Is there a way in Python to separate a string into its component words.

> Like this:
> "I would like to convert an English string (sentence) into Pig Latin."

for word in sentence.split():
    print word



Alan


From agilfoy at frontiernet.net  Fri Mar 30 02:49:48 2007
From: agilfoy at frontiernet.net (Alan Gilfoy)
Date: Fri, 30 Mar 2007 00:49:48 +0000
Subject: [Tutor] A string-manipulation question
In-Reply-To: <460C4D34.6010102@alum.rpi.edu>
References: <20070329231524.22nwfglx53tc80co@webmail.frontiernet.net>
	<460C4D34.6010102@alum.rpi.edu>
Message-ID: <20070330004948.ookxzuzpemg4w4ck@webmail.frontiernet.net>

Awesome! (I was hoping it would be a 1-line solution. :)
Thanks to batteries beign included, I don't necessarily need to worry  
about why and how .spilt() works. :)

Quoting Bob Gailer <bgailer at alum.rpi.edu>:

> Alan Gilfoy wrote:
>> Hi. I want to learn how to "break down" a string into its component  
>>   words, and then process each word somehow.
>>
>> Is there a way in Python to separate a string into its component words.
>>
>> Like this:
>> "I would like to convert an English string (sentence) into Pig Latin."
>>
>> The Pig Latin conversion I think I can handle already (if not, I'll  
>>   cross that bridge when I come to it.) However, what I want help  
>> on  is  how to make each word of the string a separate value, or at  
>>  least make it able to index the string by word, as opposed to the   
>> standard method  of strings being indexed by character.
>>
>
> "I would like to convert an English string (sentence) into Pig   
> Latin.".split()
> yields:
> ["I", "would", "like", "to", "convert", "an", "English", "string",
> "(sentence)", "into", "Pig Latin."]
>
>
> -- 
> Bob Gailer
> 510-978-4454




From cspears2002 at yahoo.com  Fri Mar 30 04:29:52 2007
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Thu, 29 Mar 2007 19:29:52 -0700 (PDT)
Subject: [Tutor] or
Message-ID: <61179.50230.qm@web51609.mail.re2.yahoo.com>

I was doodling at the interpreter:

>>> fruit = ["apples","pears","oranges"]
>>> for f in fruit:
...     if f != "apples":
...             print f
...             print "This is not an apple."
...
pears
This is not an apple.
oranges
This is not an apple.

What I can't remember is what is 'or' in python.  For
example, what if I want the loop to skip apples and
pears?  I tried this:

>>> for f in fruit:
...     if f != "apples" or "pears":
...             print f
...             print "This is not an apple or pear"
...
apples
This is not an apple or pear
pears
This is not an apple or pear
oranges
This is not an apple or pear
>>>

Actually maybe my problem is not asking the right
question?  Should I be looking for 'and' instead of
'or' ?

From john at fouhy.net  Fri Mar 30 04:54:54 2007
From: john at fouhy.net (John Fouhy)
Date: Fri, 30 Mar 2007 14:54:54 +1200
Subject: [Tutor] or
In-Reply-To: <61179.50230.qm@web51609.mail.re2.yahoo.com>
References: <61179.50230.qm@web51609.mail.re2.yahoo.com>
Message-ID: <5e58f2e40703291954y78e464bcq4d49fd727d087145@mail.gmail.com>

On 30/03/07, Christopher Spears <cspears2002 at yahoo.com> wrote:
> What I can't remember is what is 'or' in python.  For
> example, what if I want the loop to skip apples and
> pears?  I tried this:
>
> >>> for f in fruit:
> ...     if f != "apples" or "pears":
> ...             print f
> ...             print "This is not an apple or pear"
> ...
> apples
> This is not an apple or pear
> pears
> This is not an apple or pear
> oranges
> This is not an apple or pear
> >>>
>
> Actually maybe my problem is not asking the right
> question?  Should I be looking for 'and' instead of
> 'or' ?

Hi Christopher,

"or" is used to combine two boolean expressions.  What you wrote is
equivalent to:

for f in fruit:
  if (f != "apples") or ("pears"):
     # etc

So python first checks the truth of (f != "apples").  If this is true,
it continues to the body of the if statement.  If this is false,
python checks the truth of ("pears").  Because "pears" is a nonempty
string, it is always true, and so python continues to the body of the
if statement anyway.

You have a few options to correct your code.  Consider the following:

for f in fruit:
  if f == "apples" or f == "pairs":
    print f, "is an apple or a pair."

This will check if f is either "apples" or "pairs".  You can then invert that:

for f in fruit:
  if not (f == "apples" or f == "pairs"):
    print f, "is not an apple or pair."

You could then use DeMorgan's law to convert this to:

for f in fruit:
  if f != "apples" and f != "pairs":
    print f, "is not an apple or pair."

Finally, you have one more option, using the "in" operator:

for f in fruit:
  if f not in ["apples", "pairs"]:
    print f, "is not an apple or pair."

HTH!

-- 
John.

From gregp at liveammo.com  Fri Mar 30 05:33:00 2007
From: gregp at liveammo.com (Greg Perry)
Date: 29 Mar 2007 23:33:00 -0400
Subject: [Tutor] getopts question
Message-ID: <20070330032909.1117B17072@smtp2.hushmail.com>

Hello List Members,

I am working on a simple program and would like to know the best way to approach this.  Using getops I am parsing the argv array to grab command line options; from the command line the user can specify either a filename or a directory (but not both).  Is there an eloquent way with getopts to do an either/or scenario without resorting to multiple tests to see which variable is set using if then statements?

Thanks in advance



From utkarsh.tandon at gmail.com  Fri Mar 30 06:47:50 2007
From: utkarsh.tandon at gmail.com (Utkarsh Tandon)
Date: Fri, 30 Mar 2007 10:17:50 +0530
Subject: [Tutor] Tutor Digest, Vol 37, Issue 72
In-Reply-To: <mailman.47.1175162411.9468.tutor@python.org>
References: <mailman.47.1175162411.9468.tutor@python.org>
Message-ID: <32a80def0703292147u756d9ab9lcac71d86234c834a@mail.gmail.com>

Is it possible to make daemons for *nix in Python ? How ?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070330/a6163fe2/attachment.html 

From deliberatus at verizon.net  Fri Mar 30 08:36:44 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Fri, 30 Mar 2007 02:36:44 -0400
Subject: [Tutor] reafline reads file, not just 1 line
Message-ID: <460CAFFC.6030202@verizon.net>

a relevant code snip:

if os.path.exists('ConfigureMe'):
	f1=open('ConfigureMe','r')
	tablebgcolor=string.strip(f1.readline())
	papercolor=string.strip(f1.readline())
	inkcolor=string.strip(f1.readline())
	linkcolor=string.strip(f1.readline())
	f1.close()

Eacj line in the file contains color configuration information to 
include into a webpage later on (for instance, 'peach, 'wjhite', 
'black', 'Blue').

tablebgcolor contains the entire text file being read, not one line.

this program opereates in a windows 2000 environment if this helps any.

when examined in a text editor, the file is properly laid out. pLease 
help, the fingernails are getting very close to the quick.



-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From sanelson at gmail.com  Fri Mar 30 09:27:54 2007
From: sanelson at gmail.com (Stephen Nelson-Smith)
Date: Fri, 30 Mar 2007 08:27:54 +0100
Subject: [Tutor] [OT] ETL Tools
Message-ID: <b6131fdc0703300027l408f941dj7f32e745e1192aa2@mail.gmail.com>

Hello all,

Does anyone know of any ETL (Extraction, Transformation, Loading)
tools in Python (or at any rate, !Java)?

I have lots (and lots) of raw data in the form of log files which I
need to process and aggregate and then do a whole bunch of group-by
operations, before dumping them into text/relational database for a
search engine to access.

At present we have a bunch of scripts in perl and ruby, and a berkley
and mysql database for the grouping operations.  This is proving to be
a little slow with the amount of data we now have, so I am looking
into alternatives.

Does anyone have any experience of this sort of  thing?  Or know
someone who does, that I could talk to?

Best regards,

S.

From rabidpoobear at gmail.com  Fri Mar 30 09:43:21 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Fri, 30 Mar 2007 02:43:21 -0500
Subject: [Tutor] reafline reads file, not just 1 line
In-Reply-To: <460CAFFC.6030202@verizon.net>
References: <460CAFFC.6030202@verizon.net>
Message-ID: <460CBF99.5090707@gmail.com>

Kirk Bailey wrote:
> a relevant code snip:
>
> if os.path.exists('ConfigureMe'):
> 	f1=open('ConfigureMe','r')
> 	tablebgcolor=string.strip(f1.readline())
> 	papercolor=string.strip(f1.readline())
> 	inkcolor=string.strip(f1.readline())
> 	linkcolor=string.strip(f1.readline())
> 	f1.close()
>
> Eacj line in the file contains color configuration information to 
> include into a webpage later on (for instance, 'peach, 'wjhite', 
> 'black', 'Blue').
>
> tablebgcolor contains the entire text file being read, not one line.
>
> this program opereates in a windows 2000 environment if this helps any.
>
> when examined in a text editor, the file is properly laid out. pLease 
> help, the fingernails are getting very close to the quick.
>   
Let us take a gander at this file.  Include it as an attachment.
I see no reason why your code wouldn't work.
You sure you didn't accidentally make the first a call to readlines()? 
(note the 's')
-Luke
>
>
>   


From snakepit.rattlesnakes at gmail.com  Fri Mar 30 11:17:26 2007
From: snakepit.rattlesnakes at gmail.com (Joydeep Mitra)
Date: Fri, 30 Mar 2007 14:47:26 +0530
Subject: [Tutor] range()-like function for dealing with floats...?
Message-ID: <972566ff0703300217o7a916d89v565e78a5f1e479ec@mail.gmail.com>

Hi all,
I need to generate a sequence of real numbers that are evenly spaced. I have
used loops for this purpose until now, but it gets kinna messy when you
gotta do it a number of times in a program.
The range function, as per my knowledge, accepts parameters and return
values only as integers.
Is there a function in python, which performs the task of the range()
function with floats?

Joy
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070330/6f91d321/attachment.htm 

From python at kapitalisten.no  Fri Mar 30 12:59:26 2007
From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=)
Date: Fri, 30 Mar 2007 12:59:26 +0200 (CEST)
Subject: [Tutor] Sloooooow SQL
Message-ID: <16081.193.71.38.142.1175252366.squirrel@mail.sporck.net>

Hello.

I have been writing some scripts that gets data from a MSSQL-database.
However, it is very slow. If I use the script, the retrieving of data and
displaying in html takes close to 30 seconds. If I use the SQL Server
Management Query, the same query takes a second or two. Why this enormous
difference? Below is the top of one of the scripts.

Thanks in advance.


from win32com.client import Dispatch
import MSSQL
import cgitb, cgi, os, urllib
cgitb.enable()

print "Content-type: text/html"

print """<HTML>
<HEAD>
<TITLE>SQL</TITLE></HEAD><BODY>
<link href="style.css" rel="stylesheet" type="text/css">"""

form = cgi.FieldStorage()
db = MSSQL.connect('10.10.10.10','admin','admin','MYDB')
cursor = db.cursor()

ejfirma = """select x_firmanavn from ad_kopi order by x_firmanavn"""
cursor.execute(ejfirma)
result = cursor.fetchall()


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


From mail at timgolden.me.uk  Fri Mar 30 13:36:10 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Fri, 30 Mar 2007 12:36:10 +0100
Subject: [Tutor] Sloooooow SQL
In-Reply-To: <16081.193.71.38.142.1175252366.squirrel@mail.sporck.net>
References: <16081.193.71.38.142.1175252366.squirrel@mail.sporck.net>
Message-ID: <460CF62A.2090205@timgolden.me.uk>

?yvind wrote:
> I have been writing some scripts that gets data from a MSSQL-database.
> However, it is very slow. If I use the script, the retrieving of data and
> displaying in html takes close to 30 seconds. If I use the SQL Server
> Management Query, the same query takes a second or two. Why this enormous
> difference? 

Well, you need to start by distinguishing one or two things.
First, forget the HTML/CGI bit of things. Now, does your
script, reduced to pure Python, still take as long.

<code>
import MSSQL
db = MSSQL.connect('10.10.10.10','admin','admin','MYDB')
ejfirma = """select x_firmanavn from ad_kopi order by 
x_firmanavn"""
cursor.execute(ejfirma)
result = cursor.fetchall()
</code>

If you run that in the interpreter, or save it as
sqlrun.py and execute it, how long does it take?

If it *still* takes a long time, then we look at
the module and/or the quantity of data and the
way in which it is being buffered, etc.

If it only takes a second or so, then the issue is
likely with the CGI startup time or some other factor
within your script. How long does the HTML take to
produce *without* the SQL? Now, how long with a
TOP 10 or some other limiting clause? It might be
that getting the connection is slow. Is the web server
the same machine you run your Query Analyser tests on?

These aren't answers, because a lot depends on your
environment, but maybe if you come back with the problem
broken down, we'll be better placed to advise you.

TJG

From kent37 at tds.net  Fri Mar 30 13:36:05 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 30 Mar 2007 07:36:05 -0400
Subject: [Tutor] reafline reads file, not just 1 line
In-Reply-To: <460CAFFC.6030202@verizon.net>
References: <460CAFFC.6030202@verizon.net>
Message-ID: <460CF625.6070202@tds.net>

Kirk Bailey wrote:
> a relevant code snip:
> 
> if os.path.exists('ConfigureMe'):
> 	f1=open('ConfigureMe','r')
> 	tablebgcolor=string.strip(f1.readline())
> 
> Eacj line in the file contains color configuration information to 
> include into a webpage later on (for instance, 'peach, 'wjhite', 
> 'black', 'Blue').
> 
> tablebgcolor contains the entire text file being read, not one line.
> 
> this program opereates in a windows 2000 environment if this helps any.

My guess is that the file contains non-native newlines. Try opening it 
with universal newline support using
   f1=open('ConfigureMe','rU')

Kent

From kent37 at tds.net  Fri Mar 30 13:41:52 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 30 Mar 2007 07:41:52 -0400
Subject: [Tutor] range()-like function for dealing with floats...?
In-Reply-To: <972566ff0703300217o7a916d89v565e78a5f1e479ec@mail.gmail.com>
References: <972566ff0703300217o7a916d89v565e78a5f1e479ec@mail.gmail.com>
Message-ID: <460CF780.5070700@tds.net>

Joydeep Mitra wrote:
> Hi all,
> I need to generate a sequence of real numbers that are evenly spaced. I 
> have used loops for this purpose until now, but it gets kinna messy when 
> you gotta do it a number of times in a program.
> The range function, as per my knowledge, accepts parameters and return 
> values only as integers.
> Is there a function in python, which performs the task of the range() 
> function with floats?

There is nothing built-in but it is easy to make your own using a generator:
In [1]: def frange(start, stop, step):
    ...:     i = start
    ...:     while i < stop:
    ...:         yield i
    ...:         i += step
    ...:

In [2]: for i in frange(1, 3, .5):
    ...:     print i
    ...:

1
1.5
2.0
2.5

More on generators here:
http://www.python.org/doc/2.2.3/whatsnew/node5.html

Kent

From kent37 at tds.net  Fri Mar 30 13:45:50 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 30 Mar 2007 07:45:50 -0400
Subject: [Tutor] A string-manipulation question
In-Reply-To: <20070330004948.ookxzuzpemg4w4ck@webmail.frontiernet.net>
References: <20070329231524.22nwfglx53tc80co@webmail.frontiernet.net>	<460C4D34.6010102@alum.rpi.edu>
	<20070330004948.ookxzuzpemg4w4ck@webmail.frontiernet.net>
Message-ID: <460CF86E.5040500@tds.net>

Alan Gilfoy wrote:
> Awesome! (I was hoping it would be a 1-line solution. :)
> Thanks to batteries beign included, I don't necessarily need to worry  
> about why and how .spilt() works. :)

You might want to look at the docs for split() so you can use it again 
next time you have a need.
http://docs.python.org/lib/string-methods.html#l2h-262

Kent

From kent37 at tds.net  Fri Mar 30 13:47:58 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 30 Mar 2007 07:47:58 -0400
Subject: [Tutor] getopts question
In-Reply-To: <20070330032909.1117B17072@smtp2.hushmail.com>
References: <20070330032909.1117B17072@smtp2.hushmail.com>
Message-ID: <460CF8EE.1050908@tds.net>

Greg Perry wrote:
> Hello List Members,
> 
> I am working on a simple program and would like to know the best way
to approach this. Using getops I am parsing the argv array to grab
command line options; from the command line the user can specify either
a filename or a directory (but not both). Is there an eloquent way with
getopts to do an either/or scenario without resorting to multiple tests
to see which variable is set using if then statements?

I'm not really sure what you are looking for here. If you use two 
options, you will have to test to see which option is set. You could use 
one option, then you will have to test to see if the value is a file or 
a directory.

Kent

From kent37 at tds.net  Fri Mar 30 13:54:18 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 30 Mar 2007 07:54:18 -0400
Subject: [Tutor] Tutor Digest, Vol 37, Issue 72
In-Reply-To: <32a80def0703292147u756d9ab9lcac71d86234c834a@mail.gmail.com>
References: <mailman.47.1175162411.9468.tutor@python.org>
	<32a80def0703292147u756d9ab9lcac71d86234c834a@mail.gmail.com>
Message-ID: <460CFA6A.2050008@tds.net>

Utkarsh Tandon wrote:
> 
> Is it possible to make daemons for *nix in Python ? How ?

Googling "Python daemon" yields many references of which the best seem to be
http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012

Kent

From eike.welk at gmx.net  Fri Mar 30 14:14:43 2007
From: eike.welk at gmx.net (Eike Welk)
Date: Fri, 30 Mar 2007 14:14:43 +0200
Subject: [Tutor] range()-like function for dealing with floats...?
In-Reply-To: <972566ff0703300217o7a916d89v565e78a5f1e479ec@mail.gmail.com>
References: <972566ff0703300217o7a916d89v565e78a5f1e479ec@mail.gmail.com>
Message-ID: <200703301414.43852.eike.welk@gmx.net>

On Friday 30 March 2007 11:17, Joydeep Mitra wrote:
> Hi all,
> I need to generate a sequence of real numbers that are evenly
> spaced. I have used loops for this purpose until now, but it gets
> kinna messy when you gotta do it a number of times in a program.
> The range function, as per my knowledge, accepts parameters and
> return values only as integers.
> Is there a function in python, which performs the task of the
> range() function with floats?
>
> Joy

The linspace function from the NumPy library (http://numpy.scipy.org/) 
does exactly what you want:

In [1]:from numpy import *
In [2]:linspace(1, 1.1, 4)
Out[2]:array([ 1.        ,  1.03333333,  1.06666667,  1.1       ])

If you do a lot of computations with sequences of floating point 
numbers, you might consider installing this libraray.

Alternatively you could write a similar function that returns such a 
sequence. (Excuse me if this is trivial for you.):

def myLinspace(xMin, xMax, nX):
    deltaX = (xMax - xMin)/(nX-1)
    x = [xMin + deltaX*i for i in range(nX)]
    return x


Regards, Eike.

-- 
Snail:                             Phone:
Eike Welk                          xx49-241-4127686
Stolberger Str. 72
52068 Aachen                       Mail:
Germany                            eike.welk at post.rwth-aachen.de



From andreas at kostyrka.org  Fri Mar 30 13:41:00 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Fri, 30 Mar 2007 13:41:00 +0200
Subject: [Tutor] getopts question
In-Reply-To: <460CF8EE.1050908@tds.net>
References: <20070330032909.1117B17072@smtp2.hushmail.com>
	<460CF8EE.1050908@tds.net>
Message-ID: <20070330114100.GA5850@andi-lap.la.revver.com>

* Kent Johnson <kent37 at tds.net> [070330 13:04]:
> Greg Perry wrote:
> > Hello List Members,
> > 
> > I am working on a simple program and would like to know the best way
> to approach this. Using getops I am parsing the argv array to grab
> command line options; from the command line the user can specify either
> a filename or a directory (but not both). Is there an eloquent way with
> getopts to do an either/or scenario without resorting to multiple tests
> to see which variable is set using if then statements?
> 
> I'm not really sure what you are looking for here. If you use two 
> options, you will have to test to see which option is set. You could use 
> one option, then you will have to test to see if the value is a file or 
> a directory.

Alternativly, use the module optparse, which is a little bit more high
level than getopt.

Andreas

From deliberatus at verizon.net  Fri Mar 30 17:37:56 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Fri, 30 Mar 2007 11:37:56 -0400
Subject: [Tutor] reafline reads file, not just 1 line
In-Reply-To: <460CBF99.5090707@gmail.com>
References: <460CAFFC.6030202@verizon.net> <460CBF99.5090707@gmail.com>
Message-ID: <460D2ED4.5050605@verizon.net>

#!C:\Python25\pythonw.exe
#
import os, os.path, random, sys, string, time, cgitb; cgitb.enable()
#
print "Content-Type: text/html\n"
#
try:
	pagename=os.environ['QUERY_STRING']	# try to retreive the page  name requested
except exception, e:
	pagename="FrontPage"
#
if len(pagename)>3:
	pass
else:
	pagename="FrontPage"			# but default to the FrontPage file.
#
path=os.getcwd()
if os.path.exists('WW.key'):
	pass
else:
	f1=open('WW.key','w')
	f1.write('unregistered')
	f1.close()
path=path+'\\text'
os.chdir(path)		# make the pages dir current
#
"""
if os.path.exists('ConfigureMe'):
	f1=open('ConfigureMe','r')
	tablebgcolor=string.strip(f1.readline())
	papercolor=string.strip(f1.readline())
	inkcolor=string.strip(f1.readline())
	linkcolor=string.strip(f1.readline())
	f1.close()
else:
	tablebgcolor='FFC0A0'
	papercolor='White'
	inkcolor='Black'
	linkcolor='Blue'
	f1=open('ConfigureMe','w')
	f1.write(tablebgcolor+'\n')
	f1.write(papercolor+'\n')
	f1.write(inkcolor+'\n')
	f1.write(linkcolor+'\n')
	f1.write('\nThe lines above are:\n')
	f1.write('tablecolor\n')
	f1.write('papercolor\n')
	f1.write('inkcolor\n')
	f1.write('linkcolor\n\n')
	f1.write('[=@! Navigation Toolbar !@=]\n')
	f1.write('@! CategoryWiki !@\n')
	f1.close()
"""
tablebgcolor='FFC0A0'
papercolor='White'
inkcolor='Black'
linkcolor='Blue'

#
if os.path.exists(pagename):			# if the page asked for exists,
	pass						# do nothing here;
else:							# BUT if it does NOT-
	f1=open(pagename,'w')			# CREATE it!
	f1.write("""Please contribute something to this webpage.
[=@! Navigation toolbar !@=]
@! FrontPage CategoryCategory !@""")
	f1.close()
#
# page header follows
print "<html><head><title>WindowsWiki - " + pagename + "</title>"
print '<style TYPE="text/css">'
print "A:link, A:visited,  A:active { text-decoration:none; }"
print "A:hover { text-decoration:underline; }"
print 'body { margin-left: 5%; margin-right: 5%; }'
print "</style></head>"
print '<body bgcolor="' + papercolor + '" text="' + inkcolor + '" links="' + linkcolor + '">'
print '<table width=100% bgcolor="' + tablebgcolor + '" border="0" cellpadding="10" cellspacing="0">'
print '<tr>'
print '<td width="120" ><B><font size="4" face="Georgia" color="FF0000">WindowsWiki&trade;</font></B></td>'
print '<td width="*" align="center" >(click title for backsearch)</td>'
print '<td rowspan="2">&nbsp;</td>'
print '</tr><tr>'
print '<td>&nbsp;</td>'
print '<td align="center"><font size="6"><a href="./MWbacksearch.py?' + pagename + '">' + pagename + '</a></font></td>'
# put a cell here if need be
print '</tr><tr>'
print '<td>&nbsp;</td>'
print '<td align="center">'
# Begin nagware suite
birthday=os.stat('..\WW.key')[-1]
now=int(time.time())
month=60*60*24*30
age=now-birthday
if age > month:
	print 'your 1 month trial period has expired.'
	timebomb=1
else:
	naglist=[ 'Register and get free upgrades!','This software will expire-register today!','Shareware, not freeware. Please register!','Please register your shareware','Paying for shareware FEELS GOOD!','Your shareware dollar rewards creativity','Do YOU get 
paid for what you do?']
	print random.choice(naglist)
	timebomb=0
# end nagware suite
print '</td>'
print '<td width="120" align="right">Personal Edition</td>'
print '</tr></table>'
# begin suicide switch
if timebomb==1:
	print 'Shutting down. Your trial has expired. Please register your shareware.<P></body></html>'
	print 'It is time to register your shareware if you wish to continue to use it.<br>'
	print 'You can do so by going <a href="http://www.freeholdmarketing.com/WW/">HERE</a> and reegistering your copy for a mere $10.<P>'
	sys.exit()
# end suicide device
print '<div align="justify"><P>'
f1=open(pagename,'r')
page=f1.readlines()
f1.close()
#
def isin( searchthis, forthis ):	# return a 1 or 0 to control IF statements
	value = 1 + string.find(searchthis, forthis)
	if value > 0:
		return 1
	else:
		return 0
#
#
# Now we try to hash out wiether or not a word is a wikiword...
# a WikiWord is in CamelCaps. it has a 'hump' in it.
# ThisIs a WikiWord,
# but ThisISNOT,
# ANDNEITHERISTHIS,
# NorisTHIS. Fun?
#
# these functions build wikiwords.
def buildwikilink(word):		# turns a word into a hyperlink wikiword
	word = '<a href="./MW.py?' + word + '">' + word + '</a>' # it's a hyperlink anchor, normal html.
	return word
#		
def potentialword(word):		# processes word, seperates into prefix, word, and suffix
	newword=''
	prefix=''
	suffix=''
	index=0
	while 1:				# loop processes the word 1 char at a time- return breaks loop.
		if word[index] in string.ascii_letters:
			prefix, newword, suffix = mainbody(prefix, word[index:])
			return prefix, newword, suffix

		else:
			prefix=prefix+word[index]
			index=index+1
#
def mainbody(prefix, word,):
	newword=''
	suffix=''
	index=0
	for char in word:
		if char in string.ascii_letters:	
			newword=newword+char
		else:
			suffix=suffix+char	# the remainder of the word is the suffix
		index=index+1
	return prefix, newword, suffix
#
def makewikiword(word):				# combines processed link, prefizes, and suffix into a complete word.
	prefix=''
	suffix=''
	prefix, word, suffix=potentialword(word)	
	return prefix + buildwikilink(word) + suffix+' '
#
#
# these next 2 words determine if a word is a wikiword.
def processword(word):
	if word:					# it is possible to exause a word and not find another capital letter
		if word[0] in string.ascii_lowercase:	# wikiwords CAN have several lowercase letters before the next capital, after all...
			value=processword(word[1:])		# so keep invoking this word until exaustion, or a capital is found
			return value
		else: # MIGHT be a capital!
			if word[0] in string.ascii_uppercase:
				if len(word)>1: 	
					if word[1] in string.ascii_lowercase:
						return 1
					else:
						return 0	
				else:
					return 0	
			else:
				return 0		
	else:
		return 0
# def iswikiword(word):
# 	return bool(re.match('^([A-Z][a-z]+){2,}$', word))
#
def iswikiword(word):				# tests to see if a word is a wikiword.
	word=string.strip(word)
	if word:
		if word[0]in string.ascii_uppercase: # ALL wikiwords start with a capital.
			if (len(word)>3): 	# guard against small words ('A','I') blowing out the program
				if word[1] in string.ascii_lowercase:	# next letter MUST be lowercase
					if (len(word)>3):					# is there any more to process?
						if processword(word[2:]):	# is there another dipthong?
							return 1			# YES! it's a wikiword!
	return 0	# it's not a wikiword.
#
#
#
#
# this group processes the raw page to convert it to html code- but not wikiwords or links.
index=0
for line in page:
	line=string.replace(line,'<','&lt;')		# kills html tag opener
	line=string.replace(line,'>','&gt;')		# kills html tag closer
	if line == "":						# convert nulllines with P tag
		line='&nbsp;<P>'					# process the line for substrings
	line=string.replace(line,'\r',' <br> \r')		# end lines with a BR
	line=string.replace(line,'----','<hr>')		# create standard <hr>
	line=string.replace(line,'@!','<center>')		# open centering
	line=string.replace(line,'!@','</center>')	# close centering
	line=string.replace(line,"```","<b>")		# open BOLD
	line=string.replace(line,"'''","</b>")		# close BOLD
	line=string.replace(line,"``","<i>")		# open ITALIC
	line=string.replace(line,"''","</i>")		# Close Italic
	line=string.replace(line,"{{{","<pre>")		# open PREFORMATTED TEXT
	line=string.replace(line,"}}}","</pre>")	# close PREFORMATTED TEXT
	line=string.replace(line,'[=',' <table border="0" cellpadding="5" width=100% bgcolor="'+tablebgcolor+'"><tr><td><B><big>')	# create header bar
	line=string.replace(line,'=]','</big></b></td></tr></table>')	# end header bar
	line=string.replace(line,'{{{','<pre>')		# start preformastted text
	line=string.replace(line,'}}}','<pre>')		# end it.
	line=string.replace(line,'#! ','<img src="../images/')	# start an image tag
	line=string.replace(line,' !#','">')		# end an image tag
	line=string.replace(line,'[-','<ul> ')		# start an unordered list
	line=string.replace(line,'-]',' </ul> ')		# end an unordered list
	line=string.replace(line,'[#','<ol> ')		# start an ordered list
	line=string.replace(line,'#]','</ol> ')		# end an ordered list
	line=string.replace(line,'* ',' <li> ')		# declare a list item
	page[index]=line						# save resulting line
	index=index+1						# and increase the line pointer.
#
# wordscanner routine
linecounter=0							# reset the linepointer we will use it again...
for line in page:							# see?
	wordcounter=0						# start the word pointer over at 0 again
	wordlist = string.split(line,' ')			# split the line into a list of words.
	for word in wordlist:					# massage every word
		if ((isin(word,'http://')) or (isin(word,'mailto:'))):	# if this seems to be a hyperlink:
			if isin(word,'"'):			# DO NOT process a "http- it's imbedded code!
				pass					# DO NOT process; leave the word alone!
			else:						# otherwise, make a hyperlink for them to click.
				wordlist[wordcounter]='<a href="' + word + '">' + word + '</a> '
		else:
			if iswikiword(word):
				wordlist[wordcounter]=makewikiword(word)
			else:
				pass
		wordcounter=wordcounter+1
	line=string.join(wordlist,' ')
	page[linecounter]=line
	linecounter=linecounter+1
# print out the final highly modified page.
for line in page:
	print line,
#
# Page footer follows
print '\r<p></div><table border="0" width=100% cellpadding="10" bgcolor="'+tablebgcolor+'">'
print '<tr>'
print '<td width=30% >'
if not os.access(pagename,os.W_OK):
	print 'This page is Read-Only</td>'
else:
	print '<a href="./MWed1.py?'+pagename+'">Edit '+pagename+'</a></td>'
print '<td align="center" width=40% ><form method="get" action="./MWbacksearch.py?">'
print '<input type="text" size="20" maxlength="20" name="">&nbsp;<input type=submit value="SEARCH">'
print '</form></td>'
print '<td align="right" width=30% ><a href="./MWlistall.py">LIST ALL PAGES</a></td></tr>'
print '<tr><td><a href="http://www.tinylist.org/WW/">WindowsWiki V:1.4.0</a></td>'
print '<td align="center"><a href="/">Site home page</a></td>'
print '<td align="right"><a href="./MW.py?FrontPage">FrontPage</a></td></tr></table>'
print '</body></html>'


-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From HouseScript at comcast.net  Fri Mar 30 17:41:19 2007
From: HouseScript at comcast.net (HouseScript at comcast.net)
Date: Fri, 30 Mar 2007 15:41:19 +0000
Subject: [Tutor] A string-manipulation question
Message-ID: <033020071541.8590.460D2F9E000218300000218E22007343649C9A01070C9C019D0DA19C@comcast.net>

Alan Gilfoy wrote:

> Is there a way in Python to separate a string into its component words.


you could do something like this:

>>> x = Is there a way in Python to seperate a string into its compontent words.
>>> x.split()

that would yield:

['Is', 'there', 'a', 'way', 'in', 'Python', 'to', 'separate', 'a', 'string', 'into', 'its', 'component', 'words.']


As far as teh translating to pig latin.....well I honestly don't know.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070330/0dfd2b79/attachment.html 

From deliberatus at verizon.net  Fri Mar 30 17:42:29 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Fri, 30 Mar 2007 11:42:29 -0400
Subject: [Tutor] reafline reads file, not just 1 line
In-Reply-To: <460CF625.6070202@tds.net>
References: <460CAFFC.6030202@verizon.net> <460CF625.6070202@tds.net>
Message-ID: <460D2FE5.7060607@verizon.net>

BINGO! Perfect function!
GOD?**** windows. BUT THANK YOU!
(walks off mumbling curses at the billster of gates...)

Kent Johnson wrote:
> Kirk Bailey wrote:
>> a relevant code snip:
>>
>> if os.path.exists('ConfigureMe'):
>>     f1=open('ConfigureMe','r')
>>     tablebgcolor=string.strip(f1.readline())
>>
>> Eacj line in the file contains color configuration information to 
>> include into a webpage later on (for instance, 'peach, 'wjhite', 
>> 'black', 'Blue').
>>
>> tablebgcolor contains the entire text file being read, not one line.
>>
>> this program opereates in a windows 2000 environment if this helps any.
> 
> My guess is that the file contains non-native newlines. Try opening it 
> with universal newline support using
>   f1=open('ConfigureMe','rU')
> 
> Kent
> 
> 

-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From rabidpoobear at gmail.com  Fri Mar 30 17:48:04 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Fri, 30 Mar 2007 10:48:04 -0500
Subject: [Tutor] reafline reads file, not just 1 line
In-Reply-To: <460D2ED4.5050605@verizon.net>
References: <460CAFFC.6030202@verizon.net> <460CBF99.5090707@gmail.com>
	<460D2ED4.5050605@verizon.net>
Message-ID: <460D3134.7050701@gmail.com>

Kirk Bailey wrote:
> #!C:\Python25\pythonw.exe
#! is only for Unix, it's pointless here.
> #
> import os, os.path, random, sys, string, time, cgitb; cgitb.enable()
> #
> print "Content-Type: text/html\n"
> #
> try:
>     pagename=os.environ['QUERY_STRING']    # try to retreive the page  
> name requested
> except exception, e:
>     pagename="FrontPage"
> #
> if len(pagename)>3:
>     pass
> else:
>     pagename="FrontPage"            # but default to the FrontPage file.
or just:
if len(pagename < 3): pagename="FrontPage"
> #
> path=os.getcwd()
> if os.path.exists('WW.key'):
>     pass
> else:
>     f1=open('WW.key','w')
>     f1.write('unregistered')
>     f1.close()
If you find yourself passing on an if, you most likely need to take the 
complementary case.
> path=path+'\\text'
> os.chdir(path)        # make the pages dir current
> #
> """
> if os.path.exists('ConfigureMe'):
>     f1=open('ConfigureMe','r')
>     tablebgcolor=string.strip(f1.readline())
>     papercolor=string.strip(f1.readline())
>     inkcolor=string.strip(f1.readline())
>     linkcolor=string.strip(f1.readline())
>     f1.close()
This looks fine to me.  How do you know it's reading them all into the 
first item?
> else:
>     tablebgcolor='FFC0A0'
>     papercolor='White'
>     inkcolor='Black'
>     linkcolor='Blue'
>     f1=open('ConfigureMe','w')
>     f1.write(tablebgcolor+'\n')
>     f1.write(papercolor+'\n')
>     f1.write(inkcolor+'\n')
>     f1.write(linkcolor+'\n')
>     f1.write('\nThe lines above are:\n')
>     f1.write('tablecolor\n')
>     f1.write('papercolor\n')
>     f1.write('inkcolor\n')
>     f1.write('linkcolor\n\n')
What text editor are you using to view these?  Is this how you're 
determining that it's all 1 string in the first item, because there are 
no newlines in the outputted file?  I'd suggest you print out the values 
(tablebgcolor, etc) one at a time as you read them in, because it's 
possible that your text editor just chokes on \n (I believe on Windows 
you'd want to use \r\n) and that they really are stored separately.
>     f1.write('[=@! Navigation Toolbar !@=]\n')
>     f1.write('@! CategoryWiki !@\n')
>     f1.close()
> """
> tablebgcolor='FFC0A0'
> papercolor='White'
> inkcolor='Black'
> linkcolor='Blue'
>
> #
> if os.path.exists(pagename):            # if the page asked for exists,
>     pass                        # do nothing here;
> else:                            # BUT if it does NOT-
>     f1=open(pagename,'w')            # CREATE it!
>     f1.write("""Please contribute something to this webpage.
> [=@! Navigation toolbar !@=]
> @! FrontPage CategoryCategory !@""")
>     f1.close()
You really shouldn't have so many passes in if-statements.  I can't 
think of any situation where you couldn't move the else-block to the if 
and just add a 'not' to the condition.
> #
> # page header follows
> print "<html><head><title>WindowsWiki - " + pagename + "</title>"
> print '<style TYPE="text/css">'
> print "A:link, A:visited,  A:active { text-decoration:none; }"
> print "A:hover { text-decoration:underline; }"
> print 'body { margin-left: 5%; margin-right: 5%; }'
> print "</style></head>"
> print '<body bgcolor="' + papercolor + '" text="' + inkcolor + '" 
> links="' + linkcolor + '">'
> print '<table width=100% bgcolor="' + tablebgcolor + '" border="0" 
> cellpadding="10" cellspacing="0">'
> print '<tr>'
> print '<td width="120" ><B><font size="4" face="Georgia" 
> color="FF0000">WindowsWiki&trade;</font></B></td>'
> print '<td width="*" align="center" >(click title for backsearch)</td>'
> print '<td rowspan="2">&nbsp;</td>'
> print '</tr><tr>'
> print '<td>&nbsp;</td>'
> print '<td align="center"><font size="6"><a href="./MWbacksearch.py?' 
> + pagename + '">' + pagename + '</a></font></td>'
> # put a cell here if need be
> print '</tr><tr>'
> print '<td>&nbsp;</td>'
> print '<td align="center">'
I'd say you should read this in from a file.
> # Begin nagware suite
> birthday=os.stat('..\WW.key')[-1]
> now=int(time.time())
> month=60*60*24*30
> age=now-birthday
> if age > month:
>     print 'your 1 month trial period has expired.'
>     timebomb=1
> else:
>     naglist=[ 'Register and get free upgrades!','This software will 
> expire-register today!','Shareware, not freeware. Please 
> register!','Please register your shareware','Paying for shareware 
> FEELS GOOD!','Your shareware dollar rewards creativity','Do YOU get 
> paid for what you do?']
>     print random.choice(naglist)
>     timebomb=0
> # end nagware suite
You're aware that this is very easy to circumvent, right?
[snip rest of code]
Actually, my original request was for the _input file_ an an 
*attachment* not the source-code inline.
You should always include source as an attachment to prevent the e-mail 
clients from being malicious to it.

From tmikk at umn.edu  Fri Mar 30 18:59:05 2007
From: tmikk at umn.edu (Tonu Mikk)
Date: Fri, 30 Mar 2007 11:59:05 -0500
Subject: [Tutor] how to run a text file in an interpreter?
Message-ID: <460D41D9.60007@umn.edu>

Hello, I am new to the list and to programming in  general.   I want to 
learn Python as I find it an interesting language.  I also support an 
application that is written in Python called Roundup 
http://roundup.sf.net .  I find that I would like to make small tweaks 
to the program that require a knowledge of Python.

Now to my question.  I started reading Instant Python tutorial ( 
http://hetland.org/writing/instant-python.html ) and came across this 
section:
"/Note:/ To get the examples working properly, write the programs in a 
text file and then run that with the interpreter; do /not/ try to run 
them directly in the interactive interpreter - not all of them will work. "

I do not know what the author means by running a text file with the 
interpreter. I noticed that I came across an obstacle early on in trying 
out the code.

I tried writing

|first, second = second, first

into the PythonWin interpreter, but this resulted in the following error after pressing the return key:

Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
NameError: name 'second' is not defined

I imagine that I need to create a text file first and then run it with the interpreter.  How do I do that? 

Thank you,
Tonu 
|


From tmikk at umn.edu  Fri Mar 30 19:43:54 2007
From: tmikk at umn.edu (Tonu Mikk)
Date: Fri, 30 Mar 2007 12:43:54 -0500
Subject: [Tutor] how to run a text file in an interpreter?
Message-ID: <460D4C5A.6080605@umn.edu>

I started reading Instant Python tutorial ( 
http://hetland.org/writing/instant-python.html ) and came across this 
section:
"/Note:/ To get the examples working properly, write the programs in a 
text file and then run that with the interpreter; do /not/ try to run 
them directly in the interactive interpreter - not all of them will work. "

I do not know what the author means by running a text file with the 
interpreter. I noticed that I came across an obstacle early on in trying 
out the code.

I tried writing

|first, second = second, first

into the PythonWin interpreter, but this resulted in the following error after pressing the return key:

Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
NameError: name 'second' is not defined

I imagine that I need to create a text file first and then run it with the interpreter.  How do I do that? 

Thank you,
Tonu 
|



From Barry.Carroll at psc.com  Fri Mar 30 20:11:07 2007
From: Barry.Carroll at psc.com (Carroll, Barry)
Date: Fri, 30 Mar 2007 11:11:07 -0700
Subject: [Tutor] range()-like function for dealing with floats...?
In-Reply-To: <mailman.37.1175248851.24868.tutor@python.org>
Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595B4A@eugsrv400.psc.pscnet.com>

> -----Original Message-----
> Date: Fri, 30 Mar 2007 14:47:26 +0530
> From: "Joydeep Mitra" <snakepit.rattlesnakes at gmail.com>
> Subject: [Tutor] range()-like function for dealing with floats...?
> To: tutor at python.org
> Message-ID:
> 	<972566ff0703300217o7a916d89v565e78a5f1e479ec at mail.gmail.com>
> Content-Type: text/plain; charset="iso-8859-1"
> 
> Hi all,
> I need to generate a sequence of real numbers that are evenly spaced.
I
> have
> used loops for this purpose until now, but it gets kinna messy when
you
> gotta do it a number of times in a program.
> The range function, as per my knowledge, accepts parameters and return
> values only as integers.
> Is there a function in python, which performs the task of the range()
> function with floats?
> 
> Joy
Joy:

Try entering "python range float" at your personal favorite search
engine.  I tried it on Google.  Here is the first entry returned:

	ASPN : Python Cookbook : frange(), a range function with float
...
	Sadly missing in the Python standard library, this function
allows 
	to use ranges, just as the built-in function range(), but with 
	float arguments. ...
	aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66472 
	- 32k - Cached - Similar pages 

There were lots of others.  

Regards,
 
Barry
barry.carroll at psc.com
541-302-1107
________________________
We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed



From andreas at kostyrka.org  Fri Mar 30 19:13:44 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Fri, 30 Mar 2007 19:13:44 +0200
Subject: [Tutor] how to run a text file in an interpreter?
In-Reply-To: <460D4C5A.6080605@umn.edu>
References: <460D4C5A.6080605@umn.edu>
Message-ID: <20070330171344.GF5850@andi-lap.la.revver.com>

* Tonu Mikk <tmikk at umn.edu> [070330 18:52]:
> I started reading Instant Python tutorial ( 
> http://hetland.org/writing/instant-python.html ) and came across this 
> section:
> "/Note:/ To get the examples working properly, write the programs in a 
> text file and then run that with the interpreter; do /not/ try to run 
> them directly in the interactive interpreter - not all of them will work. "
> 
> I do not know what the author means by running a text file with the 
> interpreter. I noticed that I came across an obstacle early on in trying 
> out the code.
> 
> I tried writing
> 
> |first, second = second, first
> 
> into the PythonWin interpreter, but this resulted in the following error after pressing the return key:
> 
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
> NameError: name 'second' is not defined
> 
> I imagine that I need to create a text file first and then run it with the interpreter.  How do I do that?

Well, you did not mention your platform, but in this case, the
interactive one should do:
first = 1
second = 2
first, second = second, first

About these file thing:

Write your code to a file named ending in .py, and then call it as
python yourname.py

Andreas

From andreas at kostyrka.org  Fri Mar 30 19:28:51 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Fri, 30 Mar 2007 19:28:51 +0200
Subject: [Tutor] range()-like function for dealing with floats...?
In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A4304595B4A@eugsrv400.psc.pscnet.com>
References: <mailman.37.1175248851.24868.tutor@python.org>
	<2BBAEE949D384D40A2B851287ADB6A4304595B4A@eugsrv400.psc.pscnet.com>
Message-ID: <20070330172848.GG5850@andi-lap.la.revver.com>

* Carroll, Barry <Barry.Carroll at psc.com> [070330 19:15]:
> Try entering "python range float" at your personal favorite search
> engine.  I tried it on Google.  Here is the first entry returned:
> 
> 	ASPN : Python Cookbook : frange(), a range function with float
> ...
> 	Sadly missing in the Python standard library, this function
> allows 
> 	to use ranges, just as the built-in function range(), but with 
> 	float arguments. ...
> 	aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66472 
> 	- 32k - Cached - Similar pages 
> 
> There were lots of others.

Just don't forget that floats are not evenly spaced. The hole between
possible floats gets bigger the more you move away from zero.

On my IA32 Linux laptop I get:

>>> (1e+16) + 1 == (1e+16)
True
>>> (1e+16) + 10 == (1e+16)
False

So a frange(1e+16, (1e+16) + 1000, 1) won't work, or at best will
result something else than what you thought it would.

That's probably the reason why frange is not part of the standard
library: It's not possible to define it sensible for all float ranges,
and floats have many properties that make them fiendish. Typically,
programming courses just ignore the problematic aspects (at best one
learns that floats should not be used to represent money), one usually
has to take a course on Numerics to get the details.

Andreas

From rabidpoobear at gmail.com  Fri Mar 30 21:00:56 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Fri, 30 Mar 2007 14:00:56 -0500
Subject: [Tutor] reafline reads file, not just 1 line
In-Reply-To: <460D5ACD.9080909@verizon.net>
References: <460CAFFC.6030202@verizon.net> <460CBF99.5090707@gmail.com>
	<460D2ED4.5050605@verizon.net> <460D3134.7050701@gmail.com>
	<460D5ACD.9080909@verizon.net>
Message-ID: <460D5E68.3050708@gmail.com>

Kirk Bailey wrote:
>
>> This looks fine to me.  How do you know it's reading them all into 
>> the first item?
> I inserted some t4emporary code to print the variable name, then 
> value. The
> first one spewed the entire page, the others were null strings.
Okay, just makin' sure.
>>
>>> # Begin nagware suite birthday=os.stat('..\WW.key')[-1] 
>>> now=int(time.time()) month=60*60*24*30 age=now-birthday if age > 
>>> month: print 'your 1 month trial period has expired.' timebomb=1 
>>> else: naglist=[ 'Register and get free upgrades!','This software
>>> will expire-register today!','Shareware, not freeware. Please 
>>> register!','Please register your shareware','Paying for shareware 
>>> FEELS GOOD!','Your shareware dollar rewards creativity','Do YOU get 
>>> paid for what you do?'] print random.choice(naglist) timebomb=0 # 
>>> end nagware suite
>> You're aware that this is very easy to circumvent, right? 
> Sure it is- for hackers, geeks, and programmers. For roadwarriors who 
> know not bit from byte,
> who use the laptop as a tool in their career, it's cherry.
I mean... all that's required to reset the license is to delete WW.key 
and your program will recreate it.
I'm pretty sure that anyone could figure that out, even the 
roadwarriors.  Why not just use registry keys or something?
Just deleting a file is far too easy, IMHO.
Then again, I probably wouldn't make it expire after a certain period 
anyway.
> Attachments on a list? Sounds like trouble. Will they work on THIS list?
Yes.  They're recommended for source code (and input files and such).
E-mail clients will wrap code at odd places, mess with tabs and spacing, 
and things like that.
You should always send source as an attachment unless it's a short 
snippet (or you don't expect people to run it).

Well, your problem got solved already anyway, didn't it?
Have fun coding.

P.S. please reply on-list or give some explanation why you replied 
off-list, or I'll assume the private reply was an accident.
-Luke

From Barry.Carroll at psc.com  Fri Mar 30 21:13:08 2007
From: Barry.Carroll at psc.com (Carroll, Barry)
Date: Fri, 30 Mar 2007 12:13:08 -0700
Subject: [Tutor] range()-like function for dealing with floats...?
In-Reply-To: <mailman.19267.1175281266.32030.tutor@python.org>
Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595B4B@eugsrv400.psc.pscnet.com>

> -----Original Message-----
> Date: Fri, 30 Mar 2007 19:28:51 +0200
> From: Andreas Kostyrka <andreas at kostyrka.org>
> Subject: Re: [Tutor] range()-like function for dealing with floats...?
> To: "Carroll, Barry" <Barry.Carroll at psc.com>
> Cc: tutor at python.org
> Message-ID: <20070330172848.GG5850 at andi-lap.la.revver.com>
> Content-Type: text/plain; charset=us-ascii
> 
> * Carroll, Barry <Barry.Carroll at psc.com> [070330 19:15]:
> > Try entering "python range float" at your personal favorite search
> > engine.  I tried it on Google.  Here is the first entry returned:
> >
> > 	ASPN : Python Cookbook : frange(), a range function with float
> > ...
> > 	Sadly missing in the Python standard library, this function
> > allows
> > 	to use ranges, just as the built-in function range(), but with
> > 	float arguments. ...
> > 	aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66472
> > 	- 32k - Cached - Similar pages
> >
> > There were lots of others.
> 
> Just don't forget that floats are not evenly spaced. The hole between
> possible floats gets bigger the more you move away from zero.
> 
> On my IA32 Linux laptop I get:
> 
> >>> (1e+16) + 1 == (1e+16)
> True
> >>> (1e+16) + 10 == (1e+16)
> False
> 
> So a frange(1e+16, (1e+16) + 1000, 1) won't work, or at best will
> result something else than what you thought it would.
> 
> That's probably the reason why frange is not part of the standard
> library: It's not possible to define it sensible for all float ranges,
> and floats have many properties that make them fiendish. Typically,
> programming courses just ignore the problematic aspects (at best one
> learns that floats should not be used to represent money), one usually
> has to take a course on Numerics to get the details.
> 
> Andreas
> 
Andreas is right, of course.  In fact, the URL I referenced above
includes a discussion of the contributor's function and ways of
mitigating (NOT eliminating) the round-off problem.

Regards,
 
Barry
barry.carroll at psc.com
541-302-1107
________________________
We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed




From bgailer at alum.rpi.edu  Fri Mar 30 23:41:39 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Fri, 30 Mar 2007 14:41:39 -0700
Subject: [Tutor] [OT] ETL Tools
In-Reply-To: <b6131fdc0703300027l408f941dj7f32e745e1192aa2@mail.gmail.com>
References: <b6131fdc0703300027l408f941dj7f32e745e1192aa2@mail.gmail.com>
Message-ID: <460D8413.7010500@alum.rpi.edu>

Stephen Nelson-Smith wrote:
> Hello all,
>
> Does anyone know of any ETL (Extraction, Transformation, Loading)
> tools in Python (or at any rate, !Java)?
>   
I have under development a Python tool that is based on IBM's CMS 
Pipelines. I think it would be suitable for ETL. It would help me to see 
a sample of the raw data and a more detailed description of "process, 
aggregate, group-by". Perhaps your application is the nudge I need to 
bring this tool to life.

Let me know.
> I have lots (and lots) of raw data in the form of log files which I
> need to process and aggregate and then do a whole bunch of group-by
> operations, before dumping them into text/relational database for a
> search engine to access.
>
> At present we have a bunch of scripts in perl and ruby, and a berkley
> and mysql database for the grouping operations.  This is proving to be
> a little slow with the amount of data we now have, so I am looking
> into alternatives.
>
> Does anyone have any experience of this sort of  thing?  Or know
> someone who does, that I could talk to?
>
>   

-- 
Bob Gailer
510-978-4454


From bgailer at alum.rpi.edu  Fri Mar 30 23:54:17 2007
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Fri, 30 Mar 2007 14:54:17 -0700
Subject: [Tutor] A string-manipulation question
In-Reply-To: <033020071541.8590.460D2F9E000218300000218E22007343649C9A01070C9C019D0DA19C@comcast.net>
References: <033020071541.8590.460D2F9E000218300000218E22007343649C9A01070C9C019D0DA19C@comcast.net>
Message-ID: <460D8709.1070206@alum.rpi.edu>

HouseScript at comcast.net wrote:
> Alan Gilfoy wrote:
>
> > Is there a way in Python to separate a string into its component words.
> you could do something like this:
> >>> x = Is there a way in Python to seperate a string into its 
> compontent words.
> >>> x.split()
> that would yield:
> ['Is', 'there', 'a', 'way', 'in', 'Python', 'to', 'separate', 'a', 
> 'string', 'into', 'its', 'component', 'words.']
> As far as teh translating to pig latin.....well I honestly don't know.
 From Wikipedia, the rules are:

   1. For words that begin with consonant
      <http://en.wikipedia.org/wiki/Consonant> sounds, move the initial
      consonant or consonant cluster
      <http://en.wikipedia.org/wiki/Consonant_cluster> to the end of the
      word and add "ay." Examples:
          * fatso ? atso-fay
          * button ? /utton-bay/
          * star ? /ar-stay/
          * three ? /ee-thray/
          * question ? /estion-quay/
   2. For words that begin with vowel
      <http://en.wikipedia.org/wiki/Vowel> sounds (including silent
      consonants <http://en.wikipedia.org/wiki/Silent_letter>), simply
      add the syllable "ay" to the end of the word.
          * eagle ? /eagle-ay/
          * America ? /America-ay/
          * honor ? /honor-ay/

Seems pretty straightforward to translate to Python (or any other 
language). The only "hitch" I see is how one tells that an initial 
consonant is a vowel sound or not. (honor vs home)?

opehay isthay elphay

-- 
Bob Gailer
510-978-4454


From alan.gauld at btinternet.com  Sat Mar 31 01:17:51 2007
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Fri, 30 Mar 2007 23:17:51 +0000 (GMT)
Subject: [Tutor] Fw: 2) 'WHICH MULTI'
Message-ID: <20070330231751.95294.qmail@web86114.mail.ird.yahoo.com>

One of my tutorial users has come upon a really weird bug.

He has sent a transcript oif his session. Notice that wx 
is not defined yet doing help(wx) produces a strange message.
The message ius actually something he wrote as part of a 
wxPython application exercise, but this is showing up 
on a fresh start of Python.

I am completely baffled. Does anyone have any ideas? 
Any similar experiences?

Alan G.

----- Forwarded Message ----

Sorry for taking so long,i had problems accessing my email.This is the code:

Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on 
win32
Type "help", "copyright", "credits" or "license" for more information.
>>>print wx
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'wx' is not defined
>>>dir(wx)       <---- this was supposed to be just dir() but I doubt it would have helped
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'wx' is not defined
>>>help
Type help() for interactive help, or help(object) for help about object.
>>>help()

Welcome to Python 2.5!  This is the online help utility.

<snipped usual help verbiage....>

help> wx
which multi       <------- This is the string from his wx app, Alan G.
problem in <string> - <type 'exceptions.SyntaxError'>: unexpected EOF while 
parsing (<string>, line 0)

help>

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






	
	
		
___________________________________________________________ 
New Yahoo! Mail is the ultimate force in competitive emailing. Find out more at the Yahoo! Mail Championships. Plus: play games and win prizes. 
http://uk.rd.yahoo.com/evt=44106/*http://mail.yahoo.net/uk 

From gregp at liveammo.com  Sat Mar 31 02:17:00 2007
From: gregp at liveammo.com (Greg Perry)
Date: 30 Mar 2007 20:17:00 -0400
Subject: [Tutor] hashlib weirdness
Message-ID: <20070331001223.C53C71706B@smtp2.hushmail.com>

Here's one that has me stumped.

I am writing a forensic analysis tool that takes either a file or a directory as input, then calculates a hash digest based on the contents of each file.

I have created an instance of the hashlib class:

m = hashlib.md5()

I then load in a file in binary mode:

f = open("c:\python25\python.exe", "rb")

According to the docs, the hashlib update function will update the hash object with the string arg.  So:

m.update(f.read())
m.hexdigest()

The md5 hash is not correct for the file.

However, this works:

f.seek(0)
hashlib.md5(f.read()).hexdigest()

Why the difference I wonder?

Thanks in advance.



From gregp at liveammo.com  Sat Mar 31 02:23:00 2007
From: gregp at liveammo.com (Greg Perry)
Date: 30 Mar 2007 20:23:00 -0400
Subject: [Tutor] getopts question
Message-ID: <20070331001814.179191706E@smtp2.hushmail.com>

Yeah I figured that.  I am trying to find a way to have the program detect if the user input is a file or directory, which is easy enough with os.path.  However, os.path makes no distinction between a regular file and a mask, eg filename.txt or *.txt.  I guess I'll have to have a second set of tests to see if the filename contains any wildcards..?

-----Original Message-----
From: Kent Johnson

>I'm not really sure what you are looking for here. If you use two options, you will have to test to see which option is set. You could use one option, then you will have to test to see if the value is a file or a directory.
>
>Kent




From andreas at kostyrka.org  Sat Mar 31 01:23:59 2007
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Sat, 31 Mar 2007 01:23:59 +0200
Subject: [Tutor] getopts question
In-Reply-To: <20070331001814.179191706E@smtp2.hushmail.com>
References: <20070331001814.179191706E@smtp2.hushmail.com>
Message-ID: <20070330232359.GH5850@andi-lap.la.revver.com>

* Greg Perry <gregp at liveammo.com> [070331 01:21]:
> Yeah I figured that.  I am trying to find a way to have the program detect if the user input is a file or directory, which is easy enough with os.path.  However, os.path makes no distinction between a regular file and a mask, eg filename.txt or *.txt.  I guess I'll have to have a second set of tests to see if the filename contains any wildcards..?
That depends upon the OS. On Unix style systems, the wildcard is
interpreted by the shell, so typically programs don't see any
wildcards.

Andreas

From gregp at liveammo.com  Sat Mar 31 02:39:00 2007
From: gregp at liveammo.com (Greg Perry)
Date: 30 Mar 2007 20:39:00 -0400
Subject: [Tutor] os.path.isfile and isdir
Message-ID: <20070331003415.997F61705B@smtp2.hushmail.com>

It looks like both os.path.isfile and os.path.isdir evaluate to False for a wildcard, so that makes it a bit easier to deal with a mask.

Thanks to everyone for the suggestions.



From deliberatus at verizon.net  Sat Mar 31 05:08:12 2007
From: deliberatus at verizon.net (Kirk Bailey)
Date: Fri, 30 Mar 2007 23:08:12 -0400
Subject: [Tutor] reafline reads file, not just 1 line
In-Reply-To: <460D5E68.3050708@gmail.com>
References: <460CAFFC.6030202@verizon.net> <460CBF99.5090707@gmail.com>
	<460D2ED4.5050605@verizon.net> <460D3134.7050701@gmail.com>
	<460D5ACD.9080909@verizon.net> <460D5E68.3050708@gmail.com>
Message-ID: <460DD09C.6070907@verizon.net>

Setting a registry key does sound like a nice idea, but I must research 
it. Until I understand how so,mething works, I do now want to use it, 
which is why the RE. definition for determining wikiwords is commented 
out- someone suggested it, but it leaves me in the fog, I must study re 
more first.

I replied off list due to just clicking reply, not replyall, and this 
list is not set up with a replyto header. so away it went.



-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From rikard.bosnjakovic at gmail.com  Sat Mar 31 10:19:15 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Sat, 31 Mar 2007 10:19:15 +0200
Subject: [Tutor] reafline reads file, not just 1 line
In-Reply-To: <460DD09C.6070907@verizon.net>
References: <460CAFFC.6030202@verizon.net> <460CBF99.5090707@gmail.com>
	<460D2ED4.5050605@verizon.net> <460D3134.7050701@gmail.com>
	<460D5ACD.9080909@verizon.net> <460D5E68.3050708@gmail.com>
	<460DD09C.6070907@verizon.net>
Message-ID: <d9e88eaf0703310119k1281bf10yc9e65dee966e3d15@mail.gmail.com>

On 3/31/07, Kirk Bailey <deliberatus at verizon.net> wrote:

> I replied off list due to just clicking reply, not replyall, and this
> list is not set up with a replyto header. so away it went.

Youre not the first one, and definately not the last one...

-- 
- Rikard - http://bos.hack.org/cv/

From rschroev_nospam_ml at fastmail.fm  Sat Mar 31 10:19:42 2007
From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven)
Date: Sat, 31 Mar 2007 10:19:42 +0200
Subject: [Tutor] getopts question
In-Reply-To: <20070331001814.179191706E@smtp2.hushmail.com>
References: <20070331001814.179191706E@smtp2.hushmail.com>
Message-ID: <eul5iv$29h$1@sea.gmane.org>

Greg Perry schreef:
> Yeah I figured that.  I am trying to find a way to have the program
> detect if the user input is a file or directory, which is easy enough
> with os.path.  However, os.path makes no distinction between a
> regular file and a mask, eg filename.txt or *.txt.  I guess I'll have
> to have a second set of tests to see if the filename contains any
> wildcards..?

As Andreas wrote, that won't be necessary on Unix systems, since the 
shell already expands the wildcards before passing it to your program.

On Windows you can use the glob module to expand the wildcards.

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

Roel Schroeven


From rikard.bosnjakovic at gmail.com  Sat Mar 31 10:20:19 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Sat, 31 Mar 2007 10:20:19 +0200
Subject: [Tutor] getopts question
In-Reply-To: <20070331001814.179191706E@smtp2.hushmail.com>
References: <20070331001814.179191706E@smtp2.hushmail.com>
Message-ID: <d9e88eaf0703310120g43ee7d70n5f66859aee207a7@mail.gmail.com>

On 30 Mar 2007 20:23:00 -0400, Greg Perry <gregp at liveammo.com> wrote:
> Yeah I figured that.  I am trying to find a way to have the program detect if the user input is a file or directory, which is easy enough with os.path.  However, os.path makes no distinction between a regular file and a mask, eg filename.txt or *.txt.  I guess I'll have to have a second set of tests to see if the filename contains any wildcards..?

Or use the glob-module.

-- 
- Rikard - http://bos.hack.org/cv/

From dhirajsharma at optonline.net  Sat Mar 31 07:07:02 2007
From: dhirajsharma at optonline.net (Dhiraj Sharma)
Date: Sat, 31 Mar 2007 00:07:02 -0500
Subject: [Tutor] Cancelling a thread or blocked read
Message-ID: <000201c77352$6f5d5a90$0401a8c0@hp1140>

I would appreciate help on two related questions:

1. Is it possible to cancel (kill) a "child" thread from the main thread in Python running on Windows? 

2. Also, is it possible to cancel (abort) a blocking read (say, to stdin) in a function that can be called by a timer? The goal is to cancel the read if input is not forthcoming within a specified time.

I have looked in the Python manuals and the Web, but did not find any thing.

Thank you in advance.
DKS
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070331/523c5cd5/attachment.html 

From rikard.bosnjakovic at gmail.com  Sat Mar 31 15:15:45 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Sat, 31 Mar 2007 15:15:45 +0200
Subject: [Tutor] Cancelling a thread or blocked read
In-Reply-To: <000201c77352$6f5d5a90$0401a8c0@hp1140>
References: <000201c77352$6f5d5a90$0401a8c0@hp1140>
Message-ID: <d9e88eaf0703310615k6c2cda4ekc13b7e97d70a6a7c@mail.gmail.com>

On 3/31/07, Dhiraj Sharma <dhirajsharma at optonline.net> wrote:

> 2. Also, is it possible to cancel (abort) a blocking read (say, to stdin) in
> a function that can be called by a timer? The goal is to cancel the read if
> input is not forthcoming within a specified time.

For Windows, no idea. For Unix I'd use the signal-module and setup a
SIGALRM-handler.

http://docs.python.org/lib/module-signal.html

-- 
- Rikard - http://bos.hack.org/cv/

From eike.welk at gmx.net  Sat Mar 31 17:38:49 2007
From: eike.welk at gmx.net (Eike Welk)
Date: Sat, 31 Mar 2007 17:38:49 +0200
Subject: [Tutor] Cancelling a thread or blocked read
In-Reply-To: <000201c77352$6f5d5a90$0401a8c0@hp1140>
References: <000201c77352$6f5d5a90$0401a8c0@hp1140>
Message-ID: <200703311738.49604.eike.welk@gmx.net>

On Saturday 31 March 2007 07:07, Dhiraj Sharma wrote:
> I would appreciate help on two related questions:
>
> 1. Is it possible to cancel (kill) a "child" thread from the main
> thread in Python running on Windows?

I don't think so. If you want to kill part of the program you must run 
it in a different process. 

I think only in old Linux versions it was possible to kill a thread, 
because there was no fundamental difference between process and 
thread. 

Regards Eike.


From chris.arndt at web.de  Sat Mar 31 18:18:38 2007
From: chris.arndt at web.de (Christopher Arndt)
Date: Sat, 31 Mar 2007 18:18:38 +0200
Subject: [Tutor] Cancelling a thread or blocked read
In-Reply-To: <000201c77352$6f5d5a90$0401a8c0@hp1140>
References: <000201c77352$6f5d5a90$0401a8c0@hp1140>
Message-ID: <460E89DE.9080907@web.de>

Dhiraj Sharma schrieb:
> 1. Is it possible to cancel (kill) a "child" thread from the main thread
> in Python running on Windows?

If you have control over the code of the thread, it could periodically check
(in it's "run" method) an Event or Queue object, whether it should exit. See
http://www.python.org/doc/current/lib/event-objects.html

> 2. Also, is it possible to cancel (abort) a blocking read (say, to
> stdin) in a function that can be called by a timer? The goal is to
> cancel the read if input is not forthcoming within a specified time.

Under Unix-like systems I'd use the "select" module
(http://www.python.org/doc/current/lib/module-select.html), but under Windows
this only works for sockets.

Chris

From lists1 at marscode.net  Sat Mar 31 18:29:44 2007
From: lists1 at marscode.net (Peter)
Date: Sat, 31 Mar 2007 11:29:44 -0500
Subject: [Tutor] Detect errors when using os.popen.readlines()
Message-ID: <460E8C78.80803@marscode.net>

Is there a way to detect errors when running shell commands using 
os.popen?  I'm trying to get an ip address for ethernet interfaces, and 
if an interface doesn't exist I get an error from the shell command.  I 
tried using try and except, but that did seem to work.

Thanks in advance.

Peter

From jmutter at uakron.edu  Sat Mar 31 19:39:16 2007
From: jmutter at uakron.edu (Jay Mutter III)
Date: Sat, 31 Mar 2007 13:39:16 -0400
Subject: [Tutor] Another parsing question
Message-ID: <6183015B-0810-4351-A6C4-97909399D651@uakron.edu>

I have the following that I am using to extract "numbers' from a file


prompt1 = raw_input('What is the file from which you would like a  
list of patent numbers?      ')
p1 = open(prompt1,'rU')
s = p1.readlines()
prompt2 = raw_input('What is the name of the file to which you would  
like to save the list of patent numbers?      ')
p2 = open(prompt2,'aU')
patno = re.compile(r'(\d{1})[\s,.]+(\d{3})[\s,.]+(\d{3})')
for line in s:
     jay = patno.findall(line)
     print jay

which yields the following

[('1', '337', '912')]
[('1', '354', '756')]
[('1', '360', '297')]
[('1', '328', '232')]
[('1', '330', '123')]
[('1', '362', '944')]
[('1', '350', '461')]
[('1', '355', '991')]
[('1', '349', '385')]
[('1', '350', '521')]
[('1', '336', '542')]
[('1', '354', '922')]
[('1', '338', '268')]
[('1', '353', '682')]
[('1', '343', '241')]
[('1', '359', '852')]
[('1', '342', '483')]
[('1', '347', '068')]
[('1', '331', '450')]

if i try to write to a file instead of print to the screen using
p2.write(jay)
i get the message

Traceback (most recent call last):
   File "patentno.py", line 12, in ?
     p2.write(jay)
TypeError: argument 1 must be string or read-only character buffer,  
not list

I f I try writelines i get

Traceback (most recent call last):
   File "patentno.py", line 12, in ?
     p2.writelines(jay)
TypeError: writelines() argument must be a sequence of strings
jay-mutter-iiis-computer:~/documents/programming/python/patents jlm1$


So what do i have above ? A list of tuples?

How do I  send the output to a file?
Is there a way to get the output as

1337912  instead of   [('1', '337', '912')]  ?

And as always thanks in advance for the help.

jay Mutter


From jmutter at uakron.edu  Sat Mar 31 19:48:12 2007
From: jmutter at uakron.edu (Jay Mutter III)
Date: Sat, 31 Mar 2007 13:48:12 -0400
Subject: [Tutor] Another parsing question
In-Reply-To: <6183015B-0810-4351-A6C4-97909399D651@uakron.edu>
References: <6183015B-0810-4351-A6C4-97909399D651@uakron.edu>
Message-ID: <4E8C34CF-8353-4541-BD7D-7A56E589BB40@uakron.edu>

Ok after a minute of thought I did solve my second question by simply  
changing my RE to

(r'(\d{1}[\s,.]+\d{3}[\s,.]+\d{3})')

but still haven't gotten he first one.


On Mar 31, 2007, at 1:39 PM, Jay Mutter III wrote:

> I have the following that I am using to extract "numbers' from a file
>
>
> prompt1 = raw_input('What is the file from which you would like a  
> list of patent numbers?      ')
> p1 = open(prompt1,'rU')
> s = p1.readlines()
> prompt2 = raw_input('What is the name of the file to which you  
> would like to save the list of patent numbers?      ')
> p2 = open(prompt2,'aU')
> patno = re.compile(r'(\d{1})[\s,.]+(\d{3})[\s,.]+(\d{3})')
> for line in s:
>     jay = patno.findall(line)
>     print jay
>
> which yields the following
>
> [('1', '337', '912')]
> [('1', '354', '756')]
> [('1', '360', '297')]
> [('1', '328', '232')]
> [('1', '330', '123')]
> [('1', '362', '944')]
> [('1', '350', '461')]
> [('1', '355', '991')]
> [('1', '349', '385')]
> [('1', '350', '521')]
> [('1', '336', '542')]
> [('1', '354', '922')]
> [('1', '338', '268')]
> [('1', '353', '682')]
> [('1', '343', '241')]
> [('1', '359', '852')]
> [('1', '342', '483')]
> [('1', '347', '068')]
> [('1', '331', '450')]
>
> if i try to write to a file instead of print to the screen using
> p2.write(jay)
> i get the message
>
> Traceback (most recent call last):
>   File "patentno.py", line 12, in ?
>     p2.write(jay)
> TypeError: argument 1 must be string or read-only character buffer,  
> not list
>
> I f I try writelines i get
>
> Traceback (most recent call last):
>   File "patentno.py", line 12, in ?
>     p2.writelines(jay)
> TypeError: writelines() argument must be a sequence of strings
> jay-mutter-iiis-computer:~/documents/programming/python/patents jlm1$
>
>
> So what do i have above ? A list of tuples?
>
> How do I  send the output to a file?
> Is there a way to get the output as
>
> 1337912  instead of   [('1', '337', '912')]  ?
>
> And as always thanks in advance for the help.
>
> jay Mutter
>


From kent37 at tds.net  Sat Mar 31 20:27:21 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 31 Mar 2007 14:27:21 -0400
Subject: [Tutor] Another parsing question
In-Reply-To: <6183015B-0810-4351-A6C4-97909399D651@uakron.edu>
References: <6183015B-0810-4351-A6C4-97909399D651@uakron.edu>
Message-ID: <460EA809.5040108@tds.net>

Jay Mutter III wrote:
> I have the following that I am using to extract "numbers' from a file
> ...
> which yields the following
> 
> [('1', '337', '912')]
 > ...
> So what do i have above ? A list of tuples?

Yes, each line is a list containing one tuple containing three string 
values.

> How do I  send the output to a file?

When you print, the values are automatically converted to strings by 
calling str() on them. When you use p2.write(), this conversion is not 
automatic, you have to do it yourself via
   p2.write(str(jay))

You can also tell the print statement to output to a file like this:
   print >>p2, jay

> Is there a way to get the output as
> 
> 1337912  instead of   [('1', '337', '912')]  ?

In [4]: jay=[('1', '337', '912')]

jay[0] is the tuple alone:
In [6]: jay[0]
Out[6]: ('1', '337', '912')

Join the elements together using an empty string as the separator:
In [5]: ''.join(jay[0])
Out[5]: '1337912'
In [7]:

Kent

From project5 at redrival.net  Sat Mar 31 20:46:42 2007
From: project5 at redrival.net (Andrei)
Date: Sat, 31 Mar 2007 20:46:42 +0200
Subject: [Tutor] Another parsing question
In-Reply-To: <4E8C34CF-8353-4541-BD7D-7A56E589BB40@uakron.edu>
References: <6183015B-0810-4351-A6C4-97909399D651@uakron.edu>
	<4E8C34CF-8353-4541-BD7D-7A56E589BB40@uakron.edu>
Message-ID: <eumaa4$b4v$1@sea.gmane.org>

Hello Jay,

Jay Mutter III wrote:
> but still haven't gotten he first one.
> 
<snip>
>> for line in s:
>>     jay = patno.findall(line)
>>     print jay
>>
>> which yields the following
>>
>> [('1', '337', '912')]
>> [('1', '354', '756')]
<snip>
>> if i try to write to a file instead of print to the screen using
>> p2.write(jay)
>> i get the message
>>
>> Traceback (most recent call last):
>>   File "patentno.py", line 12, in ?
>>     p2.write(jay)
>> TypeError: argument 1 must be string or read-only character buffer,  
>> not list

Have a look at the output of print jay in the loop: it's a list 
containing a single tuple. The traceback is telling you that write() 
expects to get a string, not a list - you'll have to convert your list 
to a string. There are more ways to do this, depending on your needs. 
You could for example simply use p2.write(str(jay)), which will put in 
the file exactly what you see on the screen.
You could also pretty-format it like this:

   >>> prettyjay = "".join(jay[0])
   >>> p2.write(prettyjay + "\n")

This will yield strings like "1336012".

On a side-note, you should pay attention to the way you name your 
variables. prompt1 is descriptive, but strongly suggests that you have a 
prompt2, prompt3, etc. lurking somewhere in the code - and indeed, you 
do have a prompt2. Imagine a large program with many prompts, it would 
have prompt458, prompt2893. What happens if you remove prompt45 - 
renumber all the other ones?
Not only that, prompt1 is actually a filename, while the name suggests 
it's simply a string shown to the user. It would be better to name them 
e.g. InputFileName and OutputFileName and the files themselves InputFile 
and OutputFile instead of p1/p2. patno suggests it's shorthand notation 
for PatternNumber - while it's in fact a regex, not a number at all.

Naming variables after yourself, movie stars, pets or other frivolities 
- flattering as it may be - will become problematic when a couple of 
months later you're wondering why the application crashes upon adding 
Fido to DarthVader, appending the result to ApplePie and writing that to 
PamelaAnderson.

Yours,

Andrei

=====
Mail address in header catches spam. Real contact info:
''.join([''.join(s) for s in zip(
"poet at aao.l pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
"rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])


From andrei.petre at gmail.com  Sat Mar 31 23:43:16 2007
From: andrei.petre at gmail.com (Andrei Petre)
Date: Sun, 1 Apr 2007 00:43:16 +0300
Subject: [Tutor] tokenizing a simple string with split()
Message-ID: <3576e740703311443q7a25a476iba10c15fbe4345a0@mail.gmail.com>

I want to split a string like "C:\My\Doc\;D:\backup\" with two separators: \
and ;
I found that \ is handled with *raw string* notation r"". But the problem i
encountered is with split() function.
In the 2.5 reference is said that "The sep argument of the split() function
may consist of multiple characters". But I cannot figured out why this
simple example not working:

s = "spam;egg mail"
s.split("; ")

output: ['spam;egg mail']

instead of ['spam', 'egg', 'mail']

any suggestion is welcome,
andrei
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070401/1004ee19/attachment.html