From orest.kozyar at gmail.com  Thu Nov  1 00:47:38 2007
From: orest.kozyar at gmail.com (Orest Kozyar)
Date: Wed, 31 Oct 2007 19:47:38 -0400
Subject: [Tutor] perplexing error with shelve REVISED
In-Reply-To: <472905B1.8070508@brunson.com>
References: <001401c81b15$663ff5b0$bd32000a@meei.harvard.edu>	<47277521.2090802@alum.rpi.edu>
	<002101c81b23$936452d0$bd32000a@meei.harvard.edu>
	<472905B1.8070508@brunson.com>
Message-ID: <004e01c81c18$6c96e3c0$bd32000a@meei.harvard.edu>

> It appears you have a cyclic reference in your doc object.  
> Try adding "doc.unlink()" before you add it to your shelf.

That fixed the problem.  I did not realize that XML documents could have
cyclic references.  Thanks for all your help!

Orest


From kent37 at tds.net  Thu Nov  1 01:12:41 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 31 Oct 2007 20:12:41 -0400
Subject: [Tutor] perplexing error with shelve REVISED
In-Reply-To: <472905B1.8070508@brunson.com>
References: <001401c81b15$663ff5b0$bd32000a@meei.harvard.edu>	<47277521.2090802@alum.rpi.edu>	<002101c81b23$936452d0$bd32000a@meei.harvard.edu>
	<472905B1.8070508@brunson.com>
Message-ID: <472919F9.6060500@tds.net>

Eric Brunson wrote:
> Orest Kozyar wrote:
>>> Please post the entire traceback (omitting duplicate lines). 
>>>     
>> Sorry, I should have included the traceback.  I've revised the sample script
>> so that it generates the traceback when run.  The sample script is at the
>> very bottom of this email.
>>   
> 
> It appears you have a cyclic reference in your doc object.  Try adding 
> "doc.unlink()" before you add it to your shelf.

I thought pickle was supposed to deal with cyclic references? The docs say,

"The pickle module keeps track of the objects it has already serialized, 
so that later references to the same object won't be serialized again. 
marshal doesn't do this.

"This has implications both for recursive objects and object sharing. 
Recursive objects are objects that contain references to themselves. 
These are not handled by marshal, and in fact, attempting to marshal 
recursive objects will crash your Python interpreter. Object sharing 
happens when there are multiple references to the same object in 
different places in the object hierarchy being serialized. pickle stores 
such objects only once, and ensures that all other references point to 
the master copy. Shared objects remain shared, which can be very 
important for mutable objects."

Kent


From andrewwu at gmail.com  Thu Nov  1 02:16:11 2007
From: andrewwu at gmail.com (Andrew Wu)
Date: Wed, 31 Oct 2007 18:16:11 -0700
Subject: [Tutor] Regular Expression help - parsing AppleScript Lists as
	Strings
Message-ID: <99acdf3c0710311816n57c3fc24ieee53a0cb0043f55@mail.gmail.com>

Hi,

I'm writing utilities to handle return values from AppleScript in python and
one of the steps is recognizing when a returned value from an AppleScript
execution (via popen and osascript) represents a list (in AppleScript) or
not.  For the most part I think I have the correct matching pattern, but I
am hung up on one of the sample strings I was using to test it - AppleScript
allows for one level of nested lists (I believe) and I get tripped up with
attempting to match lists with nested lists.

My second question is, once I have a pattern matching correctly, I need to
convert the AppleScript list into a Python list - I've read a bit about the
findall() method of the re module and was wondering if that would work in
this instance (there's also split() but I've been having issues with that,
probably b/c my pattern matching isn't correct).


Thank you!

Andrew

(source code below)



#!/usr/bin/env python
# Sample script to test if a string represented an AppleScript List or not

import re
import os

def IsASList(thestr=''):
   # AppleScript lists are bracked by curly braces with items separate by
commas
   # Each item is an alphanumeric label(?) or a string enclosed by
   # double quotes or a list itself
   # e.g. {2, True, "hello"}
   #
   # They differ from AppleScript records in that AS records have a key and
value:
   # {name: "Buffy", field: "Slaying", job: true, age: 21}
   #
   # Now the question is how to make the distinction?

   pattern = '''
      ^{    # Must start with a curly brace
      (
      \s*?     # Group to repeat; clear the whitespace after commas first
      (       # Start of group of alternating match possibilities
      ".+?"   # Match a string
      | \d+?     # Match a number
      | true|false  # Match 'true' or 'false' label
      )       # End of group of alternating match possibilities
      ,?)*     # Items are comma-delimited, except for the last item
      }$    # Must end with a closing curly brace
   '''

   pattern2 = '''
      (
      \s*?     # Group to repeat; clear the whitespace after commas first
      (       # Start of group of alternating match possibilities
      ".+?"   # Match a string
      | \d+?     # Match a number
      | true|false  # Match 'true' or 'false' label
      )       # End of group of alternating match possibilities
      ,?)*     # Items are comma-delimited, except for the last item
   '''

   pattern3 = '''
      ^{
      (
      %s
      | {%s}   # Possible to have 1 level of nested lists
      ,?)*     # Items are comma-delimited, except for the last item
      }$
   ''' % (pattern2, pattern2)

   regex = re.compile(pattern3, re.VERBOSE)
   result = regex.match(thestr)

#   print 'Result: ',
#   try:
#      print result.groups()
#   except AttributeError:
#      pass

   if result:
      return True
   else:
      return False


# main()

sample_strs = [
   '{}',      # Empty list
   '{a}',     # Should not match
   '{a, b, c}', # Should not match
   '{"hello"}',
   '{"hello", "kitty"}',
   '{true}',
   '{false}',
   '{true, false}',
   '{9}',
   '{9,10, 11}',
   '{93214, true, false, "hello", "kitty"}',
   '{{1, 2, 3}}',  # This matches
   '{{1, 2, "cat"}, 1}',  # This matches

    # These don't match:
   '{{1,2,3},1,{4,5,6},2}',
   '{1, {2, 3, 4}, 3}',
   '{{1, 2, 3}, {4, 5, 6}, 1}',
   '{1, {1, 2, 3}}',  # Should match but doesn't
   '{93214, true, false, "hello", "kitty", {1, 2, 3}}',  # Should match but
doesn't
   '{label: "hello", value: false, num: 2}',  # AppleScript dictionary -
should not match
]

for sample in sample_strs:
   print 'Is AppleScript List:  %s;   String:  %s' % (str(IsASList(sample)),
sample)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071031/24c0bd14/attachment.htm 

From trey at opmstech.org  Thu Nov  1 03:22:19 2007
From: trey at opmstech.org (Trey Keown)
Date: Wed, 31 Oct 2007 21:22:19 -0500 (CDT)
Subject: [Tutor] Getting single values of a tuple & storing them
Message-ID: <60499.68.191.136.241.1193883739.squirrel@webmail.opmstech.org>

Hey all,
I was wondering, how could I get each value inside of a tuple, say it's
(2,4) .
The only value I really need is the second one (the tuple will always have
only two values.

Thanks for any help.


From orest.kozyar at gmail.com  Thu Nov  1 03:37:03 2007
From: orest.kozyar at gmail.com (Orest Kozyar)
Date: Wed, 31 Oct 2007 22:37:03 -0400
Subject: [Tutor] perplexing error with shelve REVISED
In-Reply-To: <472905B1.8070508@brunson.com>
References: <001401c81b15$663ff5b0$bd32000a@meei.harvard.edu>	<47277521.2090802@alum.rpi.edu>
	<002101c81b23$936452d0$bd32000a@meei.harvard.edu>
	<472905B1.8070508@brunson.com>
Message-ID: <004f01c81c30$17440200$bd32000a@meei.harvard.edu>


> It appears you have a cyclic reference in your doc object.  
> Try adding "doc.unlink()" before you add it to your shelf.

Actually, I just realized that doc.unlink() seems to delete the entire XML
content, which kind of defeats the purpose of caching it.  I'll check on
xml-sig and the comp.lang.python group to see if there are any suggestions.

Thanks again for your help!
Orest


From billburns at pennswoods.net  Thu Nov  1 04:38:12 2007
From: billburns at pennswoods.net (Bill Burns)
Date: Wed, 31 Oct 2007 22:38:12 -0500
Subject: [Tutor] Getting single values of a tuple & storing them
In-Reply-To: <60499.68.191.136.241.1193883739.squirrel@webmail.opmstech.org>
References: <60499.68.191.136.241.1193883739.squirrel@webmail.opmstech.org>
Message-ID: <47294A24.90206@pennswoods.net>

Trey Keown wrote:
> Hey all,
> I was wondering, how could I get each value inside of a tuple, say it's
> (2,4) .
> The only value I really need is the second one (the tuple will always have
> only two values.
> 
> Thanks for any help.
> 

Try one of these approaches:

In [1]: t = (2, 4)

In [2]: t[0]
Out[2]: 2

In [3]: t[1]
Out[3]: 4

In [4]: first, second = (2, 4)

In [5]: first
Out[5]: 2

In [6]: second
Out[6]: 4

HTH,

Bill

From mlangford.cs03 at gtalumni.org  Thu Nov  1 06:15:31 2007
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Thu, 1 Nov 2007 01:15:31 -0400
Subject: [Tutor] Build exe on Vista, have it run on XP?
In-Reply-To: <20071031200911.GA3578@gmail.com>
References: <82b4f5810710290759h33b5f8e3ja5a32cd1b668a74a@mail.gmail.com>
	<20071031200911.GA3578@gmail.com>
Message-ID: <82b4f5810710312215k7133ac37x2c93913282dc75f3@mail.gmail.com>

That's not really a working solution. My available development platform is a
Vista machine. I don't have an available XP platform. XP built exes run fine
on Vista, just not vice versa.

             --Michael

On 10/31/07, O.R.Senthil Kumaran <orsenthil at gmail.com> wrote:
>
> * Michael Langford <mlangford.cs03 at gtalumni.org> [2007-10-29 10:59:34]:
>
> > I'm trying to build a exe on a vista system using py2exe. It will deploy
> to
> > vista and XP systems. If it matters, the application uses pyserial, as
> well.
>
> Before you proceed with lot of other experiments, my suggestion would be
> build exes on VISTA and XP separately, and trying running on the other
> system. I am assuming the either of the two.
> a) VISTA dlls should be backward compatible with XP, which your issue
> indicates that you faced problems.
> b) functionality which is provided by exe built on XP, should be provided
> by VISTA as well.
>
> I would also suggest to check the files and for any incompatible ones,
> ship both. I doubt, if renaming of msvcrt.dll to something like
> msvcrt1.dll will work if you have carry both. Just a little research on
> py2exe checking if we can ship two same named dlls in perhaps different
> folders can help.
>
> Thanks,
> Senthil
>
>
> --
> O.R.Senthil Kumaran
> http://uthcode.sarovar.org
>



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

From aditya.n.lal at gmail.com  Thu Nov  1 07:23:42 2007
From: aditya.n.lal at gmail.com (Aditya Lal)
Date: Thu, 1 Nov 2007 11:53:42 +0530
Subject: [Tutor] question re type()
In-Reply-To: <47286B89.1030405@tds.net>
References: <20071027112905.AFC3C1E4005@bag.python.org>
	<ffv9ed$6m3$1@ger.gmane.org>
	<5df213700710270652i1c38571bl4a85edcfa54af977@mail.gmail.com>
	<4725C3D9.8000506@tds.net>
	<5df213700710302313g4e128ce6tbca45a624798a20b@mail.gmail.com>
	<47286B89.1030405@tds.net>
Message-ID: <5df213700710312323u6e5db24aw7d99b7c3e9ae6992@mail.gmail.com>

On 10/31/07, Kent Johnson <kent37 at tds.net> wrote:
>
> Aditya Lal wrote:
> > On 10/29/07, *Kent Johnson* <kent37 at tds.net <mailto:kent37 at tds.net>>
> wrote:
>
> >     - Common Python practice is to prefer the least restrictive type
> check
> >     possible.
>
> > I completely agree that the check " type(n) == int " is very intuitive
> > and simple. Its just that there are many more types that the basic ones
> > and 'types' module provide a "consistent" way for checking for types.
>
> Yes, for some types it is easiest to import types and use its
> definitions. Whether to use types.IntegerType or int is a matter of
> preference, I suppose.
> > As
> > an example - consider a function :
> >
> > def execMyFun( f ) :
> >    if type(f) == types.GeneratorType :
> >       return f.next()
> >    elif type(f) == types.FunctionType :
> >       return f()
> >    else :
> >       raise Exception("Invalid type for f : " + type(f) )
> >
> > Here types module came to the rescue which otherwise I would have
> > written using exception handling. /Well ! if you have a cleaner solution
> > do let me know./
>
> You probably should write this using exception handling. The least
> restrictive type check is to check for the specific operations you need,
> rather that checking for a type that supports the operation. This can be
> done with preflight checks - known as Look Before You Leap - or by
> trying an operation and catching exceptions in case of failure, known as
> Easier to Ask Forgiveness than Permission.
>
> In this case, it seems that if f implements the iterator protocol then
> you want the next item and if f is callable then you want to just call
> it. In both cases checking for specific operations or trying the
> operation and catching any exception will allow a wider range of
> parameters. For example, next() is meaningful for generators, iterators
> on built-in types, user-defined iterators (defined with classes).
> In [129]: import types
> In [130]: i=iter([1])
> In [131]: type(i)
> Out[131]: <type 'listiterator'>
> In [132]: type(i)==types.GeneratorType
> Out[132]: False
> In [133]: isinstance(i, types.GeneratorType)
> Out[133]: False
> In [134]: i.next
> Out[134]: <method-wrapper 'next' of listiterator object at 0x20d0050>
>
> Function call is valid for functions, bound methods, and instances of
> any class that defines a __call__() method.
>
> Here is a less restrictive LBYL implementation of your function:
> def execMyFun( f ) :
>     if hasattr(f, 'next') and callable(f.next):
>        return f.next()
>     elif callable(f):
>        return f()
>     else :
>        raise Exception("Invalid type for f : " + type(f) )
>
> Here in an EAFP implementation:
> def execMyFun( f ) :
>     try:
>        return f.next()
>     except AttributeError:
>        pass
>
>     try:
>        return f()
>     except TypeError:
>        pass
>     raise Exception("Invalid type for f : " + type(f) )
>
> I think I prefer the LBYL version here, it allows the same values for f
> and it won't hide AttributeErrors and TypeErrors raised by calling
> f.next() or f().
>
> Finally you should probably raise TypeError which is "raised when an
> operation or function is applied to an object of inappropriate type."
>
> Kent
>
>
Hey! I really liked LBYL version ... it matches exactly what I intended. And
yeah! I should raise TypeError instead of Exception. Thanx :)

-- 
Aditya
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071101/fca76332/attachment-0001.htm 

From phpmoonlighter at yahoo.com  Thu Nov  1 07:44:53 2007
From: phpmoonlighter at yahoo.com (ted b)
Date: Wed, 31 Oct 2007 23:44:53 -0700 (PDT)
Subject: [Tutor] sorting variables
Message-ID: <945459.53101.qm@web58806.mail.re1.yahoo.com>

I am using pygame and i have three variables that i
want to sort (var1, var2 and var3) and be able to
refer to them later in a statement that will use them
in sorted order:

the statement i am using is:
   objSprites = pygame.sprite.OrderedUpdates(var1,
var2, var3)

and i want var1, var2 and var3 to show up in the
statement in order of their value

so if var1 = 9, var2 = 3 and var3 = 5, i want my
statement to be equivalent to

   objSprites = pygame.sprite.OrderedUpdates(var2,
var3, var1)

i was thinking of doing something like

   objSprites = pygame.sprite.OrderedUpdates((var1,
var2, var3).sort)

but i don't think thats gunna work

any help much appreciated

__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 

From alan.gauld at btinternet.com  Thu Nov  1 08:59:47 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 1 Nov 2007 07:59:47 -0000
Subject: [Tutor] Problem with msvcrt
References: <47288171.7050106@bigfoot.com>
Message-ID: <fgc11k$5q2$1@ger.gmane.org>

"Ricardo Ar?oz" <ricaraoz at gmail.com> wrote

> if msvcrt.kbhit() :
> key = msvcrt.getch()
> if key == 'h' :
> print 'Hello'
>
> This is XP with 2.5 in Idle. Any ideas?

IDLE is a GUI app running under Tkinters event loop.
I doubt if msvcrt works under Tkinter.
Try running your code in a DOS box.

Any solution that detects keyboard input will be
very sensitive to the operational environment.
Running in a GUI (any GUI) will cause keyboard
events that are handled by the GUI toolkit.
msvcrt is designed to catch keyboasrd events
within a DOS environment.

See the event handling page of my tutor for how
to detect keypresses within Tkinter.

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 Nov  1 09:22:56 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 1 Nov 2007 08:22:56 -0000
Subject: [Tutor] Getting single values of a tuple & storing them
References: <60499.68.191.136.241.1193883739.squirrel@webmail.opmstech.org>
Message-ID: <fgc2d1$9ea$1@ger.gmane.org>


"Trey Keown" <trey at opmstech.org> wrote

> I was wondering, how could I get each value inside of a tuple, say 
> it's
> (2,4) .
> The only value I really need is the second one (the tuple will 
> always have
> only two values.

Tuples are like any other Python collection or sequence.
You can access by indexing into the tuple:

second = tup[1]   # zero based index

you can also iterate over them:

for index, item in enumerate(tup):
   print index, item
   if index = 1: second = item

And additionally collections can be 'unpacked':

one, two, three = (1,2,3)

These techniques also work with lists and strings.

So pick the method that suits you best.

HTH,

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



From evert.rol at gmail.com  Thu Nov  1 10:52:40 2007
From: evert.rol at gmail.com (Evert Rol)
Date: Thu, 1 Nov 2007 09:52:40 +0000
Subject: [Tutor] sorting variables
In-Reply-To: <945459.53101.qm@web58806.mail.re1.yahoo.com>
References: <945459.53101.qm@web58806.mail.re1.yahoo.com>
Message-ID: <8152765C-C057-4B78-BAAC-EEB5F6748B2C@gmail.com>

> i was thinking of doing something like
>
>    objSprites = pygame.sprite.OrderedUpdates((var1,
> var2, var3).sort)
>
> but i don't think thats gunna work

It won't indeed, because of 3 things:
1. you're trying to sort a tuple. Tuples don't have a sort() method,  
use a list instead
2. sort doesn't return! (well, it returns None in a way.) It's a  
thing that has caught me once too often. You'll need to do the  
sorting before using the sorted list again
3. you cannot insert a list (or tuple) as argument to a function and  
expect it to be automatically expanded to several arguments. Use the  
'*' in front of the list to expand (tuple won't work).

So what should work is:
args = [var1, var2, var3]
args.sort()
objSprites = pygame.sprite.OrderedUpdates(*args)

It's a few more lines, but that's the way it works. Hope that that  
helps.

Cheers,

   Evert


From kent37 at tds.net  Thu Nov  1 13:32:24 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 01 Nov 2007 08:32:24 -0400
Subject: [Tutor] Regular Expression help - parsing AppleScript Lists as
 Strings
In-Reply-To: <99acdf3c0710311816n57c3fc24ieee53a0cb0043f55@mail.gmail.com>
References: <99acdf3c0710311816n57c3fc24ieee53a0cb0043f55@mail.gmail.com>
Message-ID: <4729C758.8050103@tds.net>

Andrew Wu wrote:

>    pattern3 = '''
>       ^{
>       (
>       %s
>       | {%s}   # Possible to have 1 level of nested lists
>       ,?)*     # Items are comma-delimited, except for the last item
>       }$
>    ''' % (pattern2, pattern2)

The above doesn't allow comma after the first instance of pattern2 and 
it doesn't allow space after either instance. Here is a version that 
passes your tests:

    pattern3 = '''
       ^{
       (
       (%s
       | {%s})   # Possible to have 1 level of nested lists
       ,?\s*)*     # Items are comma-delimited, except for the last item
       }$
    ''' % (pattern2, pattern2)

You might want to look at doing this with pyparsing, I think it will 
make it easier to get the data out vs just recognizing the correct pattern.

Kent

PS Please post in plain text, not HTML.

From kent37 at tds.net  Thu Nov  1 14:14:26 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 01 Nov 2007 09:14:26 -0400
Subject: [Tutor] Regular Expression help - parsing AppleScript Lists as
 Strings
In-Reply-To: <4729C758.8050103@tds.net>
References: <99acdf3c0710311816n57c3fc24ieee53a0cb0043f55@mail.gmail.com>
	<4729C758.8050103@tds.net>
Message-ID: <4729D132.4080203@tds.net>

Kent Johnson wrote:
> You might want to look at doing this with pyparsing, I think it will 
> make it easier to get the data out vs just recognizing the correct pattern.

Here is a pyparsing version that correctly recognizes all of your 
patterns and returns a (possibly nested) Python list in case of a match.

Note that this version will parse lists that are nested arbitrarily 
deeply. If you don't want that you will have to define two kinds of 
lists, a singly-nested list and a non-nested list.

Kent

from pyparsing import *

List = Forward()
T = Literal('true').setParseAction( lambda s,l,t: [ True ] )
F = Literal('false').setParseAction( lambda s,l,t: [ False ] )
String = QuotedString('"')
Number = Word(nums).setParseAction( lambda s,l,t: [ int(t[0]) ] )
List << Literal('{').suppress() + 
delimitedList(T|F|String|Number|Group(List)) + Literal('}').suppress()

def IsASList(s):
    # AppleScript lists are bracked by curly braces with items separate 
by commas
    # Each item is an alphanumeric label(?) or a string enclosed by
    # double quotes or a list itself
    # e.g. {2, True, "hello"}
    try:
        parsed = List.parseString(s)
        return parsed.asList()
    except Exception, e:
        return None

sample_strs = [
    '{}',      # Empty list
    '{a}',     # Should not match
    '{a, b, c}', # Should not match
    '{"hello"}',
    '{"hello", "kitty"}',
    '{true}',
    '{false}',
    '{true, false}',
    '{9}',
    '{9,10, 11}',
    '{93214, true, false, "hello", "kitty"}',
    '{{1, 2, 3}}',  # This matches
    '{{1, 2, "cat"}, 1}',  # This matches

     # These don't match:
    '{{1,2,3},1,{4,5,6},2}',
    '{1, {2, 3, 4}, 3}',
    '{{1, 2, 3}, {4, 5, 6}, 1}',
    '{1, {1, 2, 3}}',  # Should match but doesn't
    '{93214, true, false, "hello", "kitty", {1, 2, 3}}',  # Should match 
but doesn't
    '{label: "hello", value: false, num: 2}',  # AppleScript dictionary 
- should not match
]

for sample in sample_strs:
    result = IsASList(sample)
    print 'Is AppleScript List:  %s;   String:  %s' % (bool(result), sample)
    if result:
        print result

From andrewwu at gmail.com  Thu Nov  1 17:20:53 2007
From: andrewwu at gmail.com (Andrew Wu)
Date: Thu, 1 Nov 2007 09:20:53 -0700
Subject: [Tutor] Regular Expression help - parsing AppleScript Lists as
	Strings
In-Reply-To: <4729C758.8050103@tds.net>
References: <99acdf3c0710311816n57c3fc24ieee53a0cb0043f55@mail.gmail.com>
	<4729C758.8050103@tds.net>
Message-ID: <99acdf3c0711010920g685fd3c2r42524a9a0efb255e@mail.gmail.com>

Ah - thanks for the correction!  I missed the extra grouping and the
extra spacing ... doh!  Sorry about the HTML-formatted e-mail ...

Thanks also for the pyparsing variant as well - I didn't know the
module existed before!



Andrew

On 11/1/07, Kent Johnson <kent37 at tds.net> wrote:
> Andrew Wu wrote:
>
> >    pattern3 = '''
> >       ^{
> >       (
> >       %s
> >       | {%s}   # Possible to have 1 level of nested lists
> >       ,?)*     # Items are comma-delimited, except for the last item
> >       }$
> >    ''' % (pattern2, pattern2)
>
> The above doesn't allow comma after the first instance of pattern2 and
> it doesn't allow space after either instance. Here is a version that
> passes your tests:
>
>     pattern3 = '''
>        ^{
>        (
>        (%s
>        | {%s})   # Possible to have 1 level of nested lists
>        ,?\s*)*     # Items are comma-delimited, except for the last item
>        }$
>     ''' % (pattern2, pattern2)
>
> You might want to look at doing this with pyparsing, I think it will
> make it easier to get the data out vs just recognizing the correct pattern.
>
> Kent
>
> PS Please post in plain text, not HTML.
>

From titleistfour at gmail.com  Thu Nov  1 18:49:55 2007
From: titleistfour at gmail.com (jay)
Date: Thu, 1 Nov 2007 12:49:55 -0500
Subject: [Tutor] Turning multiple Popen calls into a function
Message-ID: <7c25bb490711011049rf6c6f6bm6139c6c867216b46@mail.gmail.com>

Hello,

If I have multiple Popen calls I need to make, how can I turn these into a
function?

from subprocess import Popen, PIPE

p1 = Popen(['ls', '-l', '-a', '/etc'],stdout=PIPE)
p2 = Popen(['grep', 'hosts'], stdin=p1.stdout, stdout=PIPE)
p3 = Popen(['awk', '{print $1}'], stdin=p2.stdout, stdout=PIPE)
output = p3.communicate()[0]

p1 = Popen(['ps', '-ef'], stdout=PIPE)
p2 = Popen(['grep', '-v', '2348'], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]

I would be sending an arbitrary number of PIPES with each function call.

I'm a little stumped as to how to handle the variables.  If I have an
arbitrary number of PIPES, how do I declare my variables (p1, p2, p3,
etc...) ahead of time in the function??

Thanks for any suggestions!

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

From eric at ericwalstad.com  Thu Nov  1 19:20:13 2007
From: eric at ericwalstad.com (Eric Walstad)
Date: Thu, 01 Nov 2007 11:20:13 -0700
Subject: [Tutor] Turning multiple Popen calls into a function
In-Reply-To: <7c25bb490711011049rf6c6f6bm6139c6c867216b46@mail.gmail.com>
References: <7c25bb490711011049rf6c6f6bm6139c6c867216b46@mail.gmail.com>
Message-ID: <472A18DD.2010302@ericwalstad.com>

Hi Jay...
jay wrote:
...
> I would be sending an arbitrary number of PIPES with each function call.
> 
> I'm a little stumped as to how to handle the variables.  If I have an 
> arbitrary number of PIPES, how do I declare my variables (p1, p2, p3, 
> etc...) ahead of time in the function??
> 
> Thanks for any suggestions!


 >>> def foo(bar, *fizz, **bang):
...     print "bar:", bar
...     print "fizz:", fizz
...     print "bang:", bang
...

 >>> foo('and now for something completely different')
bar: and now for something completely different
fizz: ()
bang: {}

 >>> foo('hello', 'and', 'cows', 'eat', 'grass')
bar: hello
fizz: ('and', 'cows', 'eat', 'grass')
bang: {}

 >>> foo('hello', 'and', 'cows', 'eat', 'grass', greeting='hello', 
location='world')
bar: hello
fizz: ('and', 'cows', 'eat', 'grass')
bang: {'greeting': 'hello', 'location': 'world'}

 >>> a_tuple = ('and', 'cows', 'eat', 'grass')
 >>> a_dict = dict(greeting='hello', location='world')
 >>> foo('hello', *a_tuple, **a_dict)
bar: hello
fizz: ('and', 'cows', 'eat', 'grass')
bang: {'location': 'world', 'greeting': 'hello'}


Or, just pass the pipes in as an iterable to your function:
def pipe_handler(pipes):
     for n, pipe in enumerate(pipes):
         print "Pipe %d: '%s'" % (n, pipe)

pipes = []
pipes.append(some_pipe)
...
pipe_handler(pipes)

See also:
<http://docs.python.org/tut/node6.html#SECTION006700000000000000000>

I hope that helps,

Eric

From brunson at brunson.com  Thu Nov  1 19:30:10 2007
From: brunson at brunson.com (Eric Brunson)
Date: Thu, 01 Nov 2007 12:30:10 -0600
Subject: [Tutor] Turning multiple Popen calls into a function
In-Reply-To: <7c25bb490711011049rf6c6f6bm6139c6c867216b46@mail.gmail.com>
References: <7c25bb490711011049rf6c6f6bm6139c6c867216b46@mail.gmail.com>
Message-ID: <472A1B32.7050106@brunson.com>

jay wrote:
> Hello,
>
> If I have multiple Popen calls I need to make, how can I turn these 
> into a function?

Since you're only interested in the output of the last command on the 
pipeline, I don't see a reason to keep track of them all.  I'd do 
something like this:

def pipeline( *commandlist ):
    last = None
    for command in commandlist:
        last = Popen( command,
                      stdin=last.stdout if last else None,
                      stdout=PIPE )

    return last.communicate()[0]

print pipeline( ("ls", "-la", "/etc"),
                ("grep", "hosts"),
                ("awk", "{print $1}") )

returns:
lrwxrwxrwx



Hope that helps,
e.

> from subprocess import Popen, PIPE
>
> p1 = Popen(['ls', '-l', '-a', '/etc'],stdout=PIPE)
> p2 = Popen(['grep', 'hosts'], stdin=p1.stdout, stdout=PIPE)
> p3 = Popen(['awk', '{print $1}'], stdin=p2.stdout, stdout=PIPE)
> output = p3.communicate()[0]
>
> p1 = Popen(['ps', '-ef'], stdout=PIPE)
> p2 = Popen(['grep', '-v', '2348'], stdin=p1.stdout, stdout=PIPE)
> output = p2.communicate()[0]
>
> I would be sending an arbitrary number of PIPES with each function call.
>
> I'm a little stumped as to how to handle the variables.  If I have an 
> arbitrary number of PIPES, how do I declare my variables (p1, p2, p3, 
> etc...) ahead of time in the function??
>
> Thanks for any suggestions!
>
> Jay
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From phpmoonlighter at yahoo.com  Thu Nov  1 19:39:17 2007
From: phpmoonlighter at yahoo.com (ted b)
Date: Thu, 1 Nov 2007 11:39:17 -0700 (PDT)
Subject: [Tutor] sorting / outputting varibales
Message-ID: <961462.58258.qm@web58809.mail.re1.yahoo.com>

If i input the following in python:
   var1 = 7
   var2 = 9
   var3 = 5
   args = [var1, var2, var3]
   args.sort()

then if if type:

   args

the output is

   [5, 7, 9]

but i want the output to be

   [var3, var1, var2]

is there a function that will output the variable
names in the order they have been sorted instead of
the variable contents themselves?
thanks

__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 

From alan.gauld at btinternet.com  Thu Nov  1 19:46:57 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 1 Nov 2007 18:46:57 -0000
Subject: [Tutor] Turning multiple Popen calls into a function
References: <7c25bb490711011049rf6c6f6bm6139c6c867216b46@mail.gmail.com>
Message-ID: <fgd6v2$5ep$1@ger.gmane.org>


"jay" <titleistfour at gmail.com> wrote


> I'm a little stumped as to how to handle the variables.  If I have 
> an
> arbitrary number of PIPES, how do I declare my variables (p1, p2, 
> p3,
> etc...) ahead of time in the function??

How about passing a list of pipes?
Then you can access them as pipes[0],pipes[1], etc?

HTH,

Alan G 



From evert.rol at gmail.com  Thu Nov  1 19:52:35 2007
From: evert.rol at gmail.com (Evert Rol)
Date: Thu, 1 Nov 2007 18:52:35 +0000
Subject: [Tutor] sorting / outputting varibales
In-Reply-To: <961462.58258.qm@web58809.mail.re1.yahoo.com>
References: <961462.58258.qm@web58809.mail.re1.yahoo.com>
Message-ID: <2E904223-796B-4CD0-B034-7E0682A9AC3E@gmail.com>

> If i input the following in python:
>    var1 = 7
>    var2 = 9
>    var3 = 5
>    args = [var1, var2, var3]
>    args.sort()
>
> then if if type:
>
>    args
>
> the output is
>
>    [5, 7, 9]
>
> but i want the output to be
>
>    [var3, var1, var2]
>
> is there a function that will output the variable
> names in the order they have been sorted instead of
> the variable contents themselves?


Hm, I don't know directly how to get the name of a variable. I'd  
hoped there was a private method (var3.__<something>__), but looks  
like there isn't it.

Perhaps you can do something with a dictionary, eval and/or map? Not  
sure how that would work out, you'll have to play around a bit to get  
it working.

But I'm not really sure why you'd want to pass the variable names to  
a function; in the end, you're going to use the actual values anyway,  
not their names, right?



From titleistfour at gmail.com  Thu Nov  1 19:58:14 2007
From: titleistfour at gmail.com (jay)
Date: Thu, 1 Nov 2007 13:58:14 -0500
Subject: [Tutor] Turning multiple Popen calls into a function
In-Reply-To: <472A1B32.7050106@brunson.com>
References: <7c25bb490711011049rf6c6f6bm6139c6c867216b46@mail.gmail.com>
	<472A1B32.7050106@brunson.com>
Message-ID: <7c25bb490711011158v659731a5kcec458256d902fa0@mail.gmail.com>

Eric and Eric :-)

Thanks both for the suggestions!  I learned from each!
I believe the small function will work for me.  Its simple since I don't
have to track each pipe I open with a variable.  I had no idea I could do
that nifty if/then for the stdin, that makes it so easy. :-)

Thanks again!

Jay

On 11/1/07, Eric Brunson <brunson at brunson.com> wrote:
>
> jay wrote:
> > Hello,
> >
> > If I have multiple Popen calls I need to make, how can I turn these
> > into a function?
>
> Since you're only interested in the output of the last command on the
> pipeline, I don't see a reason to keep track of them all.  I'd do
> something like this:
>
> def pipeline( *commandlist ):
>     last = None
>     for command in commandlist:
>         last = Popen( command,
>                       stdin=last.stdout if last else None,
>                       stdout=PIPE )
>
>     return last.communicate()[0]
>
> print pipeline( ("ls", "-la", "/etc"),
>                 ("grep", "hosts"),
>                 ("awk", "{print $1}") )
>
> returns:
> lrwxrwxrwx
>
>
>
> Hope that helps,
> e.
>
> > from subprocess import Popen, PIPE
> >
> > p1 = Popen(['ls', '-l', '-a', '/etc'],stdout=PIPE)
> > p2 = Popen(['grep', 'hosts'], stdin=p1.stdout, stdout=PIPE)
> > p3 = Popen(['awk', '{print $1}'], stdin=p2.stdout, stdout=PIPE)
> > output = p3.communicate()[0]
> >
> > p1 = Popen(['ps', '-ef'], stdout=PIPE)
> > p2 = Popen(['grep', '-v', '2348'], stdin=p1.stdout, stdout=PIPE)
> > output = p2.communicate()[0]
> >
> > I would be sending an arbitrary number of PIPES with each function call.
> >
> > I'm a little stumped as to how to handle the variables.  If I have an
> > arbitrary number of PIPES, how do I declare my variables (p1, p2, p3,
> > etc...) ahead of time in the function??
> >
> > Thanks for any suggestions!
> >
> > Jay
> > ------------------------------------------------------------------------
> >
> > _______________________________________________
> > 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/20071101/5a273e1a/attachment-0001.htm 

From washakie at gmail.com  Thu Nov  1 20:15:07 2007
From: washakie at gmail.com (John)
Date: Thu, 1 Nov 2007 20:15:07 +0100
Subject: [Tutor] Automating operations... os module, mysql operations,
	more...
Message-ID: <aaf235960711011215o36995d8m3be88ca8575aae3b@mail.gmail.com>

I should begin by explaining I am not a sysadmin, I'm merely one trying to
use the right tool for the right job, and for my job I believe Python to be
that tool. Here is an outline of what I wish to accomplish, pointers to
modules, tools of interest, etc. would be greatly appreciated... Below each
number I propose the modules I've found, but please let me know if there are
better ones.. or others I should be aware of. Also, any good resources
regarding #2?? Thanks in advance!!

1) Maintain a mysql database which contains information, as well as
'control' variables, pointers to directories, etc.  for various shell
scripts / fortran code.
->pyMySQL

2) Query various servers to see if there is 'idyl' time/resources... send a
job to the server if it's available...
????????

 3) Use python to check the file system for existing files (glob?) , decide
which 'jobs' need to be run, etc.
->os, sys, glob

4) Use python as glue between the db and the shell /fortran routines. For
this I picture python querying the db, 'writing' new CONTROL files, and
using subprocess to run the scripts / fortran.
->sys, os, subprocess

5) Update the db with information regarding the status of the various
scripts / fortran.
->pyMySQL

6) Have a portion of the information available to a plone site for dynamic
html generation.
->ZMySQLDBConn
->Z SQL Methods



-- 
Configuration
``````````````````````````
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Five 1.4.1,
Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
4.1.1-51)],
PIL 1.1.6
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071101/14a4ff6f/attachment.htm 

From kent37 at tds.net  Thu Nov  1 20:21:42 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 01 Nov 2007 15:21:42 -0400
Subject: [Tutor] sorting / outputting varibales
In-Reply-To: <2E904223-796B-4CD0-B034-7E0682A9AC3E@gmail.com>
References: <961462.58258.qm@web58809.mail.re1.yahoo.com>
	<2E904223-796B-4CD0-B034-7E0682A9AC3E@gmail.com>
Message-ID: <472A2746.70206@tds.net>

Evert Rol wrote:
> Hm, I don't know directly how to get the name of a variable. I'd  
> hoped there was a private method (var3.__<something>__), but looks  
> like there isn't it.

No, the mapping from names to values is one way. It's pretty easy to 
have a value associated with no name, or more than one name, so the 
question is not really answerable in the general case.

Kent

From kent37 at tds.net  Thu Nov  1 20:23:33 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 01 Nov 2007 15:23:33 -0400
Subject: [Tutor] sorting / outputting varibales
In-Reply-To: <961462.58258.qm@web58809.mail.re1.yahoo.com>
References: <961462.58258.qm@web58809.mail.re1.yahoo.com>
Message-ID: <472A27B5.6080304@tds.net>

ted b wrote:
> If i input the following in python:
>    var1 = 7
>    var2 = 9
>    var3 = 5
>    args = [var1, var2, var3]
>    args.sort()
> 
> then if if type:
> 
>    args
> 
> the output is
> 
>    [5, 7, 9]
> 
> but i want the output to be
> 
>    [var3, var1, var2]
> 
> is there a function that will output the variable
> names in the order they have been sorted instead of
> the variable contents themselves?

Questions like this usually indicate that the questioner is on the wrong 
track. What are you trying to do? Probably it can be better done with a 
list or dictionary of values.

Is this a followup to your earlier "sorting variables" question? Evert 
showed you how to do that, is there a problem?

Kent

From dineshbvadhia at hotmail.com  Thu Nov  1 20:30:53 2007
From: dineshbvadhia at hotmail.com (Dinesh B Vadhia)
Date: Thu, 1 Nov 2007 12:30:53 -0700
Subject: [Tutor] dictionary append
Message-ID: <BAY109-DAV1957608B2FB9A176FE8087A38C0@phx.gbl>

Hello!  I'm creating a dictionary called keywords that has multiple entries each with a variable list of values eg.

keywords[1] = [1, 4, 6, 3]
keywords[2] = [67,2]
keywords[3] = [2, 8, 5, 66, 3, 23]
etc.

The keys and respective values (both are integers) are read in from a file.  For each key, the value is append'ed until the next key.  Here is the code.

.............
>>> keywords = {}
>>> with open("x.txt", "r") as f:
    k=0
    for line in f.readlines():
            keywords[k], second = map(int, line.split())
            keywords[k].append(second)
            if keywords[k] != k:
                    k=k+1
   
Traceback (most recent call last):
  File "<pyshell#44>", line 5, in <module>
    keywords[k].append(second)
AttributeError: 'int' object has no attribute 'append'
.............

Any idea why I get this error?

Dinesh


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

From evert.rol at gmail.com  Thu Nov  1 21:47:09 2007
From: evert.rol at gmail.com (Evert Rol)
Date: Thu, 1 Nov 2007 20:47:09 +0000
Subject: [Tutor] sorting / outputting varibales
In-Reply-To: <122824.47045.qm@web58813.mail.re1.yahoo.com>
References: <122824.47045.qm@web58813.mail.re1.yahoo.com>
Message-ID: <8893147E-C084-454C-8366-C5F72E186C1D@gmail.com>

> Thanks, i think a dictionary may  be the way to go
>
>> in the end, you're going to use the
>> actual values anyway,
>> not their names, right?
>
> yeah, you're right, the way i was thinking about doing
> it probably won't work. The way I am doing it now is
> actually using attibutes of the var's themselves to
> determine how they get used in the function:
>
>       if var1.value > var2.value > var3.value:
>          objSprites = pygame.sprite.OrderedUpdates
> (var1, var2, var3)
>       elif var1.value > var3.value > var2.value:
>          objSprites = pygame.sprite.OrderedUpdates
> (var1, var3, var2)
>       elif var2.value > var3.value > var1.value:
>          objSprites = pygame.sprite.OrderedUpdates
> (var2, var3, var1)
>       elif var2.value > var1.value > var3.value:
>          objSprites = pygame.sprite.OrderedUpdates
> (var2, var1, var3)
>       elif var3.value > var1.value > var2.value:
>          objSprites = pygame.sprite.OrderedUpdates
> (var3, var1, var2)
>       elif var3.value > var2.value > var1.value:
>          objSprites = pygame.sprite.OrderedUpdates
> (var3, var2, var1)



Looks like you forgot to give one essential part of information in  
your first email: varX aren't 'simple' integers or floats, but more  
complex types. Not exactly what you gave in your example. Please do  
give all the information if you're not sure what you're asking about  
(it may even put people off in follow-up answering). Oh, and please  
reply to the whole list, not just me: it'll enlighten other people as  
well.

Anyway, with this, something like this (indeed a dictionary) would do  
it:

vars = [var1, var2, var3]
dictvars = {}
for var in vars:
   dictvars[var.value] = var
keys = dictvars.keys()
keys.sort()
sortedvars = [dictvars[key] for key in keys]
objSprites = pygame.sprite.OrderedUpdates(*sortedvars)


Arguably just as lengthly, but more consistent. Depending on the type  
of 'varX' variable you're using, you might be able to simplify things  
further (by using a dictionary instead of a home-made object, which I  
assume the 'varX' variables are).

Probably putting up a solution here isn't really "tutoring", but I'm  
curious if anyone else on the list has a cleaner solution than this.


Cheers,

   Evert


From kent37 at tds.net  Thu Nov  1 21:48:31 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 01 Nov 2007 16:48:31 -0400
Subject: [Tutor] sorting / outputting varibales
In-Reply-To: <775414.75515.qm@web58813.mail.re1.yahoo.com>
References: <775414.75515.qm@web58813.mail.re1.yahoo.com>
Message-ID: <472A3B9F.8020902@tds.net>

ted b wrote:

> Here's the code i am using, but its a lot of if /
> thens and i'm trying to find a better way:
> 
>       if var1.value > var2.value > var3.value: 
>          objSprites = pygame.sprite.OrderedUpdates
> (var1, var2, var3)

Did you see Evert's reply to your original question? It was pretty close 
to the mark. Though you had not said anything about the .value 
attributes until now.

Try this:
from operator import attrgetter
vars = [ var1, var2, var3 ]
vars.sort(key=attrgetter('value'))
objSprites = pygame.sprite.OrderedUpdates(*vars)

This will sort the vars list by the value attribute of each list item, 
then pass the list as the parameter list to OrderedUpdates().

Kent

PS Please use Reply All to reply to the list.

From phpmoonlighter at yahoo.com  Thu Nov  1 22:13:56 2007
From: phpmoonlighter at yahoo.com (ted b)
Date: Thu, 1 Nov 2007 14:13:56 -0700 (PDT)
Subject: [Tutor] sorting / outputting varibales
In-Reply-To: <472A3B9F.8020902@tds.net>
Message-ID: <245686.16620.qm@web58807.mail.re1.yahoo.com>

Thanks Kent, and Evert, and everyone,
I really appreciate the advice on etiqutte and all
your help. I will think through my questions much more
thoroughly before any further inquiries and will
'reply to all' as advised.
--- Kent Johnson <kent37 at tds.net> wrote:

> ted b wrote:
> 
> > Here's the code i am using, but its a lot of if /
> > thens and i'm trying to find a better way:
> > 
> >       if var1.value > var2.value > var3.value: 
> >          objSprites = pygame.sprite.OrderedUpdates
> > (var1, var2, var3)
> 
> Did you see Evert's reply to your original question?
> It was pretty close 
> to the mark. Though you had not said anything about
> the .value 
> attributes until now.
> 
> Try this:
> from operator import attrgetter
> vars = [ var1, var2, var3 ]
> vars.sort(key=attrgetter('value'))
> objSprites = pygame.sprite.OrderedUpdates(*vars)
> 
> This will sort the vars list by the value attribute
> of each list item, 
> then pass the list as the parameter list to
> OrderedUpdates().
> 
> Kent
> 
> PS Please use Reply All to reply to the list.
> 


__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 

From mlangford.cs03 at gtalumni.org  Thu Nov  1 22:39:21 2007
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Thu, 1 Nov 2007 17:39:21 -0400
Subject: [Tutor] Automating operations... os module, mysql operations,
	more...
In-Reply-To: <aaf235960711011215o36995d8m3be88ca8575aae3b@mail.gmail.com>
References: <aaf235960711011215o36995d8m3be88ca8575aae3b@mail.gmail.com>
Message-ID: <82b4f5810711011439rf2a991fpdbdcf06eeebf4e05@mail.gmail.com>

>
> 1) Maintain a mysql database which contains information, as well as
> 'control' variables, pointers to directories, etc.  for various shell
> scripts / fortran code. ->pyMySQL
>

You're on the right track


> 2) Query various servers to see if there is 'idyl' time/resources... send
> a job to the server if it's available...
>

This and 3 can be helped out with ipython

3) Use python to check the file system for existing files (glob?) , decide
> which 'jobs' need to be run, etc.
> ->os, sys, glob
>
> 4) Use python as glue between the db and the shell /fortran routines. For
> this I picture python querying the db, 'writing' new CONTROL files, and
> using subprocess to run the scripts / fortran.
> ->sys, os, subprocess
>

I'd imagine SWIG may make it so you can actually call it if you make your
fortran compiler spit out a C compatible library. I know that one of the
Fortran95 compilers does this.

5) Update the db with information regarding the status of the various
scripts / fortran.
>
> ->pyMySQL
>
> 6) Have a portion of the information available to a plone site for dynamic
> html generation.
> ->ZMySQLDBConn
> ->Z SQL Methods
>
>
>
> --
> Configuration
> ``````````````````````````
> Plone 2.5.3-final,
> CMF-1.6.4,
> Zope (Zope 2.9.7-final, python 2.4.4, linux2),
> Five 1.4.1,
> Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
> 4.1.1-51)],
> PIL 1.1.6
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.TierOneDesign.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071101/b59ed984/attachment-0001.htm 

From alan.gauld at btinternet.com  Thu Nov  1 23:04:53 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 1 Nov 2007 22:04:53 -0000
Subject: [Tutor] Turning multiple Popen calls into a function
References: <7c25bb490711011049rf6c6f6bm6139c6c867216b46@mail.gmail.com>
	<472A1B32.7050106@brunson.com>
Message-ID: <fgdiia$jro$1@ger.gmane.org>


"Eric Brunson" <brunson at brunson.com> wrote 

>        last = Popen( command,
>                      stdin=last.stdout if last else None,
>                      stdout=PIPE )

Where does the if/else syntax come from? It doesn't 
seem to work on my Python 2.4. Is it a new feature in 2.5?

Alan G.


From washakie at gmail.com  Thu Nov  1 23:05:51 2007
From: washakie at gmail.com (John)
Date: Thu, 1 Nov 2007 23:05:51 +0100
Subject: [Tutor] Automating operations... os module, mysql operations,
	more...
In-Reply-To: <82b4f5810711011439rf2a991fpdbdcf06eeebf4e05@mail.gmail.com>
References: <aaf235960711011215o36995d8m3be88ca8575aae3b@mail.gmail.com>
	<82b4f5810711011439rf2a991fpdbdcf06eeebf4e05@mail.gmail.com>
Message-ID: <aaf235960711011505v6701301fuf29be265e105a4b8@mail.gmail.com>

>
>
>
>
> > 2) Query various servers to see if there is 'idyl' time/resources...
> > send a job to the server if it's available...
> >
>
> This and 3 can be helped out with ipython
>
>
>
> >  3) Use python to check the file system for existing files (glob?) ,
> > decide which 'jobs' need to be run, etc.
> > ->os, sys, glob
> >
>
I'm not sure I follow this? ipython is a command line interpreter, no? How
ill that help me 'automate' tasks...

>
> > 4) Use python as glue between the db and the shell /fortran routines.
> > For this I picture python querying the db, 'writing' new CONTROL files, and
> > using subprocess to run the scripts / fortran.
> > ->sys, os, subprocess
> >
>
> I'd imagine SWIG may make it so you can actually call it if you make your
> fortran compiler spit out a C compatible library. I know that one of the
> Fortran95 compilers does this.
>

Seems this would require a bit more than is required... just running the
shell scripts, which run the fortran is all I'm desiring to accomplish today
;)

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

From alan.gauld at btinternet.com  Thu Nov  1 23:14:56 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 1 Nov 2007 22:14:56 -0000
Subject: [Tutor] dictionary append
References: <BAY109-DAV1957608B2FB9A176FE8087A38C0@phx.gbl>
Message-ID: <fgdj52$lke$1@ger.gmane.org>


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

keywords[1] = [1, 4, 6, 3]
keywords[2] = [67,2]
keywords[3] = [2, 8, 5, 66, 3, 23]
etc.

The keys and respective values (both are integers) are read
in from a file.  For each key, the value is append'ed until
the next key.  Here is the code.

.............
>>> keywords = {}
>>> with open("x.txt", "r") as f:

You don;t need the with statement for this, just do

for line in open('x.txt'):

            keywords[k], second = map(int, line.split())

So keywords[k] and second are both ints

            keywords[k].append(second)

But you can't append to an int.
Try creating a temp value first:

            first, second = map(int, line.split())
            keywords[k] = [first]  # creates a list value instead of 
an int
            keywords[k].append(second)

HTH,

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



From jeff at drinktomi.com  Thu Nov  1 23:16:52 2007
From: jeff at drinktomi.com (Jeff Younker)
Date: Thu, 1 Nov 2007 15:16:52 -0700
Subject: [Tutor] Turning multiple Popen calls into a function
In-Reply-To: <fgdiia$jro$1@ger.gmane.org>
References: <7c25bb490711011049rf6c6f6bm6139c6c867216b46@mail.gmail.com>
	<472A1B32.7050106@brunson.com> <fgdiia$jro$1@ger.gmane.org>
Message-ID: <6DFF7339-168F-4C57-8FB6-DE4405BC1456@drinktomi.com>

On Nov 1, 2007, at 3:04 PM, Alan Gauld wrote:

> Where does the if/else syntax come from? It doesn't
> seem to work on my Python 2.4. Is it a new feature in 2.5?


Yes, it's a new feature in 2.5.

- Jeff Younker - jeff at drinktomi.com



From bgailer at alum.rpi.edu  Thu Nov  1 23:52:08 2007
From: bgailer at alum.rpi.edu (bob gailer)
Date: Thu, 01 Nov 2007 18:52:08 -0400
Subject: [Tutor] dictionary append
In-Reply-To: <BAY109-DAV1957608B2FB9A176FE8087A38C0@phx.gbl>
References: <BAY109-DAV1957608B2FB9A176FE8087A38C0@phx.gbl>
Message-ID: <472A5898.6040303@alum.rpi.edu>

Dinesh B Vadhia wrote:
> Hello!  I'm creating a dictionary called keywords that has multiple 
> entries each with a variable list of values eg.
>  
> keywords[1] = [1, 4, 6, 3]
> keywords[2] = [67,2]
> keywords[3] = [2, 8, 5, 66, 3, 23]
> etc.
>  
> The keys and respective values (both are integers) are read in from a 
> file. 
Please show us the lines in the file that led to that outcome.

Your program starts with k == 0. That suggests there should be a 
keywords[0] entry.
> For each key, the value is append'ed until the next key.  Here is the 
> code.
>  
> ..............
> >>> keywords = {}
> >>> with open("x.txt", "r") as f:
>     k=0
>     for line in f.readlines():
>             keywords[k], second = map(int, line.split())
>             keywords[k].append(second)
>            if keywords[k] != k:
>                    k=k+1
>    
> Traceback (most recent call last):
>   File "<pyshell#44>", line 5, in <module>
>     keywords[k].append(second)
> AttributeError: 'int' object has no attribute 'append'
> ..............
>  
> Any idea why I get this error?
Yes, and I'm surprised you have no idea! I say surprised, because a long 
time ago I learned to "walk through" my code line by line and write down 
what was happening. If you do that you should note that:

            keywords[k], second = map(int, line.split())

creates 2 integer values, and assigns the first to keywords[0]. Then you 
try to use:

            keywords[k].append(second)

to append the second integer to the first. As the message says, "'int' 
object has no attribute 'append'". append requires a list-like object.

Since your results seem incorrect anyway it is hard to diagnose. So 
please show us the input.

Also note that if you fix it so each dict entry is a list-like object, 
then keywords[k] != k will always be false, as that is comparing a list 
to an int.

Alan suggested creating a list using [first], but that only works for 
the first occurrence of each new key.

If this were my program, I'd guess that the input file looks like key, 
value pairs:

1 1
1 4
1 6
1 3
2 67
2 2
3 2
3 8
3 5
3 66
3 3
3 23

Is that accurate?

If so my program would be:

keywords = {}
for line in file("x.txt", "r"):
    key, value = map(int, line.split())
    if key not in keywords:
       keywords[key] = []
    keywords[key].append(value)

 HTH


From jeff at drinktomi.com  Fri Nov  2 00:00:25 2007
From: jeff at drinktomi.com (Jeff Younker)
Date: Thu, 1 Nov 2007 16:00:25 -0700
Subject: [Tutor] Automating operations... os module, mysql operations,
	more...
In-Reply-To: <aaf235960711011215o36995d8m3be88ca8575aae3b@mail.gmail.com>
References: <aaf235960711011215o36995d8m3be88ca8575aae3b@mail.gmail.com>
Message-ID: <14F91C9C-C701-421D-B550-8874D09D9D3B@drinktomi.com>

On Nov 1, 2007, at 12:15 PM, John wrote:

> 1) Maintain a mysql database which contains information, as well as  
> 'control' variables, pointers to directories, etc.  for various  
> shell scripts / fortran code.
> ->pyMySQL

Look at an object relational mapper like SQLObject or SQLAlchemy.  They
make the talking to the database much easier.

> 6) Have a portion of the information available to a plone site for  
> dynamic html generation.
> ->ZMySQLDBConn
> ->Z SQL Methods

Zope might be overkill.  Something like Turbogears might be better
if you're just looking for reporting.  (It will do a lot more, but  
it's really
easy to get started to with turbogears.)

- Jeff Younker - jeff at drinktomi.com



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

From ricaraoz at gmail.com  Fri Nov  2 00:14:00 2007
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Thu, 01 Nov 2007 20:14:00 -0300
Subject: [Tutor] Problem with msvcrt
In-Reply-To: <fgc11k$5q2$1@ger.gmane.org>
References: <47288171.7050106@bigfoot.com> <fgc11k$5q2$1@ger.gmane.org>
Message-ID: <472A5DB8.2000807@bigfoot.com>

Alan Gauld wrote:
> "Ricardo Ar?oz" <ricaraoz at gmail.com> wrote
> 
>> if msvcrt.kbhit() :
>> key = msvcrt.getch()
>> if key == 'h' :
>> print 'Hello'
>>
>> This is XP with 2.5 in Idle. Any ideas?
> 
> IDLE is a GUI app running under Tkinters event loop.
> I doubt if msvcrt works under Tkinter.
> Try running your code in a DOS box.
> 
> Any solution that detects keyboard input will be
> very sensitive to the operational environment.
> Running in a GUI (any GUI) will cause keyboard
> events that are handled by the GUI toolkit.
> msvcrt is designed to catch keyboasrd events
> within a DOS environment.
> 
> See the event handling page of my tutor for how
> to detect keypresses within Tkinter.
> 
> HTH,
> 

Thanks Alan.


From kent37 at tds.net  Fri Nov  2 00:43:41 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 01 Nov 2007 19:43:41 -0400
Subject: [Tutor] dictionary append
In-Reply-To: <472A5898.6040303@alum.rpi.edu>
References: <BAY109-DAV1957608B2FB9A176FE8087A38C0@phx.gbl>
	<472A5898.6040303@alum.rpi.edu>
Message-ID: <472A64AD.90205@tds.net>

bob gailer wrote:
>     if key not in keywords:
>        keywords[key] = []
>     keywords[key].append(value)

This can be written more succinctly as
   keywords.setdefault(key, []).append(value)

or in Python 2.5:
from collections import defaultdict
keywords = defaultdict(list)
...
   keywords[key].append(value)

Kent

From orsenthil at gmail.com  Fri Nov  2 05:21:00 2007
From: orsenthil at gmail.com (O.R.Senthil Kumaran)
Date: Fri, 2 Nov 2007 09:51:00 +0530
Subject: [Tutor] Build exe on Vista, have it run on XP?
In-Reply-To: <82b4f5810710312215k7133ac37x2c93913282dc75f3@mail.gmail.com>
References: <82b4f5810710290759h33b5f8e3ja5a32cd1b668a74a@mail.gmail.com>
	<20071031200911.GA3578@gmail.com>
	<82b4f5810710312215k7133ac37x2c93913282dc75f3@mail.gmail.com>
Message-ID: <20071102042100.GA3595@gmail.com>

* Michael Langford <mlangford.cs03 at gtalumni.org> [2007-11-01 01:15:31]:

> That's not really a working solution. My available development platform is a
> Vista machine. I don't have an available XP platform. XP built exes run fine
> on Vista, just not vice versa.

Then the best possible way would be to ask py2exe mailling list, if they have identified any solution for the backward compatiblities issues of VISTA exes on XP.

Thanks,
Senthil

-- 
O.R.Senthil Kumaran
http://uthcode.sarovar.org

From alan.gauld at btinternet.com  Fri Nov  2 10:03:22 2007
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Fri, 2 Nov 2007 09:03:22 +0000 (GMT)
Subject: [Tutor] repeated times
Message-ID: <184538.78377.qm@web86704.mail.ird.yahoo.com>

> > >I want to run an .exe file and get the output many times.
>> Given that I know that you know about loops I have to
>> ask what you see as the problem? 
>
>I want to run it many times and export all the output to a text file.

OK, Do you mean you want to run the program multiple times 
but put the output in the same file? Maybe at hourly intervals say?

The schedulling of the jobs will depend on what OS you are 
using. Is it Linux/Unix or Windows?

Writing to the same file should be as simple as using the 
append flag when opening the file.

Or am I still not understanding what you want?


Alan G.






From sith618 at yahoo.com  Fri Nov  2 19:31:42 2007
From: sith618 at yahoo.com (sith .)
Date: Fri, 2 Nov 2007 11:31:42 -0700 (PDT)
Subject: [Tutor] Help with setting path
Message-ID: <528418.66076.qm@web33201.mail.mud.yahoo.com>

hi,
I'm a beginner.  Can someone help me with the installation?  I've read several tutorials, possess a couple of books, and have followed the instructions, but I stil face a problem. None of the online tutorials address this issue in depth maybe because it could be too simple. I'm having problems setting my path and having the python interpreter recognize my modules in my python folders.  My python path browser is showing that the main python directory is listed, along with my subdirectories like lib, and work.  I've set python PATH in windows too.  However, when I try to run the program, which is stored in pthon25/work using IDLE, I get a traceback error.  I can run the program in dos though and it also seems to work when I open the file using the menu, and then select the run button in pythonwin.   I'd greatly appreciate it if someone could guide me with a proper setup of path.  Thanks.
 __________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071102/16e7d62c/attachment.htm 

From alan.gauld at btinternet.com  Fri Nov  2 21:05:18 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 2 Nov 2007 20:05:18 -0000
Subject: [Tutor] Help with setting path
References: <528418.66076.qm@web33201.mail.mud.yahoo.com>
Message-ID: <fgfvu0$f1b$1@ger.gmane.org>


"sith ." <sith618 at yahoo.com> wrote

> However, when I try to run the program, which is stored 
> in pthon25/work using IDLE, I get a traceback error.  

Cannyou send us the error, that helps a lot in trying to debug. 
Cut n paste the entire error text.

> I can run the program in dos though and it also seems 

That suggests that there is nothing wroing with your PATH 
settings. They mainly affect how it works under DOS.

It may be that IDLE is simply giving you a traceback 
for sys.exit() which it does because it catches the exit 
and prevents you from dropping out of IDLE itself.

Let us see the error traceback and we can decide.

HTH,


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


From kent37 at tds.net  Thu Nov  1 18:59:29 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 01 Nov 2007 13:59:29 -0400
Subject: [Tutor] List comp question
Message-ID: <472A1401.2080509@tds.net>

I am building a list like this:

     tree = []
     for top in tops:
         l2 = level2(top)
         if l2:
             tree.append((top, l2))

I would really like to turn this into a list comprehension:

tree = [ (top, level2(top)) for top in tops if level2(top) ]

but the call to level2() is expensive enough that I don't want to repeat 
it. Is there any way to do this or am I stuck with the (IMO ugly) loop form?

Kent

who actually does have a question occasionally :-)

From mlangford.cs03 at gtalumni.org  Fri Nov  2 21:24:57 2007
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Fri, 2 Nov 2007 16:24:57 -0400
Subject: [Tutor] List comp question
In-Reply-To: <472A1401.2080509@tds.net>
References: <472A1401.2080509@tds.net>
Message-ID: <82b4f5810711021324s72905bfaie3d0916b325f42ba@mail.gmail.com>

Decorate level2 with a decorator that caches:

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

    --Michael

On 11/1/07, Kent Johnson <kent37 at tds.net> wrote:
>
> I am building a list like this:
>
>      tree = []
>      for top in tops:
>          l2 = level2(top)
>          if l2:
>              tree.append((top, l2))
>
> I would really like to turn this into a list comprehension:
>
> tree = [ (top, level2(top)) for top in tops if level2(top) ]
>
> but the call to level2() is expensive enough that I don't want to repeat
> it. Is there any way to do this or am I stuck with the (IMO ugly) loop
> form?
>
> Kent
>
> who actually does have a question occasionally :-)
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.TierOneDesign.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071102/671ccde1/attachment.htm 

From washakie at gmail.com  Fri Nov  2 23:15:14 2007
From: washakie at gmail.com (John)
Date: Fri, 2 Nov 2007 23:15:14 +0100
Subject: [Tutor] subprocess stdout nohup question
Message-ID: <aaf235960711021515x24189b1eub002e25cfd67ca4a@mail.gmail.com>

When I run a python script with nohup, my print statements are not being
written to nohup.out, why is that? Should nohup.out capture all stdout
statements?

-- 
Configuration
``````````````````````````
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Five 1.4.1,
Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
4.1.1-51)],
PIL 1.1.6
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071102/8306358e/attachment.htm 

From washakie at gmail.com  Sat Nov  3 00:35:12 2007
From: washakie at gmail.com (John)
Date: Sat, 3 Nov 2007 00:35:12 +0100
Subject: [Tutor] Help with setting path
In-Reply-To: <fgfvu0$f1b$1@ger.gmane.org>
References: <528418.66076.qm@web33201.mail.mud.yahoo.com>
	<fgfvu0$f1b$1@ger.gmane.org>
Message-ID: <aaf235960711021635s7b0582aaoc54a0f7ac579e14b@mail.gmail.com>

How did you install Python? I've found that the Enthought distribution to be
the simplest and quickest way to get up and running while having good
functionality (i.e. scipy up and running).

Active state releases a good version as well... and thus, welcome, to what
in my humble opinion (a newbie as well) is the hell of Python... that is,
there is a seemingly endless number of possible ways to configure the
installations. But that's the hell, the rest is grreat! So it's a sugar
coated hell once you get up and running ;)

Good luck.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071103/3ca5a405/attachment.htm 

From ricaraoz at gmail.com  Sat Nov  3 00:56:46 2007
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Fri, 02 Nov 2007 20:56:46 -0300
Subject: [Tutor] List comp question
In-Reply-To: <472A1401.2080509@tds.net>
References: <472A1401.2080509@tds.net>
Message-ID: <472BB93E.7040105@bigfoot.com>

Kent Johnson wrote:
> I am building a list like this:
> 
>      tree = []
>      for top in tops:
>          l2 = level2(top)
>          if l2:
>              tree.append((top, l2))
> 
> I would really like to turn this into a list comprehension:
> 
> tree = [ (top, level2(top)) for top in tops if level2(top) ]
> 
> but the call to level2() is expensive enough that I don't want to repeat 
> it. Is there any way to do this or am I stuck with the (IMO ugly) loop form?
> 

Just playing around here, but would this work and be better????

tree = [ pair for pair in [ (top, level2(top)) for top in tops ]
                          if pair[1] ]



From alan.gauld at btinternet.com  Sat Nov  3 01:49:18 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 3 Nov 2007 00:49:18 -0000
Subject: [Tutor] List comp question
References: <472A1401.2080509@tds.net>
Message-ID: <fgggig$se5$1@ger.gmane.org>


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

> I would really like to turn this into a list comprehension:
>
> tree = [ (top, level2(top)) for top in tops if level2(top) ]
>
> but the call to level2() is expensive enough that I don't want to 
> repeat
> it. Is there any way to do this or am I stuck with the (IMO ugly) 
> loop form?

Not sure how this would work but you might be able to use
a temporary global var to hold the result if you wrap it in a
function (I suspect this is similar to the decorator suggestion,
just more explicit...

Pseudo code

tvar = None
def lev2(t):
   global tvar
   tvar = level2(t)
   return tvar

tree = [ (top, tvar) for top in tops if lev2(top) ]

Is that any better than the loop? I'm not sure it is...
unless you have to build the list in multiple places.

Do I like relying on side effects of functions? No.

HTH,

Alan G. 



From alan.gauld at btinternet.com  Sat Nov  3 01:53:30 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 3 Nov 2007 00:53:30 -0000
Subject: [Tutor] Help with setting path
References: <528418.66076.qm@web33201.mail.mud.yahoo.com><fgfvu0$f1b$1@ger.gmane.org>
	<aaf235960711021635s7b0582aaoc54a0f7ac579e14b@mail.gmail.com>
Message-ID: <fgggqc$stp$1@ger.gmane.org>

"John" <washakie at gmail.com> wrote

> How did you install Python?

On Windoze I use the ActiveState version and then manually
set the PATH and PYTHONPATH environment variables

> Active state releases a good version as well... and thus, welcome, 
> to what
> in my humble opinion (a newbie as well) is the hell of Python... 
> that is,
> there is a seemingly endless number of possible ways to configure 
> the
> installations.

That's the hell of Open Source software.
The basic package is there to use but lots of people think they
know how to "improve" it and so you get multiple versions.
On a bigger scale just look at the myriad of Linux distros out there.

You just have to ask youself: Is the pain worth the gain?
If the answer is yes find a distro that suits and stick to it.

Alan G. 



From gmoonn at gmail.com  Sat Nov  3 02:22:44 2007
From: gmoonn at gmail.com (Gman)
Date: Fri, 02 Nov 2007 20:22:44 -0500
Subject: [Tutor] Installation
Message-ID: <op.t06zf6aijgjj51@dialup-4.229.168.209.dial1.detroit1.level3.net>

Hello all,I will try to make this quick.Since the installation topic is  
open I have a question.
Bear in mind "newbie alert" I have 2.5 on windows M.E. and all is well,but  
if I try to use a dos box I get bad command etc. but if I use the python  
dos everything works.Is this normal
or do I need to have windows dos in the path somehow?Or does it really  
matter,it's all the same dos isnt it.And how do you clear the Tkinter  
window.I must say that much of what I read here is beyond me NOW but it is  
like chess you are only as good as your opponents!


From sith618 at yahoo.com  Sat Nov  3 04:37:31 2007
From: sith618 at yahoo.com (sith .)
Date: Fri, 2 Nov 2007 20:37:31 -0700 (PDT)
Subject: [Tutor] Help with setting path
Message-ID: <426200.10177.qm@web33206.mail.mud.yahoo.com>

Hi,
Thanks for your input.  I'm presently downloading enthought python - no asian mirror, so it'll take a really long time to download even on broadband at 10kbps) - but I don't think it's a distro problem.  I'm probably not doing it right as I'm now using IDLE and still have the same problem.  For example, here is the traceback for a simple file I made and tried to run in IDLE: 
  # test.py
x = 1 + 1 
print x
  In IDLE, I tried to run it by typing test.py 
  Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    test.py
NameError: name 'test' is not defined
  However, when I open the file in IDLE using the  menu, and then run it also from the menu, it works.
  Am I not calling the program properly?
  p.s.  Wonder why word wrap didn't work on my first post.  Thanks to all who scrolled.

 __________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071102/92ba07e6/attachment.htm 

From alan.gauld at btinternet.com  Sat Nov  3 09:37:26 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 3 Nov 2007 08:37:26 -0000
Subject: [Tutor] Help with setting path
References: <426200.10177.qm@web33206.mail.mud.yahoo.com>
Message-ID: <fghc09$ddg$1@ger.gmane.org>


"sith ." <sith618 at yahoo.com> wrote

>  For example, here is the traceback for a simple file I made and 
> tried to run in IDLE:
>  # test.py
> x = 1 + 1
> print x

>  In IDLE, I tried to run it by typing test.py

That's the problem.
You cannot run Python scripts in IDLE by calling
them like that. You should open the file using the File->Open menu
and then run it using the Run menu. IDLE is not intended for running
scripts but for writing them. To run a script just use a DOS box or
double click the script from Windows Explorer (but in your example
it will close before you can read the output! - you need to put a
raw_input() call at the end to stop that)

>  However, when I open the file in IDLE using the  menu,
> and then run it also from the menu, it works.

Thats the correct way to do it.
You don't need to use IDLE to run a program, only to edit it.

The >>> prompt in IDLE is a Python interpreter and expects
actual Python commands, not script names. On a recent
thread it was mentioned that IPython (which is another Python
interpreter) has some special commands including a run
command that does accept filenames. If that is something
you need you might like IPython.

HTH,

Alan G. 



From alan.gauld at btinternet.com  Sat Nov  3 09:44:49 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 3 Nov 2007 08:44:49 -0000
Subject: [Tutor] Installation
References: <op.t06zf6aijgjj51@dialup-4.229.168.209.dial1.detroit1.level3.net>
Message-ID: <fghce4$e7c$1@ger.gmane.org>


"Gman" <gmoonn at gmail.com> wrote

> Bear in mind "newbie alert" I have 2.5 on windows M.E. and all is 
> well,

OK, Then I wouyldn't worry too much but...

> if I try to use a dos box I get bad command etc.

Thats because the PATH envirtonment variable is not set.
To fix it open c:\AUTOEXEC.BAT in notepad
Find the line that starts

PATH=

and at the end of the line add a semicolon followed
by the path to your Python folder(the one with the exe file in)

Save AUTOEXEC.BAT and reboot.
It should now work OK

> but if I use the python dos everything works.Is this normal

Yes the installer sets up a shortcut to the interpreter
which opens a DOS window, but since about v2.2 the
installer (for some strangereason) does not set up the
PATH variable.

> or do I need to have windows dos in the path somehow?Or does it 
> really
> matter,it's all the same dos isnt it.

Its the same DOS but the problem is that the window
brought up from the menu is riunning python, the DOS
window is running plain old DOS. You cannot run
Python scripts from the Python window only from
the DOS one. This makes debugging Tkinter programs
and some others much easier that trying to run them
from within IDLE orr Pythonwin.

> And how do you clear the Tkinter  window.

Not sure what you mean. Clear what? From which Tkinter window?


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



From sith618 at yahoo.com  Sat Nov  3 10:25:05 2007
From: sith618 at yahoo.com (sith .)
Date: Sat, 3 Nov 2007 02:25:05 -0700 (PDT)
Subject: [Tutor] Help with setting path
Message-ID: <226892.217.qm@web33202.mail.mud.yahoo.com>

Thank you very much Alan.
   
  Kevin

 __________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071103/433d9594/attachment.htm 

From kent37 at tds.net  Sat Nov  3 12:48:42 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 03 Nov 2007 07:48:42 -0400
Subject: [Tutor] Inverted Index
In-Reply-To: <BAY109-DAV131DD92FE07B398C175F68A3930@phx.gbl>
References: <BAY109-DAV125440F4D6FEE6150A059FA3930@phx.gbl>
	<472895A7.10904@tds.net>
	<BAY109-DAV5BA708A2D8C6E451C483CA3930@phx.gbl>
	<47289C6B.9050305@tds.net>
	<BAY109-DAV131DD92FE07B398C175F68A3930@phx.gbl>
Message-ID: <472C601A.8000502@tds.net>

Dinesh B Vadhia wrote:
> A NumPy matrix (because we have to perform a dot matrix multiplication 
> prior to creating an inverted index).

Maybe something like this?

from collections import defaultdict
a = array(...)
index = defaultdict(list)
for i, x in ndenumerate(a):
   index[x].append(i)

This creates a dict whose keys are the values in the array and values 
are lists of indices where the value appears.

I don't know how your sparse matrix is represented but maybe you need 
some kind of filter in the loop to only record meaningful values.

http://www.scipy.org/Numpy_Example_List_With_Doc#ndenumerate

Kent



>  
> ----- Original Message -----
> 
> Dinesh B Vadhia wrote:
>  > Sure!  To create an inverted index of a very large matrix (M x N with
>  > M<>N and M>10m rows).  Most times the matrix will be sparse but
>  > sometimes it won't be.  Most times the matrix will consist of 0's and
>  > 1's but sometimes it won't.
> 
> How is the matrix represented? Is it in a numpy array? a dict? or...
> 
> Kent
>  > Dinesh B Vadhia wrote:
>  >  > Hello!  Anyone know of any example/cookbook code for implementing
>  >  > inverted indexes?
>  >
>  > Can you say more about what you are trying to do?
>

From mlangford.cs03 at gtalumni.org  Sat Nov  3 15:39:13 2007
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Sat, 3 Nov 2007 10:39:13 -0400
Subject: [Tutor] List comp question
In-Reply-To: <82b4f5810711021324s72905bfaie3d0916b325f42ba@mail.gmail.com>
References: <472A1401.2080509@tds.net>
	<82b4f5810711021324s72905bfaie3d0916b325f42ba@mail.gmail.com>
Message-ID: <82b4f5810711030739v7f1a29cdn827e3012927f1cb@mail.gmail.com>

I decided you probably should also have a cleanup function since garbage
collection won't work now unless you explicitly clean the function. This
approach works, and also works if you call the function again after you've
called cleanup (it just runs the function 1 more time, then again, returns
the cached result until you cleanup).

def func_once(func):
    "A decorator that runs a function only once."
    def decorated(*args, **kwargs):
        try:
            return decorated._once_result
        except AttributeError:
            decorated._once_result = func(*args, **kwargs)
            return decorated._once_result
    return decorated

def func_once_cleanup(func):
    del func._once_result

# Example, will only parse the document once
@func_once
def print_and_return_big_list():
    print "I'm the method you want to run once"
    return
[23,2342,234,234,234,24,654,687,54,9684,654,864981,651,849815,65498,1651,6984651,6541,654984,651,645]

if __name__=="__main__":
    print_and_return_big_list()
    print_and_return_big_list()
    print_and_return_big_list()
    print_and_return_big_list()
    print_and_return_big_list()

    func_once_cleanup(print_and_return_big_list)

    print_and_return_big_list(



On 11/2/07, Michael Langford <mlangford.cs03 at gtalumni.org> wrote:
>
> Decorate level2 with a decorator that caches:
>
>  http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/425445
>
>     --Michael
>
> On 11/1/07, Kent Johnson <kent37 at tds.net> wrote:
> >
> > I am building a list like this:
> >
> >      tree = []
> >      for top in tops:
> >          l2 = level2(top)
> >          if l2:
> >              tree.append((top, l2))
> >
> > I would really like to turn this into a list comprehension:
> >
> > tree = [ (top, level2(top)) for top in tops if level2(top) ]
> >
> > but the call to level2() is expensive enough that I don't want to repeat
> > it. Is there any way to do this or am I stuck with the (IMO ugly) loop
> > form?
> >
> > Kent
> >
> > who actually does have a question occasionally :-)
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
>
>
> --
> Michael Langford
> Phone: 404-386-0495
> Consulting: http://www.TierOneDesign.com/




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

From brunson at brunson.com  Sat Nov  3 17:51:02 2007
From: brunson at brunson.com (Eric Brunson)
Date: Sat, 03 Nov 2007 10:51:02 -0600
Subject: [Tutor] List comp question
In-Reply-To: <472BB93E.7040105@bigfoot.com>
References: <472A1401.2080509@tds.net> <472BB93E.7040105@bigfoot.com>
Message-ID: <472CA6F6.4080403@brunson.com>

Ricardo Ar?oz wrote:
> Kent Johnson wrote:
>   
>> I am building a list like this:
>>
>>      tree = []
>>      for top in tops:
>>          l2 = level2(top)
>>          if l2:
>>              tree.append((top, l2))
>>
>> I would really like to turn this into a list comprehension:
>>
>> tree = [ (top, level2(top)) for top in tops if level2(top) ]
>>
>> but the call to level2() is expensive enough that I don't want to repeat 
>> it. Is there any way to do this or am I stuck with the (IMO ugly) loop form?
>>
>>     
>
> Just playing around here, but would this work and be better????
>
> tree = [ pair for pair in [ (top, level2(top)) for top in tops ]
>                           if pair[1] ]
>
>   

I came up with something very similar:

tops = [1,2,3,4,5]

def level2(n):
    m = n ** 2
    if m%2:
        return m
    else:
        return False

tree = [ (x, y) for x, y in [ ( x, level2(x) ) for x in tops ] if y ]
print tree
[(1, 1), (3, 9), (5, 25)]


But, now I would debate conciseness vs. readability and 
maintainability.  Will someone understand what's going on if they have 
to read it?  Will you remember what it does in six months when you're 
maintaining it?

Still, an interesting academic exercise.  :-)

e.

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


From ricaraoz at gmail.com  Sat Nov  3 18:43:13 2007
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Sat, 03 Nov 2007 14:43:13 -0300
Subject: [Tutor] List comp question
In-Reply-To: <472CA6F6.4080403@brunson.com>
References: <472A1401.2080509@tds.net> <472BB93E.7040105@bigfoot.com>
	<472CA6F6.4080403@brunson.com>
Message-ID: <472CB331.8050304@bigfoot.com>

Eric Brunson wrote:
> Ricardo Ar?oz wrote:
>> Kent Johnson wrote:
>>   
>>> I am building a list like this:
>>>
>>>      tree = []
>>>      for top in tops:
>>>          l2 = level2(top)
>>>          if l2:
>>>              tree.append((top, l2))
>>>
>>> I would really like to turn this into a list comprehension:
>>>
>>> tree = [ (top, level2(top)) for top in tops if level2(top) ]
>>>
>>> but the call to level2() is expensive enough that I don't want to repeat 
>>> it. Is there any way to do this or am I stuck with the (IMO ugly) loop form?
>>>
>>>     
>> Just playing around here, but would this work and be better????
>>
>> tree = [ pair for pair in [ (top, level2(top)) for top in tops ]
>>                           if pair[1] ]
>>
>>   
> 
> I came up with something very similar:
> 
> tops = [1,2,3,4,5]
> 
> def level2(n):
>     m = n ** 2
>     if m%2:
>         return m
>     else:
>         return False
> 
> tree = [ (x, y) for x, y in [ ( x, level2(x) ) for x in tops ] if y ]
> print tree
> [(1, 1), (3, 9), (5, 25)]
> 
> 
> But, now I would debate conciseness vs. readability and 
> maintainability.  Will someone understand what's going on if they have 
> to read it?  Will you remember what it does in six months when you're 
> maintaining it?
> 
> Still, an interesting academic exercise.  :-)
> 
> e.
> 

It is perfectly understandable. Maybe the reason for doing it will not
be clear, you can always put a comment explaining you don't want to call
level2() twice.


From washakie at gmail.com  Sun Nov  4 02:47:30 2007
From: washakie at gmail.com (John)
Date: Sun, 4 Nov 2007 02:47:30 +0100
Subject: [Tutor] Help with setting path
In-Reply-To: <fgggqc$stp$1@ger.gmane.org>
References: <528418.66076.qm@web33201.mail.mud.yahoo.com>
	<fgfvu0$f1b$1@ger.gmane.org>
	<aaf235960711021635s7b0582aaoc54a0f7ac579e14b@mail.gmail.com>
	<fgggqc$stp$1@ger.gmane.org>
Message-ID: <aaf235960711031847n22e331e5x1a45cb03292c48a9@mail.gmail.com>

Good point, I think that goes for learning a programming language in general
;)  Find one that works, and master it...

I'm starting to put together the picture of what a Python installation is,
but I have to admit, when you work on multiple machines regularly, it is a
bit challenging. Especially when you're starting out...
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071104/a0efc85b/attachment.htm 

From bhaaluu at gmail.com  Sun Nov  4 04:38:48 2007
From: bhaaluu at gmail.com (bhaaluu)
Date: Sat, 3 Nov 2007 23:38:48 -0400
Subject: [Tutor] Help with setting path
In-Reply-To: <528418.66076.qm@web33201.mail.mud.yahoo.com>
References: <528418.66076.qm@web33201.mail.mud.yahoo.com>
Message-ID: <ea979d70711032038o69417d40i57232b688d48db3a@mail.gmail.com>

apt-get install python2.4

That's it! (On a Debian-based install)
-- 
b h a a l u u at g m a i l dot c o m
http://www.geocities.com/ek.bhaaluu/index.html

On 11/2/07, sith . <sith618 at yahoo.com> wrote:
> hi,
> I'm a beginner.  Can someone help me with the installation?  I've read
> several tutorials, possess a couple of books, and have followed the
> instructions, but I stil face a problem. None of the online tutorials
> address this issue in depth maybe because it could be too simple. I'm having
> problems setting my path and having the python interpreter recognize my
> modules in my python folders.  My python path browser is showing that the
> main python directory is listed, along with my subdirectories like lib, and
> work.  I've set python PATH in windows too.  However, when I try to run the
> program, which is stored in pthon25/work using IDLE, I get a traceback
> error.  I can run the program in dos though and it also seems to work when I
> open the file using the menu, and then select the run button in pythonwin.
> I'd greatly appreciate it if someone could guide me with a proper setup of
> path.  Thanks.
>
>  __________________________________________________
> Do You Yahoo!?
> Tired of spam? Yahoo! Mail has the best spam protection around
> http://mail.yahoo.com
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>

From bhaaluu at gmail.com  Sun Nov  4 04:33:25 2007
From: bhaaluu at gmail.com (bhaaluu)
Date: Sat, 3 Nov 2007 23:33:25 -0400
Subject: [Tutor] Help with setting path
In-Reply-To: <aaf235960711031847n22e331e5x1a45cb03292c48a9@mail.gmail.com>
References: <528418.66076.qm@web33201.mail.mud.yahoo.com>
	<fgfvu0$f1b$1@ger.gmane.org>
	<aaf235960711021635s7b0582aaoc54a0f7ac579e14b@mail.gmail.com>
	<fgggqc$stp$1@ger.gmane.org>
	<aaf235960711031847n22e331e5x1a45cb03292c48a9@mail.gmail.com>
Message-ID: <ea979d70711032033r5047668bga7f7e82efdf094c6@mail.gmail.com>

Greetings,
On 11/3/07, John <washakie at gmail.com> wrote:
> Good point, I think that goes for learning a programming language in general
> ;)  Find one that works, and master it...
>
> I'm starting to put together the picture of what a Python installation is,
> but I have to admit, when you work on multiple machines regularly, it is a
> bit challenging. Especially when you're starting out...
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

The bottom line is:?
1. Proprietary: The Monopoly is already established where I work and
   the Managers are MS-All-The-Way: If *I* deviate, I'm FIRED!
2. Proprietary Base: Management Looks the Other Way: Whatever Works!
3. Open: Whatever works to get the job done the best (cheapest/fastest) way.
4. Closed-source: We don't DO closed-source. You'd better learn C/Perl/Python.

I don't see Python installed as a default scripting language, except
on GNU/Linux.

You really need to check it out! You might be risking your job
by even thinking about "Python"!

Good Luck!
-- 
b h a a l u u at g m a i l dot c o m
http://www.geocities.com/ek.bhaaluu/index.html

From samrobertsmith at gmail.com  Sun Nov  4 10:39:46 2007
From: samrobertsmith at gmail.com (linda.s)
Date: Sun, 4 Nov 2007 01:39:46 -0800
Subject: [Tutor] repeated times
In-Reply-To: <184538.78377.qm@web86704.mail.ird.yahoo.com>
References: <184538.78377.qm@web86704.mail.ird.yahoo.com>
Message-ID: <1d987df30711040139o2ac323aaw685de9b9e4245744@mail.gmail.com>

On Nov 2, 2007 1:03 AM, ALAN GAULD <alan.gauld at btinternet.com> wrote:
> > > >I want to run an .exe file and get the output many times.
> >> Given that I know that you know about loops I have to
> >> ask what you see as the problem?
> >
> >I want to run it many times and export all the output to a text file.
>
> OK, Do you mean you want to run the program multiple times
> but put the output in the same file?

Yes. For example, I want to run the exe file one hundred times and
save all the results into one file.
Is there any example code to do that?
Thanks,
Linda

From washakie at gmail.com  Sun Nov  4 12:15:58 2007
From: washakie at gmail.com (John)
Date: Sun, 4 Nov 2007 12:15:58 +0100
Subject: [Tutor] Some question about OO practice
Message-ID: <aaf235960711040315p21e5b1fdha608308593c64788@mail.gmail.com>

I've now written my first set of Classes to do some fairly specific
processing for work I do. I have a few questions.

First, in looking through what I've done, I basically just incorporated all
my previous scripts into classes... they are still highly specific to my
application, though I did try to make them somewhat 'reusable' or general.
It is difficult though, as portions required hardcoding. For that I used the
__init__ method to define a bunch of 'hardcoded' variables, that could then
be set if they were passed on initiation.

I guess, I'm writing because I'm wondering now what people think about
writing classes versus just using scripts for things that are so specific.
It's hard for me to give an example, or show what I'm doing, but I would
appreciate thoughts on that matter.

One thing I am struggling with is how to assign *args and **kwargs if they
are passed, and how to ignore them if they are not... right now I do this:

def myfunc(self, *args,**kwargs):
   a=self.a
   b=self.b
   kwa=self.kwa
   kwb=self.kwb
   try:
        a=args[0]; b=args[1]
        kwa=kwargs['a']
         kwb=kwargs['b']
   except: pass


Where self.X is defined in the __init__ of the class. Is that correct?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071104/351f3512/attachment.htm 

From washakie at gmail.com  Sun Nov  4 14:07:32 2007
From: washakie at gmail.com (John)
Date: Sun, 4 Nov 2007 14:07:32 +0100
Subject: [Tutor] 'source' in python or preloading variables
In-Reply-To: <aaf235960710271057p2f9368cdx8e57fda41cac9a62@mail.gmail.com>
References: <aaf235960710270549l7b9d5b42o21e9fee603aab0f4@mail.gmail.com>
	<aaf235960710270653q2d47bfafob106a3003d1e41bb@mail.gmail.com>
	<aaf235960710270713m23e3116gaeb5ba9944dd6e4a@mail.gmail.com>
	<5df213700710270751u78e3c8f7x4ffde427444e25a4@mail.gmail.com>
	<aaf235960710270823k5625f671ye00f2d206e53e75c@mail.gmail.com>
	<5df213700710270833s380df440h3dc6f939faa3631a@mail.gmail.com>
	<aaf235960710270912i1d677294j35f0f23059ac656f@mail.gmail.com>
	<aaf235960710270915g57543fddubf9ae909485b2ef1@mail.gmail.com>
	<5df213700710271016i31627a76n16231d0300672065@mail.gmail.com>
	<aaf235960710271057p2f9368cdx8e57fda41cac9a62@mail.gmail.com>
Message-ID: <aaf235960711040507j157e3e7bwebf914eda4066abd@mail.gmail.com>

Does anyone know why the script below works fine (in regards to the 'source
function') but when I try to uncomment the line from mymod import source and
use it that way without defining the function in the script, I get an error
that N_id does not exist. It must have something to do with namespace and
global variables I don't understand...


#!/usr/bin/env python

from PyF import *
#from mymod import source
vList=['N_id','Nlat','Nlon','Nelv']
###### FUNCTION #########
def source(filename, vList):
        """ Reads a filename, collects variabls in file, and returns
variables.
        Usage: source(filename, vList) where vList is a list of variables.

        """
        import re
        # Read the file
        fid=open(filename,'r')
        lines = fid.readlines()
        fid.close()
        #how many variables
        ns=len(lines)/len(vList)
        #predefine the varibles
        for v in vList:
                exec( 'global %s ; %s = [0]*(ns+1)' % (v, v))

        # Make it python friendly: put all values in 'single quotes'
        cmd = '\n'.join([re.sub( r'^([^=]+)=(.*)$', r"\1='\2'", v) for v in
lines])
        exec(cmd)
        for v in vList:
                exec( "global %s ; %s = %s[1:]" % (v,v,v) )


source('sites_ALL',vList)

for s in N_id:
        fw=stnWeb(s)
        fw.mkStnBase()
fw.mkWebBase()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071104/cbaff03c/attachment.htm 

From alan.gauld at btinternet.com  Sun Nov  4 14:25:11 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 4 Nov 2007 13:25:11 -0000
Subject: [Tutor] Some question about OO practice
References: <aaf235960711040315p21e5b1fdha608308593c64788@mail.gmail.com>
Message-ID: <fgkh7r$n6g$1@ger.gmane.org>


"John" <washakie at gmail.com> wrote

> I've now written my first set of Classes to do some fairly specific
> processing for work I do. I have a few questions.
>
> First, in looking through what I've done, I basically just 
> incorporated all
> my previous scripts into classes... they are still highly specific 
> to my
> application, though I did try to make them somewhat 'reusable' or 
> general.

That may be OK but without knowing more about what these
scripts do then its hard to say. Its possiblye that the scripts
are all of the same general nature and deal with comon data
elements or perform similar functions but with different
algorithms or data parameters. In those cases there are
probably ways to use abstract classes to create a  uniform
class framework that can then be specialised for each task.
But to know if that makes sense requires a lot more information
about the nature of the problem

Also, it depends a bit on how you implemented the classes.
If you literally just put

class foo:

at the top of the module and treated all variables as attributes
and converted all functions to methods then probably you
haven't gained much advantage.

> I guess, I'm writing because I'm wondering now what people think 
> about
> writing classes versus just using scripts for things that are so 
> specific.

The more specific the task the less useful clases will be. As the name
suggests classes are used for solving problems that can be classified,
wjhere the generic aspects can be captured in one place (a superclass)
and the specifics put someplace else (a subclass).

> One thing I am struggling with is how to assign *args and **kwargs 
> if they
> are passed, and how to ignore them if they are not... right now I do 
> this:
>
> def myfunc(self, *args,**kwargs):
>   a=self.a
>   b=self.b
>   kwa=self.kwa
>   kwb=self.kwb
>   try:
>        a=args[0]; b=args[1]
>        kwa=kwargs['a']
>         kwb=kwargs['b']
>   except: pass
>
>
> Where self.X is defined in the __init__ of the class. Is that 
> correct?

It should work although in my (limited) experience of using 
*args/**kwargs
it is more common for them to be used in this way within the init()
itself rather than in another method. When you create an instance
you would pass all the attriubute data it needs to do its job. Once
instantiated the methods of the object should rarely need to
set lots of attributes to new values, maybe one or two but not
many. Typically that suggests that some other object is messing
with data that the instance should be managing itself!

But again without context its impossible to be definitive, there are
exceptions to every rule - especially in OOP! But the pattern would
generally raise alarm bells for me until I understood why it was that
way.

HTH,

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



From kent37 at tds.net  Sun Nov  4 14:25:13 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 04 Nov 2007 08:25:13 -0500
Subject: [Tutor] 'source' in python or preloading variables
In-Reply-To: <aaf235960711040507j157e3e7bwebf914eda4066abd@mail.gmail.com>
References: <aaf235960710270549l7b9d5b42o21e9fee603aab0f4@mail.gmail.com>	<aaf235960710270653q2d47bfafob106a3003d1e41bb@mail.gmail.com>	<aaf235960710270713m23e3116gaeb5ba9944dd6e4a@mail.gmail.com>	<5df213700710270751u78e3c8f7x4ffde427444e25a4@mail.gmail.com>	<aaf235960710270823k5625f671ye00f2d206e53e75c@mail.gmail.com>	<5df213700710270833s380df440h3dc6f939faa3631a@mail.gmail.com>	<aaf235960710270912i1d677294j35f0f23059ac656f@mail.gmail.com>	<aaf235960710270915g57543fddubf9ae909485b2ef1@mail.gmail.com>	<5df213700710271016i31627a76n16231d0300672065@mail.gmail.com>	<aaf235960710271057p2f9368cdx8e57fda41cac9a62@mail.gmail.com>
	<aaf235960711040507j157e3e7bwebf914eda4066abd@mail.gmail.com>
Message-ID: <472DC839.1030703@tds.net>

John wrote:
> Does anyone know why the script below works fine (in regards to the 
> 'source function') but when I try to uncomment the line from mymod 
> import source and use it that way without defining the function in the 
> script, I get an error that N_id does not exist. It must have something 
> to do with namespace and global variables I don't understand...

I think the exec must be using the namespace of the current execution 
context rather than the lexically scoped namespace.

Why do you need to create these variables? Could you just create a 
dictionary with the name / value pairs and use that?

Generally in Python it is better to find a solution with a dict than to 
try to create named variables.

Kent

>  
>  
> #!/usr/bin/env python
> 
> from PyF import *
> #from mymod import source
> vList=['N_id','Nlat','Nlon','Nelv']
> ###### FUNCTION #########
> def source(filename, vList):
>         """ Reads a filename, collects variabls in file, and returns 
> variables.
>         Usage: source(filename, vList) where vList is a list of variables.
>         
>         """
>         import re
>         # Read the file
>         fid=open(filename,'r')
>         lines = fid.readlines()
>         fid.close()
>         #how many variables
>         ns=len(lines)/len(vList)
>         #predefine the varibles
>         for v in vList:
>                 exec( 'global %s ; %s = [0]*(ns+1)' % (v, v))
> 
>         # Make it python friendly: put all values in 'single quotes'
>         cmd = '\n'.join([re.sub( r'^([^=]+)=(.*)$', r"\1='\2'", v) for v 
> in lines])
>         exec(cmd)
>         for v in vList:
>                 exec( "global %s ; %s = %s[1:]" % (v,v,v) )
> 
> 
> source('sites_ALL',vList)
> 
> 
> for s in N_id:
>         fw=stnWeb(s)
>         fw.mkStnBase()
> fw.mkWebBase()
>  
>  
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


From kent37 at tds.net  Sun Nov  4 14:31:00 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 04 Nov 2007 08:31:00 -0500
Subject: [Tutor] Some question about OO practice
In-Reply-To: <aaf235960711040315p21e5b1fdha608308593c64788@mail.gmail.com>
References: <aaf235960711040315p21e5b1fdha608308593c64788@mail.gmail.com>
Message-ID: <472DC994.7080403@tds.net>

John wrote:
> I've now written my first set of Classes to do some fairly specific 
> processing for work I do. I have a few questions.
>  
> First, in looking through what I've done, I basically just incorporated 
> all my previous scripts into classes... they are still highly specific 
> to my application, though I did try to make them somewhat 'reusable' or 
> general. It is difficult though, as portions required hardcoding. For 
> that I used the __init__ method to define a bunch of 'hardcoded' 
> variables, that could then be set if they were passed on initiation.

You didn't show your original script or enough context for me to judge 
if this was a useful change. A program that uses classes rather than 
simple scripts is not necessarily 'better' than one that doesn't. 
Classes are a tool that is helpful in some circumstances but not all. In 
other words don't add classes to your programs just because it seems 
like a good idea. Some good reasons for using classes are here:
http://personalpages.tds.net/~kent37/stories/00014.html

> I guess, I'm writing because I'm wondering now what people think about 
> writing classes versus just using scripts for things that are so 
> specific. It's hard for me to give an example, or show what I'm doing, 
> but I would appreciate thoughts on that matter.

It's ok for classes to be specific.

> One thing I am struggling with is how to assign *args and **kwargs if 
> they are passed, and how to ignore them if they are not... right now I 
> do this:
>  
> def myfunc(self, *args,**kwargs):
>    a=self.a
>    b=self.b
>    kwa=self.kwa
>    kwb=self.kwb
>    try:
>         a=args[0]; b=args[1]
>         kwa=kwargs['a']
>         kwb=kwargs['b']
>    except: pass
>  
>  
> Where self.X is defined in the __init__ of the class. Is that correct?

No, this will not assign from kwargs if args is not given. How about this:
def myfunc(self, *args,**kwargs):
    try:
         a=args[0]; b=args[1]
    except TypeError:
         a=self.a
         b=self.b
    try:
         kwa=kwargs['a']
         kwb=kwargs['b']
    except TypeError:
         kwa=self.kwa
         kwb=self.kwb

Kent

From washakie at gmail.com  Sun Nov  4 14:43:08 2007
From: washakie at gmail.com (John)
Date: Sun, 4 Nov 2007 14:43:08 +0100
Subject: [Tutor] Some question about OO practice
In-Reply-To: <472DC994.7080403@tds.net>
References: <aaf235960711040315p21e5b1fdha608308593c64788@mail.gmail.com>
	<472DC994.7080403@tds.net>
Message-ID: <aaf235960711040543p4346efa0g46b0e336f0ea796@mail.gmail.com>

Thanks,

One last question (okay, one MORE question ;) ) when you call a
method/function with optionaly *args **kwargs, I'm finding I need to make
the statement like;

def myFunc(self, *args,**kwargs):
  do something


In ord to pass the kwargs:
myFunc(**kwargs) # where kwargs is a dictionary

or for args:
myFunc(a,b,c, etc.)

It is correct that you need to use the '**' in the 'calling' statement?




On Nov 4, 2007 2:31 PM, Kent Johnson <kent37 at tds.net> wrote:

> John wrote:
> > I've now written my first set of Classes to do some fairly specific
> > processing for work I do. I have a few questions.
> >
> > First, in looking through what I've done, I basically just incorporated
> > all my previous scripts into classes... they are still highly specific
> > to my application, though I did try to make them somewhat 'reusable' or
> > general. It is difficult though, as portions required hardcoding. For
> > that I used the __init__ method to define a bunch of 'hardcoded'
> > variables, that could then be set if they were passed on initiation.
>
> You didn't show your original script or enough context for me to judge
> if this was a useful change. A program that uses classes rather than
> simple scripts is not necessarily 'better' than one that doesn't.
> Classes are a tool that is helpful in some circumstances but not all. In
> other words don't add classes to your programs just because it seems
> like a good idea. Some good reasons for using classes are here:
> http://personalpages.tds.net/~kent37/stories/00014.html
>
> > I guess, I'm writing because I'm wondering now what people think about
> > writing classes versus just using scripts for things that are so
> > specific. It's hard for me to give an example, or show what I'm doing,
> > but I would appreciate thoughts on that matter.
>
> It's ok for classes to be specific.
>
> > One thing I am struggling with is how to assign *args and **kwargs if
> > they are passed, and how to ignore them if they are not... right now I
> > do this:
> >
> > def myfunc(self, *args,**kwargs):
> >    a=self.a
> >    b=self.b
> >    kwa=self.kwa
> >    kwb=self.kwb
> >    try:
> >         a=args[0]; b=args[1]
> >         kwa=kwargs['a']
> >         kwb=kwargs['b']
> >    except: pass
> >
> >
> > Where self.X is defined in the __init__ of the class. Is that correct?
>
> No, this will not assign from kwargs if args is not given. How about this:
> def myfunc(self, *args,**kwargs):
>    try:
>         a=args[0]; b=args[1]
>    except TypeError:
>         a=self.a
>         b=self.b
>    try:
>         kwa=kwargs['a']
>         kwb=kwargs['b']
>    except TypeError:
>          kwa=self.kwa
>         kwb=self.kwb
>
> Kent
>



-- 
Configuration
``````````````````````````
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Five 1.4.1,
Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
4.1.1-51)],
PIL 1.1.6
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071104/204920ac/attachment-0001.htm 

From kent37 at tds.net  Sun Nov  4 15:11:59 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 04 Nov 2007 09:11:59 -0500
Subject: [Tutor] Some question about OO practice
In-Reply-To: <aaf235960711040543p4346efa0g46b0e336f0ea796@mail.gmail.com>
References: <aaf235960711040315p21e5b1fdha608308593c64788@mail.gmail.com>	
	<472DC994.7080403@tds.net>
	<aaf235960711040543p4346efa0g46b0e336f0ea796@mail.gmail.com>
Message-ID: <472DD32F.6080006@tds.net>

John wrote:
> Thanks,
>  
> One last question (okay, one MORE question ;) ) when you call a 
> method/function with optionaly *args **kwargs, I'm finding I need to 
> make the statement like;
>  
> def myFunc(self, *args,**kwargs):
>   do something
>  
>  
> In ord to pass the kwargs:
> myFunc(**kwargs) # where kwargs is a dictionary
>  
> or for args:
> myFunc(a,b,c, etc.)
>  
> It is correct that you need to use the '**' in the 'calling' statement?

Yes, if the keyword args are in a dict you have to use ** at the point 
of call. You can also specify the args directly:
myFunc(x=1, y=2)

Kent

From thorsten at thorstenkampe.de  Sun Nov  4 07:50:04 2007
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Sun, 4 Nov 2007 14:50:04 +0800
Subject: [Tutor] repeated times
References: <184538.78377.qm@web86704.mail.ird.yahoo.com>
	<1d987df30711040139o2ac323aaw685de9b9e4245744@mail.gmail.com>
Message-ID: <fgklnq$1s9$1@ger.gmane.org>

* linda.s (Sun, 4 Nov 2007 01:39:46 -0800)
> On Nov 2, 2007 1:03 AM, ALAN GAULD <alan.gauld at btinternet.com> wrote:
> > > > >I want to run an .exe file and get the output many times.
> > >> Given that I know that you know about loops I have to
> > >> ask what you see as the problem?
> > >
> > >I want to run it many times and export all the output to a text file.
> >
> > OK, Do you mean you want to run the program multiple times
> > but put the output in the same file?
> 
> Yes. For example, I want to run the exe file one hundred times and
> save all the results into one file.
> Is there any example code to do that?

There's no reason to do that in Python. You should use a batch or 
shell script for that. If you really insist on using Python then look 
at the subprocess module...

Thorsten


From tavspamnofwd at googlemail.com  Sun Nov  4 16:55:05 2007
From: tavspamnofwd at googlemail.com (Tom)
Date: Sun, 4 Nov 2007 15:55:05 +0000
Subject: [Tutor] I need an 'atomic read/ write action'
Message-ID: <ca43e5230711040755m1f80a212j46e367b0b62a6e58@mail.gmail.com>

Hi,

I am trying to write a cron/ task scheduler like system for my website. The
users of my site and also more than one external rss feed reader request my
scripts regularly and I'd like to insert code in each script that
will decide whether to run a scheduled task or not.

It would go something like this:

<pseudocode>
for task in tasks:
    if current_time inside relevant time range for task:
        if task not already done:
            record that task has been done
            do task
</pseudocode>

Now the problem is that this script could possibly be called more than once
simultaneously! Having studied 'concurrent programming' I understand the
possibility of the following pathological example:

call 1: if task not already done:
call 2: if task not already done:
call 1:     record that task x has been done
 call 2:     record that task x has been done
 call 1:     do task x
 call 2:     do task x #AGAIN

now we have the task recorded done twice and carried out twice.

So all my ideas for how to record task x as 'done', like using shelve
or writing a log file etc are not sufficient because, I need an 'atomic
read/ write action' (I think that's the jargon).

I thought about asking how to lock a log file so that it couldn't be
accessed simultaneously, but I then realise that you STILL have the problem
of the 'gap' between "sleep while log file locked" and "access log file". I
need something where the 'does the task need doing?' and the 'I'm going to
do the task. Please no one else do it!' are atomic(?) and leave no room for
mischief in between.

Another problem is that the task may fail and need redoing, but I think I
can solve that given a solution to the above.

Do let me know if my question isn't clear.
Thanks in advance!
Tom
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071104/be6e93ab/attachment.htm 

From pierre.cutellic at gmail.com  Sun Nov  4 17:01:51 2007
From: pierre.cutellic at gmail.com (pierre cutellic)
Date: Sun, 4 Nov 2007 17:01:51 +0100
Subject: [Tutor] reading and writing with csv then appending some data to a
	specific line
Message-ID: <3c8b20230711040801i508bed0aq47eb18d268664e7b@mail.gmail.com>

Hi,
I wrote this script to select some data from a csv file.
Actually it writes it into a file but i would like to append it into an
existing one to a specific line without removing existing code.
 does the open('filename.csv','a+') can do that?

here is the existing code:


*import csv
import sys

def rawdata():

    rawdata = []
    catched = []
    f = open('datalisting_000.csv','r')#the file to read to(!same path)

    try:

        reader = csv.reader(f)

        for row in reader:

            rawdata.append(row)

    finally:

        f.close()

    del rawdata[0]

    for elem in rawdata:

        ag = elem[0]
        ag.split(";")
        catched.append(ag)

    return catched

def sendingraw():

    ff = open('data.py','w')#the file to write to(!same path)
    ff.write(str(rawdata()))
    ff.close()

sendingraw()*

Cheers
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071104/22aedbfb/attachment.htm 

From washakie at gmail.com  Sun Nov  4 17:16:25 2007
From: washakie at gmail.com (John)
Date: Sun, 4 Nov 2007 17:16:25 +0100
Subject: [Tutor] reading and writing with csv then appending some data
	to a specific line
In-Reply-To: <3c8b20230711040801i508bed0aq47eb18d268664e7b@mail.gmail.com>
References: <3c8b20230711040801i508bed0aq47eb18d268664e7b@mail.gmail.com>
Message-ID: <aaf235960711040816w756455e2oe54e2e871f47408a@mail.gmail.com>

Remember to seek to the end of the file before you start writing. See:
http://mail.python.org/pipermail/python-list/2000-August/048839.html
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071104/130f530d/attachment.htm 

From aditya.n.lal at gmail.com  Sun Nov  4 18:15:28 2007
From: aditya.n.lal at gmail.com (Aditya Lal)
Date: Sun, 4 Nov 2007 22:45:28 +0530
Subject: [Tutor] repeated times
In-Reply-To: <fgklnq$1s9$1@ger.gmane.org>
References: <184538.78377.qm@web86704.mail.ird.yahoo.com>
	<1d987df30711040139o2ac323aaw685de9b9e4245744@mail.gmail.com>
	<fgklnq$1s9$1@ger.gmane.org>
Message-ID: <5df213700711040915x906cffbs3685166c9b271d63@mail.gmail.com>

On 11/4/07, Thorsten Kampe <thorsten at thorstenkampe.de> wrote:
>
> * linda.s (Sun, 4 Nov 2007 01:39:46 -0800)
> > On Nov 2, 2007 1:03 AM, ALAN GAULD <alan.gauld at btinternet.com> wrote:
> > > > > >I want to run an .exe file and get the output many times.
> > > >> Given that I know that you know about loops I have to
> > > >> ask what you see as the problem?
> > > >
> > > >I want to run it many times and export all the output to a text file.
> > >
> > > OK, Do you mean you want to run the program multiple times
> > > but put the output in the same file?
> >
> > Yes. For example, I want to run the exe file one hundred times and
> > save all the results into one file.
> > Is there any example code to do that?
>
> There's no reason to do that in Python. You should use a batch or
> shell script for that. If you really insist on using Python then look
> at the subprocess module...
>
> Thorsten
>
On Unix, you can execute "script <filename>" on the command prompt. This
will create a new session in which you execute the program as many times.
After you are done press ^D to come out of session. Everything of that
session will be saved in the file <filename>.

On Windows, you can probably build something like "script" in python. BTW,
does your executable takes any user inputs ?

-- 
Aditya
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071104/752a0a2b/attachment.htm 

From mlangford.cs03 at gtalumni.org  Sun Nov  4 22:04:40 2007
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Sun, 4 Nov 2007 16:04:40 -0500
Subject: [Tutor] I need an 'atomic read/ write action'
In-Reply-To: <ca43e5230711040755m1f80a212j46e367b0b62a6e58@mail.gmail.com>
References: <ca43e5230711040755m1f80a212j46e367b0b62a6e58@mail.gmail.com>
Message-ID: <82b4f5810711041304m366e3a2bv2303d20b3fbd6cf8@mail.gmail.com>

You don't need an atomic read and write, you need a blocking file lock
mechanism. This page explains them and how to use them:

http://www.voidspace.org.uk/python/pathutils.html#file-locking

   --Michael

On 11/4/07, Tom <tavspamnofwd at googlemail.com> wrote:
>
> Hi,
>
> I am trying to write a cron/ task scheduler like system for my
> website. The users of my site and also more than one external rss feed
> reader request my scripts regularly and I'd like to insert code in each
> script that will decide whether to run a scheduled task or not.
>
> It would go something like this:
>
> <pseudocode>
> for task in tasks:
>     if current_time inside relevant time range for task:
>         if task not already done:
>             record that task has been done
>             do task
> </pseudocode>
>
> Now the problem is that this script could possibly be called more than
> once simultaneously! Having studied 'concurrent programming' I understand
> the possibility of the following pathological example:
>
> call 1: if task not already done:
> call 2: if task not already done:
> call 1:     record that task x has been done
>  call 2:     record that task x has been done
>  call 1:     do task x
>  call 2:     do task x #AGAIN
>
> now we have the task recorded done twice and carried out twice.
>
> So all my ideas for how to record task x as 'done', like using shelve
> or writing a log file etc are not sufficient because, I need an 'atomic
> read/ write action' (I think that's the jargon).
>
> I thought about asking how to lock a log file so that it couldn't be
> accessed simultaneously, but I then realise that you STILL have the problem
> of the 'gap' between "sleep while log file locked" and "access log file". I
> need something where the 'does the task need doing?' and the 'I'm going to
> do the task. Please no one else do it!' are atomic(?) and leave no room for
> mischief in between.
>
> Another problem is that the task may fail and need redoing, but I think I
> can solve that given a solution to the above.
>
> Do let me know if my question isn't clear.
> Thanks in advance!
> Tom
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.TierOneDesign.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071104/c701c1fb/attachment-0001.htm 

From varsha.purohit at gmail.com  Sun Nov  4 22:49:58 2007
From: varsha.purohit at gmail.com (Varsha Purohit)
Date: Sun, 4 Nov 2007 13:49:58 -0800
Subject: [Tutor]  Difference between Perl and Python
Message-ID: <c2157c790711041349l69d8ebb1qb28a9cbf6949bf5a@mail.gmail.com>

Hello everyone,
       I wanted to know what are the differences between perl and
python, since both of them are scripting languages...

thanks
-- 
Varsha,

From steve at alchemy.com  Sun Nov  4 23:11:03 2007
From: steve at alchemy.com (Steve Willoughby)
Date: Sun, 04 Nov 2007 14:11:03 -0800
Subject: [Tutor] Difference between Perl and Python
In-Reply-To: <c2157c790711041349l69d8ebb1qb28a9cbf6949bf5a@mail.gmail.com>
References: <c2157c790711041349l69d8ebb1qb28a9cbf6949bf5a@mail.gmail.com>
Message-ID: <472E4377.6090204@alchemy.com>

Varsha Purohit wrote:
> Hello everyone,
>        I wanted to know what are the differences between perl and
> python, since both of them are scripting languages...

There is plenty of difference between them and between all the other 
scripting languages.  Look beyond the notion of "scripting" and look at 
the programming language and the paradigm it supports.

Personally, I don't see Python as much of a scripting language in the 
sense that Perl is, where Perl is the "king of the quick hack"... 
powerful, easy to throw together a script to get a job done in a hurry. 
  Not so easy (but undeniably possible) to keep a disciplined, careful 
approach to writing a sizable application which will be maintained over 
time.

Python, on the other hand, feels more to me like a solid, disciplined 
object-oriented (dare I say "real") programming language which happens 
to be high-level, dynamic and compiled to bytecode at runtime (much as 
Java is).  It takes a little more work to make a program in Python than 
Perl, but the code tends to be more solid and easier to maintain.

Those are gross generalizations, and depend on programmer skill, but the 
languages approach programming from such different angles, and encourage 
such different mindsets that it's worth considering as a difference.

Each language has separate strengths.  Python is less ambiguous about 
what expressions mean (Perl tries hard to "guess" at an appropriate way 
to interpret almost anything to do *something* while Python rejects 
things that are not clear and explicit as to your intent).  Python is 
*far* stronger at OOP support than Perl.  Perl has more convenient 
short-cuts for many things, but I've found the completeness of the 
Python standard lib and the flexibility of the methods and functions 
inside it to ultimately give me more power even if I can't do it in 
three characters.

The list could go on and on, but it really comes down to what you want 
to accomplish.  I'd use Perl for a lot of "scripting" kinds of needs, 
one-off scripts, simple data reformatting, process automation, but would 
prefer Python for creating more complex applications.  Likewise, TCL and 
Ruby have their own particular domains they do well within.


From Garry.Willgoose at newcastle.edu.au  Mon Nov  5 01:17:32 2007
From: Garry.Willgoose at newcastle.edu.au (Garry Willgoose)
Date: Mon, 5 Nov 2007 11:17:32 +1100
Subject: [Tutor] import and reload in modules
Message-ID: <6639A24E-5F85-405B-A5BD-8BB30E24E01A@newcastle.edu.au>

I'm writing a simple modelling environment that provides a GUI for  
dynamically coupling fortran and C subroutines to solve a science  
problem. The GUI and environment glue are all python. One thing I  
want to do is allow the user to load a python file that provides the  
user defined details on how the C/Fortran modules are to be coupled  
in the science model ... basically a script file if you like. They  
use the GUI to select and run the python file. I have no control over  
whether/when the user edits the python script and wants to rerun the  
script without restarting the environment so I need to be able to  
(repeatedly) reload the current script at any time

I'm having problems with import and reload. Here is a simple test  
code (mytest.py) that runs from the python prompt that shows the  
problem, and the log of my session from the python command line.

In the real code the variable 'model' is passed into load() ... I've  
just set it here to make the code self contained. At the first load()  
the version in siberia900.py is set to 1.00. Between the first and  
second load() I edit siberia900.py so that version is 0.00 (just an  
easy way to see if the modified code is reloaded). Clearly the reload  
fails (and if I don't have the try/except ... that is the commented  
line is executed ... it crashes with the error 'NameError: name  
'siberia900' is not defined'). Also clearly reloading mytest also  
doesn't change anything.

Now all this runs fine (i.e. the correct version numbers are output)  
at the python interpretter line so its clearly something to do with  
it being inside the module mytest which I don't understand. Finally  
if I uncomment the bottom two lines and run it at the unix command  
line as 'python mytest.py' it still fails in the same way (i.e. the  
'except' line is executed).

Can anyone please explain what's going on ... and how I might be able  
to do what I need to do.

------------------------------------
current_model_name=''

def load():
   global current_model_name
   model='siberia900'
   text1='import '+model
   text2='reload('+model+')'
   if model==current_model_name:
     try:
       exec(text2)
       print 'here 2',text2
     except:
       print 'here 3',text1
       exec(text1)
#    exec(text2)
   else:
     print 'here 10', text1
     exec(text1)
   current_model_name=model
   return(siberia900.version)

#load()
#load()
----------------------------------------
-----------------------------------------
 >>> import mytest
 >>> mytest.load()
here 10 import siberia900
'1.00'
 >>> mytest.load()
here 3 import siberia900
'1.00'
 >>> reload(mytest)
<module 'mytest' from 'mytest.pyc'>
 >>> mytest.load()
here 10 import siberia900
'1.00'
-----------------------------------------

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

Centre webpage: www.c3im.org.au

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

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





From swartmumba at yahoo.com  Mon Nov  5 02:10:08 2007
From: swartmumba at yahoo.com (SwartMumba snake)
Date: Sun, 4 Nov 2007 17:10:08 -0800 (PST)
Subject: [Tutor] images
Message-ID: <867364.13195.qm@web44802.mail.sp1.yahoo.com>

Hi

I would like to know which is the best module to use, with regard to my needs:

- I would like to read an image off a website 
e.g. http://www.examplecom/image/1/PNG/

- I would then like to read the pixels and do other things to the image

I am currently using python 2.5

Thanks in advance . . .

 __________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071104/488fa782/attachment.htm 

From detroit371 at gmail.com  Mon Nov  5 02:12:30 2007
From: detroit371 at gmail.com (Lawrence Shafer)
Date: Sun, 04 Nov 2007 19:12:30 -0600
Subject: [Tutor] importing
Message-ID: <472E6DFE.3010601@gmail.com>

What is the difference between "from name import *" and "import name"?

The reason I ask is because I was using the former, and switched to the 
latter only to find out "NameError: global name 'name' is not defined" 
and I think using the latter is going to fix another problem I have. I 
just want to know what's going on and how to work with it.

From john at fouhy.net  Mon Nov  5 02:25:29 2007
From: john at fouhy.net (John Fouhy)
Date: Mon, 5 Nov 2007 14:25:29 +1300
Subject: [Tutor] images
In-Reply-To: <867364.13195.qm@web44802.mail.sp1.yahoo.com>
References: <867364.13195.qm@web44802.mail.sp1.yahoo.com>
Message-ID: <5e58f2e40711041725v201225adqf25d6f93aa55fca9@mail.gmail.com>

On 05/11/2007, SwartMumba snake <swartmumba at yahoo.com> wrote:
> Hi
>
> I would like to know which is the best module to use, with regard to my
> needs:
>
> - I would like to read an image off a website
> e.g. http://www.examplecom/image/1/PNG/
>
> - I would then like to read the pixels and do other things to the image

For manipulating the image, your best bet is probably PIL (the Python
Image Library).

To get the image, if you know its URL, you can just use urllib or
urllib2 (in the standard library).  If you will need to do some
parsing to figure out what image you want, you could look into
BeautifulSoup.

HTH.

-- 
John.

From kent37 at tds.net  Mon Nov  5 02:50:22 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 04 Nov 2007 20:50:22 -0500
Subject: [Tutor] I need an 'atomic read/ write action'
In-Reply-To: <ca43e5230711040755m1f80a212j46e367b0b62a6e58@mail.gmail.com>
References: <ca43e5230711040755m1f80a212j46e367b0b62a6e58@mail.gmail.com>
Message-ID: <472E76DE.8060006@tds.net>

Tom wrote:
> So all my ideas for how to record task x as 'done', like using shelve 
> or writing a log file etc are not sufficient because, I need an 'atomic 
> read/ write action' (I think that's the jargon).

A couple of ideas:
- Michael's file lock
- lockfile is another way to lock files
http://pypi.python.org/pypi/lockfile/0.1

- you could put the tasks in a database that supports transactions
- you could run the scheduler as a single cron task rather than 
opportunistically when a user makes a request.
- you could just use cron as your scheduler directly

Kent


From kent37 at tds.net  Mon Nov  5 02:54:54 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 04 Nov 2007 20:54:54 -0500
Subject: [Tutor] reading and writing with csv then appending some data
 to a	specific line
In-Reply-To: <3c8b20230711040801i508bed0aq47eb18d268664e7b@mail.gmail.com>
References: <3c8b20230711040801i508bed0aq47eb18d268664e7b@mail.gmail.com>
Message-ID: <472E77EE.50908@tds.net>

pierre cutellic wrote:
> Hi,
> I wrote this script to select some data from a csv file.
> Actually it writes it into a file but i would like to append it into an 
> existing one to a specific line without removing existing code.
>  does the open(' filename.csv','a+') can do that?
> 
>         ag = elem[0]
>         ag.split(";")

Here I think you want
   ag = ag.split(';')
split() does not split the string in place, it returns a new list with 
the split elements.

Also you are opening the file for writing (which will erase the 
contents) before you read it.

Other than that your code looks OK. You might want to try writing it 
without functions, I think they may be confusing you a bit and they are 
not really needed here.

Kent

From kent37 at tds.net  Mon Nov  5 03:12:06 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 04 Nov 2007 21:12:06 -0500
Subject: [Tutor] import and reload in modules
In-Reply-To: <6639A24E-5F85-405B-A5BD-8BB30E24E01A@newcastle.edu.au>
References: <6639A24E-5F85-405B-A5BD-8BB30E24E01A@newcastle.edu.au>
Message-ID: <472E7BF6.5040008@tds.net>

I don't know what the problem is but here are some things that might help:
- don't catch the exception, let it print out. Send the traceback to the 
list.
- note you never reload siberia900 - in the load function the reload 
fails for an unknown reason and at the interpreter prompt you reload 
mytest, not siberia900.
- you don't have to use exec - import is available as __import__() and 
reload is already a function.

Kent

Garry Willgoose wrote:
> I'm writing a simple modelling environment that provides a GUI for  
> dynamically coupling fortran and C subroutines to solve a science  
> problem. The GUI and environment glue are all python. One thing I  
> want to do is allow the user to load a python file that provides the  
> user defined details on how the C/Fortran modules are to be coupled  
> in the science model ... basically a script file if you like. They  
> use the GUI to select and run the python file. I have no control over  
> whether/when the user edits the python script and wants to rerun the  
> script without restarting the environment so I need to be able to  
> (repeatedly) reload the current script at any time
> 
> I'm having problems with import and reload. Here is a simple test  
> code (mytest.py) that runs from the python prompt that shows the  
> problem, and the log of my session from the python command line.
> 
> In the real code the variable 'model' is passed into load() ... I've  
> just set it here to make the code self contained. At the first load()  
> the version in siberia900.py is set to 1.00. Between the first and  
> second load() I edit siberia900.py so that version is 0.00 (just an  
> easy way to see if the modified code is reloaded). Clearly the reload  
> fails (and if I don't have the try/except ... that is the commented  
> line is executed ... it crashes with the error 'NameError: name  
> 'siberia900' is not defined'). Also clearly reloading mytest also  
> doesn't change anything.
> 
> Now all this runs fine (i.e. the correct version numbers are output)  
> at the python interpretter line so its clearly something to do with  
> it being inside the module mytest which I don't understand. Finally  
> if I uncomment the bottom two lines and run it at the unix command  
> line as 'python mytest.py' it still fails in the same way (i.e. the  
> 'except' line is executed).
> 
> Can anyone please explain what's going on ... and how I might be able  
> to do what I need to do.
> 
> ------------------------------------
> current_model_name=''
> 
> def load():
>    global current_model_name
>    model='siberia900'
>    text1='import '+model
>    text2='reload('+model+')'
>    if model==current_model_name:
>      try:
>        exec(text2)
>        print 'here 2',text2
>      except:
>        print 'here 3',text1
>        exec(text1)
> #    exec(text2)
>    else:
>      print 'here 10', text1
>      exec(text1)
>    current_model_name=model
>    return(siberia900.version)
> 
> #load()
> #load()
> ----------------------------------------
> -----------------------------------------
>  >>> import mytest
>  >>> mytest.load()
> here 10 import siberia900
> '1.00'
>  >>> mytest.load()
> here 3 import siberia900
> '1.00'
>  >>> reload(mytest)
> <module 'mytest' from 'mytest.pyc'>
>  >>> mytest.load()
> here 10 import siberia900
> '1.00'
> -----------------------------------------
> 
> ====================================================================
> Prof Garry Willgoose,
> Australian Professorial Fellow in Environmental Engineering,
> Director, Centre for Climate Impact Management (C2IM),
> School of Engineering, The University of Newcastle,
> Callaghan, 2308
> Australia.
> 
> Centre webpage: www.c3im.org.au
> 
> Phone: (International) +61 2 4921 6050 (Tues-Fri AM); +61 2 6545 9574  
> (Fri PM-Mon)
> FAX: (International) +61 2 4921 6991 (Uni); +61 2 6545 9574 (personal  
> and Telluric)
> Env. Engg. Secretary: (International) +61 2 4921 6042
> 
> email:  garry.willgoose at newcastle.edu.au;  
> g.willgoose at telluricresearch.com
> email-for-life: garry.willgoose at alum.mit.edu
> personal webpage: www.telluricresearch.com/garry
> ====================================================================
> "Do not go where the path may lead, go instead where there is no path  
> and leave a trail"
>                            Ralph Waldo Emerson
> ====================================================================
> 
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


From kent37 at tds.net  Mon Nov  5 03:16:17 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 04 Nov 2007 21:16:17 -0500
Subject: [Tutor] importing
In-Reply-To: <472E6DFE.3010601@gmail.com>
References: <472E6DFE.3010601@gmail.com>
Message-ID: <472E7CF1.60002@tds.net>

Lawrence Shafer wrote:
> What is the difference between "from name import *" and "import name"?

http://effbot.org/pyfaq/tutor-whats-the-difference-between-import-foo-and-from-foo-import.htm

Kent

From tavspamnofwd at googlemail.com  Mon Nov  5 04:12:22 2007
From: tavspamnofwd at googlemail.com (Tom)
Date: Mon, 5 Nov 2007 03:12:22 +0000
Subject: [Tutor] I need an 'atomic read/ write action'
In-Reply-To: <472E76DE.8060006@tds.net>
References: <ca43e5230711040755m1f80a212j46e367b0b62a6e58@mail.gmail.com>
	<472E76DE.8060006@tds.net>
Message-ID: <ca43e5230711041912u235d612bgb814b80a5381f85d@mail.gmail.com>

Thank you for your replies.I think lockfile is a good solution.

Kent, I have python 2.2.3 running on my server (not my choice) could you
tell me which module(s) I could use to access cron. Otherwise the only other
relavent way I can access my sever is Secure Shell Access (SSH). And what
about for my desktop computer (Vista Task Scheduler looks fancy but doesn't
seem to work so well for me) which uses python 2.5?

Thanks again. - Hide quoted text -


On 05/11/2007, Kent Johnson <kent37 at tds.net> wrote:
> Tom wrote:
> > So all my ideas for how to record task x as 'done', like using shelve
> > or writing a log file etc are not sufficient because, I need an 'atomic
> > read/ write action' (I think that's the jargon).
>
> A couple of ideas:
> - Michael's file lock
> - lockfile is another way to lock files
> http://pypi.python.org/pypi/lockfile/0.1
>
> - you could put the tasks in a database that supports transactions
> - you could run the scheduler as a single cron task rather than
> opportunistically when a user makes a request.
> - you could just use cron as your scheduler directly
>
> Kent
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071105/c55b7197/attachment.htm 

From Garry.Willgoose at newcastle.edu.au  Mon Nov  5 04:17:01 2007
From: Garry.Willgoose at newcastle.edu.au (Garry Willgoose)
Date: Mon, 5 Nov 2007 14:17:01 +1100
Subject: [Tutor] import and reload in modules
In-Reply-To: <472E7BF6.5040008@tds.net>
References: <6639A24E-5F85-405B-A5BD-8BB30E24E01A@newcastle.edu.au>
	<472E7BF6.5040008@tds.net>
Message-ID: <D4F3158E-52A4-4C0C-8A7B-CF0B6559DC8A@newcastle.edu.au>

In response to Kent's suggestion here is an updated post showing the  
python code and the error log. The original reason for using try was  
I thought maybe this was scoping problem and that maybe 2nd time  
through the call it needed to import it again from scratch. As a side  
observation for Kent I also tried replacing the exec on the import  
statement with __init__('siberia900') and other variants using a text  
variable and while they appeared to work I got a the following error

 >>> __import__('siberia900')
<module 'siberia900' from 'siberia900.pyc'>
 >>> siberia900.version
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
NameError: name 'siberia900' is not defined

Maybe its related don't know.


Anyway here's the original problem again with more info.

---------------------------------
current_model_name=''

def load():
   global current_model_name
   model='siberia900'
   text1='import '+model
   text2='reload('+model+')'
   if model==current_model_name:
     print 'here 1', text2
     exec(text2)
   else:
     print 'here 10', text1
     exec(text1)
   current_model_name=model
   version=eval(model+'.version')
   return(version)
---------------------------------
 >>> import mytest1
 >>> mytest1.load()
here 10 import siberia900
'1.00'
 >>> mytest1.load()
here 1 reload(siberia900)
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "mytest1.py", line 10, in load
     exec(text2)
   File "<string>", line 1, in <module>
NameError: name 'siberia900' is not defined
---------------------------------


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

Phone: (International) +61 2 4921 6050 (Tues-Thurs); +61 2 6545 9574  
(Fri-Mon)
FAX: (International) +61 2 4921 6991 (Uni);
Env. Engg. Secretary: (International) +61 2 4921 6042
Centre WWW  :  www.c3im.org.au

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





From kent37 at tds.net  Mon Nov  5 13:08:48 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 05 Nov 2007 07:08:48 -0500
Subject: [Tutor] import and reload in modules
In-Reply-To: <D4F3158E-52A4-4C0C-8A7B-CF0B6559DC8A@newcastle.edu.au>
References: <6639A24E-5F85-405B-A5BD-8BB30E24E01A@newcastle.edu.au>	<472E7BF6.5040008@tds.net>
	<D4F3158E-52A4-4C0C-8A7B-CF0B6559DC8A@newcastle.edu.au>
Message-ID: <472F07D0.5020204@tds.net>

Garry Willgoose wrote:
> In response to Kent's suggestion here is an updated post showing the  
> python code and the error log. The original reason for using try was  
> I thought maybe this was scoping problem and that maybe 2nd time  
> through the call it needed to import it again from scratch. As a side  
> observation for Kent I also tried replacing the exec on the import  
> statement with __init__('siberia900') and other variants using a text  
> variable and while they appeared to work I got a the following error
> 
>  >>> __import__('siberia900')
> <module 'siberia900' from 'siberia900.pyc'>
>  >>> siberia900.version
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
> NameError: name 'siberia900' is not defined
> 
> Maybe its related don't know.

__import__() returns a value which is the imported module so you have to say
user_module = __import__('siberia900')
and then
reload(user_module)
user_module.version

> Anyway here's the original problem again with more info.

I think the problem is that the module is being imported in the scope of 
load(). The first time you run load(), a local name 'siberia900' is 
created and bound to the imported module. The second time you run 
load(), this name is not available and you get the name error.

One way to fix this would be to use a global dict as the namespace for 
the exec and eval calls. A better solution is to get rid of them 
entirely as I have suggested.

Kent

> 
> ---------------------------------
> current_model_name=''
> 
> def load():
>    global current_model_name
>    model='siberia900'
>    text1='import '+model
>    text2='reload('+model+')'
>    if model==current_model_name:
>      print 'here 1', text2
>      exec(text2)
>    else:
>      print 'here 10', text1
>      exec(text1)
>    current_model_name=model
>    version=eval(model+'.version')
>    return(version)
> ---------------------------------
>  >>> import mytest1
>  >>> mytest1.load()
> here 10 import siberia900
> '1.00'
>  >>> mytest1.load()
> here 1 reload(siberia900)
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
>    File "mytest1.py", line 10, in load
>      exec(text2)
>    File "<string>", line 1, in <module>
> NameError: name 'siberia900' is not defined
> ---------------------------------
> 
> 
> ====================================================================
> Prof Garry Willgoose,
> Australian Professorial Fellow in Environmental Engineering,
> Director, Centre for Climate Impact Management (C2IM),
> School of Engineering, The University of Newcastle,
> Callaghan, 2308
> Australia.
> 
> Phone: (International) +61 2 4921 6050 (Tues-Thurs); +61 2 6545 9574  
> (Fri-Mon)
> FAX: (International) +61 2 4921 6991 (Uni);
> Env. Engg. Secretary: (International) +61 2 4921 6042
> Centre WWW  :  www.c3im.org.au
> 
> email:  garry.willgoose at newcastle.edu.au
> email-for-life: garry.willgoose at alum.mit.edu
> ====================================================================
> "Do not go where the path may lead, go instead where there is no path  
> and leave a trail"
>                            Ralph Waldo Emerson
> ====================================================================
> 
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


From tavspamnofwd at googlemail.com  Mon Nov  5 13:43:32 2007
From: tavspamnofwd at googlemail.com (Tom)
Date: Mon, 5 Nov 2007 12:43:32 +0000
Subject: [Tutor] difflib.SequenceMatcher with get_matching_blocks is
	incorrect
In-Reply-To: <493b81e30612041006q412014cbvdf38c137155eee29@mail.gmail.com>
References: <493b81e30612041006q412014cbvdf38c137155eee29@mail.gmail.com>
Message-ID: <ca43e5230711050443m3913cefcu3d03eb6d361c263f@mail.gmail.com>

Hi, I asked this question last year but got no response.

I'm trying to write a program to test someone's typing speed and show
them their mistakes. However I'm getting weird results when looking
for the differences in longer (than 100 chars) strings:

import difflib

# a tape measure string (just makes it easier to locate a given index)
a = '1-3-5-7-9-12-15-18-21-24-27-30-33-36-39-42-45-48-51-54-57-60-63-66-69-72-75-78-81-84-87-90-93-96-99-103-107-111-115-119-123-127-131-135-139-143-147-151-155-159-163-167-171-175-179-183-187-191-195--200'

# now with a few mistakes
b = '1-3-5-7-l-12-15-18-21-24-27-30-33-36-39o42-45-48-51-54-57-60-63-66-69-72-75-78-81-84-8k-90-93-96-9l-103-107-111-115-119-12b-1v7-131-135-139-143-147-151-m55-159-163-167-a71-175j179-183-187-191-195--200'

s = difflib.SequenceMatcher(None, a ,b)
ms = s.get_matching_blocks()

print ms


>>>[(0, 0, 8), (200, 200, 0)]


Have I made a mistake or is this function designed to give up when the
input strings get too long? If so what could I use instead to compute
the mistakes in a typed text.

Thanks in advance,
Thomas

From kent37 at tds.net  Mon Nov  5 15:11:50 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 05 Nov 2007 09:11:50 -0500
Subject: [Tutor] [Fwd: Re: reading and writing with csv then appending some
 data to a specific line]
Message-ID: <472F24A6.1060500@tds.net>

Forwarding to the list...

-------- Original Message --------
Subject: 	Re: [Tutor] reading and writing with csv then appending some
data to a specific line
Date: 	Mon, 5 Nov 2007 14:54:49 +0100
From: 	pierre cutellic <pierre.cutellic at gmail.com>
To: 	Kent Johnson <kent37 at tds.net>
References:
<3c8b20230711040801i508bed0aq47eb18d268664e7b at mail.gmail.com>
<472E77EE.50908 at tds.net>



many thanks,
but i don't really want to erase the content of the file i'm writing to.
This script was a first step for me to understand how to write to a file
at a given line of the file without erasing its content. I didn't really
understood the code you linked me:
http://mail.python.org/pipermail/python-list/2000-August/048839.html .
when i'm using seek(), data is appended to the end of the file.:(

On Nov 5, 2007 2:54 AM, Kent Johnson <kent37 at tds.net
<mailto:kent37 at tds.net>> wrote:

     pierre cutellic wrote:
      > Hi,
      > I wrote this script to select some data from a csv file.
      > Actually it writes it into a file but i would like to append it
     into an
      > existing one to a specific line without removing existing code.
      >  does the open(' filename.csv','a+') can do that?
      >
      >         ag = elem[0]
      >         ag.split(";")

     Here I think you want
       ag = ag.split(';')
     split() does not split the string in place, it returns a new list with
     the split elements.

     Also you are opening the file for writing (which will erase the
     contents) before you read it.

     Other than that your code looks OK. You might want to try writing it
     without functions, I think they may be confusing you a bit and they are
     not really needed here.

     Kent




-- 
Pierre Cutellic____________
OO   33   6   15   67   17   85
___pierre.cutellic at gmail.com <http://gmail.com>

From fiyawerx at gmail.com  Mon Nov  5 22:40:19 2007
From: fiyawerx at gmail.com (Fiyawerx)
Date: Mon, 5 Nov 2007 16:40:19 -0500
Subject: [Tutor] Sorting specific files by modification date
Message-ID: <1b31ae500711051340t54a2b28axa66ab189ef32f694@mail.gmail.com>

I'm working on a small script that so far, using the xlrd module, (
http://www.lexicon.net/sjmachin/xlrd.html) will parse all the files in a
given directory for a xls file with a specific worksheet. This way, if the
file names change, or people don't save the spreadsheet with the right name,
my script will still be able to locate the correct files to use for it's
data source out of multiple files / versions. So far what I have sort of
goes like this :

import os
import xlrd

data = {}

#path may be set externally at some point
data['path'] = 'mypath_to_program'

os.chdir(data['path'])

data['xls_files'] = [ file for file in os.listdir('./') if '.xls' in file ]

first_files = [ file for file in data['xls_files'] if u'First Worksheet' in
xlrd.open_workbook(file).sheet_names() ]
data['first_file'] = ??

second_files = [ file for file in data['xls_files'] if u'Second Worsheet' in
xlrd.open_workbook(file).sheet_names() ]
data['second_file'] = ??

This is where I get stuck, I'm trying to figure out how, from the files that
match, I can select the file with the most current time stamp and use that
as my main data file.
I know I can get the modification time with os.stat(file).st_mtime, but I'm
not sure how I can sort my returns by this, to get just the most current
version. Any help / thoughts would be appreciated. I'm going to be looking
for other worksheets as well that might be in other xls's, for example
'Second Worksheet' also, but I was just trying to get the 'first_files'
working first. Instead of opening them each time, should I construct some
type of data that stores the file, it's worksheets, and its modification
times for each file found, and then just parse that list? like maybe change
my xls_files around to not just be a list of names?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071105/e6fc97ca/attachment.htm 

From mlangford.cs03 at gtalumni.org  Mon Nov  5 23:59:40 2007
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Mon, 5 Nov 2007 17:59:40 -0500
Subject: [Tutor] Sorting specific files by modification date
In-Reply-To: <1b31ae500711051340t54a2b28axa66ab189ef32f694@mail.gmail.com>
References: <1b31ae500711051340t54a2b28axa66ab189ef32f694@mail.gmail.com>
Message-ID: <82b4f5810711051459y5e37ce75y76e5c39a9193026f@mail.gmail.com>

In psudocode:

#map the files to their time.
filesByTimes = {}
for each in filesInDirectory:
     filesByTimes[os.stat(each).st_mtime]=each

#find the largest time
times = filesByTimes.keys()
sort(times)

#retrieve the file that goes with it
latestFile = filesByTimes[times[-1]]


   --Michael


On 11/5/07, Fiyawerx <fiyawerx at gmail.com> wrote:
>
> I'm working on a small script that so far, using the xlrd module, (
> http://www.lexicon.net/sjmachin/xlrd.html) will parse all the files in a
> given directory for a xls file with a specific worksheet. This way, if the
> file names change, or people don't save the spreadsheet with the right name,
> my script will still be able to locate the correct files to use for it's
> data source out of multiple files / versions. So far what I have sort of
> goes like this :
>
> import os
> import xlrd
>
> data = {}
>
> #path may be set externally at some point
> data['path'] = 'mypath_to_program'
>
> os.chdir(data['path'])
>
> data['xls_files'] = [ file for file in os.listdir('./') if '.xls' in file
> ]
>
> first_files = [ file for file in data['xls_files'] if u'First Worksheet'
> in xlrd.open_workbook(file).sheet_names() ]
> data['first_file'] = ??
>
> second_files = [ file for file in data['xls_files'] if u'Second Worsheet'
> in xlrd.open_workbook(file).sheet_names() ]
> data['second_file'] = ??
>
> This is where I get stuck, I'm trying to figure out how, from the files
> that match, I can select the file with the most current time stamp and use
> that as my main data file.
> I know I can get the modification time with os.stat(file).st_mtime, but
> I'm not sure how I can sort my returns by this, to get just the most current
> version. Any help / thoughts would be appreciated. I'm going to be looking
> for other worksheets as well that might be in other xls's, for example
> 'Second Worksheet' also, but I was just trying to get the 'first_files'
> working first. Instead of opening them each time, should I construct some
> type of data that stores the file, it's worksheets, and its modification
> times for each file found, and then just parse that list? like maybe change
> my xls_files around to not just be a list of names?
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.TierOneDesign.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071105/8cd2f5ae/attachment.htm 

From kent37 at tds.net  Tue Nov  6 03:08:35 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 05 Nov 2007 21:08:35 -0500
Subject: [Tutor] Sorting specific files by modification date
In-Reply-To: <1b31ae500711051340t54a2b28axa66ab189ef32f694@mail.gmail.com>
References: <1b31ae500711051340t54a2b28axa66ab189ef32f694@mail.gmail.com>
Message-ID: <472FCCA3.5000506@tds.net>

Fiyawerx wrote:
> first_files = [ file for file in data['xls_files'] if u'First Worksheet' 
> in xlrd.open_workbook(file).sheet_names() ]
> data['first_file'] = ??

> This is where I get stuck, I'm trying to figure out how, from the files 
> that match, I can select the file with the most current time stamp and 
> use that as my main data file.

Something like this:

def fileTime(f):
   return os.stat(f).st_mtime

newest = max(first_files, key=fileTime)

Kent

From kent37 at tds.net  Tue Nov  6 04:41:34 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 05 Nov 2007 22:41:34 -0500
Subject: [Tutor] Sorting specific files by modification date
In-Reply-To: <1b31ae500711051937i6514294fhdc42f835f1d9bab3@mail.gmail.com>
References: <1b31ae500711051340t54a2b28axa66ab189ef32f694@mail.gmail.com>	
	<472FCCA3.5000506@tds.net>
	<1b31ae500711051937i6514294fhdc42f835f1d9bab3@mail.gmail.com>
Message-ID: <472FE26E.7090904@tds.net>

Fiyawerx wrote:
> Thanks Kent, thats just what I needed, but got stuck in a single mode of 
> thought trying to do it inline, didn't even think of adding a separate 
> function since the program seemed 'too simple'.

You can always use a lambda if you like that style:
newest = max(first_files, key=lambda f: os.stat(f).st_mtime)

I would probably write it that way myself, I used the def cuz I think it 
is a bit easier to understand.

Kent

> On 11/5/07, *Kent Johnson* <kent37 at tds.net <mailto:kent37 at tds.net>> wrote:
>     def fileTime(f):
>        return os.stat(f).st_mtime
> 
>     newest = max(first_files, key=fileTime)
> 
>     Kent
> 
> 


From timmichelsen at gmx-topmail.de  Tue Nov  6 10:15:18 2007
From: timmichelsen at gmx-topmail.de (Timmie)
Date: Tue, 6 Nov 2007 09:15:18 +0000 (UTC)
Subject: [Tutor] visualizing code structure / flow charting
Message-ID: <loom.20071106T091426-26@post.gmane.org>

Hello,
I am stepping forward into learning python and write my first programs now.
To facilitate my development I have a question:

Is there a tool which I can run on my code and then get a flow chart from it or
visualize its structure in another form?


There was a discussion about that soem time ago. 
OT: Flow chart -
http://news.gmane.org/find-root.php?message_id=%3c1103452504.92b04ebcjerimed%40myrealbox.com%3e

Is there any solution that can be used without leaning UML?

Kind regards,
Timmie



From kent37 at tds.net  Tue Nov  6 13:36:51 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 06 Nov 2007 07:36:51 -0500
Subject: [Tutor] visualizing code structure / flow charting
In-Reply-To: <loom.20071106T091426-26@post.gmane.org>
References: <loom.20071106T091426-26@post.gmane.org>
Message-ID: <47305FE3.7040507@tds.net>

Timmie wrote:
> Hello,
> I am stepping forward into learning python and write my first programs now.
> To facilitate my development I have a question:
> 
> Is there a tool which I can run on my code and then get a flow chart from it or
> visualize its structure in another form?

http://pycallgraph.slowchop.com/ will show the call graph
epydoc 3.0 can create a variety of graphics including call graph, 
package diagram and class diagrams:
http://epydoc.sourceforge.net/whatsnew.html

Stepping through code in a debugger is a good way to understand it. 
Winpdb is a good choice:
http://www.digitalpeers.com/pythondebugger/

> Is there any solution that can be used without leaning UML?

UML is pretty much the standard these days for representing class structure.

But if you are just learning Python and you are writing the programs 
that you are trying to understand, I don't know why you need these kinds 
of tools. You shouldn't be writing code that you need a flow chart 
generator to understand! Maybe you need to slow down a little and write 
programs that you do understand first? Or perhaps use a debugger to help.

You can ask specific questions here, if there is a bit of code you are 
struggling with.

Kent

From bhaaluu at gmail.com  Tue Nov  6 14:24:38 2007
From: bhaaluu at gmail.com (bhaaluu)
Date: Tue, 6 Nov 2007 08:24:38 -0500
Subject: [Tutor] visualizing code structure / flow charting
In-Reply-To: <loom.20071106T091426-26@post.gmane.org>
References: <loom.20071106T091426-26@post.gmane.org>
Message-ID: <ea979d70711060524u5031a9b8t23255d9d78d33092@mail.gmail.com>

Greetings,

On Nov 6, 2007 4:15 AM, Timmie <timmichelsen at gmx-topmail.de> wrote:
> Hello,
> I am stepping forward into learning python and write my first programs now.
> To facilitate my development I have a question:
>
> Is there a tool which I can run on my code and then get a flow chart from it or
> visualize its structure in another form?
>

I have found that a very simple and inexpensive way to look at Python
code while it's running is to insert a couple of lines in the code at the
points you want to look at:

print variableName
raw_input("Pause")

The 'print variableName' will print the value the variable is pointing to,
and 'raw_input("Pause") acts like a breakpoint, stopping program execution
so you can check out what's happening. Two other items of interest are:

dir (itemName)
type (itemName)

Both are extremely helpful when you're first learning Python. They're useful
for discovering the modules and attributes in classes, and checking the
type of objects.

You can use these in addition to any graphical output tools you find.

(Just Another Noob.)
-- 
b h a a l u u at g m a i l dot c o m
http://www.geocities.com/ek.bhaaluu/python/index.html

>
> There was a discussion about that soem time ago.
> OT: Flow chart -
> http://news.gmane.org/find-root.php?message_id=%3c1103452504.92b04ebcjerimed%40myrealbox.com%3e
>
> Is there any solution that can be used without leaning UML?
>
> Kind regards,
> Timmie
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From wesbrooks at gmail.com  Tue Nov  6 15:07:57 2007
From: wesbrooks at gmail.com (Wesley Brooks)
Date: Tue, 6 Nov 2007 14:07:57 +0000
Subject: [Tutor] visualizing code structure / flow charting
In-Reply-To: <ea979d70711060524u5031a9b8t23255d9d78d33092@mail.gmail.com>
References: <loom.20071106T091426-26@post.gmane.org>
	<ea979d70711060524u5031a9b8t23255d9d78d33092@mail.gmail.com>
Message-ID: <eec9f8ee0711060607n17bf1a88q65489891a20c57b2@mail.gmail.com>

Following on from the comments above two things I've found really
helpful are the __doc__ strings and the exec command.

for example:

>>> a = 'a random string'
>>> dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__ge__', '__getattribute__', '__getitem__',
'__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__',
'__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__',
'__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count',
'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index',
'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle',
'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace',
'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split',
'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate',
'upper', 'zfill']
>>> print a.strip.__doc__
S.strip([chars]) -> string or unicode

Return a copy of the string S with leading and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping
>>>

exec is also very useful. It allows you to run python code that is in
a string, for example (Be it a simple and rather useless example!) the
string; "print 1 + 2 ":

>>> exec("print 1 + 2")
3
>>>

Taking both one step further if you can extract all the __doc__
strings for all the objects listed from the dir of an object:

a = 'a random string'
for i in dir(a):
    command = "print str." + i + ".__doc__"
    exec(command)

This will print out all the __doc__ strings for functions you can call
on your string object a. This is particually helpful when you know
what you want to do to something (for instance capitalise the first
letter each word in a string) but don't know what function to call.

Another instance when exec comes in handy is when receiving input from
a user in a user interface. If used in this way you should be careful
to check the data (parse) to ensure the user isn't running code that
will cause your program problems. For example exec("import
sys\nsys.exit()") would close the python interpreter, which will lead
to your program crashing.

[Wes at dh050238 ~]$ python
Python 2.5 (r25:51908, Apr 10 2007, 10:27:40)
[GCC 4.1.2 20070403 (Red Hat 4.1.2-8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> exec("import sys\nsys.exit()")
[Wes at dh050238 ~]$

Cheers,

Wesley.

On 06/11/2007, bhaaluu <bhaaluu at gmail.com> wrote:
> Greetings,
>
> On Nov 6, 2007 4:15 AM, Timmie <timmichelsen at gmx-topmail.de> wrote:
> > Hello,
> > I am stepping forward into learning python and write my first programs now.
> > To facilitate my development I have a question:
> >
> > Is there a tool which I can run on my code and then get a flow chart from it or
> > visualize its structure in another form?
> >
>
> I have found that a very simple and inexpensive way to look at Python
> code while it's running is to insert a couple of lines in the code at the
> points you want to look at:
>
> print variableName
> raw_input("Pause")
>
> The 'print variableName' will print the value the variable is pointing to,
> and 'raw_input("Pause") acts like a breakpoint, stopping program execution
> so you can check out what's happening. Two other items of interest are:
>
> dir (itemName)
> type (itemName)
>
> Both are extremely helpful when you're first learning Python. They're useful
> for discovering the modules and attributes in classes, and checking the
> type of objects.
>
> You can use these in addition to any graphical output tools you find.
>
> (Just Another Noob.)
> --
> b h a a l u u at g m a i l dot c o m
> http://www.geocities.com/ek.bhaaluu/python/index.html
>
> >
> > There was a discussion about that soem time ago.
> > OT: Flow chart -
> > http://news.gmane.org/find-root.php?message_id=%3c1103452504.92b04ebcjerimed%40myrealbox.com%3e
> >
> > Is there any solution that can be used without leaning UML?
> >
> > Kind regards,
> > Timmie
> >
> >
> > _______________________________________________
> > 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 pydev at rscorp.ab.ca  Tue Nov  6 17:31:17 2007
From: pydev at rscorp.ab.ca (Scott SA)
Date: Tue,  6 Nov 2007 09:31:17 -0700
Subject: [Tutor] visualizing code structure / flow charting
In-Reply-To: <eec9f8ee0711060607n17bf1a88q65489891a20c57b2@mail.gmail.com>
Message-ID: <r02010500-1049-B3A0BA388C8511DC975F001124DEBE0E@[192.168.69.99]>

On 11/6/07, Wesley Brooks (wesbrooks at gmail.com) wrote:

>Taking both one step further if you can extract all the __doc__
>strings for all the objects listed from the dir of an object:
>
>a = 'a random string'
>for i in dir(a):
>    command = "print str." + i + ".__doc__"
>    exec(command)
>
>This will print out all the __doc__ strings for functions you can call
>on your string object a. This is particually helpful when you know
>what you want to do to something (for instance capitalise the first
>letter each word in a string) but don't know what function to call.

While not as educational from one perspective, I've found the epydoc package quite useful. It extracts all of the doc strings and formats them in a nice, easy to read, layout.

    <http://epydoc.sourceforge.net/>

Scott

From dkuhlman at rexx.com  Tue Nov  6 19:50:25 2007
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Tue, 6 Nov 2007 10:50:25 -0800
Subject: [Tutor] visualizing code structure / flow charting
In-Reply-To: <47305FE3.7040507@tds.net>
References: <loom.20071106T091426-26@post.gmane.org> <47305FE3.7040507@tds.net>
Message-ID: <20071106185025.GA82631@cutter.rexx.com>

On Tue, Nov 06, 2007 at 07:36:51AM -0500, Kent Johnson wrote:
> Timmie wrote:
> > Hello,
> > I am stepping forward into learning python and write my first programs now.
> > To facilitate my development I have a question:
> > 
> > Is there a tool which I can run on my code and then get a flow chart from it or
> > visualize its structure in another form?
> 
> http://pycallgraph.slowchop.com/ will show the call graph
> epydoc 3.0 can create a variety of graphics including call graph, 
> package diagram and class diagrams:
> http://epydoc.sourceforge.net/whatsnew.html
> 
> Stepping through code in a debugger is a good way to understand it. 
> Winpdb is a good choice:
> http://www.digitalpeers.com/pythondebugger/
> 

There are a variety of IDEs (integrated development environments)
that may help.  See:

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

Two that I've looked at:

- Geany -- http://geany.uvena.de/

- Eric -- http://www.die-offenbachs.de/eric/index.html -- Eric was
  easy to install on Debian GNU/Linux, but may be more of a
  challenge on MS Windows.

Dave


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

From goldwamh at slu.edu  Tue Nov  6 18:50:54 2007
From: goldwamh at slu.edu (Michael H. Goldwasser)
Date: Tue, 6 Nov 2007 11:50:54 -0600
Subject: [Tutor] New Introductory Book
Message-ID: <18224.43390.384547.2507@euclid.slu.edu>


   We are pleased to announce the release of a new Python book.
   
      Object-Oriented Programming in Python
      by Michael H. Goldwasser and David Letscher
      Prentice Hall, 2008   (available as of 10/29/2007)

   The book differs greatly from existing introductory Python books as
   it warmly embraces the object-oriented nature of Python from the
   onset.  It is also extremely comprehensive with solid fundamentals
   as well as several "advanced" topics that can be covered as
   desired.

   This book is based on materials developed after switching our
   curriculum to the use of Python for an object-oriented CS1 course.
   Since the primary market is an introductory course, we do not
   assume any previous programming experience for our readers.  This
   should make it a very good match for those who wish to self-study.
   The book includes 93 end-of-chapter "practice" problems with full
   solutions in an appendix, as well as an additional 300
   end-of-chapter exercises.  There is also an appendix that helps
   readers who have finished the book transition their skills to
   additional language, showing side-by-side examples of code in
   Python, Java and C++.

   More information can be found at http://www.prenhall.com/goldwasser

With regard,
Michael Goldwasser

       +-----------------------------------------------+
       | Michael Goldwasser                            |
       | Associate Professor                           |
       | Dept. Mathematics and Computer Science        |
       | Saint Louis University                        |
       | 220 North Grand Blvd.                         |
       | St. Louis, MO 63103-2007                      |
       |                                               |
       | Office: Ritter Hall 6                         |
       | Email:  goldwamh at slu.edu                      |
       | URL:    euler.slu.edu/~goldwasser             |
       | Phone:  (314) 977-7039                        |
       | Fax:    (314) 977-1452                        |
       +-----------------------------------------------+


From rikard.bosnjakovic at gmail.com  Tue Nov  6 20:21:00 2007
From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic)
Date: Tue, 6 Nov 2007 20:21:00 +0100
Subject: [Tutor] New Introductory Book
In-Reply-To: <18224.43390.384547.2507@euclid.slu.edu>
References: <18224.43390.384547.2507@euclid.slu.edu>
Message-ID: <d9e88eaf0711061121l62a72665h251c7824643ce7c0@mail.gmail.com>

On 06/11/2007, Michael H. Goldwasser <goldwamh at slu.edu> wrote:

>    We are pleased to announce the release of a new Python book.

[...yadayada...]

I thought this list was supposed to be clean from commercial advertisements.


-- 
- Rikard.

From timmichelsen at gmx-topmail.de  Tue Nov  6 20:23:03 2007
From: timmichelsen at gmx-topmail.de (Timmie)
Date: Tue, 6 Nov 2007 19:23:03 +0000 (UTC)
Subject: [Tutor] visualizing code structure / flow charting
References: <loom.20071106T091426-26@post.gmane.org> <47305FE3.7040507@tds.net>
Message-ID: <loom.20071106T190955-716@post.gmane.org>

> > Is there a tool which I can run on my code and then get a flow chart from 
it or
> > visualize its structure in another form?
> 
> http://pycallgraph.slowchop.com/ will show the call graph
I think this is exactly what I was after. I still need to install Graphviz but 
from the homepage it seems the right one.

> epydoc 3.0 can create a variety of graphics including call graph, 
> package diagram and class diagrams:
> http://epydoc.sourceforge.net/whatsnew.html
This one is a alternative to pydoc, right?
But from what I read on the web page it only focusses on the modules and 
libraries whereas pycallgraph looks at the actual script you write.

> Stepping through code in a debugger is a good way to understand it. 
> Winpdb is a good choice:
> http://www.digitalpeers.com/pythondebugger/
I good hint. Thanks. Although I wasn't really after a debugger It looks nice.

 
> > Is there any solution that can be used without leaning UML?
> UML is pretty much the standard these days for representing class structure.
Yes, I know. But like epydoc does care if it in it's lastest version I do not 
need to get into the basics and can stick to deepen my python skills.
 
> But if you are just learning Python and you are writing the programs 
> that you are trying to understand,
I understand /my/ own programs.

> I don't know why you need these kinds 
> of tools. You shouldn't be writing code that you need a flow chart 
> generator to understand! 
I would like to employ a lot of modules and ready made libraries that are 
around in the wild and also extend and write my own modules because I am 
heading towards number crunching with scipy/numpy et. al.

Even if the basic script is well written and documented and kept short I would 
like to use the graphs to get a quick overview on what is done at what point, 
which modules are imported. This could also help to validate and improve the 
approach my script is based on. Furthermore, flow charts can be included into 
publications and discussed in presentations.

I hope my needs are now a litte understandable.

For the real debugging I will follow the hints the other posters pointed out 
anserwing my question. Thanks for your help on that.

> You can ask specific questions here, if there is a bit of code you are 
> struggling with.
I know and am thankful for this patient atmosphere here!

Kind regards,
Timmie


From kent37 at tds.net  Tue Nov  6 20:38:18 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 06 Nov 2007 14:38:18 -0500
Subject: [Tutor] New Introductory Book
In-Reply-To: <d9e88eaf0711061121l62a72665h251c7824643ce7c0@mail.gmail.com>
References: <18224.43390.384547.2507@euclid.slu.edu>
	<d9e88eaf0711061121l62a72665h251c7824643ce7c0@mail.gmail.com>
Message-ID: <4730C2AA.2040506@tds.net>

Rikard Bosnjakovic wrote:
> On 06/11/2007, Michael H. Goldwasser <goldwamh at slu.edu> wrote:
> 
>>    We are pleased to announce the release of a new Python book.
> 
> [...yadayada...]
> 
> I thought this list was supposed to be clean from commercial advertisements.

I don't think there is a specific rule about that. I'm happy to have 
on-topic announcements which I think this is. IIRC I announced the new 
edition of Learning Python and Wesley Chun announced the new edition of 
his book, Core Python.

Kent

From titleistfour at gmail.com  Tue Nov  6 20:42:22 2007
From: titleistfour at gmail.com (jay)
Date: Tue, 6 Nov 2007 13:42:22 -0600
Subject: [Tutor] New Introductory Book
In-Reply-To: <4730C2AA.2040506@tds.net>
References: <18224.43390.384547.2507@euclid.slu.edu>
	<d9e88eaf0711061121l62a72665h251c7824643ce7c0@mail.gmail.com>
	<4730C2AA.2040506@tds.net>
Message-ID: <7c25bb490711061142i2e9649f3h29393c67b33b6712@mail.gmail.com>

I agree as well.  Its not like there is a flood of these books coming
out, or emails slamming the list announcing them.

Jay

On Nov 6, 2007 1:38 PM, Kent Johnson <kent37 at tds.net> wrote:
> Rikard Bosnjakovic wrote:
> > On 06/11/2007, Michael H. Goldwasser <goldwamh at slu.edu> wrote:
> >
> >>    We are pleased to announce the release of a new Python book.
> >
> > [...yadayada...]
> >
> > I thought this list was supposed to be clean from commercial advertisements.
>
> I don't think there is a specific rule about that. I'm happy to have
> on-topic announcements which I think this is. IIRC I announced the new
> edition of Learning Python and Wesley Chun announced the new edition of
> his book, Core Python.
>
> Kent
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From jeff at san-dc.com  Tue Nov  6 21:51:09 2007
From: jeff at san-dc.com (Jeff Johnson)
Date: Tue, 06 Nov 2007 13:51:09 -0700
Subject: [Tutor] New Introductory Book
In-Reply-To: <d9e88eaf0711061121l62a72665h251c7824643ce7c0@mail.gmail.com>
References: <18224.43390.384547.2507@euclid.slu.edu>
	<d9e88eaf0711061121l62a72665h251c7824643ce7c0@mail.gmail.com>
Message-ID: <4730D3BD.2070700@san-dc.com>

As far as I am concerned this may be a commercial advertisement, but is 
it a book on Python to help people learn Python.  I get all of my 
information from books and then turn to the lists (Tutor being one) to 
get my questions asked or what I have learned clarified.  I have a 
difficult time reading on line and prefer books.

So I for one appreciate the post.

Thank you,

Jeff

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

Rikard Bosnjakovic wrote:
> On 06/11/2007, Michael H. Goldwasser <goldwamh at slu.edu> wrote:
> 
>>    We are pleased to announce the release of a new Python book.
> 
> [...yadayada...]
> 
> I thought this list was supposed to be clean from commercial advertisements.
> 
> 

From cbc at unc.edu  Tue Nov  6 23:36:59 2007
From: cbc at unc.edu (Chris Calloway)
Date: Tue, 06 Nov 2007 17:36:59 -0500
Subject: [Tutor] New Introductory Book
In-Reply-To: <18224.43390.384547.2507@euclid.slu.edu>
References: <18224.43390.384547.2507@euclid.slu.edu>
Message-ID: <4730EC8B.8060501@unc.edu>

Michael H. Goldwasser wrote:
>    We are pleased to announce the release of a new Python book.

Why is this book $102?

-- 
Sincerely,

Chris Calloway
http://www.seacoos.org
office: 332 Chapman Hall   phone: (919) 962-4323
mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599




From wescpy at gmail.com  Wed Nov  7 00:05:38 2007
From: wescpy at gmail.com (wesley chun)
Date: Tue, 6 Nov 2007 15:05:38 -0800
Subject: [Tutor] New Introductory Book
In-Reply-To: <4730C2AA.2040506@tds.net>
References: <18224.43390.384547.2507@euclid.slu.edu>
	<d9e88eaf0711061121l62a72665h251c7824643ce7c0@mail.gmail.com>
	<4730C2AA.2040506@tds.net>
Message-ID: <78b3a9580711061505s19e46ea9meebf2dd76cc1ec8@mail.gmail.com>

On 11/6/07, Kent Johnson <kent37 at tds.net> wrote:
> Rikard Bosnjakovic wrote:
> > On 06/11/2007, Michael H. Goldwasser <goldwamh at slu.edu> wrote:
> >>    We are pleased to announce the release of a new Python book.
> > I thought this list was supposed to be clean from commercial advertisements.
>
> I don't think there is a specific rule about that. I'm happy to have
> on-topic announcements which I think this is. IIRC I announced the new
> edition of Learning Python and Wesley Chun announced the new edition of
> his book, Core Python.


i also make announcements for my upcoming public Python courses, which
happen b/w 2-4 times a year.  it's very infrequent, and although could
be seen as commercial advertisments, is definitely for the benefit of
the community and helps put food on my table.  some have complained
about it, but many more others have said things to the effect of,
"*thanks* for posting your course announcements... i've been wanting
to take your class," or "i wouldn't have been able to find out about
it any other way," etc.  bottom line:

if infrequent:
    GOOD
else:
    SPAM

-- 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 aezell at gmail.com  Wed Nov  7 00:22:23 2007
From: aezell at gmail.com (Alex Ezell)
Date: Tue, 6 Nov 2007 17:22:23 -0600
Subject: [Tutor] New Introductory Book
In-Reply-To: <4730EC8B.8060501@unc.edu>
References: <18224.43390.384547.2507@euclid.slu.edu> <4730EC8B.8060501@unc.edu>
Message-ID: <71dd7f400711061522o23adbd93s68d1245324d29f41@mail.gmail.com>

On 11/6/07, Chris Calloway <cbc at unc.edu> wrote:
> Michael H. Goldwasser wrote:
> >    We are pleased to announce the release of a new Python book.
>
> Why is this book $102?

Supply and demand aside, I suspect the market for this, based on both
the publisher and the author's employment, is mostly
educational/collegiate. Therefore, this book is likely to be assigned
as a textbook and can command a premium price from buyers who have
little to no choice but to buy it. Additionally, it may not be
marketed on the wider bookstore shelves, so must make the most of the
market which it does reach.

That's all conjecture. What I do know is fact is that I can't afford it.

/alex

From goldwamh at slu.edu  Wed Nov  7 00:15:50 2007
From: goldwamh at slu.edu (Michael H. Goldwasser)
Date: Tue, 6 Nov 2007 17:15:50 -0600
Subject: [Tutor] New Introductory Book
In-Reply-To: <7c25bb490711061142i2e9649f3h29393c67b33b6712@mail.gmail.com>
References: <18224.43390.384547.2507@euclid.slu.edu>
	<d9e88eaf0711061121l62a72665h251c7824643ce7c0@mail.gmail.com>
	<4730C2AA.2040506@tds.net>
	<7c25bb490711061142i2e9649f3h29393c67b33b6712@mail.gmail.com>
Message-ID: <18224.62886.807753.738322@euclid.slu.edu>


Thanks to the many voices supporting our decision to post to Tutor.
We only posted to the most directly relevant mailing lists (announce,
tutor, edusig).  As an introductory book, it seemed quite appropriate
for tutor.

In fact, the topic of our (developing) book was raised in a thread on
Tutor this past August 9/10th. Ironically, the topic at that time is
the same as that raised by Chris Calloway's question today, about the
$102 list price. 

The discrepency is because this is being published primarily as an
academic book through Prentice Hall's Education line (as opposed to
the Prentice Proffessional label that publishes books such as Wesley
Chun's Core Python Programming).  I'm not on the business side, so I
don't know that I understand all the factors; could be a combination
of the captive audience together with a lot of additional money spent
on sending review copies to educators and sending representatives to
campuses.  In any event, we believe that the book can be quite useful
outside the traditional classroom for new programmers or those new to
object-oriented programming.

Best regards,
Michael


On Tuesday November 6, 2007, jay wrote: 

>    I agree as well.  Its not like there is a flood of these books coming
>    out, or emails slamming the list announcing them.
>    
>    Jay
>    
>    On Nov 6, 2007 1:38 PM, Kent Johnson <kent37 at tds.net> wrote:
>    > Rikard Bosnjakovic wrote:
>    > > On 06/11/2007, Michael H. Goldwasser <goldwamh at slu.edu> wrote:
>    > >
>    > >>    We are pleased to announce the release of a new Python book.
>    > >
>    > > [...yadayada...]
>    > >
>    > > I thought this list was supposed to be clean from commercial advertisements.
>    >
>    > I don't think there is a specific rule about that. I'm happy to have
>    > on-topic announcements which I think this is. IIRC I announced the new
>    > edition of Learning Python and Wesley Chun announced the new edition of
>    > his book, Core Python.
>    >
>    > Kent



On Tuesday November 6, 2007, Chris Calloway wrote: 

>    Michael H. Goldwasser wrote:
>    >    We are pleased to announce the release of a new Python book.
>    
>    Why is this book $102?
>    
>    -- 
>    Sincerely,
>    
>    Chris Calloway
>    http://www.seacoos.org
>    office: 332 Chapman Hall   phone: (919) 962-4323
>    mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599



From brunson at brunson.com  Wed Nov  7 01:34:11 2007
From: brunson at brunson.com (Eric Brunson)
Date: Tue, 06 Nov 2007 17:34:11 -0700
Subject: [Tutor] New Introductory Book
In-Reply-To: <18224.62886.807753.738322@euclid.slu.edu>
References: <18224.43390.384547.2507@euclid.slu.edu>	<d9e88eaf0711061121l62a72665h251c7824643ce7c0@mail.gmail.com>	<4730C2AA.2040506@tds.net>	<7c25bb490711061142i2e9649f3h29393c67b33b6712@mail.gmail.com>
	<18224.62886.807753.738322@euclid.slu.edu>
Message-ID: <47310803.4060503@brunson.com>

Michael H. Goldwasser wrote:
> Thanks to the many voices supporting our decision to post to Tutor.
> We only posted to the most directly relevant mailing lists (announce,
> tutor, edusig).  As an introductory book, it seemed quite appropriate
> for tutor.
>
> In fact, the topic of our (developing) book was raised in a thread on
> Tutor this past August 9/10th. Ironically, the topic at that time is
> the same as that raised by Chris Calloway's question today, about the
> $102 list price. 
>
> The discrepency is because this is being published primarily as an
> academic book through Prentice Hall's Education line (as opposed to
> the Prentice Proffessional label that publishes books such as Wesley
> Chun's Core Python Programming).  

I.e. the students have to buy it no matter what because the professor 
says so, so we may as well rake them over the coals.  Their rich parents 
are paying for it anyway, so who cares. 

Not that I'm bitter or anything.  ;-)

Sincerely insincerely,
e.

> I'm not on the business side, so I
> don't know that I understand all the factors; could be a combination
> of the captive audience together with a lot of additional money spent
> on sending review copies to educators and sending representatives to
> campuses.  In any event, we believe that the book can be quite useful
> outside the traditional classroom for new programmers or those new to
> object-oriented programming.
>
> Best regards,
> Michael
>
>
> On Tuesday November 6, 2007, jay wrote: 
>
>   
>>    I agree as well.  Its not like there is a flood of these books coming
>>    out, or emails slamming the list announcing them.
>>    
>>    Jay
>>    
>>    On Nov 6, 2007 1:38 PM, Kent Johnson <kent37 at tds.net> wrote:
>>    > Rikard Bosnjakovic wrote:
>>    > > On 06/11/2007, Michael H. Goldwasser <goldwamh at slu.edu> wrote:
>>    > >
>>    > >>    We are pleased to announce the release of a new Python book.
>>    > >
>>    > > [...yadayada...]
>>    > >
>>    > > I thought this list was supposed to be clean from commercial advertisements.
>>    >
>>    > I don't think there is a specific rule about that. I'm happy to have
>>    > on-topic announcements which I think this is. IIRC I announced the new
>>    > edition of Learning Python and Wesley Chun announced the new edition of
>>    > his book, Core Python.
>>    >
>>    > Kent
>>     
>
>
>
> On Tuesday November 6, 2007, Chris Calloway wrote: 
>
>   
>>    Michael H. Goldwasser wrote:
>>    >    We are pleased to announce the release of a new Python book.
>>    
>>    Why is this book $102?
>>    
>>    -- 
>>    Sincerely,
>>    
>>    Chris Calloway
>>    http://www.seacoos.org
>>    office: 332 Chapman Hall   phone: (919) 962-4323
>>    mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599
>>     
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From ericlake at ubuntu.com  Wed Nov  7 02:05:03 2007
From: ericlake at ubuntu.com (Eric Lake)
Date: Tue, 06 Nov 2007 20:05:03 -0500
Subject: [Tutor] New Introductory Book
In-Reply-To: <71dd7f400711061522o23adbd93s68d1245324d29f41@mail.gmail.com>
References: <18224.43390.384547.2507@euclid.slu.edu> <4730EC8B.8060501@unc.edu>
	<71dd7f400711061522o23adbd93s68d1245324d29f41@mail.gmail.com>
Message-ID: <47310F3F.8070707@ubuntu.com>

For that price the book better write my code for me.

Alex Ezell wrote:
> On 11/6/07, Chris Calloway <cbc at unc.edu> wrote:
>> Michael H. Goldwasser wrote:
>>>    We are pleased to announce the release of a new Python book.
>> Why is this book $102?
> 
> Supply and demand aside, I suspect the market for this, based on both
> the publisher and the author's employment, is mostly
> educational/collegiate. Therefore, this book is likely to be assigned
> as a textbook and can command a premium price from buyers who have
> little to no choice but to buy it. Additionally, it may not be
> marketed on the wider bookstore shelves, so must make the most of the
> market which it does reach.
> 
> That's all conjecture. What I do know is fact is that I can't afford it.
> 
> /alex
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 544 bytes
Desc: OpenPGP digital signature
Url : http://mail.python.org/pipermail/tutor/attachments/20071106/4b52b8d2/attachment.pgp 

From jeff at san-dc.com  Wed Nov  7 02:41:44 2007
From: jeff at san-dc.com (Jeff Johnson)
Date: Tue, 06 Nov 2007 18:41:44 -0700
Subject: [Tutor] New Introductory Book
In-Reply-To: <47310F3F.8070707@ubuntu.com>
References: <18224.43390.384547.2507@euclid.slu.edu>
	<4730EC8B.8060501@unc.edu>	<71dd7f400711061522o23adbd93s68d1245324d29f41@mail.gmail.com>
	<47310F3F.8070707@ubuntu.com>
Message-ID: <473117D8.9000602@san-dc.com>

I have been developing software for over 25 years in various languages. 
  I am new to Python because for me it is the very best fit for my 
business going forward.  People ask me how do I keep up with the 
industry - probably the fastest moving industry there is.  Books, email 
lists and conferences is how I keep up.  I make a good living writing 
software and books and conferences are my education.

I can certainly sympathize with you if you are new to the programming 
world or can't afford books or conferences.  I was in that situation for 
many years.  There are tons of affordable or free resources for Python.

I went to Amazon and ordered the book right away.

Jeff

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

Eric Lake wrote:
> For that price the book better write my code for me.
> 
> Alex Ezell wrote:
>> On 11/6/07, Chris Calloway <cbc at unc.edu> wrote:
>>> Michael H. Goldwasser wrote:
>>>>    We are pleased to announce the release of a new Python book.
>>> Why is this book $102?
>> Supply and demand aside, I suspect the market for this, based on both
>> the publisher and the author's employment, is mostly
>> educational/collegiate. Therefore, this book is likely to be assigned
>> as a textbook and can command a premium price from buyers who have
>> little to no choice but to buy it. Additionally, it may not be
>> marketed on the wider bookstore shelves, so must make the most of the
>> market which it does reach.
>>
>> That's all conjecture. What I do know is fact is that I can't afford it.
>>
>> /alex
>> _______________________________________________
>> 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 wescpy at gmail.com  Wed Nov  7 03:56:15 2007
From: wescpy at gmail.com (wesley chun)
Date: Tue, 6 Nov 2007 18:56:15 -0800
Subject: [Tutor] New Introductory Book
In-Reply-To: <18224.62886.807753.738322@euclid.slu.edu>
References: <18224.43390.384547.2507@euclid.slu.edu>
	<d9e88eaf0711061121l62a72665h251c7824643ce7c0@mail.gmail.com>
	<4730C2AA.2040506@tds.net>
	<7c25bb490711061142i2e9649f3h29393c67b33b6712@mail.gmail.com>
	<18224.62886.807753.738322@euclid.slu.edu>
Message-ID: <78b3a9580711061856g5ca26d3bte2d78960bc508259@mail.gmail.com>

> In fact, the topic of our (developing) book was raised in a thread on
> Tutor this past August 9/10th. Ironically, the topic at that time is
> the same as that raised by Chris Calloway's question today, about the
> $102 list price.


fyi, here is a link to the 1st post of the august thread from kent:
http://mail.python.org/pipermail/tutor/2007-August/056230.html

the sale price was excellent back then (45%) but now gone since the
school year's started. :-) at least you can get a 12% discount from
bookpool (but they're [understandably] OoS at the moment). anyhow, i
look fwd to learning something from michael's and david's book.

additionally, here is a short article on pricing in the book industry
that may some more light:
http://publishing.articlesarchive.net/retail-margin-trade-discount-what-it-means-for-the-author.html

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 kent37 at tds.net  Wed Nov  7 04:26:20 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 06 Nov 2007 22:26:20 -0500
Subject: [Tutor] New Introductory Book
In-Reply-To: <473117D8.9000602@san-dc.com>
References: <18224.43390.384547.2507@euclid.slu.edu>	<4730EC8B.8060501@unc.edu>	<71dd7f400711061522o23adbd93s68d1245324d29f41@mail.gmail.com>	<47310F3F.8070707@ubuntu.com>
	<473117D8.9000602@san-dc.com>
Message-ID: <4731305C.4030103@tds.net>

Jeff Johnson wrote:

> I went to Amazon and ordered the book right away.

I hope you will tell us about it when you receive your copy!

Kent

From bryan.fodness at gmail.com  Tue Nov  6 20:54:45 2007
From: bryan.fodness at gmail.com (Bryan Fodness)
Date: Tue, 6 Nov 2007 14:54:45 -0500
Subject: [Tutor] manipulating data
Message-ID: <fbf64d2b0711061154v4f6547bcx133c342f2d5aac27@mail.gmail.com>

I would like to have my data in a format so that I can create a contour plot.

My data is in a file with a format, where there may be multiple fields

field = 1

1a	0
2a	0
3a	5
4a	5
5a	5
6a	5
7a	5
8a	5
9a	0
10a	0
1b	0
2b	0
3b	5
4b	5
5b	5
6b	5
7b	5
8b	5
9b	0
10b	0

field = 2

1a	0
2a	0
3a	0
4a	4
5a	4
6a	4
7a	4
8a	0
9a	0
10a	0
1b	0
2b	0
3b	0
4b	4
5b	4
6b	4
7b	4
8b	0
9b	0
10b	0

field = 3

1a	0
2a	0
3a	0
4a	0
5a	3
6a	3
7a	0
8a	0
9a	0
10a	0
1b	0
2b	0
3b	0
4b	0
5b	3
6b	3
7b	0
8b	0
9b	0
10b	0

where,

                           a           b
  a           b	                          a            b
10	0000000000|0000000000	0000000000|0000000000	0000000000|0000000000
9	0000000000|0000000000	0000000000|0000000000	0000000000|0000000000
8	0000011111|1111100000	0000000000|0000000000	0000000000|0000000000
7	0000011111|1111100000	0000001111|1111000000	0000000000|0000000000
6	0000011111|1111100000	0000001111|1111000000	0000000111|1110000000
5	0000011111|1111100000	0000001111|1111000000	0000000111|1110000000
4	0000011111|1111100000	0000001111|1111000000	0000000000|0000000000
3	0000011111|1111100000	0000000000|0000000000	0000000000|0000000000
2	0000000000|0000000000	0000000000|0000000000	0000000000|0000000000
1	0000000000|0000000000	0000000000|0000000000	0000000000|0000000000

I could possibly have many of these that I will add together and
normalize to one.
Also, there are 60 a and b blocks, the middle 40 are 0.5 times the
width of the outer 20.

I thought about filling an array, but there is not a one to one symmetry.

I cannot seem to get my head around this. Can anybody help me get started?

From bhaaluu at gmail.com  Wed Nov  7 13:40:37 2007
From: bhaaluu at gmail.com (bhaaluu)
Date: Wed, 7 Nov 2007 07:40:37 -0500
Subject: [Tutor] New Introductory Book
In-Reply-To: <18224.62886.807753.738322@euclid.slu.edu>
References: <18224.43390.384547.2507@euclid.slu.edu>
	<d9e88eaf0711061121l62a72665h251c7824643ce7c0@mail.gmail.com>
	<4730C2AA.2040506@tds.net>
	<7c25bb490711061142i2e9649f3h29393c67b33b6712@mail.gmail.com>
	<18224.62886.807753.738322@euclid.slu.edu>
Message-ID: <ea979d70711070440g703f8c44rd4a795f8305dc137@mail.gmail.com>

Greetings,
Many books have the source code available for download somewhere,
or even a sample chapter? Are the examples in the book complete
programs, or are they snippets illustrating a concept? If the programs
are complete, what type of programs are they (business, science, other)?
Does the source code work with GNU/Linux, or is it for MS-Windows only?
-- 
b h a a l u u at g m a i l dot c o m
http://www.geocities.com/ek.bhaaluu/index.html

On Nov 6, 2007 6:15 PM, Michael H. Goldwasser <goldwamh at slu.edu> wrote:
>
> Thanks to the many voices supporting our decision to post to Tutor.
> We only posted to the most directly relevant mailing lists (announce,
> tutor, edusig).  As an introductory book, it seemed quite appropriate
> for tutor.
>
> In fact, the topic of our (developing) book was raised in a thread on
> Tutor this past August 9/10th. Ironically, the topic at that time is
> the same as that raised by Chris Calloway's question today, about the
> $102 list price.
>
> The discrepency is because this is being published primarily as an
> academic book through Prentice Hall's Education line (as opposed to
> the Prentice Proffessional label that publishes books such as Wesley
> Chun's Core Python Programming).  I'm not on the business side, so I
> don't know that I understand all the factors; could be a combination
> of the captive audience together with a lot of additional money spent
> on sending review copies to educators and sending representatives to
> campuses.  In any event, we believe that the book can be quite useful
> outside the traditional classroom for new programmers or those new to
> object-oriented programming.
>
> Best regards,
> Michael
>

From tavspamnofwd at googlemail.com  Wed Nov  7 14:52:09 2007
From: tavspamnofwd at googlemail.com (Tom)
Date: Wed, 7 Nov 2007 13:52:09 +0000
Subject: [Tutor] making a typing speed tester
Message-ID: <ca43e5230711070552n5b5a4068ie2fad149344b17d4@mail.gmail.com>

Hi, I asked this question last year but got no response.

I'm trying to write a program to test someones typing speed and show
them their mistakes. However I'm getting weird results when looking
for the differences in longer (than 100 chars) strings:

import difflib

# a tape measure string (just makes it easier to locate a given index)
a = '1-3-5-7-9-12-15-18-21-24-27-30-33-36-39-42-45-48-51-54-57-60-63-66-69-72-75-78-81-84-87-90-93-96-99-103-107-111-115-119-123-127-131-135-139-143-147-151-155-159-163-167-171-175-179-183-187-191-195--200'

# now with a few mistakes
b = '1-3-5-7-l-12-15-18-21-24-27-30-33-36-39o42-45-48-51-54-57-60-63-66-69-72-75-78-81-84-8k-90-93-96-9l-103-107-111-115-119-12b-1v7-131-135-139-143-147-151-m55-159-163-167-a71-175j179-183-187-191-195--200'

s = difflib.SequenceMatcher(None, a ,b)
ms = s.get_matching_blocks()

print ms

>>>[(0, 0, 8), (200, 200, 0)]

Have I made a mistake or is this function designed to give up when the
input strings get too long? If so what could I use instead to compute
the mistakes in a typed text?

Thanks in advance,
Thomas

From kent37 at tds.net  Wed Nov  7 14:52:39 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 07 Nov 2007 08:52:39 -0500
Subject: [Tutor] manipulating data
In-Reply-To: <fbf64d2b0711061154v4f6547bcx133c342f2d5aac27@mail.gmail.com>
References: <fbf64d2b0711061154v4f6547bcx133c342f2d5aac27@mail.gmail.com>
Message-ID: <4731C327.6000704@tds.net>

Bryan Fodness wrote:
> I would like to have my data in a format so that I can create a contour plot.
> 
> My data is in a file with a format, where there may be multiple fields
> 
> field = 1
> 
> 1a	0

If your data is really this regular, it is pretty easy to parse. A 
useful technique is to access a file's next method directly. Something 
like this (not tested!):

f = open('data.txt')
fields = {} # build a dict of fields
try:
   while True:
     # Get the field line
     line = f.next()
     field = int(line.split()[-1]) # last part of the line as an int

     f.next() # skip blank line

     data = {} # for each field, map (row, col) to value
     for i in range(20): # read 20 data lines
       line = f.next()
       ix, value = f.split()
       row = int(ix[:-1])
       col = ix[-1]
       data[row, col] = int(value)

     fields[field] = data

     f.next()
except StopIteration:
   pass

This builds a dict whose keys are field numbers and values are 
themselves dicts mapping (row, col) pairs to a value.

> where,
> 
>                            a           b
>   a           b	                          a            b
> 10	0000000000|0000000000	0000000000|0000000000	0000000000|0000000000
> 9	0000000000|0000000000	0000000000|0000000000	0000000000|0000000000
> 8	0000011111|1111100000	0000000000|0000000000	0000000000|0000000000
> 7	0000011111|1111100000	0000001111|1111000000	0000000000|0000000000
> 6	0000011111|1111100000	0000001111|1111000000	0000000111|1110000000
> 5	0000011111|1111100000	0000001111|1111000000	0000000111|1110000000
> 4	0000011111|1111100000	0000001111|1111000000	0000000000|0000000000
> 3	0000011111|1111100000	0000000000|0000000000	0000000000|0000000000
> 2	0000000000|0000000000	0000000000|0000000000	0000000000|0000000000
> 1	0000000000|0000000000	0000000000|0000000000	0000000000|0000000000

I guess this is the intended output? Do you want to actually create a 
printed table like this, or some kind of data structure that represents 
the table, or what?

Kent

From bryan.fodness at gmail.com  Wed Nov  7 16:04:07 2007
From: bryan.fodness at gmail.com (Bryan Fodness)
Date: Wed, 7 Nov 2007 10:04:07 -0500
Subject: [Tutor] manipulating data
In-Reply-To: <4731C327.6000704@tds.net>
References: <fbf64d2b0711061154v4f6547bcx133c342f2d5aac27@mail.gmail.com>
	<4731C327.6000704@tds.net>
Message-ID: <fbf64d2b0711070704q23831263pd2cebd9194eb3dc7@mail.gmail.com>

I also have some information at the beginning of the file and between
each field.  Is there a way to get the info at the beginning and tell
it once it sees Leaf 1A to read the values for the next 120 and then
repeat until there are no more Fields.

File Rev = G
Treatment = Dynamic Dose
Last Name = Fodness
First Name = Bryan
Patient ID = 0001
Number of Fields = 4
Number of Leaves = 120
Tolerance = 0.50

Field = 10
Index = 0.0000
Carriage Group = 1
Operator =
Collimator = 0.0
Leaf  1A =   0.00
Leaf  2A =   0.00
Leaf  3A =   0.00
Leaf  4A =   0.00
...
Leaf 57B =   0.00
Leaf 58B =   0.00
Leaf 59B =   0.00
Leaf 60B =   0.00
Note = 0
Shape = 4
  500   500
  500  -500
 -500  -500
 -500   500
Magnification = 1.00

Field = 8
Index = 0.4000
Carriage Group = 1
Operator =
Collimator = 0.0
Leaf  1A =   0.00
Leaf  2A =   0.00
Leaf  3A =   0.00
Leaf  4A =   0.00
...
Leaf 57B =   0.00
Leaf 58B =   0.00
Leaf 59B =   0.00
Leaf 60B =   0.00
Note = 0
Shape = 4
  400   400
  400  -400
 -400  -400
 -400   400
Magnification = 1.00

I would like to have a data structure that I can use in one of the
graphing utilities (matpolotlib?).  I probably want to populate an
array with values, but I have not figured out how I want to do that
yet.

On Nov 7, 2007 8:52 AM, Kent Johnson <kent37 at tds.net> wrote:
> Bryan Fodness wrote:
> > I would like to have my data in a format so that I can create a contour plot.
> >
> > My data is in a file with a format, where there may be multiple fields
> >
> > field = 1
> >
> > 1a    0
>
> If your data is really this regular, it is pretty easy to parse. A
> useful technique is to access a file's next method directly. Something
> like this (not tested!):
>
> f = open('data.txt')
> fields = {} # build a dict of fields
> try:
>   while True:
>     # Get the field line
>     line = f.next()
>     field = int(line.split()[-1]) # last part of the line as an int
>
>     f.next() # skip blank line
>
>     data = {} # for each field, map (row, col) to value
>     for i in range(20): # read 20 data lines
>       line = f.next()
>       ix, value = f.split()
>       row = int(ix[:-1])
>       col = ix[-1]
>       data[row, col] = int(value)
>
>     fields[field] = data
>
>     f.next()
> except StopIteration:
>   pass
>
> This builds a dict whose keys are field numbers and values are
> themselves dicts mapping (row, col) pairs to a value.
>
> > where,
> >
> >                            a           b
> >   a           b                                 a            b
> > 10    0000000000|0000000000   0000000000|0000000000   0000000000|0000000000
> > 9     0000000000|0000000000   0000000000|0000000000   0000000000|0000000000
> > 8     0000011111|1111100000   0000000000|0000000000   0000000000|0000000000
> > 7     0000011111|1111100000   0000001111|1111000000   0000000000|0000000000
> > 6     0000011111|1111100000   0000001111|1111000000   0000000111|1110000000
> > 5     0000011111|1111100000   0000001111|1111000000   0000000111|1110000000
> > 4     0000011111|1111100000   0000001111|1111000000   0000000000|0000000000
> > 3     0000011111|1111100000   0000000000|0000000000   0000000000|0000000000
> > 2     0000000000|0000000000   0000000000|0000000000   0000000000|0000000000
> > 1     0000000000|0000000000   0000000000|0000000000   0000000000|0000000000
>
> I guess this is the intended output? Do you want to actually create a
> printed table like this, or some kind of data structure that represents
> the table, or what?
>
> Kent
>

From kent37 at tds.net  Wed Nov  7 16:19:12 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 07 Nov 2007 10:19:12 -0500
Subject: [Tutor] manipulating data
In-Reply-To: <fbf64d2b0711070704q23831263pd2cebd9194eb3dc7@mail.gmail.com>
References: <fbf64d2b0711061154v4f6547bcx133c342f2d5aac27@mail.gmail.com>	
	<4731C327.6000704@tds.net>
	<fbf64d2b0711070704q23831263pd2cebd9194eb3dc7@mail.gmail.com>
Message-ID: <4731D770.5010503@tds.net>

Bryan Fodness wrote:
> I also have some information at the beginning of the file and between
> each field.  Is there a way to get the info at the beginning and tell
> it once it sees Leaf 1A to read the values for the next 120 and then
> repeat until there are no more Fields.

This should be a pretty simple modification to the technique I showed 
you using f.next(). Just add another loop to process the header fields. 
If you have variable-length sections then you may have to 'prefetch' the 
next line, something like this:

try:
   line = f.next()
   while True:
     if 'Leaf 1A' in line:
       break
     # process header line

   # 'line' already contains the next line
   while True:
     # process body line
     line = f.next()

Kent

From eddie_armstrong at ntlworld.com  Wed Nov  7 16:40:50 2007
From: eddie_armstrong at ntlworld.com (Eddie Armstrong)
Date: Wed, 07 Nov 2007 15:40:50 +0000
Subject: [Tutor] New Introductory Book
In-Reply-To: <d9e88eaf0711061121l62a72665h251c7824643ce7c0@mail.gmail.com>
References: <18224.43390.384547.2507@euclid.slu.edu>
	<d9e88eaf0711061121l62a72665h251c7824643ce7c0@mail.gmail.com>
Message-ID: <4731DC82.3060809@ntlworld.com>

Whatever the rationale for the price you could buy 2nd Ed 'Core', Chun 
*and *3rd edition(when it arrives) 'Learning Python', Lutz (the two 
standard, known and respected beginners texts) for the price of this.
Mmm, I wonder what I would buy or rather have as a student.

Eddie

PS (My apologies for inadvertently sending this to the original poster 
instead of the list)

From evert.rol at gmail.com  Wed Nov  7 17:34:20 2007
From: evert.rol at gmail.com (Evert Rol)
Date: Wed, 7 Nov 2007 16:34:20 +0000
Subject: [Tutor] making a typing speed tester
In-Reply-To: <ca43e5230711070552n5b5a4068ie2fad149344b17d4@mail.gmail.com>
References: <ca43e5230711070552n5b5a4068ie2fad149344b17d4@mail.gmail.com>
Message-ID: <F1DAFB38-F3F1-4D67-8C7B-887FF975647A@gmail.com>

   Hi Tom,

> I'm trying to write a program to test someones typing speed and show
> them their mistakes. However I'm getting weird results when looking
> for the differences in longer (than 100 chars) strings:
>
> import difflib
>
> # a tape measure string (just makes it easier to locate a given index)
> a =  
> '1-3-5-7-9-12-15-18-21-24-27-30-33-36-39-42-45-48-51-54-57-60-63-66-69 
> -72-75-78-81-84-87-90-93-96-99-103-107-111-115-119-123-127-131-135-139 
> -143-147-151-155-159-163-167-171-175-179-183-187-191-195--200'
>
> # now with a few mistakes
> b = '1-3-5-7- 
> l-12-15-18-21-24-27-30-33-36-39o42-45-48-51-54-57-60-63-66-69-72-75-78 
> -81-84-8k-90-93-96-9l-103-107-111-115-119-12b-1v7-131-135-139-143-147- 
> 151-m55-159-163-167-a71-175j179-183-187-191-195--200'
>
> s = difflib.SequenceMatcher(None, a ,b)
> ms = s.get_matching_blocks()
>
> print ms
>
>>>> [(0, 0, 8), (200, 200, 0)]
>
> Have I made a mistake or is this function designed to give up when the
> input strings get too long? If so what could I use instead to compute
> the mistakes in a typed text?


Ok, I wasn't on the list last year, but I was a few days ago, so  
persistence pays off; partly, as I don't have a full answer.

I got curious and looked at the source of difflib. There's a method  
__chain_b() which sets up the b2j variable, which contains the  
occurrences of characters in string b. So cutting b to 199  
characters, it looks like this:
    b2j= 19 {'a': [168], 'b': [122], 'm': [152], 'k': [86], 'v':  
[125], '-': [1, 3, 5, 7, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 42,  
45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93,  
96, 99, 103, 107, 111, 115, 119, 123, 127, 131, 135, 139, 143, 147,  
151, 155, 159, 163, 167, 171, 179, 183, 187, 191, 195, 196], 'l': [8,  
98], 'o': [39], 'j': [175], '1': [0, 10, 13, 16, 20, 50, 80, 100,  
104, 108, 109, 110, 112, 113, 116, 117, 120, 124, 128, 130, 132, 136,  
140, 144, 148, 150, 156, 160, 164, 170, 172, 176, 180, 184, 188, 190,  
192], '0': [29, 59, 89, 101, 105, 198], '3': [2, 28, 31, 32, 34, 37,  
62, 92, 102, 129, 133, 137, 142, 162, 182], '2': [11, 19, 22, 25, 41,  
71, 121, 197], '5': [4, 14, 44, 49, 52, 55, 74, 114, 134, 149, 153,  
154, 157, 174, 194], '4': [23, 40, 43, 46, 53, 83, 141, 145], '7':  
[6, 26, 56, 70, 73, 76, 106, 126, 146, 166, 169, 173, 177, 186], '6':  
[35, 58, 61, 64, 65, 67, 95, 161, 165], '9': [38, 68, 88, 91, 94, 97,  
118, 138, 158, 178, 189, 193], '8': [17, 47, 77, 79, 82, 85, 181, 185]}

This little detour is because of how b2j is built. Here's a part from  
the comments of __chain_b():

    # Before the tricks described here, __chain_b was by far the most
    # time-consuming routine in the whole module!  If anyone sees
    # Jim Roskind, thank him again for profile.py -- I never would
    # have guessed that.

And the part of the actual code reads:
         b = self.b
         n = len(b)
         self.b2j = b2j = {}
         populardict = {}
         for i, elt in enumerate(b):
             if elt in b2j:
                 indices = b2j[elt]
                 if n >= 200 and len(indices) * 100 > n:     # <--- !!
                     populardict[elt] = 1
                     del indices[:]
                 else:
                     indices.append(i)
             else:
                 b2j[elt] = [i]

So you're right: it has a stop at the (somewhat arbitrarily) limit of  
200 characters. How that exactly works, I don't know (needs more  
delving into the code), though it looks like there also need to be a  
lot of indices (len(indices*100>n); I guess that's caused in your  
strings by the dashes, '1's and '0's (that's why I printed the b2j  
string).
If you feel safe enough and on a fast platform, you can probably up  
that limit (or even put it somewhere as an optional variable in the  
code, which I would think is generally better).
Not sure who the author of the module is (doesn't list in the file  
itself), but perhaps you can find out and email him/her, to see what  
can be altered.

Hope that helps.

   Evert



From marc.tompkins at gmail.com  Wed Nov  7 21:08:57 2007
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Wed, 7 Nov 2007 12:08:57 -0800
Subject: [Tutor] In-place expansion of list members... possible?
Message-ID: <40af687b0711071208wcfb83daia507a30cc62ec009@mail.gmail.com>

This question has probably been asked and answered many times, but I can't
figure out how to word my question to get relevant results from Google.  So
I thought I'd try some human beings, eh?

I'm working with delimited files (ANSI X12 EDI nonsense, to be precise.)
First I load the records to a list:
        tmpSegs = inString.split(self.SegTerm)

Now, I want to replace each string in that list with a string:

        for seg in tmpSegs:       # 'seg' is short for 'segment'
            seg = seg.split(self.ElemSep)

It doesn't work.  If I check the contents of tmpSegs, it's still a list of
strings - not a list of lists.  So I do this instead:
        tmpSegs2 = []
        for seg in tmpSegs:
            tmpSegs2.append(seg.split(self.sElemSep))
        del tmpSegs

This works.  And, for the size of files that I'm likely to run into,
creating the extra list and burning the old one is probably not going to
swamp the machine - but it feels clumsy to me, like if I just knew the
secret I could be much more elegant about it.  I don't want the next guy who
reads my code to scratch his head and say 'What was he thinking?' -
especially if it's me in a year's time!

What puzzles me most is that I can replace 'seg' with just about anything
else -
        for seg in tmpSegs:
            seg = seg.strip()
or
        for seg in tmpSegs:
            seg = 'bananas'
or
        for seg in tmpSegs:
            seg = seg + ' bananas'
and it works.  So why can't I replace it with its own split?

It's not a burning question - development continues - but I'm really
curious.

Thanks!
-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071107/7c4b59d3/attachment.htm 

From brunson at brunson.com  Wed Nov  7 21:28:02 2007
From: brunson at brunson.com (Eric Brunson)
Date: Wed, 07 Nov 2007 13:28:02 -0700
Subject: [Tutor] In-place expansion of list members... possible?
In-Reply-To: <40af687b0711071208wcfb83daia507a30cc62ec009@mail.gmail.com>
References: <40af687b0711071208wcfb83daia507a30cc62ec009@mail.gmail.com>
Message-ID: <47321FD2.9060607@brunson.com>

Marc Tompkins wrote:
> This question has probably been asked and answered many times, but I 
> can't figure out how to word my question to get relevant results from 
> Google.  So I thought I'd try some human beings, eh?
>
> I'm working with delimited files (ANSI X12 EDI nonsense, to be 
> precise.)  First I load the records to a list:
>         tmpSegs = inString.split(self.SegTerm)
>
> Now, I want to replace each string in that list with a string:
>
>         for seg in tmpSegs:       # 'seg' is short for 'segment'
>             seg = seg.split(self.ElemSep)

A list is an array of pointers to objects, what you've done here is 
create a new name referencing an item in the list, then making that new 
name point to something different.

Try this (untested code):

for index in xrange(0, len(tmpSegs)):
    tmpSegs[index] = tmpSegs[index].split(self.ElemSep)


This will iterate through the list and set each reference in the list to 
point to your new object.

Hope that helps,
e.


>
> It doesn't work.  If I check the contents of tmpSegs, it's still a 
> list of strings - not a list of lists.  So I do this instead:
>         tmpSegs2 = []
>         for seg in tmpSegs:
>             tmpSegs2.append(seg.split(self.sElemSep))
>         del tmpSegs
>
> This works.  And, for the size of files that I'm likely to run into, 
> creating the extra list and burning the old one is probably not going 
> to swamp the machine - but it feels clumsy to me, like if I just knew 
> the secret I could be much more elegant about it.  I don't want the 
> next guy who reads my code to scratch his head and say 'What was he 
> thinking?' - especially if it's me in a year's time!
>
> What puzzles me most is that I can replace 'seg' with just about 
> anything else -
>         for seg in tmpSegs:
>             seg = seg.strip()
> or
>         for seg in tmpSegs:
>             seg = 'bananas'
> or
>         for seg in tmpSegs:
>             seg = seg + ' bananas'
> and it works.  So why can't I replace it with its own split?
>
> It's not a burning question - development continues - but I'm really 
> curious.
>
> Thanks!
> -- 
> www.fsrtechnologies.com <http://www.fsrtechnologies.com>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From kent37 at tds.net  Wed Nov  7 21:41:18 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 07 Nov 2007 15:41:18 -0500
Subject: [Tutor] In-place expansion of list members... possible?
In-Reply-To: <40af687b0711071208wcfb83daia507a30cc62ec009@mail.gmail.com>
References: <40af687b0711071208wcfb83daia507a30cc62ec009@mail.gmail.com>
Message-ID: <473222EE.3020803@tds.net>

Marc Tompkins wrote:
> I'm working with delimited files (ANSI X12 EDI nonsense, to be 
> precise.)  First I load the records to a list:
>         tmpSegs = inString.split(self.SegTerm)
> 
> Now, I want to replace each string in that list with a string:
> 
>         for seg in tmpSegs:       # 'seg' is short for 'segment'
>             seg = seg.split(self.ElemSep)
> 
> It doesn't work.  If I check the contents of tmpSegs, it's still a list 
> of strings - not a list of lists.  So I do this instead:
>         tmpSegs2 = []
>         for seg in tmpSegs:
>             tmpSegs2.append(seg.split(self.sElemSep))
>         del tmpSegs
> 
> This works.  And, for the size of files that I'm likely to run into, 
> creating the extra list and burning the old one is probably not going to 
> swamp the machine - but it feels clumsy to me, like if I just knew the 
> secret I could be much more elegant about it.

Creating a new list is fine, actually. You can do it more elegantly with 
a list comprehension, and it's fine to assign to the same name, which 
will implicitly delete the old list:
tmpSegs = [ seg.split(self.ElemSep) for seg in tmpSegs ]

If you really want to replace elements in the same list you can use 
enumerate to get indices:

for i, seg in enumerate(tmpSegs):
   tmpSegs[i] = seg.split(self.ElemSep)

or use slice assignment:
tmpSegs[:] = [ seg.split(self.ElemSep) for seg in tmpSegs ]

but I doubt those are needed in this case.

> What puzzles me most is that I can replace 'seg' with just about 
> anything else -
>         for seg in tmpSegs:
>             seg = seg.strip()
> or
>         for seg in tmpSegs:
>             seg = 'bananas'
> or
>         for seg in tmpSegs:
>             seg = seg + ' bananas'
> and it works.  So why can't I replace it with its own split?

If by 'it works' you mean that tmpSegs is changed...you are mistaken or 
there is something you are not showing. Can you show why you think this 
changes tmpSegs?

Kent

From marc.tompkins at gmail.com  Wed Nov  7 21:42:28 2007
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Wed, 7 Nov 2007 12:42:28 -0800
Subject: [Tutor] In-place expansion of list members... possible?
In-Reply-To: <47321FD2.9060607@brunson.com>
References: <40af687b0711071208wcfb83daia507a30cc62ec009@mail.gmail.com>
	<47321FD2.9060607@brunson.com>
Message-ID: <40af687b0711071242o18df3f25pdc2dd639e7892cdc@mail.gmail.com>

Try this (untested code):

for index in xrange(0, len(tmpSegs)):
   tmpSegs[index] = tmpSegs[index].split(self.ElemSep)


Thank you - that works nicely, and it's a much better replacement for
something else I was doing to achieve the same result (you know, the old
count+=1 nonsense - every day, in every way, I'm struggling to become more
and more Pythonic.)

Now, I did already (intellectually) understand this:

A list is an array of pointers to objects, what you've done here is
create a new name referencing an item in the list, then making that new
name point to something different.

Given that, however, I still don't entirely understand why the other
examples I gave DO work.  Seems it should be one or the other, no?

I'm probably just being dense, though.

Marc

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

From marc.tompkins at gmail.com  Wed Nov  7 22:04:34 2007
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Wed, 7 Nov 2007 13:04:34 -0800
Subject: [Tutor] In-place expansion of list members... possible?
In-Reply-To: <473222EE.3020803@tds.net>
References: <40af687b0711071208wcfb83daia507a30cc62ec009@mail.gmail.com>
	<473222EE.3020803@tds.net>
Message-ID: <40af687b0711071304g518f07c7v2b9764e9674d6e5c@mail.gmail.com>

> > What puzzles me most is that I can replace 'seg' with just about
> > anything else -
> >         for seg in tmpSegs:
> >             seg = seg.strip()
> > or
> >         for seg in tmpSegs:
> >             seg = 'bananas'
> > or
> >         for seg in tmpSegs:
> >             seg = seg + ' bananas'
> > and it works.  So why can't I replace it with its own split?
>
> If by 'it works' you mean that tmpSegs is changed...you are mistaken or
> there is something you are not showing. Can you show why you think this
> changes tmpSegs?


I see I have been misled by trying too many things in a short time and
confusing my results.  I could have sworn that late last night, before I hit
on the solution of assigning to a new list altogether, I tried the above
examples and followed them with another "for seg in tmpSegs" loop that
simply printed the contents.

I now suspect myself of being too sleepy (and probably inadvertently
assigning to a new list anyway!) at the time, because - as you already know
- when I try it now, tmpSegs is unchanged.  I hang my head in shame.


Thanks for the responses -

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

From john at fouhy.net  Wed Nov  7 22:06:06 2007
From: john at fouhy.net (John Fouhy)
Date: Thu, 8 Nov 2007 10:06:06 +1300
Subject: [Tutor] In-place expansion of list members... possible?
In-Reply-To: <40af687b0711071242o18df3f25pdc2dd639e7892cdc@mail.gmail.com>
References: <40af687b0711071208wcfb83daia507a30cc62ec009@mail.gmail.com>
	<47321FD2.9060607@brunson.com>
	<40af687b0711071242o18df3f25pdc2dd639e7892cdc@mail.gmail.com>
Message-ID: <5e58f2e40711071306o4e3c565dgbab3cee2879d0a8b@mail.gmail.com>

On 08/11/2007, Marc Tompkins <marc.tompkins at gmail.com> wrote:
> Now, I did already (intellectually) understand this:
>   A list is an array of pointers to objects, what you've done here is
>   create a new name referencing an item in the list, then making that new
>   name point to something different.
> Given that, however, I still don't entirely understand why the other
> examples I gave DO work.  Seems it should be one or the other, no?

Could you post some code/results (or an interpreter session) showing
one of the other examples working?

If you did, for example,

        tmpSegs = inString.split(self.SegTerm)
        for seg in tmpSegs:
            seg = 'bananas'

I would expect tmpSegs to be unchanged.  If it is changed, then that
seems strange to me..

-- 
John.

From brunson at brunson.com  Wed Nov  7 22:37:19 2007
From: brunson at brunson.com (Eric Brunson)
Date: Wed, 07 Nov 2007 14:37:19 -0700
Subject: [Tutor] In-place expansion of list members... possible?
In-Reply-To: <5e58f2e40711071306o4e3c565dgbab3cee2879d0a8b@mail.gmail.com>
References: <40af687b0711071208wcfb83daia507a30cc62ec009@mail.gmail.com>	<47321FD2.9060607@brunson.com>	<40af687b0711071242o18df3f25pdc2dd639e7892cdc@mail.gmail.com>
	<5e58f2e40711071306o4e3c565dgbab3cee2879d0a8b@mail.gmail.com>
Message-ID: <4732300F.1030102@brunson.com>

John Fouhy wrote:
> On 08/11/2007, Marc Tompkins <marc.tompkins at gmail.com> wrote:
>   
>> Now, I did already (intellectually) understand this:
>>   A list is an array of pointers to objects, what you've done here is
>>   create a new name referencing an item in the list, then making that new
>>   name point to something different.
>> Given that, however, I still don't entirely understand why the other
>> examples I gave DO work.  Seems it should be one or the other, no?
>>     
>
> Could you post some code/results (or an interpreter session) showing
> one of the other examples working?
>
> If you did, for example,
>
>         tmpSegs = inString.split(self.SegTerm)
>         for seg in tmpSegs:
>             seg = 'bananas'
>
> I would expect tmpSegs to be unchanged.  If it is changed, then that
> seems strange to me..
>
>   
I'd like to see it, too.  I'll admit, I didn't finish reading your post, 
so I missed replying to that, but honestly I don't think it should do 
what you say it does.

:-)


From brunson at brunson.com  Wed Nov  7 22:38:29 2007
From: brunson at brunson.com (Eric Brunson)
Date: Wed, 07 Nov 2007 14:38:29 -0700
Subject: [Tutor] In-place expansion of list members... possible?
In-Reply-To: <473222EE.3020803@tds.net>
References: <40af687b0711071208wcfb83daia507a30cc62ec009@mail.gmail.com>
	<473222EE.3020803@tds.net>
Message-ID: <47323055.5040304@brunson.com>

Kent Johnson wrote:
> Marc Tompkins wrote:
>   
>> I'm working with delimited files (ANSI X12 EDI nonsense, to be 
>> precise.)  First I load the records to a list:
>>         tmpSegs = inString.split(self.SegTerm)
>>
>> Now, I want to replace each string in that list with a string:
>>
>>         for seg in tmpSegs:       # 'seg' is short for 'segment'
>>             seg = seg.split(self.ElemSep)
>>
>> It doesn't work.  If I check the contents of tmpSegs, it's still a list 
>> of strings - not a list of lists.  So I do this instead:
>>         tmpSegs2 = []
>>         for seg in tmpSegs:
>>             tmpSegs2.append(seg.split(self.sElemSep))
>>         del tmpSegs
>>
>> This works.  And, for the size of files that I'm likely to run into, 
>> creating the extra list and burning the old one is probably not going to 
>> swamp the machine - but it feels clumsy to me, like if I just knew the 
>> secret I could be much more elegant about it.
>>     
>
> Creating a new list is fine, actually. You can do it more elegantly with 
> a list comprehension, and it's fine to assign to the same name, which 
> will implicitly delete the old list:
> tmpSegs = [ seg.split(self.ElemSep) for seg in tmpSegs ]
>
> If you really want to replace elements in the same list you can use 
> enumerate to get indices:
>
> for i, seg in enumerate(tmpSegs):
>    tmpSegs[i] = seg.split(self.ElemSep)
>   

Very nice use of enumerate(), I like this better than my solution.

Thanks, Kent.

> or use slice assignment:
> tmpSegs[:] = [ seg.split(self.ElemSep) for seg in tmpSegs ]
>
> but I doubt those are needed in this case.
>
>   
>> What puzzles me most is that I can replace 'seg' with just about 
>> anything else -
>>         for seg in tmpSegs:
>>             seg = seg.strip()
>> or
>>         for seg in tmpSegs:
>>             seg = 'bananas'
>> or
>>         for seg in tmpSegs:
>>             seg = seg + ' bananas'
>> and it works.  So why can't I replace it with its own split?
>>     
>
> If by 'it works' you mean that tmpSegs is changed...you are mistaken or 
> there is something you are not showing. Can you show why you think this 
> changes tmpSegs?
>
> Kent
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From dineshbvadhia at hotmail.com  Wed Nov  7 23:41:24 2007
From: dineshbvadhia at hotmail.com (Dinesh B Vadhia)
Date: Wed, 7 Nov 2007 14:41:24 -0800
Subject: [Tutor] Elegant argument index sort
Message-ID: <BAY109-DAV12253EA708B09DA79834F7A38A0@phx.gbl>

I'm sorting a 1-d (NumPy) matrix array (a) and wanting the index results (b).  This is what I have:

b = a.argsort(0)
b = b+1

The one (1) is added to b so that there isn't a zero index element.  Is there a more elegant way to do this?

Dinesh
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071107/35de0af1/attachment.htm 

From wescpy at gmail.com  Thu Nov  8 00:47:02 2007
From: wescpy at gmail.com (wesley chun)
Date: Wed, 7 Nov 2007 15:47:02 -0800
Subject: [Tutor] New Introductory Book
In-Reply-To: <4731DC82.3060809@ntlworld.com>
References: <18224.43390.384547.2507@euclid.slu.edu>
	<d9e88eaf0711061121l62a72665h251c7824643ce7c0@mail.gmail.com>
	<4731DC82.3060809@ntlworld.com>
Message-ID: <78b3a9580711071547q66eb188h793a3f674b0520b7@mail.gmail.com>

eddie,

> Whatever the rationale for the price you could buy 2nd Ed 'Core', Chun
> *and *3rd edition(when it arrives) 'Learning Python', Lutz (the two
> standard, known and respected beginners texts) for the price of this.
> Mmm, I wonder what I would buy or rather have as a student.


i've been skimming through michael's and david's book over the past
week. fiscally, you are correct with your remark, but i have to be
honest and say that michael's and david's book spends a bit more time
introducing the concepts of OOP/OOD more carefully and more thought
out than either mine or david's and mark's books.

our books target existing programmers who (may already have some OO
under their belt and/or) want to pick up python right away, rather
than someone new to object-oriented methodologies (and perhaps
programming) using python as the primary development vehicle. of
course there is an OO intro in Core Python, but it is not a thorough
treatment. as i've hinted, it's really the target audience.

still, your point is well taken. fwiw, most aspects of the selling of
a book (including its cover price) is almost -always out of the
control of the author(s).

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 dineshbvadhia at hotmail.com  Thu Nov  8 02:10:43 2007
From: dineshbvadhia at hotmail.com (Dinesh B Vadhia)
Date: Wed, 7 Nov 2007 17:10:43 -0800
Subject: [Tutor] From Numpy Import *
Message-ID: <BAY109-DAV11A9CF74CD538300639683A38B0@phx.gbl>

Hello!  The standard Python practice for importing modules is, for example:

import sys
import os
etc.

In NumPy (and SciPy) the 'book' suggests using:

from numpy import *
from scipy import *

However, when I instead use 'import numpy' it causes all sorts of errors in my existing code.

What do you suggest?

Dinesh
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071107/541bda32/attachment.htm 

From goldwamh at slu.edu  Thu Nov  8 02:37:24 2007
From: goldwamh at slu.edu (Michael H. Goldwasser)
Date: Wed, 7 Nov 2007 19:37:24 -0600
Subject: [Tutor]  From Numpy Import *
In-Reply-To: <BAY109-DAV11A9CF74CD538300639683A38B0@phx.gbl>
References: <BAY109-DAV11A9CF74CD538300639683A38B0@phx.gbl>
Message-ID: <18226.26708.59491.319828@euclid.slu.edu>


On Wednesday November 7, 2007, Dinesh B Vadhia wrote: 

>    Hello!  The standard Python practice for importing modules is, for example:
>    
>    import sys
>    import os
>    etc.
>    
>    In NumPy (and SciPy) the 'book' suggests using:
>    
>    from numpy import *
>    from scipy import *
>    
>    However, when I instead use 'import numpy' it causes all sorts of errors in my existing code.

The issue is the following.  The numpy module includes many definitions, for
example a class named array.   When you use the syntax,

   from numpy import *

That takes all definitions from the module and places them into your
current namespace.  At this point, it would be fine to use a command
such as 

  values = array([1.0, 2.0, 3.0])

which instantiates a (numpy) array.


If you instead use the syntax

   import numpy

things brings that module as a whole into your namespace, but to
access definitions from that module you have to give a qualified
name, for example as

  values = numpy.array([1.0, 2.0, 3.0])

You cannot simply use the word array as in the first scenario.  This
would explain why your existing code would no longer work with the
change.

>    What do you suggest?

The advantage of the "from numpy import *" syntax is mostly
convenience.   However, the better style is "import numpy" precisely
becuase it does not automatically introduce many other definitions
into your current namespace.

If you were using some other package that also defined an "array" and
then you were to use the "from numpy import *", the new definition
would override the other definition.  The use of qualified names helps
to avoid these collisions and makes clear where those definitions are
coming from.

With regard,
Michael


From kent37 at tds.net  Thu Nov  8 02:56:30 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 07 Nov 2007 20:56:30 -0500
Subject: [Tutor] From Numpy Import *
In-Reply-To: <18226.26708.59491.319828@euclid.slu.edu>
References: <BAY109-DAV11A9CF74CD538300639683A38B0@phx.gbl>
	<18226.26708.59491.319828@euclid.slu.edu>
Message-ID: <47326CCE.6060104@tds.net>

Michael H. Goldwasser wrote:
>    from numpy import *
>    import numpy

There is a third option which provides the safety/control of import 
numpy with a little less typing:
   import numpy as np
   values = np.array([1.0, 2.0, 3.0])

and you can also import just the names you need:

   from numpy import array
   values = array(...)

Kent


From samrobertsmith at gmail.com  Thu Nov  8 03:30:59 2007
From: samrobertsmith at gmail.com (linda.s)
Date: Wed, 7 Nov 2007 19:30:59 -0700
Subject: [Tutor] repeated times
In-Reply-To: <5df213700711040915x906cffbs3685166c9b271d63@mail.gmail.com>
References: <184538.78377.qm@web86704.mail.ird.yahoo.com>
	<1d987df30711040139o2ac323aaw685de9b9e4245744@mail.gmail.com>
	<fgklnq$1s9$1@ger.gmane.org>
	<5df213700711040915x906cffbs3685166c9b271d63@mail.gmail.com>
Message-ID: <1d987df30711071830q6da0a60dx8682368911bc986e@mail.gmail.com>

On 11/4/07, Aditya Lal <aditya.n.lal at gmail.com> wrote:
> On 11/4/07, Thorsten Kampe <thorsten at thorstenkampe.de> wrote:
> > * linda.s (Sun, 4 Nov 2007 01:39:46 -0800)
> > > On Nov 2, 2007 1:03 AM, ALAN GAULD < alan.gauld at btinternet.com> wrote:
> > > > > > >I want to run an .exe file and get the output many times.
> > > > >> Given that I know that you know about loops I have to
> > > > >> ask what you see as the problem?
> > > > >
> > > > >I want to run it many times and export all the output to a text file.
> > > >
> > > > OK, Do you mean you want to run the program multiple times
> > > > but put the output in the same file?
> > >
> > > Yes. For example, I want to run the exe file one hundred times and
> > > save all the results into one file.
> > > Is there any example code to do that?
> >
> > There's no reason to do that in Python. You should use a batch or
> > shell script for that. If you really insist on using Python then look
> > at the subprocess module...
> >
> > Thorsten
> >
>
> On Unix, you can execute "script <filename>" on the command prompt. This
> will create a new session in which you execute the program as many times.
> After you are done press ^D to come out of session. Everything of that
> session will be saved in the file <filename>.
>
> On Windows, you can probably build something like "script" in python. BTW,
> does your executable takes any user inputs ?
>
> --
> Aditya

My executable takes any user inputs and the input will be adjusted
based on the former result. So I need do some analysis based on the
output every time.
hanks,
Linda

From annaraven at gmail.com  Thu Nov  8 04:23:10 2007
From: annaraven at gmail.com (Anna Martelli Ravenscroft)
Date: Wed, 7 Nov 2007 19:23:10 -0800
Subject: [Tutor] repeated times
In-Reply-To: <1d987df30711071830q6da0a60dx8682368911bc986e@mail.gmail.com>
References: <184538.78377.qm@web86704.mail.ird.yahoo.com>
	<1d987df30711040139o2ac323aaw685de9b9e4245744@mail.gmail.com>
	<fgklnq$1s9$1@ger.gmane.org>
	<5df213700711040915x906cffbs3685166c9b271d63@mail.gmail.com>
	<1d987df30711071830q6da0a60dx8682368911bc986e@mail.gmail.com>
Message-ID: <03295A5B-7314-48EE-AAFA-066E4C2A5911@gmail.com>

I'm not sure if this is what youre asking but if you want to collect  
all of the output into a file without overwriting, open the output  
file with " a" instead of "w" and the output will. be appended. Iwould  
suggest in that case that you include info about the user input so you  
can distinguish the output . Hth

Sent from my iPhone

On Nov 7, 2007, at 6:30 PM, "linda.s" <samrobertsmith at gmail.com> wrote:

> On 11/4/07, Aditya Lal <aditya.n.lal at gmail.com> wrote:
>> On 11/4/07, Thorsten Kampe <thorsten at thorstenkampe.de> wrote:
>>> * linda.s (Sun, 4 Nov 2007 01:39:46 -0800)
>>>> On Nov 2, 2007 1:03 AM, ALAN GAULD < alan.gauld at btinternet.com>  
>>>> wrote:
>>>>>>>> I want to run an .exe file and get the output many times.
>>>>>>> Given that I know that you know about loops I have to
>>>>>>> ask what you see as the problem?
>>>>>>
>>>>>> I want to run it many times and export all the output to a text  
>>>>>> file.
>>>>>
>>>>> OK, Do you mean you want to run the program multiple times
>>>>> but put the output in the same file?
>>>>
>>>> Yes. For example, I want to run the exe file one hundred times and
>>>> save all the results into one file.
>>>> Is there any example code to do that?
>>>
>>> There's no reason to do that in Python. You should use a batch or
>>> shell script for that. If you really insist on using Python then  
>>> look
>>> at the subprocess module...
>>>
>>> Thorsten
>>>
>>
>> On Unix, you can execute "script <filename>" on the command prompt.  
>> This
>> will create a new session in which you execute the program as many  
>> times.
>> After you are done press ^D to come out of session. Everything of  
>> that
>> session will be saved in the file <filename>.
>>
>> On Windows, you can probably build something like "script" in  
>> python. BTW,
>> does your executable takes any user inputs ?
>>
>> --
>> Aditya
>
> My executable takes any user inputs and the input will be adjusted
> based on the former result. So I need do some analysis based on the
> output every time.
> hanks,
> Linda
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

From eddie_armstrong at ntlworld.com  Thu Nov  8 12:29:12 2007
From: eddie_armstrong at ntlworld.com (Eddie Armstrong)
Date: Thu, 08 Nov 2007 11:29:12 +0000
Subject: [Tutor] New Introductory Book
In-Reply-To: <78b3a9580711071547q66eb188h793a3f674b0520b7@mail.gmail.com>
References: <18224.43390.384547.2507@euclid.slu.edu>	
	<d9e88eaf0711061121l62a72665h251c7824643ce7c0@mail.gmail.com>	
	<4731DC82.3060809@ntlworld.com>
	<78b3a9580711071547q66eb188h793a3f674b0520b7@mail.gmail.com>
Message-ID: <4732F308.9070908@ntlworld.com>

wesley chun wrote:
> michael's and david's book spends a bit more time
> introducing the concepts of OOP/OOD more carefully and more though
If it had been half the price I'd have bought it for a strong exposition 
of OO principles in Python. However at less than 700pp and c. ?54 in the 
UK it won't be added to my bookshelf.
> most aspects of the selling of
> a book (including its cover price) is almost -always out of the
> control of the author(s).
>   
I wasn't necessarily accusing the authors of anything, how could I? I 
expect marketing thought they'd get more money this way.   As a previous 
poster said it's probably priced for  academic use.
I also realise the cost of producing books etc
If I were allocating books for students I would still spare them the 
exorbitant cost of this and recommend one or both of the other books. 
They could even get 'Core' + 'Programming'(Lutz), over 2000 quality 
pages for less then the price of this.

And I'm quite sure any educational establishment worthy of the name 
would bridge any gaps.

No disrespect to the authors or for what may be an excellent book but 
not for me. And I think it's a shame - if it specialised in the OOP 
aspects - at half the price it would have been a worthy addition to the 
beginners' library.
Just my opinion

Eddie



From bgailer at alum.rpi.edu  Thu Nov  8 13:10:25 2007
From: bgailer at alum.rpi.edu (bob gailer)
Date: Thu, 08 Nov 2007 07:10:25 -0500
Subject: [Tutor] Elegant argument index sort
In-Reply-To: <BAY109-DAV12253EA708B09DA79834F7A38A0@phx.gbl>
References: <BAY109-DAV12253EA708B09DA79834F7A38A0@phx.gbl>
Message-ID: <4732FCB1.9070405@alum.rpi.edu>

Dinesh B Vadhia wrote:
> I'm sorting a 1-d (NumPy) matrix array (a) and wanting the index 
> results (b). 
I can't tell from your comments and code what you want. Please provide a 
better explanation and give an example of input and output numbers. Also 
I am not familiar with argsort.
> This is what I have:
>  
> b = a.argsort(0)
> b = b+1
>  
> The one (1) is added to b so that there isn't a zero index element.  
> Is there a more elegant way to do this?


From kent37 at tds.net  Thu Nov  8 14:55:56 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 08 Nov 2007 08:55:56 -0500
Subject: [Tutor] Elegant argument index sort
In-Reply-To: <BAY109-DAV12253EA708B09DA79834F7A38A0@phx.gbl>
References: <BAY109-DAV12253EA708B09DA79834F7A38A0@phx.gbl>
Message-ID: <4733156C.3020507@tds.net>

Dinesh B Vadhia wrote:
> I'm sorting a 1-d (NumPy) matrix array (a) and wanting the index results 
> (b).  This is what I have:
>  
> b = a.argsort(0)
> b = b+1
>  
> The one (1) is added to b so that there isn't a zero index element.  Is 
> there a more elegant way to do this?

b = a.argsort(0) + 1

?

Kent

From ladynikon at gmail.com  Thu Nov  8 15:08:52 2007
From: ladynikon at gmail.com (Danyelle Gragsone)
Date: Thu, 8 Nov 2007 09:08:52 -0500
Subject: [Tutor] New Introductory Book
In-Reply-To: <4732F308.9070908@ntlworld.com>
References: <18224.43390.384547.2507@euclid.slu.edu>
	<d9e88eaf0711061121l62a72665h251c7824643ce7c0@mail.gmail.com>
	<4731DC82.3060809@ntlworld.com>
	<78b3a9580711071547q66eb188h793a3f674b0520b7@mail.gmail.com>
	<4732F308.9070908@ntlworld.com>
Message-ID: <59f9c5160711080608h12d35b0u7ebbe43f6ed1cd97@mail.gmail.com>

It look great.. but being a student I can't afford such a high priced
item.  I guess I will have to wait for the used copies to show up on
amazon :).

Danyelle

From kent37 at tds.net  Thu Nov  8 15:33:48 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 08 Nov 2007 09:33:48 -0500
Subject: [Tutor] New Introductory Book
In-Reply-To: <59f9c5160711080608h12d35b0u7ebbe43f6ed1cd97@mail.gmail.com>
References: <18224.43390.384547.2507@euclid.slu.edu>	<d9e88eaf0711061121l62a72665h251c7824643ce7c0@mail.gmail.com>	<4731DC82.3060809@ntlworld.com>	<78b3a9580711071547q66eb188h793a3f674b0520b7@mail.gmail.com>	<4732F308.9070908@ntlworld.com>
	<59f9c5160711080608h12d35b0u7ebbe43f6ed1cd97@mail.gmail.com>
Message-ID: <47331E4C.3050402@tds.net>

Danyelle Gragsone wrote:
> It look great.. but being a student I can't afford such a high priced
> item.  I guess I will have to wait for the used copies to show up on
> amazon :).

FWIW this book is available to anyone with a .edu email address for 
$71.53 plus shipping, from
http://www.a1books.com/cgi-bin/mktSearch?act=showDesc&itemcode=0136150314

A little more ($75.29) without a .edu email but still the best price 
found by BestBookDeal:
http://www.bestbookdeal.com/book/compare/0136150314/

Kent

From bhaaluu at gmail.com  Thu Nov  8 17:13:05 2007
From: bhaaluu at gmail.com (bhaaluu)
Date: Thu, 8 Nov 2007 11:13:05 -0500
Subject: [Tutor] New Introductory Book
In-Reply-To: <47331E4C.3050402@tds.net>
References: <18224.43390.384547.2507@euclid.slu.edu>
	<d9e88eaf0711061121l62a72665h251c7824643ce7c0@mail.gmail.com>
	<4731DC82.3060809@ntlworld.com>
	<78b3a9580711071547q66eb188h793a3f674b0520b7@mail.gmail.com>
	<4732F308.9070908@ntlworld.com>
	<59f9c5160711080608h12d35b0u7ebbe43f6ed1cd97@mail.gmail.com>
	<47331E4C.3050402@tds.net>
Message-ID: <ea979d70711080813q1c165f1cya5b52131ea68d30e@mail.gmail.com>

On Nov 8, 2007 9:33 AM, Kent Johnson <kent37 at tds.net> wrote:
> Danyelle Gragsone wrote:
> > It look great.. but being a student I can't afford such a high priced
> > item.  I guess I will have to wait for the used copies to show up on
> > amazon :).
>
> FWIW this book is available to anyone with a .edu email address for
> $71.53 plus shipping, from
> http://www.a1books.com/cgi-bin/mktSearch?act=showDesc&itemcode=0136150314
>
> A little more ($75.29) without a .edu email but still the best price
> found by BestBookDeal:
> http://www.bestbookdeal.com/book/compare/0136150314/
>
> Kent
>

You probably won't have to wait much longer than a college semester
for used copies of this textbook to start showing up on the Net
depending on how many CS professors adopt it as a CS-1 textbook.

I asked if the source code for the textbook is available for download?
One of the best ways to judge the quality of a textbook is by the example
source code. I also asked if a sample chapter was available to read?
Sometimes an author's writing style just doesn't click (too bad for
students who HAVE TO buy the textbook for a class -- then they have
to suffer through it). But for others, studying on their own, being able
to read a sample chapter and look at the example source code might
be the stimulus to buy the book (even at $102/$71.53/$whatever).
OTOH, having a look at the example source, and a sample chapter
might be a good enough reason not to touch the book with a 10 foot
pole! It can go either way....

Another way to judge how the book is, is by reading the posts the author
sends to THIS list in order to help people. Mr. Chun and Mr. Gauld are
two authors who provide help on this list. I certainly don't mind if they
advertise their books on occassion -- they are also Tutors!

http://used.addall.com/  lists used copies for many used-book brokers.

Just Another Noob.
-- 
b h a a l u u at g m a i l dot c o m
http://www.geocities.com/ek.bhaaluu/python/index.html

From ladynikon at gmail.com  Thu Nov  8 17:15:16 2007
From: ladynikon at gmail.com (Danyelle Gragsone)
Date: Thu, 8 Nov 2007 11:15:16 -0500
Subject: [Tutor] New Introductory Book
In-Reply-To: <ea979d70711080813q1c165f1cya5b52131ea68d30e@mail.gmail.com>
References: <18224.43390.384547.2507@euclid.slu.edu>
	<d9e88eaf0711061121l62a72665h251c7824643ce7c0@mail.gmail.com>
	<4731DC82.3060809@ntlworld.com>
	<78b3a9580711071547q66eb188h793a3f674b0520b7@mail.gmail.com>
	<4732F308.9070908@ntlworld.com>
	<59f9c5160711080608h12d35b0u7ebbe43f6ed1cd97@mail.gmail.com>
	<47331E4C.3050402@tds.net>
	<ea979d70711080813q1c165f1cya5b52131ea68d30e@mail.gmail.com>
Message-ID: <59f9c5160711080815j661e5dc2p15312042e45c749c@mail.gmail.com>

I wonder what schools offer python as a course.  Sadly all the
colleges here offer only perl.

:(

From goldwamh at slu.edu  Thu Nov  8 17:46:51 2007
From: goldwamh at slu.edu (Michael H. Goldwasser)
Date: Thu, 8 Nov 2007 10:46:51 -0600
Subject: [Tutor] New Introductory Book
In-Reply-To: <ea979d70711080813q1c165f1cya5b52131ea68d30e@mail.gmail.com>
References: <18224.43390.384547.2507@euclid.slu.edu>
	<d9e88eaf0711061121l62a72665h251c7824643ce7c0@mail.gmail.com>
	<4731DC82.3060809@ntlworld.com>
	<78b3a9580711071547q66eb188h793a3f674b0520b7@mail.gmail.com>
	<4732F308.9070908@ntlworld.com>
	<59f9c5160711080608h12d35b0u7ebbe43f6ed1cd97@mail.gmail.com>
	<47331E4C.3050402@tds.net>
	<ea979d70711080813q1c165f1cya5b52131ea68d30e@mail.gmail.com>
Message-ID: <18227.15739.680724.37877@euclid.slu.edu>


On Thursday November 8, 2007, bhaaluu wrote: 

>    I asked if the source code for the textbook is available for download?
>    One of the best ways to judge the quality of a textbook is by the example
>    source code. I also asked if a sample chapter was available to read?
>    Sometimes an author's writing style just doesn't click (too bad for
>    students who HAVE TO buy the textbook for a class -- then they have
>    to suffer through it). But for others, studying on their own, being able
>    to read a sample chapter and look at the example source code might
>    be the stimulus to buy the book (even at $102/$71.53/$whatever).
>    OTOH, having a look at the example source, and a sample chapter
>    might be a good enough reason not to touch the book with a 10 foot
>    pole! It can go either way....

Thats a great idea.  I'll contact our publisher today so that we can
get full source code from the entire book up on their website.  I'm
not sure of their willingness for a sample chapter, but will ask about
that as well.

With regard,
Michael


       +-----------------------------------------------+
       | Michael Goldwasser                            |
       | Associate Professor                           |
       | Dept. Mathematics and Computer Science        |
       | Saint Louis University                        |
       | 220 North Grand Blvd.                         |
       | St. Louis, MO 63103-2007                      |
       |                                               |
       | Office: Ritter Hall 6                         |
       | Email:  goldwamh at slu.edu                      |
       | URL:    euler.slu.edu/~goldwasser             |
       | Phone:  (314) 977-7039                        |
       | Fax:    (314) 977-1452                        |
       +-----------------------------------------------+


From alan.gauld at btinternet.com  Thu Nov  8 19:06:36 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 8 Nov 2007 18:06:36 -0000
Subject: [Tutor] New Introductory Book
References: <18224.43390.384547.2507@euclid.slu.edu><d9e88eaf0711061121l62a72665h251c7824643ce7c0@mail.gmail.com><4731DC82.3060809@ntlworld.com><78b3a9580711071547q66eb188h793a3f674b0520b7@mail.gmail.com><4732F308.9070908@ntlworld.com><59f9c5160711080608h12d35b0u7ebbe43f6ed1cd97@mail.gmail.com><47331E4C.3050402@tds.net><ea979d70711080813q1c165f1cya5b52131ea68d30e@mail.gmail.com>
	<18227.15739.680724.37877@euclid.slu.edu>
Message-ID: <fgvj7j$iqn$1@ger.gmane.org>

"Michael H. Goldwasser" <goldwamh at slu.edu> wrote

>>    to suffer through it). But for others, studying on their own, 
>> being able
>>    to read a sample chapter and look at the example source code 
>> might
>>    be the stimulus to buy the book
>
> Thats a great idea.  I'll contact our publisher today so that we can
> get full source code from the entire book up on their website.  I'm
> not sure of their willingness for a sample chapter, but will ask 
> about
> that as well.

Its not an unusual thing - the Amazon "Look Inside" logo is widely
used and is usually more helpful than a hindrance in getting sales.
In fact the ideal for you is probably to try to get them to put the
sample chapter on Amazon because more folks will look there
than on the publisher's own web site!

If they are going to rely purely on academic sales then that will
greatly reduce their marketplace (and your royalties!)


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



From cbc at unc.edu  Thu Nov  8 20:47:59 2007
From: cbc at unc.edu (Chris Calloway)
Date: Thu, 08 Nov 2007 14:47:59 -0500
Subject: [Tutor] New Introductory Book
In-Reply-To: <59f9c5160711080815j661e5dc2p15312042e45c749c@mail.gmail.com>
References: <18224.43390.384547.2507@euclid.slu.edu>	<d9e88eaf0711061121l62a72665h251c7824643ce7c0@mail.gmail.com>	<4731DC82.3060809@ntlworld.com>	<78b3a9580711071547q66eb188h793a3f674b0520b7@mail.gmail.com>	<4732F308.9070908@ntlworld.com>	<59f9c5160711080608h12d35b0u7ebbe43f6ed1cd97@mail.gmail.com>	<47331E4C.3050402@tds.net>	<ea979d70711080813q1c165f1cya5b52131ea68d30e@mail.gmail.com>
	<59f9c5160711080815j661e5dc2p15312042e45c749c@mail.gmail.com>
Message-ID: <473367EF.6010802@unc.edu>

Danyelle Gragsone wrote:
> I wonder what schools offer python as a course.

It has been rather widely publicized of late that MIT this year switched 
all their incoming computer science and electrical engineering students 
to Python (from Lisp) as their introductory programming language.

They use this well regarded $26.40 textbook:

http://www.amazon.com/Python-Programming-Introduction-Computer-Science/dp/1887902996/

There is a computer science department at my university. They don't 
teach languages. Teaching languages is frowned upon in some computer 
science departments under the logic that if you belong in a computer 
science class, you'd better show up for class already knowing something 
as easy to grasp as an implementation language. Some computer science 
courses at my university have an implementation language used in the 
class. I've noticed both Python and Lisp used.

-- 
Sincerely,

Chris Calloway
http://www.seacoos.org
office: 332 Chapman Hall   phone: (919) 962-4323
mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599




From wescpy at gmail.com  Thu Nov  8 20:52:45 2007
From: wescpy at gmail.com (wesley chun)
Date: Thu, 8 Nov 2007 11:52:45 -0800
Subject: [Tutor] New Introductory Book
In-Reply-To: <59f9c5160711080815j661e5dc2p15312042e45c749c@mail.gmail.com>
References: <18224.43390.384547.2507@euclid.slu.edu>
	<d9e88eaf0711061121l62a72665h251c7824643ce7c0@mail.gmail.com>
	<4731DC82.3060809@ntlworld.com>
	<78b3a9580711071547q66eb188h793a3f674b0520b7@mail.gmail.com>
	<4732F308.9070908@ntlworld.com>
	<59f9c5160711080608h12d35b0u7ebbe43f6ed1cd97@mail.gmail.com>
	<47331E4C.3050402@tds.net>
	<ea979d70711080813q1c165f1cya5b52131ea68d30e@mail.gmail.com>
	<59f9c5160711080815j661e5dc2p15312042e45c749c@mail.gmail.com>
Message-ID: <78b3a9580711081152h1358c4eau3af062807b2a6c03@mail.gmail.com>

> I wonder what schools offer python as a course.  Sadly all the
> colleges here offer only perl.

Danyelle's question brings up an issue i have, and that is that
courses in colleges are typically "computer science" courses, at least
at the university level.  there really aren't any "programming
language courses," or at least, not when i was in college.  a regular
CS course is where you learn the fundamentals but then implement your
projects/homework in a chosen language (or 2), such as Java and
Scheme.

courses that *do* teach specific languages are usually electives and
not part of the core curriculum. one of the best things about Python,
as you are all aware, is that it is so "diet," that students get to
focus on learning the key/core concepts of computer science without
getting bogged down by difficult syntax, data structure, or memory
mgmt issues.


On 11/8/07, bhaaluu <bhaaluu at gmail.com> wrote:
> Another way to judge how the book is, is by reading the posts the author
> sends to THIS list in order to help people. Mr. Chun and Mr. Gauld are
> two authors who provide help on this list. I certainly don't mind if they
> advertise their books on occassion -- they are also Tutors!



just my $0.02,
-- 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 wescpy at gmail.com  Thu Nov  8 20:55:43 2007
From: wescpy at gmail.com (wesley chun)
Date: Thu, 8 Nov 2007 11:55:43 -0800
Subject: [Tutor] New Introductory Book
In-Reply-To: <78b3a9580711081152h1358c4eau3af062807b2a6c03@mail.gmail.com>
References: <18224.43390.384547.2507@euclid.slu.edu>
	<d9e88eaf0711061121l62a72665h251c7824643ce7c0@mail.gmail.com>
	<4731DC82.3060809@ntlworld.com>
	<78b3a9580711071547q66eb188h793a3f674b0520b7@mail.gmail.com>
	<4732F308.9070908@ntlworld.com>
	<59f9c5160711080608h12d35b0u7ebbe43f6ed1cd97@mail.gmail.com>
	<47331E4C.3050402@tds.net>
	<ea979d70711080813q1c165f1cya5b52131ea68d30e@mail.gmail.com>
	<59f9c5160711080815j661e5dc2p15312042e45c749c@mail.gmail.com>
	<78b3a9580711081152h1358c4eau3af062807b2a6c03@mail.gmail.com>
Message-ID: <78b3a9580711081155g79dc9e89h566fc96adb1d54ad@mail.gmail.com>

apologies... meant to click the "save now" button but inadvertently
hit "send" instead...

> On 11/8/07, bhaaluu <bhaaluu at gmail.com> wrote:
> > Another way to judge how the book is, is by reading the posts the author
> > sends to THIS list in order to help people. Mr. Chun and Mr. Gauld are
> > two authors who provide help on this list. I certainly don't mind if they
> > advertise their books on occassion -- they are also Tutors!

nah... that's a conflict of interest... the book can sell itself.  :-)
 *but* it surely doesn't hurt to ask alan to update his book to a 2nd
ed!  ;) *nudge*

-wesley

From alan.gauld at btinternet.com  Thu Nov  8 23:19:59 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 8 Nov 2007 22:19:59 -0000
Subject: [Tutor] New Introductory Book
References: <18224.43390.384547.2507@euclid.slu.edu>	<d9e88eaf0711061121l62a72665h251c7824643ce7c0@mail.gmail.com>	<4731DC82.3060809@ntlworld.com>	<78b3a9580711071547q66eb188h793a3f674b0520b7@mail.gmail.com>	<4732F308.9070908@ntlworld.com>	<59f9c5160711080608h12d35b0u7ebbe43f6ed1cd97@mail.gmail.com>	<47331E4C.3050402@tds.net>	<ea979d70711080813q1c165f1cya5b52131ea68d30e@mail.gmail.com><59f9c5160711080815j661e5dc2p15312042e45c749c@mail.gmail.com>
	<473367EF.6010802@unc.edu>
Message-ID: <fh022o$7jt$1@ger.gmane.org>

"Chris Calloway" <cbc at unc.edu> wrote

> teach languages. Teaching languages is frowned upon in some computer
> science departments under the logic that if you belong in a computer
> science class, you'd better show up for class already knowing 
> something
> as easy to grasp as an implementation language.

I don't like CS courses to focus on a language either, but neither do 
I think
we should expect students to already know one. But learning a computer
language should be a trivial exercise once you understand the CS 
concepts
of algorithms and data and I/O etc.

One of the worst things I find as an employer is the number of CS
grads I get to interview who insist they only know one language. I 
wonder
what they learned at college. That's like an electronics engineer 
saying
he only knows how to solder, or a civil engineer who only knows how
to lay bricks! A CS course should concentrate on principles and
theory and learning languages should be a practical detail that the
student does almost by osmosis.

And this is, of course, why my tutorial teaches three languages
not just python ;-)

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




From christopher.henk at allisontransmission.com  Thu Nov  8 23:43:00 2007
From: christopher.henk at allisontransmission.com (christopher.henk at allisontransmission.com)
Date: Thu, 8 Nov 2007 17:43:00 -0500
Subject: [Tutor] New Introductory Book
In-Reply-To: <fh022o$7jt$1@ger.gmane.org>
Message-ID: <OFDAF87479.AB0F88F0-ON8525738D.007C033C-8525738D.007CC9AF@gm.com>

tutor-bounces at python.org wrote on 11/08/2007 05:19:59 PM:

> "Chris Calloway" <cbc at unc.edu> wrote
> 
> > teach languages. Teaching languages is frowned upon in some computer
> > science departments under the logic that if you belong in a computer
> > science class, you'd better show up for class already knowing 
> > something
> > as easy to grasp as an implementation language.
> 
> I don't like CS courses to focus on a language either, but neither do 
> I think
> we should expect students to already know one. But learning a computer
> language should be a trivial exercise once you understand the CS 
> concepts
> of algorithms and data and I/O etc.
> 
> One of the worst things I find as an employer is the number of CS
> grads I get to interview who insist they only know one language. I 
> wonder
> what they learned at college. That's like an electronics engineer 
> saying
> he only knows how to solder, or a civil engineer who only knows how
> to lay bricks! A CS course should concentrate on principles and
> theory and learning languages should be a practical detail that the
> student does almost by osmosis.
> 
> And this is, of course, why my tutorial teaches three languages
> not just python ;-)
> 
> -- 
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld

One of the worse things I found as a recent job hunter, was the number of 
employers who are not willing to accept that after completing a CS program 
that focuses on the science of CS, learning the language they are using is 
a trivial exercise.  On the plus side it helps identify the companies I 
didn't want to work for.

Chris Henk
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071108/dd609a42/attachment.htm 

From ladynikon at gmail.com  Fri Nov  9 00:01:32 2007
From: ladynikon at gmail.com (Danyelle Gragsone)
Date: Thu, 8 Nov 2007 18:01:32 -0500
Subject: [Tutor] New Introductory Book
In-Reply-To: <OFDAF87479.AB0F88F0-ON8525738D.007C033C-8525738D.007CC9AF@gm.com>
References: <fh022o$7jt$1@ger.gmane.org>
	<OFDAF87479.AB0F88F0-ON8525738D.007C033C-8525738D.007CC9AF@gm.com>
Message-ID: <59f9c5160711081501i75b696eem3b1922e311e5bef7@mail.gmail.com>

This is why I am going for programming instead of just CS. I am a very
hands on person.. although I know theory is good.. I just think it
needs to be evened out a bit :D.

From dineshbvadhia at hotmail.com  Fri Nov  9 00:56:06 2007
From: dineshbvadhia at hotmail.com (Dinesh B Vadhia)
Date: Thu, 8 Nov 2007 15:56:06 -0800
Subject: [Tutor] From Numpy Import *
References: <BAY109-DAV11A9CF74CD538300639683A38B0@phx.gbl>
	<18226.26708.59491.319828@euclid.slu.edu>
Message-ID: <BAY109-DAV13EE4C7452FE3C3895EAD0A38B0@phx.gbl>

Thank-you!  It is important for us to avoid potential code conflicts and so we'll standardize on the import <package name> syntax.

On a related note: 
We are using both NumPy and SciPy.  Consider the example y = Ax where A is a sparse matrix.  If A is qualified as a scipy object then do y and x also have to be scipy objects or can they be numpy objects?

Dinesh


----- Original Message ----- 
From: Michael H. Goldwasser 
To: Dinesh B Vadhia 
Cc: tutor at python.org 
Sent: Wednesday, November 07, 2007 5:37 PM
Subject: [Tutor] From Numpy Import *



On Wednesday November 7, 2007, Dinesh B Vadhia wrote: 

>    Hello!  The standard Python practice for importing modules is, for example:
>    
>    import sys
>    import os
>    etc.
>    
>    In NumPy (and SciPy) the 'book' suggests using:
>    
>    from numpy import *
>    from scipy import *
>    
>    However, when I instead use 'import numpy' it causes all sorts of errors in my existing code.

The issue is the following.  The numpy module includes many definitions, for
example a class named array.   When you use the syntax,

   from numpy import *

That takes all definitions from the module and places them into your
current namespace.  At this point, it would be fine to use a command
such as 

  values = array([1.0, 2.0, 3.0])

which instantiates a (numpy) array.


If you instead use the syntax

   import numpy

things brings that module as a whole into your namespace, but to
access definitions from that module you have to give a qualified
name, for example as

  values = numpy.array([1.0, 2.0, 3.0])

You cannot simply use the word array as in the first scenario.  This
would explain why your existing code would no longer work with the
change.

>    What do you suggest?

The advantage of the "from numpy import *" syntax is mostly
convenience.   However, the better style is "import numpy" precisely
becuase it does not automatically introduce many other definitions
into your current namespace.

If you were using some other package that also defined an "array" and
then you were to use the "from numpy import *", the new definition
would override the other definition.  The use of qualified names helps
to avoid these collisions and makes clear where those definitions are
coming from.

With regard,
Michael

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

From evert.rol at gmail.com  Fri Nov  9 10:10:46 2007
From: evert.rol at gmail.com (Evert Rol)
Date: Fri, 9 Nov 2007 09:10:46 +0000
Subject: [Tutor] From Numpy Import *
In-Reply-To: <BAY109-DAV13EE4C7452FE3C3895EAD0A38B0@phx.gbl>
References: <BAY109-DAV11A9CF74CD538300639683A38B0@phx.gbl>
	<18226.26708.59491.319828@euclid.slu.edu>
	<BAY109-DAV13EE4C7452FE3C3895EAD0A38B0@phx.gbl>
Message-ID: <E55B747B-6B17-49D9-A135-51A7562CCC84@gmail.com>

> Thank-you!  It is important for us to avoid potential code  
> conflicts and so we'll standardize on the import <package name>  
> syntax.
>
> On a related note:
> We are using both NumPy and SciPy.  Consider the example y = Ax  
> where A is a sparse matrix.  If A is qualified as a scipy object  
> then do y and x also have to be scipy objects or can they be numpy  
> objects?


scipy is mostly written with numpy as its core, so in general you  
should be able to use numpy objects with scipy objects (not sure, but  
I guess most scipy objects will have a numpy object as their base).
The best is simply to try it out! In this particular case, x can be a  
numpy array; y is created in the process, so will be the type of  
object most suited to the outcome of the equation (ie, you cannot  
state beforehand if it's a numpy or scipy object); in this case,  
again a numpy array.
See also the scipy tutorial on the scipy.org website, where numpy and  
scipy objects are freely mixed.


From wesbrooks at gmail.com  Fri Nov  9 12:02:56 2007
From: wesbrooks at gmail.com (Wesley Brooks)
Date: Fri, 9 Nov 2007 11:02:56 +0000
Subject: [Tutor] __doc__ strings for attributes?
Message-ID: <eec9f8ee0711090302h6d892cddtb1b46ba8179d585@mail.gmail.com>

Dear Users,

How can I add information to an object to explain what it expects as
it's attributes? For instance I may have an object that creates a CAD
file based on a set of default values which are set by the __init__
but can be altered before it runs. for example;

class MakeBasicShape:
    def __init__(self):
        self.boundsOptions = ['cuboid', 'cylinder', 'cad']
        self.boundsInfo = ['cuboid', [0.,10.,0.,10.,0.,10.]']

    def MakeIt(self):
        assert self.boundsInfo[0] in self.boundsOptions,
               "Option not recognised: %s", self.boundsInfo[0]
        if self.boundsInfo[0] == 'cuboid'
            bounds = self.boundsInfo[1]
            .... # code to make box
        elif self.boundsInfo[0] == 'cylinder'
            [height, radius, noSides] = self.boundsInfo[1]
            .... # code to make cylinder
        elif self.boundsInfo[0] == 'cad'
            fileName = self.boundsInfo[1]
            .... # code to load CAD file
        return shape


if __name__ == '__main__':
    shapeFactory0 = MakeBasicShape()
    shape0 = shapeFactory.MakeIt() # a box

    shapeFactory1 = MakeBasicShape()
    shapeFactory1.boundsInfo = ['cylinder' ,[20.,10.,36]]
    shape1 = shapeFactory.MakeIt() # a cylinder

    shapeFactory2 = MakeBasicShape()
    shapeFactory2.boundsInfo = ['cad' ,'/home/Wes/BigHand.stl']
    shape2 = shapeFactory.MakeIt() # a CAD file

While this example could be coded with different functions for making
a box, cylinder, and loading the CAD file I wanted to use attributes
to control the object to simplify interaction with it from the user
interface code. I would like to move away from getters and setters as
they're taking up vast chunks of my code at the moment and do very
little!

Can I also stop new attributes being added to the MakeBasicShape class?

Thanks in advance of any help.

Wesley Brooks

From evert.rol at gmail.com  Fri Nov  9 12:32:51 2007
From: evert.rol at gmail.com (Evert Rol)
Date: Fri, 9 Nov 2007 11:32:51 +0000
Subject: [Tutor] __doc__ strings for attributes?
In-Reply-To: <eec9f8ee0711090302h6d892cddtb1b46ba8179d585@mail.gmail.com>
References: <eec9f8ee0711090302h6d892cddtb1b46ba8179d585@mail.gmail.com>
Message-ID: <9D26CBB3-B16F-41BF-A6AD-2DD07BA3D367@gmail.com>

> How can I add information to an object to explain what it expects as
> it's attributes? For instance I may have an object that creates a CAD
> file based on a set of default values which are set by the __init__
> but can be altered before it runs. for example;

Why don't you specify a doc-string in your class declaration?

class MakeBasicShape:
     """basic information

     detailed information about attributes
     """


But, with what you do, why don't you add parameters to MakeIt()?

     def MakeIt(self, shape='cuboid', bounds=[0.,10.,0.,10.,0.,10.]):
         self.boundsInfo = [shape, bounds]


Or perhaps, let your class be the object you're creating (and rename  
it to 'BasicShape'; verbs in class names seem a bit odd to me)? The  
__init__ method would then fulfill the function of the MakeIt method,  
and things would become:
shape0 = BasicShape()
shape1 = BasicShape('cylinder', [20.,10.,36.])
etc.

That is, unless you're doing other things in your factory object that  
don't show up here.


>     def MakeIt(self):
>         assert self.boundsInfo[0] in self.boundsOptions,
>                "Option not recognised: %s", self.boundsInfo[0]

I also wouldn't use assert, but try: except:  in MakeIt() for example  
(assert is really for debugging, but here it looks more like you're  
trying to prevent user mistakes).


Anyway, hope that that gets you further.

   Evert


>         if self.boundsInfo[0] == 'cuboid'
>             bounds = self.boundsInfo[1]
>             .... # code to make box
>         elif self.boundsInfo[0] == 'cylinder'
>             [height, radius, noSides] = self.boundsInfo[1]
>             .... # code to make cylinder
>         elif self.boundsInfo[0] == 'cad'
>             fileName = self.boundsInfo[1]
>             .... # code to load CAD file
>         return shape
>
>
> if __name__ == '__main__':
>     shapeFactory0 = MakeBasicShape()
>     shape0 = shapeFactory.MakeIt() # a box
>
>     shapeFactory1 = MakeBasicShape()
>     shapeFactory1.boundsInfo = ['cylinder' ,[20.,10.,36]]
>     shape1 = shapeFactory.MakeIt() # a cylinder
>
>     shapeFactory2 = MakeBasicShape()
>     shapeFactory2.boundsInfo = ['cad' ,'/home/Wes/BigHand.stl']
>     shape2 = shapeFactory.MakeIt() # a CAD file
>
> While this example could be coded with different functions for making
> a box, cylinder, and loading the CAD file I wanted to use attributes
> to control the object to simplify interaction with it from the user
> interface code. I would like to move away from getters and setters as
> they're taking up vast chunks of my code at the moment and do very
> little!
>
> Can I also stop new attributes being added to the MakeBasicShape  
> class?
>
> Thanks in advance of any help.
>
> Wesley Brooks
>

From wesbrooks at gmail.com  Fri Nov  9 13:35:16 2007
From: wesbrooks at gmail.com (Wesley Brooks)
Date: Fri, 9 Nov 2007 12:35:16 +0000
Subject: [Tutor] __doc__ strings for attributes?
In-Reply-To: <9D26CBB3-B16F-41BF-A6AD-2DD07BA3D367@gmail.com>
References: <eec9f8ee0711090302h6d892cddtb1b46ba8179d585@mail.gmail.com>
	<9D26CBB3-B16F-41BF-A6AD-2DD07BA3D367@gmail.com>
Message-ID: <eec9f8ee0711090435p554f6b2aj4ac2605b726901c8@mail.gmail.com>

Thanks for the comments.

>shape0 = BasicShape()
>shape1 = BasicShape('cylinder', [20.,10.,36.])

I like this way of doing things, I could inherit the 3D data object's
class and get it to build on itself. I could for example use a
function definition like the following:

def __init__(*args, **paramDict):
    self.args = args
    self.xScanSpacing = paramDict['xScanSpacing']
    etc.

and I get a very flexible base to expand on. I do however get a real
problem when it comes to documenting the expected keywords and running
into huge doc strings, when I prefer concise documentation.

I like the following:

class a:
    def __init__(*args, **paramDict):
        expectedParam = ['xScanSpacing', 'yScanSpacing'....]
        paramDocDict = {'xScanSpacing': 'float mm spacing for x axis
hatches', ...}

To find out what parameters this object works with I could do;

>>> aa = a()
>>> aa.expectedParam
['xScanSpacing', 'yScanSpacing'....]
>>> aa.paramDocDict['xScanSpacing']
'float mm spacing for x axis hatches'

Is there an standard way of doing this?

This isn't as nice to use as the doc strings and dir function. For
example if I wanted to find out what I can do with a string I could
call dir(' ') on the interpreter and have a list of functions and
attributes contained in the string object. If I wanted a quick
explanation of one function I could run;

>>> print ' '.strip.__doc__
S.strip([chars]) -> string or unicode

Return a copy of the string S with leading and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping
>>>

Cheers,

Wesley Brooks.

On 09/11/2007, Evert Rol <evert.rol at gmail.com> wrote:
> > How can I add information to an object to explain what it expects as
> > it's attributes? For instance I may have an object that creates a CAD
> > file based on a set of default values which are set by the __init__
> > but can be altered before it runs. for example;
>
> Why don't you specify a doc-string in your class declaration?
>
> class MakeBasicShape:
>      """basic information
>
>      detailed information about attributes
>      """
>
>
> But, with what you do, why don't you add parameters to MakeIt()?
>
>      def MakeIt(self, shape='cuboid', bounds=[0.,10.,0.,10.,0.,10.]):
>          self.boundsInfo = [shape, bounds]
>
>
> Or perhaps, let your class be the object you're creating (and rename
> it to 'BasicShape'; verbs in class names seem a bit odd to me)? The
> __init__ method would then fulfill the function of the MakeIt method,
> and things would become:
> shape0 = BasicShape()
> shape1 = BasicShape('cylinder', [20.,10.,36.])
> etc.
>
> That is, unless you're doing other things in your factory object that
> don't show up here.
>
>
> >     def MakeIt(self):
> >         assert self.boundsInfo[0] in self.boundsOptions,
> >                "Option not recognised: %s", self.boundsInfo[0]
>
> I also wouldn't use assert, but try: except:  in MakeIt() for example
> (assert is really for debugging, but here it looks more like you're
> trying to prevent user mistakes).
>
>
> Anyway, hope that that gets you further.
>
>    Evert
>
>
> >         if self.boundsInfo[0] == 'cuboid'
> >             bounds = self.boundsInfo[1]
> >             .... # code to make box
> >         elif self.boundsInfo[0] == 'cylinder'
> >             [height, radius, noSides] = self.boundsInfo[1]
> >             .... # code to make cylinder
> >         elif self.boundsInfo[0] == 'cad'
> >             fileName = self.boundsInfo[1]
> >             .... # code to load CAD file
> >         return shape
> >
> >
> > if __name__ == '__main__':
> >     shapeFactory0 = MakeBasicShape()
> >     shape0 = shapeFactory.MakeIt() # a box
> >
> >     shapeFactory1 = MakeBasicShape()
> >     shapeFactory1.boundsInfo = ['cylinder' ,[20.,10.,36]]
> >     shape1 = shapeFactory.MakeIt() # a cylinder
> >
> >     shapeFactory2 = MakeBasicShape()
> >     shapeFactory2.boundsInfo = ['cad' ,'/home/Wes/BigHand.stl']
> >     shape2 = shapeFactory.MakeIt() # a CAD file
> >
> > While this example could be coded with different functions for making
> > a box, cylinder, and loading the CAD file I wanted to use attributes
> > to control the object to simplify interaction with it from the user
> > interface code. I would like to move away from getters and setters as
> > they're taking up vast chunks of my code at the moment and do very
> > little!
> >
> > Can I also stop new attributes being added to the MakeBasicShape
> > class?
> >
> > Thanks in advance of any help.
> >
> > Wesley Brooks
> >
>

From kent37 at tds.net  Fri Nov  9 13:57:46 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 09 Nov 2007 07:57:46 -0500
Subject: [Tutor] __doc__ strings for attributes?
In-Reply-To: <eec9f8ee0711090302h6d892cddtb1b46ba8179d585@mail.gmail.com>
References: <eec9f8ee0711090302h6d892cddtb1b46ba8179d585@mail.gmail.com>
Message-ID: <4734594A.3070401@tds.net>

Wesley Brooks wrote:
> Dear Users,
> 
> How can I add information to an object to explain what it expects as
> it's attributes? For instance I may have an object that creates a CAD
> file based on a set of default values which are set by the __init__
> but can be altered before it runs. for example;
> 
> class MakeBasicShape:
>     def __init__(self):
>         self.boundsOptions = ['cuboid', 'cylinder', 'cad']
>         self.boundsInfo = ['cuboid', [0.,10.,0.,10.,0.,10.]']
> 
>     def MakeIt(self):
>         assert self.boundsInfo[0] in self.boundsOptions,
>                "Option not recognised: %s", self.boundsInfo[0]
>         if self.boundsInfo[0] == 'cuboid'
>             bounds = self.boundsInfo[1]
>             .... # code to make box
>         elif self.boundsInfo[0] == 'cylinder'
>             [height, radius, noSides] = self.boundsInfo[1]
>             .... # code to make cylinder
>         elif self.boundsInfo[0] == 'cad'
>             fileName = self.boundsInfo[1]
>             .... # code to load CAD file
>         return shape

I would write this as a factory function and use a dict as a lookup 
table to get the correct class to return:

assuming:
class Cuboid(object):
   # etc...

_makers = dict(cuboid=Cuboid, cylinder=Cylinder, cad=Cad)

def makeBasicShape(shape='cuboid', bounds=[0.,10.,0.,10.,0.,10.]):
   try:
     maker = _makers[shape]
   except KeyError:
     # Code to handle invalid shape option
   else:
     return maker(*bounds)

Kent

> 
> 
> if __name__ == '__main__':
>     shapeFactory0 = MakeBasicShape()
>     shape0 = shapeFactory.MakeIt() # a box
> 
>     shapeFactory1 = MakeBasicShape()
>     shapeFactory1.boundsInfo = ['cylinder' ,[20.,10.,36]]
>     shape1 = shapeFactory.MakeIt() # a cylinder
> 
>     shapeFactory2 = MakeBasicShape()
>     shapeFactory2.boundsInfo = ['cad' ,'/home/Wes/BigHand.stl']
>     shape2 = shapeFactory.MakeIt() # a CAD file
> 
> While this example could be coded with different functions for making
> a box, cylinder, and loading the CAD file I wanted to use attributes
> to control the object to simplify interaction with it from the user
> interface code. I would like to move away from getters and setters as
> they're taking up vast chunks of my code at the moment and do very
> little!

Simple getters and setters are not needed in Python. The flexibility 
they give in Java and C++ is provided by Python properties.

> Can I also stop new attributes being added to the MakeBasicShape class?

Yes, but it is rarely worth the trouble; Python culture tends to a 
philosophy of "we're all adults here" and doesn't try too hard to 
prevent programmers from shooting themselves in the foot.

The preferred way to do this IIRC is to define __setattr__ on your class 
and check for valid attribute names.

Kent

From kent37 at tds.net  Fri Nov  9 14:02:49 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 09 Nov 2007 08:02:49 -0500
Subject: [Tutor] __doc__ strings for attributes?
In-Reply-To: <eec9f8ee0711090435p554f6b2aj4ac2605b726901c8@mail.gmail.com>
References: <eec9f8ee0711090302h6d892cddtb1b46ba8179d585@mail.gmail.com>	<9D26CBB3-B16F-41BF-A6AD-2DD07BA3D367@gmail.com>
	<eec9f8ee0711090435p554f6b2aj4ac2605b726901c8@mail.gmail.com>
Message-ID: <47345A79.5080600@tds.net>

Wesley Brooks wrote:

> I do however get a real
> problem when it comes to documenting the expected keywords and running
> into huge doc strings, when I prefer concise documentation.

> Is there an standard way of doing this?

docstrings are the only standard way to document classes and functions. 
Here is an example of long docstrings with lots of potential keyword args:
http://matplotlib.sourceforge.net/matplotlib.axes.html

Kent




From evert.rol at gmail.com  Fri Nov  9 14:21:21 2007
From: evert.rol at gmail.com (Evert Rol)
Date: Fri, 9 Nov 2007 13:21:21 +0000
Subject: [Tutor] __doc__ strings for attributes?
In-Reply-To: <eec9f8ee0711090435p554f6b2aj4ac2605b726901c8@mail.gmail.com>
References: <eec9f8ee0711090302h6d892cddtb1b46ba8179d585@mail.gmail.com>
	<9D26CBB3-B16F-41BF-A6AD-2DD07BA3D367@gmail.com>
	<eec9f8ee0711090435p554f6b2aj4ac2605b726901c8@mail.gmail.com>
Message-ID: <DA241364-CECA-418D-9F9C-5A37FCCB2A9C@gmail.com>

> Thanks for the comments.
>
>> shape0 = BasicShape()
>> shape1 = BasicShape('cylinder', [20.,10.,36.])
>
> I like this way of doing things, I could inherit the 3D data object's
> class and get it to build on itself. I could for example use a
> function definition like the following:
>
> def __init__(*args, **paramDict):
>     self.args = args
>     self.xScanSpacing = paramDict['xScanSpacing']
>     etc.

Careful; your 'self' argument is here included in *args. You'll want  
__init__(self, *args, ...)


> and I get a very flexible base to expand on. I do however get a real
> problem when it comes to documenting the expected keywords and running
> into huge doc strings, when I prefer concise documentation.
>
> I like the following:
>
> class a:
>     def __init__(*args, **paramDict):
>         expectedParam = ['xScanSpacing', 'yScanSpacing'....]
>         paramDocDict = {'xScanSpacing': 'float mm spacing for x axis
> hatches', ...}
>
> To find out what parameters this object works with I could do;
>
>>>> aa = a()
>>>> aa.expectedParam
> ['xScanSpacing', 'yScanSpacing'....]
>>>> aa.paramDocDict['xScanSpacing']
> 'float mm spacing for x axis hatches'
>
> Is there an standard way of doing this?

In line with Kent's remark, I think you'll need doc strings. It's the  
whole point of documentation probably. And if you use the class often  
enough, you'll know the defaults and meaning of parameters anyway; no  
quick lookup needed (after all, here you need to first obtain an  
object from your class, then get the keyword names, before you can  
ask for the actual specifics; by that time, a 'help' on the class  
will have given you the information needed.)

Btw, consider using the help function instead of print the doc string  
(function/method/class.__doc__) additionally gives you the function  
declaration, as long as it's a Python-written function. Ie, you'll  
directly see the required parameters (in won't work for builtin  
functions like map, or the string-strip as below, but will work for  
home-written stuff).
It also gives you a lot more information in general. Compare help 
(dict) versus print dict.__doc__



> This isn't as nice to use as the doc strings and dir function. For
> example if I wanted to find out what I can do with a string I could
> call dir(' ') on the interpreter and have a list of functions and
> attributes contained in the string object. If I wanted a quick
> explanation of one function I could run;
>
>>>> print ' '.strip.__doc__
> S.strip([chars]) -> string or unicode
>
> Return a copy of the string S with leading and trailing
> whitespace removed.
> If chars is given and not None, remove characters in chars instead.
> If chars is unicode, S will be converted to unicode before stripping
>>>>
>
> Cheers,
>
> Wesley Brooks.
>
> On 09/11/2007, Evert Rol <evert.rol at gmail.com> wrote:
>>> How can I add information to an object to explain what it expects as
>>> it's attributes? For instance I may have an object that creates a  
>>> CAD
>>> file based on a set of default values which are set by the __init__
>>> but can be altered before it runs. for example;
>>
>> Why don't you specify a doc-string in your class declaration?
>>
>> class MakeBasicShape:
>>      """basic information
>>
>>      detailed information about attributes
>>      """
>>
>>
>> But, with what you do, why don't you add parameters to MakeIt()?
>>
>>      def MakeIt(self, shape='cuboid', bounds=[0.,10.,0.,10.,0.,10.]):
>>          self.boundsInfo = [shape, bounds]
>>
>>
>> Or perhaps, let your class be the object you're creating (and rename
>> it to 'BasicShape'; verbs in class names seem a bit odd to me)? The
>> __init__ method would then fulfill the function of the MakeIt method,
>> and things would become:
>> shape0 = BasicShape()
>> shape1 = BasicShape('cylinder', [20.,10.,36.])
>> etc.
>>
>> That is, unless you're doing other things in your factory object that
>> don't show up here.
>>
>>
>>>     def MakeIt(self):
>>>         assert self.boundsInfo[0] in self.boundsOptions,
>>>                "Option not recognised: %s", self.boundsInfo[0]
>>
>> I also wouldn't use assert, but try: except:  in MakeIt() for example
>> (assert is really for debugging, but here it looks more like you're
>> trying to prevent user mistakes).
>>
>>
>> Anyway, hope that that gets you further.
>>
>>    Evert
>>
>>
>>>         if self.boundsInfo[0] == 'cuboid'
>>>             bounds = self.boundsInfo[1]
>>>             .... # code to make box
>>>         elif self.boundsInfo[0] == 'cylinder'
>>>             [height, radius, noSides] = self.boundsInfo[1]
>>>             .... # code to make cylinder
>>>         elif self.boundsInfo[0] == 'cad'
>>>             fileName = self.boundsInfo[1]
>>>             .... # code to load CAD file
>>>         return shape
>>>
>>>
>>> if __name__ == '__main__':
>>>     shapeFactory0 = MakeBasicShape()
>>>     shape0 = shapeFactory.MakeIt() # a box
>>>
>>>     shapeFactory1 = MakeBasicShape()
>>>     shapeFactory1.boundsInfo = ['cylinder' ,[20.,10.,36]]
>>>     shape1 = shapeFactory.MakeIt() # a cylinder
>>>
>>>     shapeFactory2 = MakeBasicShape()
>>>     shapeFactory2.boundsInfo = ['cad' ,'/home/Wes/BigHand.stl']
>>>     shape2 = shapeFactory.MakeIt() # a CAD file
>>>
>>> While this example could be coded with different functions for  
>>> making
>>> a box, cylinder, and loading the CAD file I wanted to use attributes
>>> to control the object to simplify interaction with it from the user
>>> interface code. I would like to move away from getters and  
>>> setters as
>>> they're taking up vast chunks of my code at the moment and do very
>>> little!
>>>
>>> Can I also stop new attributes being added to the MakeBasicShape
>>> class?
>>>
>>> Thanks in advance of any help.
>>>
>>> Wesley Brooks
>>>
>>


From chernevik at gmail.com  Fri Nov  9 15:48:01 2007
From: chernevik at gmail.com (Chernev Chernev)
Date: Fri, 9 Nov 2007 09:48:01 -0500
Subject: [Tutor] Type() Getting Type Error
Message-ID: <6ff879a00711090648m4ef82f30i1e7c67b2ae111a51@mail.gmail.com>

I'm debugging a script and want to check the type of an object.

So in the script I write:
print type([object]

This bombs, and I get
"TypeError: 'str' object is not callable'

I've also tried
x = type([object])
print x

Same thing.

In the interactive, 'type([object])' works fine.

What am I missing here?

From kent37 at tds.net  Fri Nov  9 16:09:03 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 09 Nov 2007 10:09:03 -0500
Subject: [Tutor] Type() Getting Type Error
In-Reply-To: <6ff879a00711090648m4ef82f30i1e7c67b2ae111a51@mail.gmail.com>
References: <6ff879a00711090648m4ef82f30i1e7c67b2ae111a51@mail.gmail.com>
Message-ID: <4734780F.2040600@tds.net>

Chernev Chernev wrote:
> I'm debugging a script and want to check the type of an object.
> 
> So in the script I write:
> print type([object]
> 
> This bombs, and I get
> "TypeError: 'str' object is not callable'
> 
> What am I missing here?

Probably you have a variable named 'type' in your script that is hiding 
the builtin 'type' object.

Kent

From evert.rol at gmail.com  Fri Nov  9 16:10:35 2007
From: evert.rol at gmail.com (Evert Rol)
Date: Fri, 9 Nov 2007 15:10:35 +0000
Subject: [Tutor] Type() Getting Type Error
In-Reply-To: <6ff879a00711090648m4ef82f30i1e7c67b2ae111a51@mail.gmail.com>
References: <6ff879a00711090648m4ef82f30i1e7c67b2ae111a51@mail.gmail.com>
Message-ID: <871FF0DC-1113-4AB5-B9CE-E9F61E7C6F41@gmail.com>


On 9 Nov 2007, at 14:48 , Chernev Chernev wrote:

> I'm debugging a script and want to check the type of an object.
>
> So in the script I write:
> print type([object]
>
> This bombs, and I get
> "TypeError: 'str' object is not callable'
>
> I've also tried
> x = type([object])
> print x
>
> Same thing.

Works fine for me for both cases. What version of Python are you  
running? Both 2.5 and 2.3 seem to work for me (on Mac OS X).

Is there anything else in your script that can cause this error?


>
> In the interactive, 'type([object])' works fine.
>
> What am I missing here?
>

From chernevik at gmail.com  Fri Nov  9 16:17:05 2007
From: chernevik at gmail.com (Chernev Chernev)
Date: Fri, 9 Nov 2007 10:17:05 -0500
Subject: [Tutor] Type() Getting Type Error
In-Reply-To: <4734780F.2040600@tds.net>
References: <6ff879a00711090648m4ef82f30i1e7c67b2ae111a51@mail.gmail.com>
	<4734780F.2040600@tds.net>
Message-ID: <6ff879a00711090717m4c6212f9me18bd429df95fc81@mail.gmail.com>

On Nov 9, 2007 10:09 AM, Kent Johnson <kent37 at tds.net> wrote:
> > So in the script I write:
> > print type([object]
> >
> > This bombs, and I get
> > "TypeError: 'str' object is not callable'
> >
> Probably you have a variable named 'type' in your script that is hiding
> the builtin 'type' object.

Just so.  I renamed that variable and the script ran fine.

Thank you, and thanks to everyone who looked at this.

From bhaaluu at gmail.com  Fri Nov  9 16:51:42 2007
From: bhaaluu at gmail.com (bhaaluu)
Date: Fri, 9 Nov 2007 10:51:42 -0500
Subject: [Tutor] New Introductory Book
In-Reply-To: <59f9c5160711081501i75b696eem3b1922e311e5bef7@mail.gmail.com>
References: <fh022o$7jt$1@ger.gmane.org>
	<OFDAF87479.AB0F88F0-ON8525738D.007C033C-8525738D.007CC9AF@gm.com>
	<59f9c5160711081501i75b696eem3b1922e311e5bef7@mail.gmail.com>
Message-ID: <ea979d70711090751n7954d564x7471c3dec80cc5b2@mail.gmail.com>

Algorithm Education in Python
http://www.ece.uci.edu/~chou/py02/python.html

This article from Pai H. Chou at University of California, Irvine
shows how well the Python programming language maps itself
to the pseudocode used in _Introduction to Algorithms Second Editon_
[Corman, Leiserson, Rivest, Stein. 2001. McGraw-Hill. ISBN 0262032937].

Excerpt from the article:
<quote>
7. Conclusions and Future Educational Plans
This paper reports our use of Python in an algorithms course in the
past two years. As an
algorithm-oriented language, Python enables our students to learn key
concepts in algorithm
design, instead of struggling with low-level, idiosyncratic features
of conventional programming
languages. The way Python handles data types represents a perfect
match with the way
textbooks present algorithms, and its interpretive nature encourages
students to experiment
with the language.
</quote>

I have a copy of Corman, and it really is amazing how "Python" all the
pseudocode is!

On Nov 8, 2007 6:01 PM, Danyelle Gragsone <ladynikon at gmail.com> wrote:
> This is why I am going for programming instead of just CS. I am a very
> hands on person.. although I know theory is good.. I just think it
> needs to be evened out a bit :D.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

-- 
b h a a l u u at g m a i l dot c o m
http://www.geocities.com/ek.bhaaluu/python/index.html

From alan.gauld at btinternet.com  Fri Nov  9 22:42:53 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 9 Nov 2007 21:42:53 -0000
Subject: [Tutor] Type() Getting Type Error
References: <6ff879a00711090648m4ef82f30i1e7c67b2ae111a51@mail.gmail.com>
Message-ID: <fh2k94$b4t$1@ger.gmane.org>


"Chernev Chernev" <chernevik at gmail.com> wrote

> So in the script I write:
> print type([object]
> 
> This bombs, and I get
> "TypeError: 'str' object is not callable'

> In the interactive, 'type([object])' works fine.

Looks like you have defined type as a local variable 
somewhere in your script and this is masking the 
type() function.

HTH,


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


From ricaraoz at gmail.com  Thu Nov  8 13:34:48 2007
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Thu, 08 Nov 2007 09:34:48 -0300
Subject: [Tutor] manipulating data
In-Reply-To: <4731C327.6000704@tds.net>
References: <fbf64d2b0711061154v4f6547bcx133c342f2d5aac27@mail.gmail.com>
	<4731C327.6000704@tds.net>
Message-ID: <47330268.1080304@bigfoot.com>

Kent Johnson wrote:
> Bryan Fodness wrote:
>> I would like to have my data in a format so that I can create a contour plot.
>>
>> My data is in a file with a format, where there may be multiple fields
>>
>> field = 1
>>
>> 1a	0
> 
> If your data is really this regular, it is pretty easy to parse. A 
> useful technique is to access a file's next method directly. Something 
> like this (not tested!):
> 
> f = open('data.txt')
> fields = {} # build a dict of fields
> try:
>    while True:
>      # Get the field line
>      line = f.next()
>      field = int(line.split()[-1]) # last part of the line as an int
> 
>      f.next() # skip blank line
> 
>      data = {} # for each field, map (row, col) to value
>      for i in range(20): # read 20 data lines
>        line = f.next()
>        ix, value = f.split()
>        row = int(ix[:-1])
>        col = ix[-1]
>        data[row, col] = int(value)
> 
>      fields[field] = data
> 
>      f.next()
> except StopIteration:
>    pass
> 

Or maybe just (untested) :

fields = {} # build a dict of fields
for line in open('data.txt') :
    if line :    # skip blank lines
	if line.split()[0] = 'field' :
            field = int(line.split()[-1])
        else :
            fields[field] = tuple(line.split())





From ricaraoz at gmail.com  Thu Nov  8 13:44:28 2007
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Thu, 08 Nov 2007 09:44:28 -0300
Subject: [Tutor] In-place expansion of list members... possible?
In-Reply-To: <473222EE.3020803@tds.net>
References: <40af687b0711071208wcfb83daia507a30cc62ec009@mail.gmail.com>
	<473222EE.3020803@tds.net>
Message-ID: <473304AC.5050709@bigfoot.com>

Kent Johnson wrote:
> Marc Tompkins wrote:
>> I'm working with delimited files (ANSI X12 EDI nonsense, to be 
>> precise.)  First I load the records to a list:
>>         tmpSegs = inString.split(self.SegTerm)
>>
>> Now, I want to replace each string in that list with a string:
>>
>>         for seg in tmpSegs:       # 'seg' is short for 'segment'
>>             seg = seg.split(self.ElemSep)
>>
>> It doesn't work.  If I check the contents of tmpSegs, it's still a list 
>> of strings - not a list of lists.  So I do this instead:
>>         tmpSegs2 = []
>>         for seg in tmpSegs:
>>             tmpSegs2.append(seg.split(self.sElemSep))
>>         del tmpSegs
>>
>> This works.  And, for the size of files that I'm likely to run into, 
>> creating the extra list and burning the old one is probably not going to 
>> swamp the machine - but it feels clumsy to me, like if I just knew the 
>> secret I could be much more elegant about it.
> 
> Creating a new list is fine, actually. You can do it more elegantly with 
> a list comprehension, and it's fine to assign to the same name, which 
> will implicitly delete the old list:
> tmpSegs = [ seg.split(self.ElemSep) for seg in tmpSegs ]
> 
> If you really want to replace elements in the same list you can use 
> enumerate to get indices:
> 
> for i, seg in enumerate(tmpSegs):
>    tmpSegs[i] = seg.split(self.ElemSep)
> 
> or use slice assignment:
> tmpSegs[:] = [ seg.split(self.ElemSep) for seg in tmpSegs ]

Won't the slice assignment create a new list and then assign it to the
old list (which the OP is trying to avoid)?


From sith618 at yahoo.com  Sat Nov 10 02:53:53 2007
From: sith618 at yahoo.com (sith .)
Date: Fri, 9 Nov 2007 17:53:53 -0800 (PST)
Subject: [Tutor] parsing an array
Message-ID: <484769.64736.qm@web33201.mail.mud.yahoo.com>

newfile = open('y.txt')
  >>> for line in newfile:
  ...  print line.rstrip()
  
3 5 7
  11 8 10
   
  Hi,
I'm trying to parse an array.  Now that I can open and read lines in my array, how can I access individual elements of my multidimensional array?  I'd like to loop through the array and compare values in each line.  
If w is the array, if w[0][1]<w[0][2], write w[0][0] to w[0][3]
Numpy?  Thanks.

 __________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071109/5216dfc8/attachment.htm 

From trey at opmstech.org  Sat Nov 10 02:58:24 2007
From: trey at opmstech.org (Trey Keown)
Date: Fri, 9 Nov 2007 19:58:24 -0600 (CST)
Subject: [Tutor] Calling a function within a function within a class...
Message-ID: <61087.68.191.136.241.1194659904.squirrel@webmail.opmstech.org>

Hey all...
I'm creating a module for my program, and I need to call a function.
Here's how it's set up:
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
class DoStuff:
    def Thing1(self):
        def ThingToCall(self):
            print "It worked!"
    def Thing2(self):
        #Call the function "ThingToCall" here.
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Thanks for any help. I haven't used classes that much before...


From brunson at brunson.com  Sat Nov 10 03:43:20 2007
From: brunson at brunson.com (Eric Brunson)
Date: Fri, 09 Nov 2007 19:43:20 -0700
Subject: [Tutor] Calling a function within a function within a class...
In-Reply-To: <61087.68.191.136.241.1194659904.squirrel@webmail.opmstech.org>
References: <61087.68.191.136.241.1194659904.squirrel@webmail.opmstech.org>
Message-ID: <47351AC8.303@brunson.com>

Trey Keown wrote:
> Hey all...
> I'm creating a module for my program, and I need to call a function.
> Here's how it's set up:
> -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
> class DoStuff:
>     def Thing1(self):
>         def ThingToCall(self):
>             print "It worked!"
>     def Thing2(self):
>         #Call the function "ThingToCall" here.
> -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
> Thanks for any help. I haven't used classes that much before...
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   

Unless someone knows something very clever, I don't think you can.  One 
of the few reasons to declare a function like that is to make the scope 
local to Thing1() so you can pretty much expressly *not* call it from 
outside that scope.  If you don't have a good reason for declaring the 
function in that manner, you shouldn't, especially if you have a need to 
call externally from enclosing scope.

The obvious question is, why would you do that?  :-)

e.


From orsenthil at gmail.com  Sat Nov 10 04:08:49 2007
From: orsenthil at gmail.com (O.R.Senthil Kumaran)
Date: Sat, 10 Nov 2007 08:38:49 +0530
Subject: [Tutor] parsing an array
In-Reply-To: <484769.64736.qm@web33201.mail.mud.yahoo.com>
References: <484769.64736.qm@web33201.mail.mud.yahoo.com>
Message-ID: <20071110030848.GA3583@gmail.com>

* sith . <sith618 at yahoo.com> [2007-11-09 17:53:53]:

> newfile = open('y.txt')
>   >>> for line in newfile:
>   ...  print line.rstrip()
>   
> 3 5 7
>   11 8 10

This example is different from a array handling one. This is a file handle with with reading the contents of the file through a loop.

>    
>   Hi,
> I'm trying to parse an array.  Now that I can open and read lines in my array, how can I access individual elements of my multidimensional array?  I'd like to loop through the array and compare values in each line.  
> If w is the array, if w[0][1]<w[0][2], write w[0][0] to w[0][3]
> Numpy?  Thanks.

You dont require Numpy for a simple task as this.
Suppose your array is:

a = [[0,1,2,3,4,5],[1,2,3,4,5,6]]

You cannot modify the same array when you are looping through it. You have to loop through the copy of the contents :- a[:].

# Untested code

for i in a[:]: # You are looping through the copy of contents
   for j in i:
       # implement your logic with j
       if j < i[0]: # or any dynamic conditional check.
	  a[i][j] = j


Does this help you?

Thanks,

-- 
O.R.Senthil Kumaran
http://uthcode.sarovar.org

From aditya.n.lal at gmail.com  Fri Nov  9 19:24:14 2007
From: aditya.n.lal at gmail.com (Aditya Lal)
Date: Fri, 9 Nov 2007 23:54:14 +0530
Subject: [Tutor] Swapping variables ...
Message-ID: <5df213700711091024l325d019bq636ed056ad201d99@mail.gmail.com>

 After quizzing newbies in C on swapping without 3rd variable, I found this
to be really *cool* construct to swap :)
x = 10
y = 20
x,y = y,x

--
Aditya
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071109/2ebdeb42/attachment.htm 

From orsenthil at gmail.com  Sat Nov 10 04:30:47 2007
From: orsenthil at gmail.com (O.R.Senthil Kumaran)
Date: Sat, 10 Nov 2007 09:00:47 +0530
Subject: [Tutor] *args, **kargs as arguments
Message-ID: <20071110033047.GB3583@gmail.com>

I know it can be a FAQ, but still I want ask to clarify my doubts and
assumptions.

I find usually in derived classes, a construct like this:

class Derived(BaseClass):
	def __init__(self, *args, **kargs):
		BaseClass.__init__(self, *args, **kargs)


- *args, **kargs passes a tuple and a dictionary to the BaseClass constructor.

My assumption is the BaseClass will always have a constructor that will
be receiving the tuple and a dictionary. Am I right?

Something of the sort.

class BaseClass:
	def __init__(self, atuple, adict):

I also found a construct something like this:

class URLopener:
	def __init__(self, proxies=None, **x509):

This is specifically from urllib.py where my doubts stem from.
Is the above construct still receiving a tuple and a dictionary?


Another doubt is, if we are not explicitly passing a dictionary, and the
dictionary is not a default argument, then is the dictionary values being passed through the namespace? 

I am scanning through the urllib.py code to understand the urlopen method and I am having the above doubts when trying to understand it. Please help.

Thank you.
-- 
O.R.Senthil Kumaran
http://uthcode.sarovar.org

From kent37 at tds.net  Sat Nov 10 05:43:10 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 09 Nov 2007 23:43:10 -0500
Subject: [Tutor] In-place expansion of list members... possible?
In-Reply-To: <473304AC.5050709@bigfoot.com>
References: <40af687b0711071208wcfb83daia507a30cc62ec009@mail.gmail.com>
	<473222EE.3020803@tds.net> <473304AC.5050709@bigfoot.com>
Message-ID: <473536DE.8090304@tds.net>

Ricardo Ar?oz wrote:
> Kent Johnson wrote:
>> or use slice assignment:
>> tmpSegs[:] = [ seg.split(self.ElemSep) for seg in tmpSegs ]
> 
> Won't the slice assignment create a new list and then assign it to the
> old list (which the OP is trying to avoid)?

Yes, it will, thanks! You can assign a generator expression to the list:
tmpSegs[:] = ( seg.split(self.ElemSep) for seg in tmpSegs )

I don't know if that creates a temp list or assigns directly into the 
old list though. At the byte-code level at least it seems to assign the 
iterator to the slice.

Kent

From wescpy at gmail.com  Sat Nov 10 06:16:04 2007
From: wescpy at gmail.com (wesley chun)
Date: Fri, 9 Nov 2007 21:16:04 -0800
Subject: [Tutor] *args, **kargs as arguments
In-Reply-To: <20071110033047.GB3583@gmail.com>
References: <20071110033047.GB3583@gmail.com>
Message-ID: <78b3a9580711092116v1d54f7bcod06264de8a96207c@mail.gmail.com>

hi, and welcome to Python!!

> class Derived(BaseClass):
>         def __init__(self, *args, **kargs):
>                 BaseClass.__init__(self, *args, **kargs)
>
> - *args, **kargs passes a tuple and a dictionary to the BaseClass constructor.
>
> My assumption is the BaseClass will always have a constructor that will
> be receiving the tuple and a dictionary. Am I right?

not quite.  you're on the right track though. a couple of thoughts.
let's take this question outside of classes for a moment.

1. you are not "receiving" a tuple or dict. rather, any variables
(non-keyworded and keyworded) will be passed to those designated
variables if there are no direct variables corresponding to those
parameters. let's talk about the '*' for a moment.  when placed in a
function signature, it means to accept a variable number of arguments.
 for example:

def foo(x, *rest):
     pass

you can call foo() with one argument only, i.e., foo(123), foo('xxx'),
etc.  but you can also call this argument with any number of
parameters, i.e., foo(123, 'xyz'), foo(3.14, 'xyz', 123), etc.  the
1st argument will be assigned to 'x' while the "rest" of the arguments
get put into the tuple 'rest':  x = 3.14 and rest = ('xyz', 123). if
only 'x' is passed in, the 'rest' is an empty tuple. this differs
from:

def foo(*all):
    pass

in the earlier example, 'x' is required.  in this example, no
parameters are required. foo() is just as good as foo(123), foo(123,
'xyz'), etc.

2. this is not a question you asked, but sometimes people get confused
when '*' is used in function *calls* (vs. signatures as in the above).
when you define a function like this:

def foo(x, y, z):
    pass

you must call foo() with 3 parameters, i.e., foo(12, 'abc', 3.14).
one use of the "*" is to designate its members as parameters to the
called function. the use case comes up when you have a list, say t =
[12, 'abc', 3.14].  to call the function, you would have to do this:
foo(t[0], t[1], t[2]).

now, intuitively, you would naturally ask the question, "can i pass in
the entire list such that all of its elements are assigned to the
individual parameters?"  the answer is "YES:" foo(*t) does the same
thing, but is easier on the programmer, yet does not make the code
significantly more complicated

3. the same arguments above apply to '**', dictionaries, and keyworded
arguments like, foo=123.

4. also not 100%-related to your question:  __init__() is not really a
"constructor" in the true sense.  in Python, the *interpreter* creates
the instance object *for* you, one of the reasons why there is no
"new" keyword.  __init__() is the 1st method that the interpreter
calls after it creates the instance for you.  when you instantiate a
class, you call the class as if it were a function, i.e., Derived().
in the example above with __init__(self, *t, **d), this just means
that this function can take any number of both keyworded or
non-keyworded parameters.

> class BaseClass:
>         def __init__(self, atuple, adict):

this signature differs from __init__(self, *atuple, **adict) because
the former takes exactly 2 arguments (in addition to 'self') while
this latter one can take any number of arguments.

> I also found a construct something like this:
>
> class URLopener:
>         def __init__(self, proxies=None, **x509):

this function potentially takes a single object (assigned to proxies)
and any number of keyworded arguments (which go into the 'x509' dict).

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 alan.gauld at btinternet.com  Sat Nov 10 10:17:05 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 10 Nov 2007 09:17:05 -0000
Subject: [Tutor] Calling a function within a function within a class...
References: <61087.68.191.136.241.1194659904.squirrel@webmail.opmstech.org>
Message-ID: <fh3suo$1pg$1@ger.gmane.org>

"Trey Keown" <trey at opmstech.org> wrote

> I'm creating a module for my program, and I need to call a function.
> Here's how it's set up:
> -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
> class DoStuff:
>    def Thing1(self):
>        def ThingToCall(self):
>            print "It worked!"
>    def Thing2(self):
>        #Call the function "ThingToCall" here.
> -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
> Thanks for any help. I haven't used classes that much before...

This doesn't have much of anything to do with classes.
The same happens if you just use functions:

def f(x):
   def g(x):
      print 'in g'

You cannot call g() outside of f() because it is not visible
You need to return g to make it visible outside f, like this:

def f(x):
   def g(x):
      print 'in g'
   return g

Now you can call g() by doing:

myG = f(42)
myG(25)

or

f(42)(25)

So in your class example, if you add a return to
Thing1 you could do:

d = DoStuff()
f = d.Thing1()
f()

BTW Its usually a sign of bad OO design to have a
class name that is a verb, objects are things so
should be named with nouns. The methods should
be named with verbs - they *do* stuff to things.
So you class would be more conventional if it was

class Thing:
    def doStuff1()
    def doStuff2()

That then allows you to extend your program using
subclassing and polymorphism which in turn usually
saves you some coding. Classes named after verbs
usually wind up with very long if/elif chains inside
each method which is slow and hard to maintain.

However there are occasional cases where it makes
sense, and your may be one of those exceptions.
Just a thought.

HTH

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



From orsenthil at gmail.com  Sun Nov 11 01:54:59 2007
From: orsenthil at gmail.com (O.R.Senthil Kumaran)
Date: Sun, 11 Nov 2007 06:24:59 +0530
Subject: [Tutor] *args, **kargs as arguments
In-Reply-To: <78b3a9580711092116v1d54f7bcod06264de8a96207c@mail.gmail.com>
References: <20071110033047.GB3583@gmail.com>
	<78b3a9580711092116v1d54f7bcod06264de8a96207c@mail.gmail.com>
Message-ID: <20071111005459.GA3677@gmail.com>


> 
> > class Derived(BaseClass):
> >         def __init__(self, *args, **kargs):
> >                 BaseClass.__init__(self, *args, **kargs)
> >
> > - *args, **kargs passes a tuple and a dictionary to the BaseClass constructor.
> >
> > My assumption is the BaseClass will always have a constructor that will
> > be receiving the tuple and a dictionary. Am I right?
> 
> not quite.  you're on the right track though. a couple of thoughts.


Thank you Wesley for the examples and the explaination.
And thanks Jeff for your explaination. It helped me clarify my doubts. :-)
Really helpful.

-- 
O.R.Senthil Kumaran
http://uthcode.sarovar.org

From cappy2112 at gmail.com  Sun Nov 11 02:23:11 2007
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Sat, 10 Nov 2007 17:23:11 -0800
Subject: [Tutor] Wrong version of Python being executed
Message-ID: <8249c4ac0711101723u44fd0352r8325db01443124f1@mail.gmail.com>

I've got Python 2.3, 2.4 and 2.5 installed on a Windows XP machine..

I currently have Python 2.5 in my path, and there are no other
versions of Python in the path.

I'm trying to run a program which expects Python 2.4 or later to be
installed, because there is a call to logging.BasicConfig(arg1, arg2)
which is passed two arguments

In Python 2.3, logging.BasicConfig() did not take any arguments.

When I run this python script, the following exception is thrown,
implying that it is being executed with Python 2.3
So I've added this print statement to the main function, which shows
the logging module is being imported from the Python 2.3 directory

print"\nlogging.__file__ = %s" % logging.__file__

logging.__file__ = C:\Python23\lib\logging\__init__.pyc



Traceback (most recent call last):
  File "c:\Project\myscript.py", line 584, in
?
    main(sys.argv)
  File "c:\Project\myscript.py", line 518, in
main
    logging.basicConfig(level=config.verbosity,format='%(message)s')
TypeError: basicConfig() takes no arguments (2 given)


The really odd thing is when I bring up the python interpreter at the
same command prompt where i ran the script above,
Python 2.5 is invoked, as seen by


Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.version
'2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)]'


How is it that running a script invokes Python 2.3, but running the
interpreter without the script invoked Python 2.5?

From kent37 at tds.net  Sun Nov 11 03:16:16 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 10 Nov 2007 21:16:16 -0500
Subject: [Tutor] Wrong version of Python being executed
In-Reply-To: <8249c4ac0711101723u44fd0352r8325db01443124f1@mail.gmail.com>
References: <8249c4ac0711101723u44fd0352r8325db01443124f1@mail.gmail.com>
Message-ID: <473665F0.2050704@tds.net>

Tony Cappellini wrote:
> When I run this python script, the following exception is thrown,
> implying that it is being executed with Python 2.3
> So I've added this print statement to the main function, which shows
> the logging module is being imported from the Python 2.3 directory
> 
> print"\nlogging.__file__ = %s" % logging.__file__
> 
> logging.__file__ = C:\Python23\lib\logging\__init__.pyc
> 
> 
> 
> Traceback (most recent call last):
>   File "c:\Project\myscript.py", line 584, in
> ?
>     main(sys.argv)
>   File "c:\Project\myscript.py", line 518, in
> main
>     logging.basicConfig(level=config.verbosity,format='%(message)s')
> TypeError: basicConfig() takes no arguments (2 given)
> 
> 
> The really odd thing is when I bring up the python interpreter at the
> same command prompt where i ran the script above,
> Python 2.5 is invoked, as seen by
> 
> 
> Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import sys
>>>> sys.version
> '2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)]'
> 
> 
> How is it that running a script invokes Python 2.3, but running the
> interpreter without the script invoked Python 2.5?

A couple of possibilities...
Is there a #! line at the start of the script that specifies Python 2.3 
(I'm not sure if those work in windows though...)

How do you run the script? If you double-click it, perhaps the file 
association with .py files is to Python 2.3?

Conceivably the Python 2.5 module path is incorrect and imports the 
wrong module. What happens if you import logging from the interpreter 
prompt and print its file? What do you get if you print sys.path from 
the interpreter?

HTH,
Kent

From cappy2112 at gmail.com  Sun Nov 11 03:35:13 2007
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Sat, 10 Nov 2007 18:35:13 -0800
Subject: [Tutor] Wrong version of Python being executed
In-Reply-To: <473665F0.2050704@tds.net>
References: <8249c4ac0711101723u44fd0352r8325db01443124f1@mail.gmail.com>
	<473665F0.2050704@tds.net>
Message-ID: <8249c4ac0711101835t1a070a2k237d1a8bab893806@mail.gmail.com>

Thanks for replying Kent.
This is quite a strange mystery.

> A couple of possibilities...
> Is there a #! line at the start of the script that specifies Python 2.3
> (I'm not sure if those work in windows though...)
No- The shebang line is for non-Windows systems (Unix variants)

> How do you run the script? If you double-click it, perhaps the file
> association with .py files is to Python 2.3?
I run the script by typing python script.py

> Conceivably the Python 2.5 module path is incorrect and imports the
> wrong module. What happens if you import logging from the interpreter
> prompt and print its file?

Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import logging
>>> logging.__file__
'C:\\PYTHON25\\lib\\logging\\__init__.pyc'


What do you get if you print sys.path from
> the interpreter?

>>> import sys
>>> sys.path
['', 'C:\\WINDOWS\\system32\\python25.zip', 'C:\\PYTHON25\\DLLs',
'C:\\PYTHON25\\lib', 'C:\\PYTHON25\\lib\\plat-win', 'C
:\\PYTHON25\\lib\\lib-tk', 'C:\\PYTHON25',
'C:\\PYTHON25\\lib\\site-packages',
'C:\\PYTHON25\\lib\\site-packages\\win32'
, 'C:\\PYTHON25\\lib\\site-packages\\win32\\lib',
'C:\\PYTHON25\\lib\\site-packages\\Pythonwin', 'C:\\PYTHON25\\lib\\sit
e-packages\\wx-2.8-msw-ansi']

From cappy2112 at gmail.com  Sun Nov 11 03:49:50 2007
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Sat, 10 Nov 2007 18:49:50 -0800
Subject: [Tutor] Wrong version of Python being executed
In-Reply-To: <473665F0.2050704@tds.net>
References: <8249c4ac0711101723u44fd0352r8325db01443124f1@mail.gmail.com>
	<473665F0.2050704@tds.net>
Message-ID: <8249c4ac0711101849xf1c795ar77d28a68f239b5fd@mail.gmail.com>

>>What do you get if you print sys.path from
> the interpreter?

I've printed out sys.path from inside the script as well,
and all references to Python25 are replaced with Python23


FWIW- This isn't a problem unique to this script.
I've just printed out sys.path from another script in another
directory, and Python2.3 is referenced.
So, it's a system wide issue- but I still don't know how or why it's happening.

From r.lokesh at gmail.com  Sat Nov 10 14:30:27 2007
From: r.lokesh at gmail.com (Lokesh R)
Date: Sat, 10 Nov 2007 19:00:27 +0530
Subject: [Tutor] Happy Diwali
In-Reply-To: <82c58b390711080519i760eb8e8p949b48341cf32187@mail.gmail.com>
References: <82c58b390711080519i760eb8e8p949b48341cf32187@mail.gmail.com>
Message-ID: <537aae9f0711100530u4c21624dm8c659b613bd2600a@mail.gmail.com>

ThankQ & WIsh you the same...

And Congrats for Getting Engaged ;)


Best Regards,
Lokesh



On 11/8/07, Amit Saxena <amitsaxena69 at gmail.com> wrote:
>
> Hi,
>
> Wishing u all and ur family a very HAPPY DIWALI
>
>
> Cheers
> Amit
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071110/20e540fd/attachment-0001.htm 

From oclbdk at gmail.com  Sat Nov 10 23:20:07 2007
From: oclbdk at gmail.com (Johnston Jiaa)
Date: Sat, 10 Nov 2007 17:20:07 -0500
Subject: [Tutor] Bitmap editor and File-saving
Message-ID: <F6FD4F11-96D0-47DA-9BC2-C722E43A905F@GMAIL.COM>

Hello, I already asked this on python-list, but would like to improve  
the odds of having my question answered, so I am asking it here too.   
I apologize if this bothers anyone.

I am using Tkinter to create a program in which the user can draw a  
simple bitmap image.  What library would be best to use in this  
circumstance?  I have no idea how I would go about doing this except  
maybe I would use Tkinter's canvas component?

In order for the program to be useful, it should save the picture  
too.  I'd like for it to save the image with some strings of text.   
How can I implement such a file-saving feature?  Would pickling  
work?  I have no idea how to accomplish this task efficiently.

Thanks in advance,
Johnston

From mwalsh at groktech.org  Sun Nov 11 06:13:10 2007
From: mwalsh at groktech.org (Martin Walsh)
Date: Sat, 10 Nov 2007 23:13:10 -0600
Subject: [Tutor] Wrong version of Python being executed
In-Reply-To: <8249c4ac0711101849xf1c795ar77d28a68f239b5fd@mail.gmail.com>
References: <8249c4ac0711101723u44fd0352r8325db01443124f1@mail.gmail.com>	<473665F0.2050704@tds.net>
	<8249c4ac0711101849xf1c795ar77d28a68f239b5fd@mail.gmail.com>
Message-ID: <47368F66.7020509@groktech.org>

Tony Cappellini wrote:
>>> What do you get if you print sys.path from
>> the interpreter?
> 
> I've printed out sys.path from inside the script as well,
> and all references to Python25 are replaced with Python23
> 
> 
> FWIW- This isn't a problem unique to this script.
> I've just printed out sys.path from another script in another
> directory, and Python2.3 is referenced.
> So, it's a system wide issue- but I still don't know how or why it's happening.

That is odd.

Try using the full path to python, just to be sure: c:\python25\python
script.py -- do you get the same behavior?

Also, if you haven't already, you can run python with the -E and/or -S
flags (ex. 'c:\python25\python -E -S script.py'). The -E flag will cause
the PYTHONPATH and PYTHONHOME environment variables to be ignored. And
the -S flag prevents 'import site' at python startup. Regardless, even
if these are configured incorrectly I would expect the same behavior if
running a script or using the interactive interpreter.

You mentioned that python 2.4 is installed also... does it have the same
sys.path problem?

HTH,
Marty



From orsenthil at gmail.com  Sun Nov 11 06:35:41 2007
From: orsenthil at gmail.com (O.R.Senthil Kumaran)
Date: Sun, 11 Nov 2007 11:05:41 +0530
Subject: [Tutor] Swapping variables ...
In-Reply-To: <5df213700711091024l325d019bq636ed056ad201d99@mail.gmail.com>
References: <5df213700711091024l325d019bq636ed056ad201d99@mail.gmail.com>
Message-ID: <20071111053541.GC3663@gmail.com>

>  After quizzing newbies in C on swapping without 3rd variable, I found this
> to be really *cool* construct to swap :)
> x = 10
> y = 20
> x,y = y,x
> 

Keep in mind that, this is actually a tuple assignment.
A new tuple x,y is created with the older one y,x, and with the side effect thatthe variables are swapped as we see it.

yes, tuple concepts does not exist in C (as it is not a Very High Level Language).

yes, I too find it "cool" when I got introduced to it.



-- 
O.R.Senthil Kumaran
http://uthcode.sarovar.org

From alan.gauld at btinternet.com  Sun Nov 11 10:29:56 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 11 Nov 2007 09:29:56 -0000
Subject: [Tutor] Bitmap editor and File-saving
References: <F6FD4F11-96D0-47DA-9BC2-C722E43A905F@GMAIL.COM>
Message-ID: <fh6i2s$jrk$1@ger.gmane.org>


"Johnston Jiaa" <oclbdk at gmail.com> wrote

> I am using Tkinter to create a program in which the user can draw a
> simple bitmap image.  What library would be best to use in this
> circumstance?  I have no idea how I would go about doing this except
> maybe I would use Tkinter's canvas component?

The canvas widget is probably adequate for simple drawing.
More advanvced libraries like PIL might be useful for converting
the format or doing large scale transformations.

> In order for the program to be useful, it should save the picture
> too.  I'd like for it to save the image with some strings of text.
> How can I implement such a file-saving feature?

You could either save two files one with the text and the other
the bitmap. Or you could convert the text to binary data and
write it to the same file as the bitmap. To read it back you will
need to write code to strip the text off again however. Or you
could use uuencode, or similar, to convert the image to text
and add your strings to that. Again you will need to write the
reverse process for retrieving it.

HTH,

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



From cappy2112 at gmail.com  Sun Nov 11 21:47:46 2007
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Sun, 11 Nov 2007 12:47:46 -0800
Subject: [Tutor] Wrong version of Python being executed
Message-ID: <8249c4ac0711111247x2ce4d5fcs80066b1c90f2d722@mail.gmail.com>

Martin Walsh mwalsh at groktech.org
Sun Nov 11 06:13:10 CET 2007

>>That is odd.

>>Try using the full path to python, just to be sure: c:\python25\python
>>script.py -- do you get the same behavior?
This works just fine- I would expect it to.

>>Also, if you haven't already, you can run python with the -E and/or -S
>>flags (ex. 'c:\python25\python -E -S script.py'). The -E flag will cause
>>the PYTHONPATH and PYTHONHOME environment variables to be ignored. And

This also works just fine. I've tried both switches independently, and
the scrip runs normally when I use either and both at the same time.
If I don't use them, then Python2.3 is being invoked somehow.

However, when I type set PYTHONPATH and
set PYTHONHOME

at the cmd prompt

SET PYTHONPATH
Environment variable PYTHONPATH not defined

SET PYTHONHOME
Environment variable PYTHONHOME not defined

Very strange indeed. It's starting to remind me of an episode from The
Twilight Zone ;-)

Is ti possible that my registry is corrupted?

From mwalsh at groktech.org  Sun Nov 11 23:57:01 2007
From: mwalsh at groktech.org (Martin Walsh)
Date: Sun, 11 Nov 2007 16:57:01 -0600
Subject: [Tutor] Wrong version of Python being executed
In-Reply-To: <8249c4ac0711111247x2ce4d5fcs80066b1c90f2d722@mail.gmail.com>
References: <8249c4ac0711111247x2ce4d5fcs80066b1c90f2d722@mail.gmail.com>
Message-ID: <473788BD.7060806@groktech.org>

Tony Cappellini wrote:
> Martin Walsh mwalsh at groktech.org
> Sun Nov 11 06:13:10 CET 2007
> 
>>> That is odd.
> 
>>> Try using the full path to python, just to be sure: c:\python25\python
>>> script.py -- do you get the same behavior?
> This works just fine- I would expect it to.

Actually, I would have expected the opposite. My initial thought based
on your description was that python2.5 is being invoked with PYTHON* env
vars from a previous install, or some site module weirdness. But, the
fact that running python.exe with it's full path corrects the issue,
seems to indicate a problem with your PATH, rather than any python
specific environment setting. What does 'set PATH' report?

Though this still doesn't explain why you get python2.5 interactively,
and python2.3 when running a script -- perhaps I'm still unclear what
you are seeing. Would the following be an accurate description of the
behavior?

assuming:
- you run inside a fresh 'cmd' console each time (typing 'cmd' at the
run dialog, or similar), to be sure there is no app environment kruft

- the current working directory doesn't contain any programs, scripts or
possibly links that could interfere (preferably an empty path)

- you don't have any PYTHON* environment vars set (including PYTHONSTARTUP)

you observe:
- when you type 'python' (only 'python') at the prompt, you get
python2.5 interactively

- when you use the form 'python script.py', the script is run with
python2.3 (can you verify with sys.version?) with sys.path appropriate
for 2.3

- when you use the form 'c:\python25\python.exe script.py', the script
is executed with python2.5 and you have the correct sys.path (for 2.5)

> 
>>> Also, if you haven't already, you can run python with the -E and/or -S
>>> flags (ex. 'c:\python25\python -E -S script.py'). The -E flag will cause
>>> the PYTHONPATH and PYTHONHOME environment variables to be ignored. And
> 
> This also works just fine. I've tried both switches independently, and
> the scrip runs normally when I use either and both at the same time.
> If I don't use them, then Python2.3 is being invoked somehow.

Yeah, very odd indeed.

 > Very strange indeed. It's starting to remind me of an episode from The
> Twilight Zone ;-)
> 
> Is ti possible that my registry is corrupted?

I wouldn't think so, but I suppose it is possible. I believe all the
pertinent registry keys are store under
"HKLM\Software\Python\Pythoncore\<version>", so you could have a look.
There are settings stored elsewhere, but I think they are all related to
file associations, and enabling double-click launching etc. I hope
someone will correct or clarify, if I'm wrong.

If it is a registry issue, re-installing python2.5 *may* provide a quick
fix. BTW, are you using an alternate distribution of python (ex.
ActiveState), or the standard python.org version?

HTH,
Marty

From rdm at rcblue.com  Mon Nov 12 00:46:45 2007
From: rdm at rcblue.com (Dick Moores)
Date: Sun, 11 Nov 2007 15:46:45 -0800
Subject: [Tutor] Problem with default arguments for function
Message-ID: <20071111235352.CC7C21E4002@bag.python.org>

I just discovered mpmath 
(<http://code.google.com/p/mpmath/wiki/Documentation>) and am trying 
to write a useful function that uses it to compute factorials. Here's 
what I have:

def fact(n, precision=15, full=False):
     """
     compute n!
     """
     from mpmath import mpf
     if not isinstance(n, int):
         return None
     elif n < 0:
         return None
     n = mpf(n)
     if full:
         precision = n * 10   # ensures that for n < 1 billion, 
product will not be in scientific notation (i.e., no '+')
     mpf.dps = precision
     product = mpf(1)
     while n > mpf(1):
         product *= n
         n -= 1
     if '+' in str(product):
         return product
     else:
         return int(str(product)[:-2])      #  product is a float, 
ending in '.0', so this needs to be removed and string converted to int.

The code is also at <http://python.pastebin.com/m33d52d54>.

And a couple of example uses that illustrate my problem:

# 1 (precision default overridden and set to 20; full left at default of False)
 >>> print fact(50, 20)
3.0414093201713378044e+64

# 2 (both precision and full left at their defaults)
 >>> print fact(50)
3.04140932017134e+64

# 3 (full set to True, forcing precision to be specified--but 
irrelevant what it is set to)
 >>> print fact(50, 3, True)
30414093201713378043612608166064768844377641568960512000000000000

# 4 (see # 3)
 >>> print fact(50, 30, True)
30414093201713378043612608166064768844377641568960512000000000000

And if the function is rewritten as def fact(n, full=False, precision=15)
there would be the analogous problem involving full.

Is there a way to solve this problem of the unnecessary setting of 
the 2nd argument?

Thanks,

Dick Moores


From alan.gauld at btinternet.com  Mon Nov 12 01:16:35 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 12 Nov 2007 00:16:35 -0000
Subject: [Tutor] Wrong version of Python being executed
References: <8249c4ac0711111247x2ce4d5fcs80066b1c90f2d722@mail.gmail.com>
	<473788BD.7060806@groktech.org>
Message-ID: <fh861b$up1$1@ger.gmane.org>

"Martin Walsh" <mwalsh at groktech.org> wrote

>>>> Try using the full path to python, just to be sure: 
>>>> c:\python25\python
>>>> script.py -- do you get the same behavior?
>> This works just fine- I would expect it to.
>
> Actually, I would have expected the opposite.

Me too.

> Though this still doesn't explain why you get python2.5 
> interactively,
> and python2.3 when running a script -- perhaps I'm still unclear 
> what
> you are seeing. Would the following be an accurate description of 
> the
> behavior?
>
> assuming:
> - you run inside a fresh 'cmd' console each time (typing 'cmd' at 
> the
> run dialog, or similar), to be sure there is no app environment 
> kruft

This is very important. If you just type python at the Run
dialog it uses a different algorithm to find the exe than if
you type python at a DOS prompt inside a CMD window.
Its the second algorithm that is used if you type
python foo.py at a cmd prompt but the first that
is used if you double click foo.py within explorer
(actually that could even be a different one again!)
or type python foo.py in the Run dialog.

> fix. BTW, are you using an alternate distribution of python (ex.
> ActiveState), or the standard python.org version?

That *shouldn't* make any difference...but you can never be 100% sure!


-- 
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 Nov 12 01:22:18 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 12 Nov 2007 00:22:18 -0000
Subject: [Tutor] Problem with default arguments for function
References: <20071111235352.CC7C21E4002@bag.python.org>
Message-ID: <fh86c3$vfg$1@ger.gmane.org>


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

> And if the function is rewritten as def fact(n, full=False, 
> precision=15)
> there would be the analogous problem involving full.
>
> Is there a way to solve this problem of the unnecessary setting of
> the 2nd argument?

The most common solution I've seen is to write wrappers
around the basic function like:

def fullFact(n, precision=15):
    return fact(n,True,precision)

def precisionFact(n, full=False):
    return fact(n, full, 15)

Not terribly elegant but is at least short and simple.

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



From bryan.fodness at gmail.com  Mon Nov 12 02:02:21 2007
From: bryan.fodness at gmail.com (Bryan Fodness)
Date: Sun, 11 Nov 2007 20:02:21 -0500
Subject: [Tutor] manipulating data
In-Reply-To: <47330268.1080304@bigfoot.com>
References: <fbf64d2b0711061154v4f6547bcx133c342f2d5aac27@mail.gmail.com>
	<4731C327.6000704@tds.net> <47330268.1080304@bigfoot.com>
Message-ID: <fbf64d2b0711111702g7161a4bal2b3bc83bb6761d84@mail.gmail.com>

Using,

fields = {}
for line in open('data.txt') :
   if line :
       if line.split()[0] == 'field' :
           field = int(line.split()[-1])
       else :
           fields[field] = tuple(line.split())

I get,

fields[field] = tuple(line.split())
NameError: name 'field' is not defined




On Nov 8, 2007 7:34 AM, Ricardo Ar?oz <ricaraoz at gmail.com> wrote:
>
> Kent Johnson wrote:
> > Bryan Fodness wrote:
> >> I would like to have my data in a format so that I can create a contour plot.
> >>
> >> My data is in a file with a format, where there may be multiple fields
> >>
> >> field = 1
> >>
> >> 1a   0
> >
> > If your data is really this regular, it is pretty easy to parse. A
> > useful technique is to access a file's next method directly. Something
> > like this (not tested!):
> >
> > f = open('data.txt')
> > fields = {} # build a dict of fields
> > try:
> >    while True:
> >      # Get the field line
> >      line = f.next()
> >      field = int(line.split()[-1]) # last part of the line as an int
> >
> >      f.next() # skip blank line
> >
> >      data = {} # for each field, map (row, col) to value
> >      for i in range(20): # read 20 data lines
> >        line = f.next()
> >        ix, value = f.split()
> >        row = int(ix[:-1])
> >        col = ix[-1]
> >        data[row, col] = int(value)
> >
> >      fields[field] = data
> >
> >      f.next()
> > except StopIteration:
> >    pass
> >
>
> Or maybe just (untested) :
>
> fields = {} # build a dict of fields
> for line in open('data.txt') :
>    if line :    # skip blank lines
>        if line.split()[0] == 'field' :
>            field = int(line.split()[-1])
>        else :
>            fields[field] = tuple(line.split())
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From kent37 at tds.net  Mon Nov 12 02:38:27 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 11 Nov 2007 20:38:27 -0500
Subject: [Tutor] Problem with default arguments for function
In-Reply-To: <20071111235352.CC7C21E4002@bag.python.org>
References: <20071111235352.CC7C21E4002@bag.python.org>
Message-ID: <4737AE93.3000506@tds.net>

Dick Moores wrote:

> def fact(n, precision=15, full=False):
   ...

> # 3 (full set to True, forcing precision to be specified--but 
> irrelevant what it is set to)
>  >>> print fact(50, 3, True)
> 30414093201713378043612608166064768844377641568960512000000000000

You don't have to specify precision if you pass full as a keyword argument:
fact(50, full=True)

Kent

From rdm at rcblue.com  Mon Nov 12 03:57:08 2007
From: rdm at rcblue.com (Dick Moores)
Date: Sun, 11 Nov 2007 18:57:08 -0800
Subject: [Tutor] Problem with default arguments for function
In-Reply-To: <18231.43012.646716.111029@euclid.slu.edu>
References: <20071111235352.CC7C21E4002@bag.python.org>
	<18231.43012.646716.111029@euclid.slu.edu>
Message-ID: <20071112030434.80A681E4016@bag.python.org>

At 05:10 PM 11/11/2007, Michael H. Goldwasser wrote:


>Dick,
>
>Another typical strategy is to use some prescribed special value for
>the precision parameter to designate the desire for full precision.
>For example, since precisions should presumably be positive, one could
>design this function as:
>
>def fact(n, precision=15):
>     """compute n!.
>
>     precision    the minimum desired precision.
>                  If -1 is specified, computed to full precision.
>     """
>     # ...
>     if precision == -1:
>         precision = n * 10  # insures that for n < 1 billion, ...
>     # ...
>
>
>If you are not happy with the oddity of -1 (or in cases where -1 might
>be a legitimate parameter value), you can pick the flag from a
>different data type.  In this case, perhaps None would be a more
>natural way to say that you do not want any limit on the precision.
>So this could be coded as
>
>def fact(n, precision=15):
>     """compute n!.
>
>     precision    the minimum desired precision.
>                  If None is specified, computed to full precision.
>     """
>     # ...
>     if precision is None:
>         precision = n * 10  # insures that for n < 1 billion, ...
>     # ...
>
>Looking at your examples, this should (unteste) behave as:
>
># 1 (precision default overridden and set to 20)
>  >>> print fact(50, 20)
>3.0414093201713378044e+64
>
># 2 (without explicit value, precision defaults to 15)
>  >>> print fact(50)
>3.04140932017134e+64
>
># 3 (explicitly says not to limit precision)
>  >>> print fact(50, None)
>30414093201713378043612608166064768844377641568960512000000000000

Beautiful! Thanks!

Dick



From rdm at rcblue.com  Mon Nov 12 04:05:37 2007
From: rdm at rcblue.com (Dick Moores)
Date: Sun, 11 Nov 2007 19:05:37 -0800
Subject: [Tutor] Problem with default arguments for function
In-Reply-To: <4737AE93.3000506@tds.net>
References: <20071111235352.CC7C21E4002@bag.python.org>
	<4737AE93.3000506@tds.net>
Message-ID: <20071112030541.B53C41E4023@bag.python.org>

At 05:38 PM 11/11/2007, Kent Johnson wrote:
>Dick Moores wrote:
>
>>def fact(n, precision=15, full=False):
>   ...
>
>># 3 (full set to True, forcing precision to be specified--but 
>>irrelevant what it is set to)
>>  >>> print fact(50, 3, True)
>>30414093201713378043612608166064768844377641568960512000000000000
>
>You don't have to specify precision if you pass full as a keyword argument:
>fact(50, full=True)

Ah, good to know. Thanks.

Dick



From rdm at rcblue.com  Mon Nov 12 04:07:46 2007
From: rdm at rcblue.com (Dick Moores)
Date: Sun, 11 Nov 2007 19:07:46 -0800
Subject: [Tutor] Problem with default arguments for function
In-Reply-To: <fh86c3$vfg$1@ger.gmane.org>
References: <20071111235352.CC7C21E4002@bag.python.org>
	<fh86c3$vfg$1@ger.gmane.org>
Message-ID: <20071112030750.C06631E4034@bag.python.org>

At 04:22 PM 11/11/2007, Alan Gauld wrote:

>"Dick Moores" <rdm at rcblue.com> wrote
>
> > And if the function is rewritten as def fact(n, full=False,
> > precision=15)
> > there would be the analogous problem involving full.
> >
> > Is there a way to solve this problem of the unnecessary setting of
> > the 2nd argument?
>
>The most common solution I've seen is to write wrappers
>around the basic function like:
>
>def fullFact(n, precision=15):
>     return fact(n,True,precision)
>
>def precisionFact(n, full=False):
>     return fact(n, full, 15)
>
>Not terribly elegant but is at least short and simple.

Alan, I won't adopt this solution for my fact(), but I'm glad to know about it.

Thanks,

Dick



From goldwamh at slu.edu  Mon Nov 12 02:10:28 2007
From: goldwamh at slu.edu (Michael H. Goldwasser)
Date: Sun, 11 Nov 2007 19:10:28 -0600
Subject: [Tutor]  Problem with default arguments for function
In-Reply-To: <20071111235352.CC7C21E4002@bag.python.org>
References: <20071111235352.CC7C21E4002@bag.python.org>
Message-ID: <18231.43012.646716.111029@euclid.slu.edu>



Dick,

Another typical strategy is to use some prescribed special value for
the precision parameter to designate the desire for full precision.
For example, since precisions should presumably be positive, one could
design this function as:

def fact(n, precision=15):
    """compute n!.

    precision    the minimum desired precision.
                 If -1 is specified, computed to full precision.
    """
    # ...
    if precision == -1:
        precision = n * 10  # insures that for n < 1 billion, ...
    # ...


If you are not happy with the oddity of -1 (or in cases where -1 might
be a legitimate parameter value), you can pick the flag from a
different data type.  In this case, perhaps None would be a more
natural way to say that you do not want any limit on the precision.
So this could be coded as

def fact(n, precision=15):
    """compute n!.

    precision    the minimum desired precision.
                 If None is specified, computed to full precision.
    """
    # ...
    if precision is None:
        precision = n * 10  # insures that for n < 1 billion, ...
    # ...

Looking at your examples, this should (unteste) behave as:

# 1 (precision default overridden and set to 20)
 >>> print fact(50, 20)
3.0414093201713378044e+64

# 2 (without explicit value, precision defaults to 15)
 >>> print fact(50)
3.04140932017134e+64

# 3 (explicitly says not to limit precision)
 >>> print fact(50, None)
30414093201713378043612608166064768844377641568960512000000000000


With regard,
Michael

On Sunday November 11, 2007, Dick Moores wrote: 

>    def fact(n, precision=15, full=False):
>         """
>         compute n!
>         """


>    And a couple of example uses that illustrate my problem:
>    
>    # 1 (precision default overridden and set to 20; full left at default of False)
>     >>> print fact(50, 20)
>    3.0414093201713378044e+64
>    
>    # 2 (both precision and full left at their defaults)
>     >>> print fact(50)
>    3.04140932017134e+64
>    
>    # 3 (full set to True, forcing precision to be specified--but 
>    irrelevant what it is set to)
>     >>> print fact(50, 3, True)
>    30414093201713378043612608166064768844377641568960512000000000000
>    
>    # 4 (see # 3)
>     >>> print fact(50, 30, True)
>    30414093201713378043612608166064768844377641568960512000000000000
>    
>    And if the function is rewritten as def fact(n, full=False, precision=15)
>    there would be the analogous problem involving full.
>    
>    Is there a way to solve this problem of the unnecessary setting of 
>    the 2nd argument?
>    
>    Thanks,
>    
>    Dick Moores
>    
>    _______________________________________________
>    Tutor maillist  -  Tutor at python.org
>    http://mail.python.org/mailman/listinfo/tutor


From varsha.purohit at gmail.com  Mon Nov 12 04:10:44 2007
From: varsha.purohit at gmail.com (Varsha Purohit)
Date: Sun, 11 Nov 2007 19:10:44 -0800
Subject: [Tutor] [tutor] File format conversion
Message-ID: <c2157c790711111910u2ea003adg408ca5383aac9250@mail.gmail.com>

Hello All,
       In one application i want to convert format of ascii file to
binary file. And using that binary file in a function of PIL i can
convert it to an image file. So i wanted to know how to convert the
file format in python... is it possible by Numpy ?? And is there any
other alternative to convert an ascii into an bitmap image directly in
PIL without Numpy??

thanks,

-- 
Varsha

From ryan251 at gmail.com  Mon Nov 12 05:21:57 2007
From: ryan251 at gmail.com (Ryan Hughes)
Date: Sun, 11 Nov 2007 22:21:57 -0600
Subject: [Tutor] assignment question
Message-ID: <962068b0711112021u748172ecv4eedbc5f2b3a385f@mail.gmail.com>

Hello,

Why does the following not return [1,2,3,4] ?

>>> x = [1,2,3].append(4)
>>> print x
None
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071111/ceaa7a63/attachment.htm 

From john at fouhy.net  Mon Nov 12 05:30:43 2007
From: john at fouhy.net (John Fouhy)
Date: Mon, 12 Nov 2007 17:30:43 +1300
Subject: [Tutor] assignment question
In-Reply-To: <962068b0711112021u748172ecv4eedbc5f2b3a385f@mail.gmail.com>
References: <962068b0711112021u748172ecv4eedbc5f2b3a385f@mail.gmail.com>
Message-ID: <5e58f2e40711112030q9c53188jd36ec594fbc245e2@mail.gmail.com>

On 12/11/2007, Ryan Hughes <ryan251 at gmail.com> wrote:
> Why does the following not return [1,2,3,4] ?
>
> >>> x = [1,2,3].append(4)
> >>> print x
> None

List methods like .append() and .sort() modify lists in-place, as
opposed to creating new lists.  To remind you of this, those methods
return None instead of returning the modified list.

Otherwise (if .append() returned the modified list), you might be
tempted to write code like this:

  x = getSomeList()
  y = x.append(3)

and forget that x and y are the same list.

If you want to join two lists together to make a new one, you can use +:

>>> x = [1, 2, 3] + [4]
>>> x
[1, 2, 3, 4]

Hope this helps,

-- 
John.

From goldwamh at slu.edu  Mon Nov 12 05:34:26 2007
From: goldwamh at slu.edu (Michael H. Goldwasser)
Date: Sun, 11 Nov 2007 22:34:26 -0600
Subject: [Tutor]  assignment question
In-Reply-To: <962068b0711112021u748172ecv4eedbc5f2b3a385f@mail.gmail.com>
References: <962068b0711112021u748172ecv4eedbc5f2b3a385f@mail.gmail.com>
Message-ID: <18231.55250.463396.348395@euclid.slu.edu>


On Sunday November 11, 2007, Ryan Hughes wrote: 

>    Hello,
>    
>    Why does the following not return [1,2,3,4] ?
>    
>    >>> x = [1,2,3].append(4)
>    >>> print x
>    None


The reason is that the append method does not return anything.  In
effect, the expresison [1,2,3].append(4) temporarily causes 4 to be
appended to the (unnamed) list.  However the assignment

x = blah

sets the variable x equal to the result of the expression blah (which
in this case is None, since append does not return anything).

In contrast, consider the following interaction:

>>> x = [1,2,3]
>>> x.append(4)
>>> print x
[1, 2, 3, 4]





From cappy2112 at gmail.com  Mon Nov 12 05:37:03 2007
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Sun, 11 Nov 2007 20:37:03 -0800
Subject: [Tutor] Wrong version of Python being executed
Message-ID: <8249c4ac0711112037y4bd6fb8dgb8e6ef4140f91611@mail.gmail.com>

Message: 2
Date: Sun, 11 Nov 2007 16:57:01 -0600
From: Martin Walsh <mwalsh at groktech.org>
Subject: Re: [Tutor] Wrong version of Python being executed
To: Tutor Python <tutor at python.org>
Message-ID: <473788BD.7060806 at groktech.org>
Content-Type: text/plain; charset=ISO-8859-1


>>My initial thought based on your description was that python2.5 is
being invoked with PYTHON* env
>>vars from a previous install, or some site module weirdness.

Not sure how the "previous install" surfaced, but I installed all
python installations and packages on my computer.

I have to switch between 2.3 and 2.5, so to make it easy, I use an
environment variable called CURRENT_PYTHON.
(someone on this list or the wxPython list told me I should NOT use
PYTHONPATH and modify it the way I am using CURRENT_PYTHON)

CURRENT_PYTHON=C:\PYTHON2X
path=%CURRENT_PYTHON%
(The existing path isn't shown, only for brevity)

Note, these are entered in Ctrl Panel, System environment variables,
NOT at the command line.


>>But, the fact that running python.exe with it's full path corrects the issue,
>>seems to indicate a problem with your PATH, rather than any python
Yes, my conclusion also, but what is wrong with the path?
I've posted the contents of PATH in the original email or one of the
subsequent ones.

>>Would the following be an accurate description of the behavior?

>>assuming:
>>- you run inside a fresh 'cmd' console each time (typing 'cmd' at the
>>run dialog, or similar), to be sure there is no app environment kruft

correct-

>>- the current working directory doesn't contain any programs, scripts or
>>possibly links that could interfere (preferably an empty path)

Not that I can see

>>- you don't have any PYTHON* environment vars set (including PYTHONSTARTUP)

No- see for yourself. No python anything variables.
C:\Documents and Settings\z30032as>set python
Environment variable python not defined

>>you observe:
>>- when you type 'python' (only 'python') at the prompt, you get
>>python2.5 interactively

Correct

>>- when you use the form 'python script.py', the script is run with
>>python2.3 (can you verify with sys.version?) with sys.path appropriate
>>for 2.3

Correct

>>- when you use the form 'c:\python25\python.exe script.py', the script
>>is executed with python2.5 and you have the correct sys.path (for 2.5)
Correct

>>I wouldn't think so, but I suppose it is possible. I believe all the
>>pertinent registry keys are store under
>>"HKLM\Software\Python\Pythoncore\<version>", so you could have a look.

Already did. There IS a PYTHONPATH entry for each of the 3 versions of
Python I have installed.
They are all identical, with the exception of the last 2 digits for
the Python version.
This looks ok to me. No other rogue entries of PYTHONPATH were found
in the registry.

>>BTW, are you using an alternate distribution of python (ex.
>>ActiveState), or the standard python.org version?

No. I always use the regular Python.Org distributions. I never
understood what was so special about ActiveState anyway.
I;d rather have full control of my installs, and all the packages.
Although, at this point, I'm not in control over what is happening
with my path ;-)

From cappy2112 at gmail.com  Mon Nov 12 05:45:17 2007
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Sun, 11 Nov 2007 20:45:17 -0800
Subject: [Tutor] Tutor Digest, Vol 45, Issue 30
In-Reply-To: <mailman.4019.1194836742.13604.tutor@python.org>
References: <mailman.4019.1194836742.13604.tutor@python.org>
Message-ID: <8249c4ac0711112045y39a7b84ahc972837d6ff16888@mail.gmail.com>

> Message: 4
> Date: Mon, 12 Nov 2007 00:16:35 -0000
> From: "Alan Gauld" <alan.gauld at btinternet.com>
> Subject: Re: [Tutor] Wrong version of Python being executed
> To: tutor at python.org
> Message-ID: <fh861b$up1$1 at ger.gmane.org>
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
>         reply-type=original
>

> This is very important. If you just type python at the Run
> dialog it uses a different algorithm to find the exe than if
> you type python at a DOS prompt inside a CMD window.

I never type anything in the Run dialog other than Regedit, or CMD.
I dont want that to sound defensive, but usually when I need a CMD
prompt, I'm need to be there for a long time, and that's why I open
it.
It never even occurred to me to type Python at the Run prompt.

Most of the time, I open a cmd prompt IN the directory where I want to
run a script, by using "Command Prompt Here", from Microsoft.
(why isn't this built into the OS after all this time ??????????)

But while troubleshooting this problem, I've not been using it, and
have been CD'ing down to where my sources are.

> Its the second algorithm that is used if you type
> python foo.py at a cmd prompt but the first that
> is used if you double click foo.py within explorer
I typically dont double click my scripts, unless they are guis, or exes'

> That *shouldn't* make any difference...but you can never be 100% sure!

I think a this point, I'll just re-install 2.3 and 2.5 to see if that
fixes it, with a reboot in-between.
I dont know what else to do.

From steve at alchemy.com  Mon Nov 12 05:50:30 2007
From: steve at alchemy.com (Steve Willoughby)
Date: Sun, 11 Nov 2007 20:50:30 -0800
Subject: [Tutor] assignment question
In-Reply-To: <962068b0711112021u748172ecv4eedbc5f2b3a385f@mail.gmail.com>
References: <962068b0711112021u748172ecv4eedbc5f2b3a385f@mail.gmail.com>
Message-ID: <4737DB96.8080202@alchemy.com>

Ryan Hughes wrote:
> Hello,
> 
> Why does the following not return [1,2,3,4] ?
> 
>>>> x = [1,2,3].append(4)
>>>> print x
> None

because the append() method doesn't return a copy of the list object; it 
just modifies the list itself.

so your code constructs a list object with 3 elements, appends a fourth 
element to it, and throws that list object away, keeping only the return 
value of append().


From jeff at drinktomi.com  Mon Nov 12 05:49:52 2007
From: jeff at drinktomi.com (Jeff Younker)
Date: Sun, 11 Nov 2007 20:49:52 -0800
Subject: [Tutor] assignment question
In-Reply-To: <962068b0711112021u748172ecv4eedbc5f2b3a385f@mail.gmail.com>
References: <962068b0711112021u748172ecv4eedbc5f2b3a385f@mail.gmail.com>
Message-ID: <1BF2128E-6D18-4573-B1A0-ADB3FBA5F798@drinktomi.com>

Append modifies the array as a side effect.  It has no
meaningful return value.

 >>> x = [1, 2, 3]
 >>> x.append(4)
 >>> print x
[1, 2, 3, 4]

- Jeff Younker - jeff at drinktomi.com - 510.798.5804 -


On Nov 11, 2007, at 8:21 PM, Ryan Hughes wrote:

>
> Hello,
>
> Why does the following not return [1,2,3,4] ?
>
> >>> x = [1,2,3].append(4)
> >>> print x
> None
> _______________________________________________
> 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/20071111/f3968169/attachment-0001.htm 

From wescpy at gmail.com  Mon Nov 12 07:42:40 2007
From: wescpy at gmail.com (wesley chun)
Date: Sun, 11 Nov 2007 22:42:40 -0800
Subject: [Tutor] Swapping variables ...
In-Reply-To: <20071111053541.GC3663@gmail.com>
References: <5df213700711091024l325d019bq636ed056ad201d99@mail.gmail.com>
	<20071111053541.GC3663@gmail.com>
Message-ID: <78b3a9580711112242u44fc7198v59751d3011898469@mail.gmail.com>

On 11/10/07, O.R.Senthil Kumaran <orsenthil at gmail.com> wrote:
> >  After quizzing newbies in C on swapping without 3rd variable, I found this
> > to be really *cool* construct to swap :)
> > x = 10
> > y = 20
> > x,y = y,x
>
> Keep in mind that, this is actually a tuple assignment.
> A new tuple x,y is created with the older one y,x, and with the side effect thatthe variables are swapped as we see it.

you can dig even *deeper* within the tuple assignment.  keep in mind
that the right-hand side (RHS) is always evaluated 1st, whenever there
is an assignment operation.  an alias or reference mapping is made
using the variable name (in the current or designated namespace) to
whatever object appears on the RHS.

this means that 'x' on the LHS gets whatever object 'y' was
referencing during evaluation time, and likewise, 'y' becomes an alias
to whatever object 'x' was pointing to.  it's just a "coincidence"
that the new mapping variables are just reversed to what they were
previously. the interpreter makes no special distinction just because
this is the case.

if you are still thinking of variables as data structures which
contain values, you need to "unlearn what you have learned." :-)
variables in Python are merely references to objects and such
references can be manipulated at will. for example, a variable 'a' as
in 'a = 123' can be immediately reassigned to a string, i.e., "a =
'foo'". getting comfortable with objects, references, and the mapping
of names to objects are some ways of understanding Python more fully
and with greater success.

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 alan.gauld at btinternet.com  Mon Nov 12 09:59:41 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 12 Nov 2007 08:59:41 -0000
Subject: [Tutor] manipulating data
References: <fbf64d2b0711061154v4f6547bcx133c342f2d5aac27@mail.gmail.com><4731C327.6000704@tds.net>
	<47330268.1080304@bigfoot.com>
	<fbf64d2b0711111702g7161a4bal2b3bc83bb6761d84@mail.gmail.com>
Message-ID: <fh94m5$1h6$1@ger.gmane.org>

"Bryan Fodness" <bryan.fodness at gmail.com> wrote in

> fields = {}
> for line in open('data.txt') :
>    if line :   ## You shouldn't need this.
>       if line.split()[0] == 'field' :
>           field = int(line.split()[-1])
>       else :
>           fields[field] = tuple(line.split())
>
> fields[field] = tuple(line.split())
> NameError: name 'field' is not defined

As you should expect since you only define field inside
the if branch so if you go down the else route first then
field will not exist.

I'm jumping into this rather late but I'd have thought
something like this (untested code) might work:

fields = {}
for line in open('data.txt'):
    try:
       name,value = line.split()
       fields[name] = int(value)
    except AttributeError: pass  # catches blank lines

Or if you can control the data format the ConfigParser module
might be a better solution.


HTH,

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






On Nov 8, 2007 7:34 AM, Ricardo Ar?oz <ricaraoz at gmail.com> wrote:
>
> Kent Johnson wrote:
> > Bryan Fodness wrote:
> >> I would like to have my data in a format so that I can create a 
> >> contour plot.
> >>
> >> My data is in a file with a format, where there may be multiple 
> >> fields
> >>
> >> field = 1
> >>
> >> 1a   0
> >
> > If your data is really this regular, it is pretty easy to parse. A
> > useful technique is to access a file's next method directly. 
> > Something
> > like this (not tested!):
> >
> > f = open('data.txt')
> > fields = {} # build a dict of fields
> > try:
> >    while True:
> >      # Get the field line
> >      line = f.next()
> >      field = int(line.split()[-1]) # last part of the line as an 
> > int
> >
> >      f.next() # skip blank line
> >
> >      data = {} # for each field, map (row, col) to value
> >      for i in range(20): # read 20 data lines
> >        line = f.next()
> >        ix, value = f.split()
> >        row = int(ix[:-1])
> >        col = ix[-1]
> >        data[row, col] = int(value)
> >
> >      fields[field] = data
> >
> >      f.next()
> > except StopIteration:
> >    pass
> >
>
> Or maybe just (untested) :
>
> fields = {} # build a dict of fields
> for line in open('data.txt') :
>    if line :    # skip blank lines
>        if line.split()[0] == 'field' :
>            field = int(line.split()[-1])
>        else :
>            fields[field] = tuple(line.split())
>
> _______________________________________________
> 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 alan.gauld at btinternet.com  Mon Nov 12 10:06:49 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 12 Nov 2007 09:06:49 -0000
Subject: [Tutor] [tutor] File format conversion
References: <c2157c790711111910u2ea003adg408ca5383aac9250@mail.gmail.com>
Message-ID: <fh953h$2rg$1@ger.gmane.org>


"Varsha Purohit" <varsha.purohit at gmail.com> wrote

>       In one application i want to convert format of ascii file to
> binary file.

That depends entirely on what the ASCII file contains.
Is it a comma separated list of RGB values? Or is it
a uuencode of the binary data? Or something else...

> And using that binary file in a function of PIL i can
> convert it to an image file.

Depending on the formatting you may not need PIL,
but it all depends on what the ASCII contains.

> So i wanted to know how to convert the
> file format in python... is it possible by Numpy ??

You may only need one of the encode/decode libraries
for something like uuencoding or maybe the struct module
will do if its just raw bitmap data.

> other alternative to convert an ascii into an bitmap image directly 
> in
> PIL without Numpy??

Yes you can always do it manually but it all depends
on the format of the data.

-- 
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 Nov 12 10:14:05 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 12 Nov 2007 09:14:05 -0000
Subject: [Tutor] Wrong version of Python being executed
References: <8249c4ac0711112037y4bd6fb8dgb8e6ef4140f91611@mail.gmail.com>
Message-ID: <fh95h5$47r$1@ger.gmane.org>


"Tony Cappellini" <cappy2112 at gmail.com> wrote

> I have to switch between 2.3 and 2.5, so to make it easy, I use an
> environment variable called CURRENT_PYTHON.
> (someone on this list or the wxPython list told me I should NOT use
> PYTHONPATH and modify it the way I am using CURRENT_PYTHON)
>
> CURRENT_PYTHON=C:\PYTHON2X
> path=%CURRENT_PYTHON%
> (The existing path isn't shown, only for brevity)

> Note, these are entered in Ctrl Panel, System environment variables,
> NOT at the command line.

Umm, have you rebooted? Probably an obvious step but I don't
think environment vars get reset in real time. They didn't used
to on NT but that may have changed in W2K or XP... I haven't
checked in a while.

Othewise I'm as stumped as you.

Alan G 



From alan.gauld at btinternet.com  Mon Nov 12 10:19:14 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 12 Nov 2007 09:19:14 -0000
Subject: [Tutor] Problem with default arguments for function
References: <20071111235352.CC7C21E4002@bag.python.org><18231.43012.646716.111029@euclid.slu.edu>
	<20071112030434.80A681E4016@bag.python.org>
Message-ID: <fh95qq$583$1@ger.gmane.org>


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

>>Another typical strategy is to use some prescribed special value for
>>the precision parameter to designate the desire for full precision.
> ....
> Beautiful! Thanks!

It seems I misunderstood your question.

I thought you were referring to the general problem of having
two (or more) default value parameters and wanting to refer to
either without using names or having to use all 3 values. Thats
when a wrapper is required. The solution above is better
where you are only using one parameter to control another.

Just to clarify things. The wrapper solution is not nice for
this problem but the only one I know of for the "any 2 from 3"
scenario.

Alan G.




From kent37 at tds.net  Mon Nov 12 12:50:58 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 12 Nov 2007 06:50:58 -0500
Subject: [Tutor] visualizing code structure / flow charting
In-Reply-To: <loom.20071106T091426-26@post.gmane.org>
References: <loom.20071106T091426-26@post.gmane.org>
Message-ID: <47383E22.3040701@tds.net>

Timmie wrote:
> Hello,
> I am stepping forward into learning python and write my first programs now.
> To facilitate my development I have a question:
> 
> Is there a tool which I can run on my code and then get a flow chart from it or
> visualize its structure in another form?

Here is another tool that you might be interested in:
http://codeinvestigator.googlepages.com/main

I haven't tried it, I would be interested in a report if someone does...
Kent

From mwalsh at groktech.org  Mon Nov 12 15:51:16 2007
From: mwalsh at groktech.org (Martin Walsh)
Date: Mon, 12 Nov 2007 08:51:16 -0600
Subject: [Tutor] Wrong version of Python being executed
In-Reply-To: <fh95h5$47r$1@ger.gmane.org>
References: <8249c4ac0711112037y4bd6fb8dgb8e6ef4140f91611@mail.gmail.com>
	<fh95h5$47r$1@ger.gmane.org>
Message-ID: <47386864.6030801@groktech.org>

Alan Gauld wrote:
> "Tony Cappellini" <cappy2112 at gmail.com> wrote
> 
>> I have to switch between 2.3 and 2.5, so to make it easy, I use an
>> environment variable called CURRENT_PYTHON.
>> (someone on this list or the wxPython list told me I should NOT use
>> PYTHONPATH and modify it the way I am using CURRENT_PYTHON)
>>
>> CURRENT_PYTHON=C:\PYTHON2X
>> path=%CURRENT_PYTHON%
>> (The existing path isn't shown, only for brevity)
> 
>> Note, these are entered in Ctrl Panel, System environment variables,
>> NOT at the command line.

That seems like a perfectly rational approach, and good advice.

Unfortunately I don't have a windows machine to test/confirm at the
moment, but IIRC you can set both user-space and system-wide environment
variables this way. I think PATH is special, in that user-space PATH is
appended to the *end* of the system-wide PATH, where other vars set in
user-space override the system defaults? Is it possible you have
python23 in your system-wide path, and you've edited user-space path to
include %CURRENT_PYTHON%?

Regardless, as a test you might try to add C:\Python25 to the front of
your system-wide PATH temporarily. This should aid in diagnosing a
simple PATH lookup problem. But, I'm stumped also. I don't know of any
reason why you would be seeing this behavior if you are invoking python
in a consistent way.

> 
> Umm, have you rebooted? Probably an obvious step but I don't
> think environment vars get reset in real time. They didn't used
> to on NT but that may have changed in W2K or XP... I haven't
> checked in a while.

I believe that this has changed somewhat, where the environment is read
at program startup. So the env is not refreshed until you close and
re-launch the program in question (in this case 'cmd'). Not sure how
windows explorer is effected, which may require a logoff/logon.  But,
again I don't have a windows machine available to confirm, so take that
for what it's worth. It's not going to hurt to reboot, that's for certain.

> 
> Othewise I'm as stumped as you.
> 
> Alan G 


From marc.tompkins at gmail.com  Mon Nov 12 17:46:58 2007
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Mon, 12 Nov 2007 08:46:58 -0800
Subject: [Tutor] XP environment variables (was: Wrong version of Python
	being executed)
Message-ID: <40af687b0711120846j2ca970fo5d3225e7a707b8e2@mail.gmail.com>

Thus spake Alan G:

> > Note, these are entered in Ctrl Panel, System environment variables,
> > NOT at the command line.
>
> Umm, have you rebooted? Probably an obvious step but I don't
> think environment vars get reset in real time. They didn't used
> to on NT but that may have changed in W2K or XP... I haven't
> checked in a while.
>

Not quite true.
In W2K and XP (not sure about NT), changes to environment variables made via
the Control Panel will affect any NEW environments instantiated from the
moment you click OK in the Environment Variables dialog.
Easy to test:  Start/Run/CMD; type SET.  Go to
CPanel/System/Advanced/Environment Variables, create a new variable, click
OK to get back to System.  Switch back to your cmd prompt, type SET: no new
variable!    Start/Run/CMD again to start a new prompt; type SET: new
variable exists.

Something to be aware of, though - if CMD is being started by some other
process, it may inherit a 'stale' environment.  For instance, when I start a
command prompt via Launchy, my new variable does NOT exist.  It took me a
moment to realize that the new prompt was running in Launchy's environment,
which doesn't get refreshed until I reboot.
(The original poster mentioned that he always uses Start/Run/CMD, so this is
not affecting him; I merely mention this for others who might run into it.)

Let me also mention that this is the only drawback I've found to using
Launchy (www.launchy.net) in the months since I started using it, I've
probably saved several hours I would have wasted poking around in my Start
menu.  I've tried reorganizing my menus, but the mix of programs I use
day-to-day changes constantly.  I wholeheartedly recommend Launchy to any
Windows users out there.  (I have a similar utility in Ubuntu, but I don't
remember its name.  Mac users, of course, don't need anything like this, as
theirs is an entirely faith-based interface.)

Marc
-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071112/6f5a4cd1/attachment.htm 

From mail at timgolden.me.uk  Mon Nov 12 18:01:55 2007
From: mail at timgolden.me.uk (Tim Golden)
Date: Mon, 12 Nov 2007 17:01:55 +0000
Subject: [Tutor] XP environment variables (was: Wrong version of Python
 being executed)
In-Reply-To: <40af687b0711120846j2ca970fo5d3225e7a707b8e2@mail.gmail.com>
References: <40af687b0711120846j2ca970fo5d3225e7a707b8e2@mail.gmail.com>
Message-ID: <47388703.7040500@timgolden.me.uk>

Marc Tompkins wrote:
> In W2K and XP (not sure about NT), changes to environment variables made via
> the Control Panel will affect any NEW environments instantiated from the
> moment you click OK in the Environment Variables dialog.

...

> Something to be aware of, though - if CMD is being started by some other
> process, it may inherit a 'stale' environment.

*That's* why it is. For years I've launched my command shells from one
of various shortcut-key utils and I *never* tumbled to the fact that
that meant my cmd shell was running inside that util's process and so
didn't inherit env var changes. Thanks so much.

I have used Launchy, as a matter of fact, but for some reason it never
really clicked for me -- maybe I use a small enough range of programs
normally -- so I ended up uninstalling it. I agree it did what it did
very well, though.

TJG

From cappy2112 at gmail.com  Mon Nov 12 18:27:59 2007
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Mon, 12 Nov 2007 09:27:59 -0800
Subject: [Tutor] Wrong version of Python being executed
Message-ID: <8249c4ac0711120927k576c14aaid7707e95c94ac707@mail.gmail.com>

Date: Mon, 12 Nov 2007 09:14:05 -0000
From: "Alan Gauld" <alan.gauld at btinternet.com>
Subject: Re: [Tutor] Wrong version of Python being executed
To: tutor at python.org
Message-ID: <fh95h5$47r$1 at ger.gmane.org>
Content-Type: text/plain; format=flowed; charset="iso-8859-1";
       reply-type=original



>>Umm, have you rebooted? Probably an obvious step but I don't
many times

From marc.tompkins at gmail.com  Mon Nov 12 18:55:22 2007
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Mon, 12 Nov 2007 09:55:22 -0800
Subject: [Tutor] XP environment variables (was: Wrong version of Python
	being executed)
In-Reply-To: <47388703.7040500@timgolden.me.uk>
References: <40af687b0711120846j2ca970fo5d3225e7a707b8e2@mail.gmail.com>
	<47388703.7040500@timgolden.me.uk>
Message-ID: <40af687b0711120955s32248768tc43a14973530b870@mail.gmail.com>

Glad to help!  It wouldn't have occurred to me as quickly as it did, except
that I use Sysinternals' Process Explorer as a Task Mangler replacement - it
allows you to see a hierarchical list of processes, as well as the usual
sorted lists - and a week or two ago I happened to notice that CMD was
running as a child of Launchy.  Actually, "noticed" is too strong a word -
but today it clicked.  Learn something new every day, eh?


On Nov 12, 2007 9:01 AM, Tim Golden <mail at timgolden.me.uk> wrote:

>
> > Something to be aware of, though - if CMD is being started by some other
> > process, it may inherit a 'stale' environment.
>
> *That's* why it is. For years I've launched my command shells from one
> of various shortcut-key utils and I *never* tumbled to the fact that
> that meant my cmd shell was running inside that util's process and so
> didn't inherit env var changes. Thanks so much.
>
> I have used Launchy, as a matter of fact, but for some reason it never
> really clicked for me -- maybe I use a small enough range of programs
> normally -- so I ended up uninstalling it. I agree it did what it did
> very well, though.
>
> TJG
>

I do understand that Launchy might not be for everybody - but I expect to
use fifteen or twenty different programs today, and they are not necessarily
the same fifteen or twenty that I used yesterday.  So until I got hooked on
Launchy, I was wasting a lot of time poking around the Start Menu.  Since
using Launchy,  I've had to find other ways to waste time...

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

From matt at mattanddawn.orangehome.co.uk  Mon Nov 12 21:11:52 2007
From: matt at mattanddawn.orangehome.co.uk (Matt Smith)
Date: Mon, 12 Nov 2007 20:11:52 +0000
Subject: [Tutor] How to keep trying something until it doesn't return an
	error?
Message-ID: <4738B388.5050205@mattanddawn.orangehome.co.uk>

Hi there,

I am currently working on a noughts and crosses program to try and teach 
myself some very simple AI programming and also to start to use OOP in 
Python.

I am currently writing the framework for the game so I can then write a 
number of functions or a class to deal with the strategy side of things.

I'm stuck trying to write a method which will only accept a legal move 
and will keep asking until it gets a legal answer. I can see that 
working out how to do this efficiently will be very useful in my future 
programming as well.

I currently have the following code.

while 1:
     try:
         xpos = input ("Where do you want to go? ")
         gameboard.addx(xpos)
         gameboard.draw()
         break
     except cantgo:
         print "You can't go there!"

which calls the following method:

     def addx(self,pos):
         if pos in range(1,10) and self.state[pos-1] == "":
             self.state[pos-1] = "X"
         else:
             raise cantgo

The cells of the game are referenced by the numbers 1 to 9. The code 
gave the following error:

Traceback (most recent call last):
   File "noughts_and_crosses.py", line 49, in <module>
     except cantgo:
NameError: name 'cantgo' is not defined

Interesting the first pass of the code above did not return an error but 
the second pass did. Currently I have the same code twice for X's and 
O's. Next, I defined the error using:

cantgo = "can't go"

And now I get:

noughts_and_crosses.py:33: DeprecationWarning: raising a string 
exception is deprecated
   raise cantgo
You can't go there!

But the program will not let me enter any (valid) move at all now. This 
looks like it is not breaking out of the while loop correctly, which, 
when I look back at my code, is to be expected.

Is there a typical 'Pythonic' way of dealing with this situation.





From alan.gauld at btinternet.com  Mon Nov 12 23:22:43 2007
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Mon, 12 Nov 2007 22:22:43 +0000 (GMT)
Subject: [Tutor] manipulating data
Message-ID: <519328.57222.qm@web86710.mail.ird.yahoo.com>

Brian,

>     if line.split()[0] == 'Field':
>        field = int(line.split()[-1])
>
> IndexError: list index out of range


You have blank lines in the file, when you try to call split 
on an empty string you get an empty list so trying to 
index any element will result in an Index error.

That's why I suggested using exceptions, testing for 
every possible error condition could take a long time
and be error prone. Unfortunately I guessed the wrong 
error code and didn't realise you had some dross to 
wade through first... so its a wee bit more complex.

Personally I'd use a flag to detect when field had 
been found and set - ie set field to None and then 
test for that changing, then test for Leaf as you do.

So I think your algorithm should be

for line in file
    if 'Field' in line:
       field = int(line.split()[-1])
    elif 'Leaf' in line:
       fields[field] = line.split()[-1]
    else: file.next()

But I think there's another problem in that you are 
then overwriting the value of Leaf when I think you 
are trying to build a list? I'm not 100% sure what 
you are aiming for but hopefully its some help!

Alan G.




From ricaraoz at gmail.com  Mon Nov 12 14:25:18 2007
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Mon, 12 Nov 2007 10:25:18 -0300
Subject: [Tutor] manipulating data
In-Reply-To: <fh94m5$1h6$1@ger.gmane.org>
References: <fbf64d2b0711061154v4f6547bcx133c342f2d5aac27@mail.gmail.com><4731C327.6000704@tds.net>	<47330268.1080304@bigfoot.com>	<fbf64d2b0711111702g7161a4bal2b3bc83bb6761d84@mail.gmail.com>
	<fh94m5$1h6$1@ger.gmane.org>
Message-ID: <4738543E.7030800@bigfoot.com>

Alan Gauld wrote:
> "Bryan Fodness" <bryan.fodness at gmail.com> wrote in
> 
>> fields = {}
>> for line in open('data.txt') :
>>    if line :   ## You shouldn't need this.
>>       if line.split()[0] == 'field' :
>>           field = int(line.split()[-1])
>>       else :
>>           fields[field] = tuple(line.split())
>>
>> fields[field] = tuple(line.split())
>> NameError: name 'field' is not defined
> 
> As you should expect since you only define field inside
> the if branch so if you go down the else route first then
> field will not exist.
> 
> I'm jumping into this rather late but I'd have thought
> something like this (untested code) might work:
> 
> fields = {}
> for line in open('data.txt'):
>     try:
>        name,value = line.split()
>        fields[name] = int(value)
>     except AttributeError: pass  # catches blank lines
> 
> Or if you can control the data format the ConfigParser module
> might be a better solution.
> 
> 
> HTH,
> 

Nice use of try block!
I should point though that the OP's file has this structure :

> My data is in a file with a format, where there may be multiple fields
> > >>
> > >> field = 1
> > >>
> > >> 1a   0
> >
> >

So you have a line where you get the field key and then a line where you
get the values for that field (that's how I interpreted it), in that
case the error comes from the fact that there is no "field = n" line
before a value pair (if that would happen later the code I submitted
wouldn't catch the error). OR the OP's line "field = 0" was not part of
the file and then you have two choices, the "field" in the example
submitted is "1" and the data : (a, 0) and there may be multiple lines
with the same field, or there will be one data tuple for each "field"
value. That would be : (yes, I used Alan's code, nicer than mine)

Case 1) multiple tuples per field value
 fields = {}
 for line in open('data.txt'):
     try:
        name,value = line.split()
        fields.setdefault(name[:-1],
				[]).append(tuple(name[-1],int(value)))
     except AttributeError: pass  # catches blank lines


case 2) one tuple per field value
 fields = {}
 for line in open('data.txt'):
     try:
        name,value = line.split()
        fields[name[:-1]] = tuple(name[-1],int(value))
     except AttributeError: pass  # catches blank lines


I don't have the OP's original post at hand so maybe he should clarify
his file's structure.



From wescpy at gmail.com  Mon Nov 12 23:30:18 2007
From: wescpy at gmail.com (wesley chun)
Date: Mon, 12 Nov 2007 14:30:18 -0800
Subject: [Tutor] How to keep trying something until it doesn't return an
	error?
In-Reply-To: <4738B388.5050205@mattanddawn.orangehome.co.uk>
References: <4738B388.5050205@mattanddawn.orangehome.co.uk>
Message-ID: <78b3a9580711121430n4b3bd166wfcd97a30c72b639c@mail.gmail.com>

i won't have time to elaborate on everything here... i'll let the
other smart tutors on the list do that, but i'll give some short
snippets of advice down below....

> I'm stuck trying to write a method which will only accept a legal move
> and will keep asking until it gets a legal answer. I can see that
> working out how to do this efficiently will be very useful in my future
> programming as well.
>
> while 1:

you can use True/False for 1/0 now in Python.


>      try:
>          xpos = input ("Where do you want to go? ")

try to avoid use of input()... stick with raw_input() as it is less "dangerous."


>          gameboard.addx(xpos)
>          gameboard.draw()
>          break
>      except cantgo:
>          print "You can't go there!"

based on the this code plus that of addx() which you defined, you can
probably do this entire excercise without using exceptions at all...
it will help simplify things in this situation where exceptions are
not necessarily called for.


> cantgo = "can't go"
>
> And now I get:
>
> noughts_and_crosses.py:33: DeprecationWarning: raising a string
> exception is deprecated
>    raise cantgo

the reason why this is the case  is because exceptions used to be
strings but now are required to be classes.  if you really want to use
exceptions, you need to create something like:

class CantGoError(Exception):
    pass

hope this helps, if only a little!
-- 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 bryan.fodness at gmail.com  Tue Nov 13 00:14:33 2007
From: bryan.fodness at gmail.com (Bryan Fodness)
Date: Mon, 12 Nov 2007 18:14:33 -0500
Subject: [Tutor] manipulating data
In-Reply-To: <519328.57222.qm@web86710.mail.ird.yahoo.com>
References: <519328.57222.qm@web86710.mail.ird.yahoo.com>
Message-ID: <fbf64d2b0711121514x69f87e1aj69697c25fd75e17@mail.gmail.com>

Using the algorithm below, I get:

     Traceback (most recent call last):
       File "C:\Users\bryan\Documents\Yennes Medical
Physics\mlcShape\findvalue.py", line 49, in <module>
         file.next()
     TypeError: descriptor 'next' of 'file' object needs an argument

And, it is true that I am trying to build a list and not overwrite the value.

On Nov 12, 2007 5:22 PM, ALAN GAULD <alan.gauld at btinternet.com> wrote:
> Brian,
>
> >     if line.split()[0] == 'Field':
> >        field = int(line.split()[-1])
> >
> > IndexError: list index out of range
>
>
> You have blank lines in the file, when you try to call split
> on an empty string you get an empty list so trying to
> index any element will result in an Index error.
>
> That's why I suggested using exceptions, testing for
> every possible error condition could take a long time
> and be error prone. Unfortunately I guessed the wrong
> error code and didn't realise you had some dross to
> wade through first... so its a wee bit more complex.
>
> Personally I'd use a flag to detect when field had
> been found and set - ie set field to None and then
> test for that changing, then test for Leaf as you do.
>
> So I think your algorithm should be
>
> for line in file
>    if 'Field' in line:
>       field = int(line.split()[-1])
>    elif 'Leaf' in line:
>       fields[field] = line.split()[-1]
>    else: file.next()
>
> But I think there's another problem in that you are
> then overwriting the value of Leaf when I think you
> are trying to build a list? I'm not 100% sure what
> you are aiming for but hopefully its some help!
>
> Alan G.
>
>
>
>

From alan.gauld at btinternet.com  Tue Nov 13 00:55:14 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 12 Nov 2007 23:55:14 -0000
Subject: [Tutor] manipulating data
References: <519328.57222.qm@web86710.mail.ird.yahoo.com>
	<fbf64d2b0711121514x69f87e1aj69697c25fd75e17@mail.gmail.com>
Message-ID: <fhap5b$qh5$1@ger.gmane.org>

The lesson here is not to try to do two things at once...

>         file.next()
>     TypeError: descriptor 'next' of 'file' object needs an argument

OK, My algorithm was meant to be pseudo code so file was
not intended to be taken literally, its just a marker for an open
file object.

> And, it is true that I am trying to build a list and not overwrite 
> the value.

OK, That adds a bit more tweaking...

>> Personally I'd use a flag to detect when field had
>> been found and set - ie set field to None and then
>> test for that changing, then test for Leaf as you do.

That was before I went back to testing my own project....

>> So I think your algorithm should be
>>
>> for line in file
>>    if 'Field' in line:
>>       field = int(line.split()[-1])

and this was after - with no flag anywhere in sight! Oops.

I intended the if test to include a check for field == None...

if field == None and 'Field' in line:....

>>    elif 'Leaf' in line:
>>       fields[field] = line.split()[-1]
>>    else: file.next()
>>
>> But I think there's another problem in that you are
>> then overwriting the value of Leaf when I think you
>> are trying to build a list?

So we need to create an empty list entry where we
define field and then append here, so my pseudo
code now becomes:

f = open('foo.dat')
for line in f:
    if field == None and 'Field' in line:
       field = int(line.split()[-1])
       fields[field] = []
    elif 'Leaf' in line:
       fields[field].append(line.split()[-1])
    else: f.next()

still untested I'm afraid, so it still may not work.

HTH,

Alan G.



From bryan.fodness at gmail.com  Tue Nov 13 01:10:17 2007
From: bryan.fodness at gmail.com (Bryan Fodness)
Date: Mon, 12 Nov 2007 19:10:17 -0500
Subject: [Tutor] manipulating data
In-Reply-To: <fhap5b$qh5$1@ger.gmane.org>
References: <519328.57222.qm@web86710.mail.ird.yahoo.com>
	<fbf64d2b0711121514x69f87e1aj69697c25fd75e17@mail.gmail.com>
	<fhap5b$qh5$1@ger.gmane.org>
Message-ID: <fbf64d2b0711121610l7bb33348oc497d670ba228a73@mail.gmail.com>

I have tried,

f = open('TEST1.MLC')
fields = {}
for line in f:
  the_line = line.split()
  if the_line:
    if the_line[0] == 'Field':
      field = int(the_line[-1])
    elif the_line[0] == 'Leaf':
      fields[field] = the_line[-1]

which, sort of works, but it overwrites each value.

On Nov 12, 2007 6:55 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> The lesson here is not to try to do two things at once...
>
> >         file.next()
> >     TypeError: descriptor 'next' of 'file' object needs an argument
>
> OK, My algorithm was meant to be pseudo code so file was
> not intended to be taken literally, its just a marker for an open
> file object.
>
> > And, it is true that I am trying to build a list and not overwrite
> > the value.
>
> OK, That adds a bit more tweaking...
>
> >> Personally I'd use a flag to detect when field had
> >> been found and set - ie set field to None and then
> >> test for that changing, then test for Leaf as you do.
>
> That was before I went back to testing my own project....
>
> >> So I think your algorithm should be
> >>
> >> for line in file
> >>    if 'Field' in line:
> >>       field = int(line.split()[-1])
>
> and this was after - with no flag anywhere in sight! Oops.
>
> I intended the if test to include a check for field == None...
>
> if field == None and 'Field' in line:....
>
> >>    elif 'Leaf' in line:
> >>       fields[field] = line.split()[-1]
> >>    else: file.next()
> >>
> >> But I think there's another problem in that you are
> >> then overwriting the value of Leaf when I think you
> >> are trying to build a list?
>
> So we need to create an empty list entry where we
> define field and then append here, so my pseudo
> code now becomes:
>
> f = open('foo.dat')
> for line in f:
>    if field == None and 'Field' in line:
>       field = int(line.split()[-1])
>       fields[field] = []
>    elif 'Leaf' in line:
>       fields[field].append(line.split()[-1])
>    else: f.next()
>
> still untested I'm afraid, so it still may not work.
>
> HTH,
>
> Alan G.
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From sith618 at yahoo.com  Tue Nov 13 03:59:24 2007
From: sith618 at yahoo.com (sith .)
Date: Mon, 12 Nov 2007 18:59:24 -0800 (PST)
Subject: [Tutor] parsing an array
Message-ID: <892735.68371.qm@web33203.mail.mud.yahoo.com>

a = [[0,1,2,3,4,5],[1,2,3,4,5,6]]
  You cannot modify the same array when you are looping through it. You have to loop through the copy of the contents :- a[:].
   
  # Untested code
  for i in a[:]: # You are looping through the copy of contents
   
  # I'm new I'm going to try and explain my understanding of this code; pls correct if wrong
# i[0] is [0,1,2,3,4,5] and i[1] is the other
# the loop first goes to the list on the left then goes to the list on the right
  
   for j in i:
  
#each element in the sublist is now evaluated
# first 0 in i[0] then 1 in i[1] then back to 1 in i[0] and then to 2 in i[1]--------- is this right? 
       # implement your logic with j
       if j < i[0]: # or any dynamic conditional check.
  
the first time this loops,
0 in the first list or i[0] is evaulated against itself
what is the next j value for the next loop?
   a[i][j] = j <--------- don't understand this bit
   
   
  
Does this help you?
   
  I've looked on the net as well as my book (python dummies), but can't find an explantion for nested for loops in nested lists.  Would it be possible to explain?  Thank you.

       
---------------------------------
Never miss a thing.   Make Yahoo your homepage.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071112/4d25bea4/attachment.htm 

From somas1 at gmail.com  Tue Nov 13 01:59:21 2007
From: somas1 at gmail.com (somas1)
Date: Mon, 12 Nov 2007 19:59:21 -0500
Subject: [Tutor] issues with pyglet and OS X Leopard
Message-ID: <2A26EAB9-8B70-4D21-B37F-98B2237233BA@gmail.com>

I've recently upgraded to  OS X 10.5 and have really appreciated the  
perks of having Python 2.5 being part of the standard install as well  
as easy_install, wxpython and others.   I've been trying to experiment  
with pyglet from http://www.pyglet.org and have been having some  
surprising difficulties.

I've downloaded http://pyglet.googlecode.com/files/pyglet-1.0beta1.dmg  
and installed the .mpkg. When I try to import pyglet, I get an error  
message stating that there is no module named pyglet.

I've tried to install via easy_install pyglet-1.0beta1-py2.5.egg and I  
get a message stating "Installed /Library/Python/2.5/site-packages/ 
pyglet-1.0beta1-py2.5.egg", however, when I try to import pyglet I get  
an error message stating there is no module named pyglet.

It looks like all of the default python modules are installed under / 
System/Library/Frameworks/Python Framework/Versions/2.5/lib/ 
python2.5.  Is this where I need to install pyglet?  If so why did the  
dmg and he egg I dl'ed from pyglet.org not install to the right place?  
I've never had this problem running OS X panther or tiger.


Any help will be appreciated.

John



From oclbdk at gmail.com  Tue Nov 13 04:39:05 2007
From: oclbdk at gmail.com (Johnston Jiaa)
Date: Mon, 12 Nov 2007 22:39:05 -0500
Subject: [Tutor] Tkinter Canvas Widget
Message-ID: <6927525B-8840-413B-9D45-6534A5459346@gmail.com>

I'm trying to create a free-hand drawing area on my program using the  
Tkinter canvas widget.  I have read through all the methods on Canvas  
objects <http://infohost.nmt.edu/tcc/help/pubs/tkinter/canvas- 
methods.html>, but do not see how to get the coordinates of the mouse  
on the canvas.

Also, after I get those coordinates, which methods would be  
appropriate to draw the points onto the canvas itself?

I appreciate any pointers or links to resources or anything at all.

Johnston Jiaa

From john at fouhy.net  Tue Nov 13 04:59:30 2007
From: john at fouhy.net (John Fouhy)
Date: Tue, 13 Nov 2007 16:59:30 +1300
Subject: [Tutor] Tkinter Canvas Widget
In-Reply-To: <6927525B-8840-413B-9D45-6534A5459346@gmail.com>
References: <6927525B-8840-413B-9D45-6534A5459346@gmail.com>
Message-ID: <5e58f2e40711121959j1e1997e4i7276fbb2893b324b@mail.gmail.com>

On 13/11/2007, Johnston Jiaa <oclbdk at gmail.com> wrote:
> I'm trying to create a free-hand drawing area on my program using the
> Tkinter canvas widget.  I have read through all the methods on Canvas
> objects <http://infohost.nmt.edu/tcc/help/pubs/tkinter/canvas-
> methods.html>, but do not see how to get the coordinates of the mouse
> on the canvas.
>
> Also, after I get those coordinates, which methods would be
> appropriate to draw the points onto the canvas itself?

It's been a while since I used Tkinter, but from memory:

To get the mouse coordinates, you'll need to use events.  Check out
http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm for some
details.

Essentially, you'll need to bind a function to the B1-Motion event,
and then inspect the event object to find out the mouse location.

(I'm assuming here that you only want to draw your lines when the user
has a button depressed..)

To draw points, you could perhaps use canvas.create_oval with a small
bounding box.

HTH!

-- 
John.

From aditya.n.lal at gmail.com  Tue Nov 13 06:55:49 2007
From: aditya.n.lal at gmail.com (Aditya Lal)
Date: Tue, 13 Nov 2007 11:25:49 +0530
Subject: [Tutor] parsing an array
In-Reply-To: <892735.68371.qm@web33203.mail.mud.yahoo.com>
References: <892735.68371.qm@web33203.mail.mud.yahoo.com>
Message-ID: <5df213700711122155v686a1911i910d6c6e96887a98@mail.gmail.com>

On Nov 13, 2007 8:29 AM, sith . <sith618 at yahoo.com> wrote:

> a = [[0,1,2,3,4,5],[1,2,3,4,5,6]]
> You cannot modify the same array when you are looping through it. You have
> to loop through the copy of the contents :- a[:].
>
> # Untested code
> for i in a[:]: # You are looping through the copy of contents
>
> # I'm new I'm going to try and explain my understanding of this code; pls
> correct if wrong
> # i[0] is [0,1,2,3,4,5] and i[1] is the other
> # the loop first goes to the list on the left then goes to the list on the
> right
>
>    for j in i:
>
> #each element in the sublist is now evaluated
> # first 0 in i[0] then 1 in i[1] then back to 1 in i[0] and then to 2 in
> i[1]--------- is this right?
>        # implement your logic with j
>        if j < i[0]: # or any dynamic conditional check.
>
> the first time this loops,
> 0 in the first list or i[0] is evaulated against itself
> what is the next j value for the next loop?
>    a[i][j] = j <--------- don't understand this bit
>
>
>
> Does this help you?
>
> I've looked on the net as well as my book (python dummies), but can't find
> an explantion for nested for loops in nested lists.  Would it be possible to
> explain?  Thank you.
>
> ------------------------------
>
>
Not sure but it looks like you want to iterate over an array of array (using
C syntax).

for i in a[:] will make i point to the elements of the list and not its
index. For getting the index you need to use enumerate or just range(len(a))
as in :

for i in range(len(a)) :
    # now you can access element as a[i]
    for j in range(len(a[i])) :
        # now you can access the inner array element as a[i][j]
        a[i][j] *= 2

You can use this to modify the array content as well. But do exercise
caution in case of length change.

Or have I completely misunderstood your question ?

--
Aditya
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071113/74763c03/attachment.htm 

From alan.gauld at btinternet.com  Tue Nov 13 09:59:39 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 13 Nov 2007 08:59:39 -0000
Subject: [Tutor] Tkinter Canvas Widget
References: <6927525B-8840-413B-9D45-6534A5459346@gmail.com>
Message-ID: <fhbp24$4au$1@ger.gmane.org>


"Johnston Jiaa" <oclbdk at gmail.com> wrote

> methods.html>, but do not see how to get the coordinates of the 
> mouse
> on the canvas.

Any mouse event will give you the coordinates within the event data.
Trapping the mouse Movment will ensure you track the current position,

> Also, after I get those coordinates, which methods would be
> appropriate to draw the points onto the canvas itself?

There are lots of drawing methods depending on what kind of
thing you want to draw. You can draw lines, arcs, ovals,
rectangles etc. If you just want to draw a single point then you
can use a very short line or very small filled rectangle or circle.

If you can show us some sample code where you are having
problems we can be of more help.


-- 
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 Nov 13 10:03:00 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 13 Nov 2007 09:03:00 -0000
Subject: [Tutor] manipulating data
References: <519328.57222.qm@web86710.mail.ird.yahoo.com><fbf64d2b0711121514x69f87e1aj69697c25fd75e17@mail.gmail.com><fhap5b$qh5$1@ger.gmane.org>
	<fbf64d2b0711121610l7bb33348oc497d670ba228a73@mail.gmail.com>
Message-ID: <fhbp8d$504$1@ger.gmane.org>


"Bryan Fodness" <bryan.fodness at gmail.com> 

> f = open('TEST1.MLC')
> fields = {}
> for line in f:
>  the_line = line.split()
>  if the_line:
>    if the_line[0] == 'Field':
>      field = int(the_line[-1])
>    elif the_line[0] == 'Leaf':
>      fields[field] = the_line[-1]
> 
> which, sort of works, but it overwrites each value.

You need to create an empty list when you define field
and you need to append top that list. See the pseudo 
code I sent last time...

>> So we need to create an empty list entry where we
>> define field and then append here, so my pseudo
>> code now becomes:
>>
>> f = open('foo.dat')
>> for line in f:
>>    if field == None and 'Field' in line:
>>       field = int(line.split()[-1])
>>       fields[field] = []
>>    elif 'Leaf' in line:
>>       fields[field].append(line.split()[-1])
>>    else: f.next()
>>

Alan G.


From bgailer at alum.rpi.edu  Tue Nov 13 14:36:11 2007
From: bgailer at alum.rpi.edu (bob gailer)
Date: Tue, 13 Nov 2007 08:36:11 -0500
Subject: [Tutor] parsing an array
In-Reply-To: <5df213700711122155v686a1911i910d6c6e96887a98@mail.gmail.com>
References: <892735.68371.qm@web33203.mail.mud.yahoo.com>
	<5df213700711122155v686a1911i910d6c6e96887a98@mail.gmail.com>
Message-ID: <4739A84B.50308@alum.rpi.edu>

Aditya Lal wrote:
> [snip]

> for i in a[:] will make i point to the elements of the list
To be more precise:
a[:] is a copy of the list
the for statement assigns each list element in turn to i. Assign is not 
exactly the same as point.


From aditya.n.lal at gmail.com  Tue Nov 13 14:48:04 2007
From: aditya.n.lal at gmail.com (Aditya Lal)
Date: Tue, 13 Nov 2007 19:18:04 +0530
Subject: [Tutor] parsing an array
In-Reply-To: <4739A84B.50308@alum.rpi.edu>
References: <892735.68371.qm@web33203.mail.mud.yahoo.com>
	<5df213700711122155v686a1911i910d6c6e96887a98@mail.gmail.com>
	<4739A84B.50308@alum.rpi.edu>
Message-ID: <5df213700711130548h5505f1efg536e4667e833de72@mail.gmail.com>

On Nov 13, 2007 7:06 PM, bob gailer <bgailer at alum.rpi.edu> wrote:

> Aditya Lal wrote:
> > [snip]
>
> > for i in a[:] will make i point to the elements of the list
> To be more precise:
> a[:] is a copy of the list
> the for statement assigns each list element in turn to i. Assign is not
> exactly the same as point.
>
>
Yup! Bob is right. I just cut-paste the example from previous mail. It
should be for i in a :
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071113/081a5bfa/attachment.htm 

From sanelson at gmail.com  Tue Nov 13 15:13:08 2007
From: sanelson at gmail.com (Stephen Nelson-Smith)
Date: Tue, 13 Nov 2007 14:13:08 +0000
Subject: [Tutor] NNTP Client
Message-ID: <b6131fdc0711130613n4a39c334n7c00c04a6beb7ae0@mail.gmail.com>

Hello all,

I wish to pull all the articles for one particular newsgroup to a
local machine, on a regular basis.  I don't wish to read them - I will
be parsing the contents programatically.  In your view is it going to
be best to use an 'off-the-shelf' news reader, or ought it to be
straightforward to write a client that does this task?  If so, any
pointers would be most welcome.

S.

From sanelson at gmail.com  Tue Nov 13 17:01:30 2007
From: sanelson at gmail.com (Stephen Nelson-Smith)
Date: Tue, 13 Nov 2007 16:01:30 +0000
Subject: [Tutor] NNTP Client
In-Reply-To: <b6131fdc0711130613n4a39c334n7c00c04a6beb7ae0@mail.gmail.com>
References: <b6131fdc0711130613n4a39c334n7c00c04a6beb7ae0@mail.gmail.com>
Message-ID: <b6131fdc0711130801l379a9765yef3b39854bbb4e78@mail.gmail.com>

On Nov 13, 2007 2:13 PM, Stephen Nelson-Smith <sanelson at gmail.com> wrote:

> ought it to be straightforward to write a client that does this task?

Well:

>>> server = NNTP('news.gmane.org')
>>> resp, count, first, last, name =
server.group("gmane.linux.redhat.enterprise.announce")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.5/nntplib.py", line 346, in group
    resp = self.shortcmd('GROUP ' + name)
  File "/usr/lib/python2.5/nntplib.py", line 260, in shortcmd
    return self.getresp()
  File "/usr/lib/python2.5/nntplib.py", line 215, in getresp
    resp = self.getline()
  File "/usr/lib/python2.5/nntplib.py", line 207, in getline
    if not line: raise EOFError
EOFError

What's wrong with that then?

S.

From dineshbvadhia at hotmail.com  Tue Nov 13 17:40:50 2007
From: dineshbvadhia at hotmail.com (Dinesh B Vadhia)
Date: Tue, 13 Nov 2007 08:40:50 -0800
Subject: [Tutor] global is bad but ...
Message-ID: <BAY109-DAV3A862EE3CDD3919DB9648A3800@phx.gbl>

Consider a data structure (say, an array) that is operated on by a bunch of functions eg.

def function_A
    global array_G
    do stuff with array_G
    return

def function_B
    global array_G
    do stuff with array_G
    return

def function_C
    global array_G
    do stuff with array_G
    return

The described way is to place the statement 'global' in line 1 of each function.  On the other hand, wiser heads say that the use of 'global' is bad and that reworking the code into classes and objects is better.

What do you think and suggest?

Dinesh
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071113/9538cca9/attachment.htm 

From kent37 at tds.net  Tue Nov 13 18:03:57 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 13 Nov 2007 11:03:57 -0600
Subject: [Tutor] global is bad but ...
In-Reply-To: <BAY109-DAV3A862EE3CDD3919DB9648A3800@phx.gbl>
Message-ID: <20071113110357.UL13K.170447.root@webfep12>


---- Dinesh B Vadhia <dineshbvadhia at hotmail.com> wrote: 
> Consider a data structure (say, an array) that is operated on by a bunch of functions
> 
> The described way is to place the statement 'global' in line 1 of each function.  On the other hand, wiser heads say that the use of 'global' is bad and that reworking the code into classes and objects is better.
> 
> What do you think and suggest?

Yes, global is bad.

- Pass array_G as a parameter to each function
or
- Make all three functions methods of a class with array_G as an attribute.

Kent
> 
> Dinesh


From brunson at brunson.com  Tue Nov 13 18:25:22 2007
From: brunson at brunson.com (Eric Brunson)
Date: Tue, 13 Nov 2007 10:25:22 -0700
Subject: [Tutor] global is bad but ...
In-Reply-To: <20071113110357.UL13K.170447.root@webfep12>
References: <20071113110357.UL13K.170447.root@webfep12>
Message-ID: <4739DE02.9090407@brunson.com>

Kent Johnson wrote:
> ---- Dinesh B Vadhia <dineshbvadhia at hotmail.com> wrote: 
>   
>> Consider a data structure (say, an array) that is operated on by a bunch of functions
>>
>> The described way is to place the statement 'global' in line 1 of each function.  On the other hand, wiser heads say that the use of 'global' is bad and that reworking the code into classes and objects is better.
>>
>> What do you think and suggest?
>>     
>
> Yes, global is bad.
>
> - Pass array_G as a parameter to each function
> or
> - Make all three functions methods of a class with array_G as an attribute.
>   

Global is almost always bad.  Sometimes you can make a valid argument 
that information truly has a global context, such as a debug flag, or 
the parsed options that were passed from the command line.

Different philosophies...

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


From sanelson at gmail.com  Tue Nov 13 19:13:07 2007
From: sanelson at gmail.com (Stephen Nelson-Smith)
Date: Tue, 13 Nov 2007 18:13:07 +0000
Subject: [Tutor] NNTP Client
In-Reply-To: <b6131fdc0711130801l379a9765yef3b39854bbb4e78@mail.gmail.com>
References: <b6131fdc0711130613n4a39c334n7c00c04a6beb7ae0@mail.gmail.com>
	<b6131fdc0711130801l379a9765yef3b39854bbb4e78@mail.gmail.com>
Message-ID: <b6131fdc0711131013p99b4bb1ga7bda363f8ae3ab2@mail.gmail.com>

On Nov 13, 2007 4:01 PM, Stephen Nelson-Smith <sanelson at gmail.com> wrote:
> >>> server = NNTP('news.gmane.org')
>
> What's wrong with that then?

server, apparently:>>> s.group("gmane.discuss")
('211 11102 10 11329 gmane.discuss', '11102', '10', '11329', 'gmane.discuss')
>>> server.group("gmane.discuss")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.5/nntplib.py", line 346, in group
    resp = self.shortcmd('GROUP ' + name)
  File "/usr/lib/python2.5/nntplib.py", line 259, in shortcmd
    self.putcmd(line)
  File "/usr/lib/python2.5/nntplib.py", line 199, in putcmd
    self.putline(line)
  File "/usr/lib/python2.5/nntplib.py", line 194, in putline
    self.sock.sendall(line)
  File "<string>", line 1, in sendall
socket.error: (32, 'Broken pipe')

Stupid of me.

S.

From ajayan_rs at yahoo.com  Tue Nov 13 21:10:18 2007
From: ajayan_rs at yahoo.com (Ajaya Mohan R. S.)
Date: Tue, 13 Nov 2007 12:10:18 -0800 (PST)
Subject: [Tutor] Error: 'module' object is not callable
Message-ID: <716815.92160.qm@web53701.mail.re2.yahoo.com>

Hi,
I am trying to run a code for plotting Taylor diagram,
ending up with the following errors. How do I fix
these errors? Help appreciated.

best,
Ajay

Read observation data...
Read 'mri_cgcm2_3_2a' model output...
Compute comparison statistics...
Error treating model: mri_cgcm2_3_2a
Error: 'module' object is not callable
Model: mri_cgcm2_3_2a ignored
Traceback (most recent call last):
  File "model_vs_data_comp_stat.py", line 1471, in ?
    normalize_sign_option=normalize_sign_option,
scaling_factor=scaling_factor)
  File "model_vs_data_comp_stat.py", line 1197, in
model_vs_data_comp_stat
    all_model_output = MV.sort (all_model_output, 0)
  File
"/usr/local/cdat-4.1.2/lib/python2.4/site-packages/cdms/MV.py",
line 310, in sort
    maresult = MA.sort(a, axis)
  File
"/usr/local/cdat-4.1.2/lib/python2.4/site-packages/Numeric/MA/MA.py",
line 2029, in sort
    s = Numeric.sort(d, axis)
  File
"/usr/local/cdat-4.1.2/lib/python2.4/site-packages/Numeric/Numeric.py",
line 257, in sort
    raise ValueError, "sort axis argument out of
bounds"
ValueError: sort axis argument out of bounds



      ___________________________________________________________
Yahoo! Answers - Got a question? Someone out there knows the answer. Try it
now.
http://uk.answers.yahoo.com/ 

From washakie at gmail.com  Tue Nov 13 22:40:37 2007
From: washakie at gmail.com (John)
Date: Tue, 13 Nov 2007 22:40:37 +0100
Subject: [Tutor] subprocess help, nohup
Message-ID: <aaf235960711131340wda4ef16qbc8fb1cb05ab6c09@mail.gmail.com>

Hello,

I've written a script which conducts several subprocess calls and then
ultimately calls a shell script which runs even more programs... my script
is using subprocess to execute a few sed calls, and then execute the script.
I'm getting strange behavior:

Here's a snippet of my script (any general comments are also welcome):

   if RUNS[k][3]==1: #model run complete, run is a DICT
    compWebPages=self.getCompletedWeb() #returns a DICT, which
RUNS[k][0] COULD be a key
    if RUNS[k][0] not in compWebPages.keys():
     runFile='make_'+RUNS[k][0]
     cmd = """sed -e 's/RUNmin=[0-9][0-9]*/RUNmin=%s/g' %s  > jnk""" %
(k,'make_wwwpages');
     subprocess.call(cmd,shell=True)
     cmd = """cat jnk | sed -e 's/RUNmax=[0-9][0-9]*/RUNmax=%s/g' > %s""" %
(k,runFile);
     subprocess.call(cmd,shell=True); subprocess.call('rm jnk',shell=True);
     os.chmod(runFile,0744)
     cmd="""./%s""" % (runFile)
     print "Starting %s" % (runFile)
     #subprocess.call(cmd,shell=True)
     q=raw_input('continue?');
     print "Done with: %s" % (RUNS[k][0])
     cmd="""rm %s""" % (runFile); subprocess.call(cmd,shell=True)


You'll notice, the last subprocess call is commented out. Right now I'm just
getting to that point to make sure everything is working. So, it seems to
work, but I'm not sure how to get it to work if I change the command to
nohup. I still want python to wait for it to return, in fact, I would like
to set the python job running in the background as well... so what I'm
looking at doing is:

% nohup myControl.py
   ---> which will make several subprocess.call(s) including some that
should be 'nohupped' as well...

Suggestions on the syntax of how to do this?

Thanks!






-- 
Configuration
``````````````````````````
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Five 1.4.1,
Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
4.1.1-51)],
PIL 1.1.6
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071113/73531047/attachment-0001.htm 

From nanoennui at gmail.com  Tue Nov 13 21:57:10 2007
From: nanoennui at gmail.com (Da'Nivek)
Date: Tue, 13 Nov 2007 15:57:10 -0500
Subject: [Tutor] Maya anyone?
Message-ID: <007c01c82637$c4ebbea0$6401a8c0@Zoe>

Hey there,

I'm trying to learn python to use in Maya
Would it be appropriate to post a question here?

thanks
Nivek

                       3D Artist 
                  
                        Kevin Nield   
                        http://www.kevinnield.com
                        AIM: nanoennui  mobile:  773 551 4678  
                       
                 
            
     
            Always have my latest info Want a signature like this? 
     
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071113/ca080a79/attachment.htm 

From alan.gauld at btinternet.com  Wed Nov 14 00:11:49 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 13 Nov 2007 23:11:49 -0000
Subject: [Tutor] global is bad but ...
References: <BAY109-DAV3A862EE3CDD3919DB9648A3800@phx.gbl>
Message-ID: <fhdavu$lao$1@ger.gmane.org>

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

> Consider a data structure (say, an array) that is operated 
> on by a bunch of functions eg.
>
> def function_A
>     global array_G

> def function_B
>     global array_G

> etc...

> On the other hand, wiser heads say that the use of 'global' 
> is bad and that reworking the code into classes and objects 
> is better.

Rather than answer your question directly can I ask, do 
you know *why* wiser heads say global is bad? What 
problems does using global introduce? What problems 
does it solve?

> What do you think and suggest?

I think it's better to understand issues and make informed 
choices rather than following the rules of others.

I suggest you consider whether global is bad in this case 
and what other solutions might be used instead. Then make 
an informed choice. If, having researched the subject you 
don't understand why global is (sometimes) bad ask for 
more info here.

HTH (a little),

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


From varsha.purohit at gmail.com  Wed Nov 14 00:12:20 2007
From: varsha.purohit at gmail.com (Varsha Purohit)
Date: Tue, 13 Nov 2007 15:12:20 -0800
Subject: [Tutor] [tutor] File format conversion
In-Reply-To: <fh953h$2rg$1@ger.gmane.org>
References: <c2157c790711111910u2ea003adg408ca5383aac9250@mail.gmail.com>
	<fh953h$2rg$1@ger.gmane.org>
Message-ID: <c2157c790711131512m432713cbi24293c9cd7f99ae8@mail.gmail.com>

Hello Alan,
     It is a file having colour data grid.. just like any simple ascii
file and i need to manipulate the numbers with colours. But at this
stage i am not much bothered with colurs i can associate it with
simple RGB value for all different numbers. ex. of such simple file
can be like this..
ncols         4
nrows         4
xllcorner     392800
yllcorner     5376340
cellsize      55
NODATA_value  -9999
9 3 7 3
8 3 2 7
3 2 1 3
3 7 3 2


and i need to associate each pixel of the image with this data in the
ascii... Did that help ??

thanks,
Varsha

On Nov 12, 2007 1:06 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> "Varsha Purohit" <varsha.purohit at gmail.com> wrote
>
> >       In one application i want to convert format of ascii file to
> > binary file.
>
> That depends entirely on what the ASCII file contains.
> Is it a comma separated list of RGB values? Or is it
> a uuencode of the binary data? Or something else...
>
> > And using that binary file in a function of PIL i can
> > convert it to an image file.
>
> Depending on the formatting you may not need PIL,
> but it all depends on what the ASCII contains.
>
> > So i wanted to know how to convert the
> > file format in python... is it possible by Numpy ??
>
> You may only need one of the encode/decode libraries
> for something like uuencoding or maybe the struct module
> will do if its just raw bitmap data.
>
> > other alternative to convert an ascii into an bitmap image directly
> > in
> > PIL without Numpy??
>
> Yes you can always do it manually but it all depends
> on the format of the data.
>
> --
> 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 bryan.fodness at gmail.com  Wed Nov 14 00:18:07 2007
From: bryan.fodness at gmail.com (Bryan Fodness)
Date: Tue, 13 Nov 2007 18:18:07 -0500
Subject: [Tutor] NumPy Question - numpy.put in multi-dimensional array
Message-ID: <fbf64d2b0711131518r10592613mc6b4f8aa7a3e2dfb@mail.gmail.com>

I see how to do it in a one-dimenstional array, but do not know the
syntax for the multi-dimensional case.


from numpy import *

a = zeros((60,40), int)

fields = {}
field = 10
fields[field] = '30A', 5

iy = int(fields[field][1])
ix = int(fields[field][0].rstrip('AB'))

for j in range(iy):
     put(a,[39 - j],[1])

Can someone help me figure out how I would do it for multiple rows?

I thought,

for i in range(ix):
   for j in range(iy):
        put(a,[i][39-j],[1])

but,

Traceback (most recent call last):
   put(a,[i][39 - j],[1])
IndexError: list index out of range

From alan.gauld at btinternet.com  Wed Nov 14 00:19:05 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 13 Nov 2007 23:19:05 -0000
Subject: [Tutor] Error: 'module' object is not callable
References: <716815.92160.qm@web53701.mail.re2.yahoo.com>
Message-ID: <fhdbdi$mhm$1@ger.gmane.org>

"Ajaya Mohan R. S." <ajayan_rs at yahoo.com> wrote 

> I am trying to run a code for plotting Taylor diagram,
> ending up with the following errors. How do I fix
> these errors? Help appreciated.

Without any sight of the code that caused them its hard 
to give sensible answers. We can only suggest general 
options:

> Error: 'module' object is not callable

Suggests that you are trying to call a module!
Do you have a pair of parens after a module name 
(or a reference to a module name) For example

import foo

# do some stuff

bar = foo
# more stuff
bar()   # error here coz bar refers to module foo


> Traceback (most recent call last):
>  File "model_vs_data_comp_stat.py", line 1471, in ?
>    normalize_sign_option=normalize_sign_option,
> scaling_factor=scaling_factor)

This looks like the end of a function/method call but 
we can't see the beginning...


>  File "model_vs_data_comp_stat.py", line 1197, in
> model_vs_data_comp_stat
>    all_model_output = MV.sort (all_model_output, 0)

> ValueError: sort axis argument out of bounds

So where is the axis value derived?

Other than that I doubt we can help without visibility 
of some code.

HTH,

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


From ajayan_rs at yahoo.com  Wed Nov 14 00:56:48 2007
From: ajayan_rs at yahoo.com (Ajaya Mohan R. S.)
Date: Tue, 13 Nov 2007 15:56:48 -0800 (PST)
Subject: [Tutor] Error: 'module' object is not callable
In-Reply-To: <fhdbdi$mhm$1@ger.gmane.org>
Message-ID: <699390.77128.qm@web53702.mail.re2.yahoo.com>

Hi,

Thanks. I have used the following code  

http://www.ipsl.jussieu.fr/~jmesce/Taylor_diagram/Miscelaneous/model_vs_data_comp_stat.py


ajay


--- Alan Gauld <alan.gauld at btinternet.com> wrote:

> "Ajaya Mohan R. S." <ajayan_rs at yahoo.com> wrote 
> 
> > I am trying to run a code for plotting Taylor
> diagram,
> > ending up with the following errors. How do I fix
> > these errors? Help appreciated.
> 
> Without any sight of the code that caused them its
> hard 
> to give sensible answers. We can only suggest
> general 
> options:
> 
> > Error: 'module' object is not callable
> 
> Suggests that you are trying to call a module!
> Do you have a pair of parens after a module name 
> (or a reference to a module name) For example
> 
> import foo
> 
> # do some stuff
> 
> bar = foo
> # more stuff
> bar()   # error here coz bar refers to module foo
> 
> 
> > Traceback (most recent call last):
> >  File "model_vs_data_comp_stat.py", line 1471, in
> ?
> >    normalize_sign_option=normalize_sign_option,
> > scaling_factor=scaling_factor)
> 
> This looks like the end of a function/method call
> but 
> we can't see the beginning...
> 
> 
> >  File "model_vs_data_comp_stat.py", line 1197, in
> > model_vs_data_comp_stat
> >    all_model_output = MV.sort (all_model_output,
> 0)
> 
> > ValueError: sort axis argument out of bounds
> 
> So where is the axis value derived?
> 
> Other than that I doubt we can help without
> visibility 
> of some code.
> 
> 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
> 



      ___________________________________________________________ 
Want ideas for reducing your carbon footprint? Visit Yahoo! For Good  http://uk.promotions.yahoo.com/forgood/environment.html

From jim at well.com  Wed Nov 14 01:21:32 2007
From: jim at well.com (jim stockford)
Date: Tue, 13 Nov 2007 16:21:32 -0800
Subject: [Tutor] global is bad but ...
In-Reply-To: <fhdavu$lao$1@ger.gmane.org>
References: <BAY109-DAV3A862EE3CDD3919DB9648A3800@phx.gbl>
	<fhdavu$lao$1@ger.gmane.org>
Message-ID: <2bba6212a31a865533787f74bf082113@well.com>

On Nov 13, 2007, at 3:11 PM, Alan Gauld wrote:

> Rather than answer your question directly can I ask, do
> you know *why* wiser heads say global is bad? What
> problems does using global introduce? What problems
> does it solve?


i'll try:

    globals are good because they provide common data to
one's entire program without issues of scope.

    globals are bad because one can design (or just allow to
happen) software in which globals are changed by
different entities within the program without coordination.
    the classic:
globflag = True
proc_1 checks globflag and starts to perform accordingly
proc_2 changes globflag to False for some good reason
before proc_1 has finished, and enough before so that
there's trouble.

    how to get the good without the bad? in a small program,
be a disciplined coder. in a large program, wrap the globals
in some function wrapper that doesn't easily allow changes
to the global data. in the above case, write some kind of
not_yet code to keep proc_2 from changing globflag until
after proc_1 is finished.

    okay, i tried. so why are globals bad and what problems
do they solve?


From eike.welk at gmx.net  Wed Nov 14 01:18:27 2007
From: eike.welk at gmx.net (Eike Welk)
Date: Wed, 14 Nov 2007 01:18:27 +0100
Subject: [Tutor] NumPy Question - numpy.put in multi-dimensional array
In-Reply-To: <fbf64d2b0711131518r10592613mc6b4f8aa7a3e2dfb@mail.gmail.com>
References: <fbf64d2b0711131518r10592613mc6b4f8aa7a3e2dfb@mail.gmail.com>
Message-ID: <200711140118.27645.eike.welk@gmx.net>

Hello Bryan!

On Wednesday 14 November 2007 00:18, Bryan Fodness wrote:
> I see how to do it in a one-dimenstional array, but do not know the
> syntax for the multi-dimensional case.
>
> >from numpy import *
>
> a = zeros((60,40), int)
>
> fields = {}
> field = 10
> fields[field] = '30A', 5
>
> iy = int(fields[field][1])
> ix = int(fields[field][0].rstrip('AB'))
>
> for j in range(iy):
>      put(a,[39 - j],[1])
Should be maybe:
       a[0, 39 - j] = 1

>
> Can someone help me figure out how I would do it for multiple rows?
>
> I thought,
>
> for i in range(ix):
>    for j in range(iy):
>         put(a,[i][39-j],[1])
change to:
          a[i, 39-j] = 1

You could replace the nested for loops by the following code:
a[:ix, :iy:-1] = 1

I think you shouldn't use put(...) in your code. It is a fairly 
specialized function.  

More information:
http://www.scipy.org/Numpy_Example_List_With_Doc#head-5202db3259f69441c695ab0efc0cdf45341829fc

Regards, 
Eike

From bryan.fodness at gmail.com  Wed Nov 14 01:57:23 2007
From: bryan.fodness at gmail.com (Bryan Fodness)
Date: Tue, 13 Nov 2007 19:57:23 -0500
Subject: [Tutor] NumPy Question - numpy.put in multi-dimensional array
In-Reply-To: <200711140118.27645.eike.welk@gmx.net>
References: <fbf64d2b0711131518r10592613mc6b4f8aa7a3e2dfb@mail.gmail.com>
	<200711140118.27645.eike.welk@gmx.net>
Message-ID: <fbf64d2b0711131657p78303d70vb3b1131bde54a1fa@mail.gmail.com>

Thank you.  That works great!

On Nov 13, 2007 7:18 PM, Eike Welk <eike.welk at gmx.net> wrote:
> Hello Bryan!
>
> On Wednesday 14 November 2007 00:18, Bryan Fodness wrote:
> > I see how to do it in a one-dimenstional array, but do not know the
> > syntax for the multi-dimensional case.
> >
> > >from numpy import *
> >
> > a = zeros((60,40), int)
> >
> > fields = {}
> > field = 10
> > fields[field] = '30A', 5
> >
> > iy = int(fields[field][1])
> > ix = int(fields[field][0].rstrip('AB'))
> >
> > for j in range(iy):
> >      put(a,[39 - j],[1])
> Should be maybe:
>       a[0, 39 - j] = 1
>
> >
> > Can someone help me figure out how I would do it for multiple rows?
> >
> > I thought,
> >
> > for i in range(ix):
> >    for j in range(iy):
> >         put(a,[i][39-j],[1])
> change to:
>          a[i, 39-j] = 1
>
> You could replace the nested for loops by the following code:
> a[:ix, :iy:-1] = 1
>
> I think you shouldn't use put(...) in your code. It is a fairly
> specialized function.
>
> More information:
> http://www.scipy.org/Numpy_Example_List_With_Doc#head-5202db3259f69441c695ab0efc0cdf45341829fc
>
> Regards,
> Eike
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From wescpy at gmail.com  Wed Nov 14 03:03:02 2007
From: wescpy at gmail.com (wesley chun)
Date: Tue, 13 Nov 2007 18:03:02 -0800
Subject: [Tutor] global is bad but ...
In-Reply-To: <2bba6212a31a865533787f74bf082113@well.com>
References: <BAY109-DAV3A862EE3CDD3919DB9648A3800@phx.gbl>
	<fhdavu$lao$1@ger.gmane.org>
	<2bba6212a31a865533787f74bf082113@well.com>
Message-ID: <78b3a9580711131803g5c1a14c1r5d3ea7d98a5048fe@mail.gmail.com>

>     okay, i tried. so why are globals bad and what problems
> do they solve?

now, my OS theory may be a bit rusty -- pls correct me where i'm
wrong, but from what i recall, one reason they're bad is because they
take up "unneeded" amount of memory.  in a traditional stack model --
think C, assembly, and how binaries are loaded into the OS for
execution: you have the TEXT section, which consists of the executable
code, the DATA section (sometimes divided up into 2 separate areas,
for zero- and nonzero-initialized/BSS data) for static variables,
global variables, etc., and the STACK and HEAP, as in this diagram
(drawn upside-down):

http://www.informit.com/content/images/chap3_0131429647/elementLinks/03fig01.jpg

the STACK is for tracking function calls (plus local variables
including parameters) while all dynamically-allocated memory comes
from the HEAP.  by increasing the size of your DATA section for
globals, it reduces the overall number of stack frames (function
calls) you can chain together, and likewise, you reduce the total
amount of memory that can be dynamically-allocated.  the STACK grows
upward while the HEAP grows downward, and memory issues occur when the
twain meet. if you have tons of globals, it increases the chance of
these types of collisions.

this GDB tutorial page is also useful in understanding these concepts:
http://www.dirac.org/linux/gdb/02a-Memory_Layout_And_The_Stack.php

the way it relates to Python is that Python is (of course) written in
C, and unless you're using the Stackless version of Python, each
Python function call results in one Python stack frame which results
in one C stack frame.

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 varsha.purohit at gmail.com  Wed Nov 14 03:38:04 2007
From: varsha.purohit at gmail.com (Varsha Purohit)
Date: Tue, 13 Nov 2007 18:38:04 -0800
Subject: [Tutor] [wxPython-users] Executing a python script in WxPython
Message-ID: <c2157c790711131838v1d0ae6e4u4ba2a40feac3697a@mail.gmail.com>

Hello,
      I have an application where i need to run a python script from
wxpython gui. I am calling the script from the button click event. And
the moment button is pressed the python script should be executed.

thanks,
Varsha Purohit,
Graduate Student

From kent37 at tds.net  Wed Nov 14 04:06:06 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 13 Nov 2007 22:06:06 -0500
Subject: [Tutor] global is bad but ...
In-Reply-To: <2bba6212a31a865533787f74bf082113@well.com>
References: <BAY109-DAV3A862EE3CDD3919DB9648A3800@phx.gbl>	<fhdavu$lao$1@ger.gmane.org>
	<2bba6212a31a865533787f74bf082113@well.com>
Message-ID: <473A661E.6060502@tds.net>

jim stockford wrote:
>     okay, i tried. so why are globals bad and what problems
> do they solve?

Wikipedia has a decent list:
http://en.wikipedia.org/wiki/Global_variable

Kent

From kent37 at tds.net  Wed Nov 14 04:10:59 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 13 Nov 2007 22:10:59 -0500
Subject: [Tutor] Maya anyone?
In-Reply-To: <007c01c82637$c4ebbea0$6401a8c0@Zoe>
References: <007c01c82637$c4ebbea0$6401a8c0@Zoe>
Message-ID: <473A6743.2020906@tds.net>

Da'Nivek wrote:
> Hey there,
>  
> I'm trying to learn python to use in Maya
> Would it be appropriate to post a question here?

You can certainly post a question...if it is too Maya-specific you may 
have better luck on a Maya list. We are good at Python, maybe not so 
good at Maya.

Kent

From goldwamh at slu.edu  Wed Nov 14 04:25:52 2007
From: goldwamh at slu.edu (Michael H. Goldwasser)
Date: Tue, 13 Nov 2007 21:25:52 -0600
Subject: [Tutor] global is bad but ...
In-Reply-To: <78b3a9580711131803g5c1a14c1r5d3ea7d98a5048fe@mail.gmail.com>
References: <BAY109-DAV3A862EE3CDD3919DB9648A3800@phx.gbl>
	<fhdavu$lao$1@ger.gmane.org>
	<2bba6212a31a865533787f74bf082113@well.com>
	<78b3a9580711131803g5c1a14c1r5d3ea7d98a5048fe@mail.gmail.com>
Message-ID: <18234.27328.591976.766754@euclid.slu.edu>


>    >     okay, i tried. so why are globals bad and what problems
>    > do they solve?

The biggest complaint I have with the original example is that you've
writen code to "do stuff" with array G, yet that code cannot directly
be used to do the same stuff to some other array.  In this sense, the
code is not reusable.  If it accepted G as a parameter, then it would
be more general.

The main advantage of globals is convenience (for example, if all you
care about is getting this particular program working as soon as
possible).

With regard,
Michael









From kent37 at tds.net  Wed Nov 14 04:34:38 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 13 Nov 2007 22:34:38 -0500
Subject: [Tutor] [wxPython-users] Executing a python script in WxPython
In-Reply-To: <c2157c790711131838v1d0ae6e4u4ba2a40feac3697a@mail.gmail.com>
References: <c2157c790711131838v1d0ae6e4u4ba2a40feac3697a@mail.gmail.com>
Message-ID: <473A6CCE.6010601@tds.net>

Varsha Purohit wrote:
> Hello,
>       I have an application where i need to run a python script from
> wxpython gui. I am calling the script from the button click event. And
> the moment button is pressed the python script should be executed.

If you can import the script and call the required function that is the 
simplest approach. If you have to run the script as from the command 
line then use os.system or subprocess.Popen.

Kent
> 
> thanks,
> Varsha Purohit,
> Graduate Student
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


From varsha.purohit at gmail.com  Wed Nov 14 05:27:39 2007
From: varsha.purohit at gmail.com (Varsha Purohit)
Date: Tue, 13 Nov 2007 20:27:39 -0800
Subject: [Tutor] [wxPython-users] Executing a python script in WxPython
In-Reply-To: <473A6CCE.6010601@tds.net>
References: <c2157c790711131838v1d0ae6e4u4ba2a40feac3697a@mail.gmail.com>
	<473A6CCE.6010601@tds.net>
Message-ID: <c2157c790711132027i56ff908es5ad204c900a08a1c@mail.gmail.com>

Thanks for the help its working now !!!

On Nov 13, 2007 7:34 PM, Kent Johnson <kent37 at tds.net> wrote:
> Varsha Purohit wrote:
> > Hello,
> >       I have an application where i need to run a python script from
> > wxpython gui. I am calling the script from the button click event. And
> > the moment button is pressed the python script should be executed.
>
> If you can import the script and call the required function that is the
> simplest approach. If you have to run the script as from the command
> line then use os.system or subprocess.Popen.
>
> Kent
> >
> > thanks,
> > Varsha Purohit,
> > Graduate Student
>
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
>



-- 
Varsha Purohit,
Graduate Student

From alan.gauld at btinternet.com  Wed Nov 14 06:19:44 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 14 Nov 2007 05:19:44 -0000
Subject: [Tutor] [wxPython-users] Executing a python script in WxPython
References: <c2157c790711131838v1d0ae6e4u4ba2a40feac3697a@mail.gmail.com>
Message-ID: <fhe0hq$5tb$1@ger.gmane.org>

"Varsha Purohit" <varsha.purohit at gmail.com> wrote

>      I have an application where i need to run a python script from
> wxpython gui. I am calling the script from the button click event. 
> And
> the moment button is pressed the python script should be executed.

This comes up from time to time and is usually a bad idea.
Is there a reason why you cannot import the script as a module and
then call a function (or functions) within the script instead of 
executing
the script? That is a much safer and more flexible process.

However, if that is impossible you can use subprocess module
to execute any external program including python, so simply call
that fom your event handler.

If you are having difficulties post some sample code and we
can give more specific help.

HTH,


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



From dineshbvadhia at hotmail.com  Wed Nov 14 06:34:45 2007
From: dineshbvadhia at hotmail.com (Dinesh B Vadhia)
Date: Tue, 13 Nov 2007 21:34:45 -0800
Subject: [Tutor] global is bad but ...
Message-ID: <BAY109-DAV378A316FA836F742D2347A3810@phx.gbl>

Alan/Jim:

It's good to hear some pragmatic advice.  

This particular module has 8 small functions that share common data (structures, primarily in arrays and vectors).  I tried passing array_G as a parameter but that doesn't work because everything in the function remains local and I cannot get back the altered data (unless you know better?). 

The 'global' route works a treat so far.

Dinesh

...............................................................
Date: Tue, 13 Nov 2007 23:11:49 -0000
From: "Alan Gauld" <alan.gauld at btinternet.com>
Subject: Re: [Tutor] global is bad but ...
To: tutor at python.org
Message-ID: <fhdavu$lao$1 at ger.gmane.org>
Content-Type: text/plain; format=flowed; charset="iso-8859-1";
reply-type=original

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

> Consider a data structure (say, an array) that is operated 
> on by a bunch of functions eg.
>
> def function_A
>     global array_G

> def function_B
>     global array_G

> etc...

> On the other hand, wiser heads say that the use of 'global' 
> is bad and that reworking the code into classes and objects 
> is better.

Rather than answer your question directly can I ask, do 
you know *why* wiser heads say global is bad? What 
problems does using global introduce? What problems 
does it solve?

> What do you think and suggest?

I think it's better to understand issues and make informed 
choices rather than following the rules of others.

I suggest you consider whether global is bad in this case 
and what other solutions might be used instead. Then make 
an informed choice. If, having researched the subject you 
don't understand why global is (sometimes) bad ask for 
more info here.

HTH (a little),

-- 
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/20071113/3b5abab2/attachment-0001.htm 

From varsha.purohit at gmail.com  Wed Nov 14 09:08:35 2007
From: varsha.purohit at gmail.com (Varsha Purohit)
Date: Wed, 14 Nov 2007 00:08:35 -0800
Subject: [Tutor] [wxPython-users] Displaying filename of open dialog box
Message-ID: <c2157c790711140008w71395dcat16546de7a57bf246@mail.gmail.com>

Hello,
      I am new to wxPython. I have made an application where i created
a button which opens the file from a directory. I created a static
text box near the button. I want to display the filename of file which
is opened using this open button. How can i read the file opened and
put that text in the static text box???

thanks,
-- 
Varsha Purohit,
Graduate Student

From bryan_magalski at yahoo.com  Wed Nov 14 12:06:16 2007
From: bryan_magalski at yahoo.com (Bryan Magalski)
Date: Wed, 14 Nov 2007 03:06:16 -0800 (PST)
Subject: [Tutor] Interactive Menu Woes
Message-ID: <224108.54779.qm@web36702.mail.mud.yahoo.com>

Greetings all!!

This is my first post and I am going to probably be vague at first, but, I will try my best to be specific.  I am a very GREEN scripter/programmer, so please be as descriptive as possible.  Ok, enough excuses, on with my question!

Here is my issue:

I am trying to build a menu for the following script to make it more "user friendly".  Nothing fancy, just a simple add data and look up the entered results.

The problem is that when I run my modified version with this snippet (please see attachment for original and my modified versions):

[code]
class MenuInput:
  
 # ask user to input data and store to be passed to manageable variables.
        def addName(self):
                print "To add a name, please input he following information: "
                self.enter = phoneentry()
                self.name = raw_input("Name: ")
                self.number = raw_input("Number: ")
                self.get = int(raw_input("What type of number is this? (choose one): \n 1. Home:\n 2. Work:\n 3. Cell:\n : "))
                def numberType(self, get = 1):
                        if self.get == 1:
                                self.returnType = HOME
                                #return self.getType
                        elif self.gete == 2:
                                self.returnType = WORK
                                #return self.getType
                        elif self.get == 3:
                                self.returnType = FAX
                                #return self.getType
                        return self.returnType
                        
                self.type = numberType(self.get)
                self.enter(self.name, self.number, self.returnType)
 
        def display(self):
                print "Enter a name to look up: (leave blank to exit)"
                self.Name = str(raw_input("Name: "))
                print "%s has the following information: " % self.Name
                if self.Name != "":
                        foo = phonedb()
                        for entry in foo.lookup(self.Name):
                                print '%-40s %s (%s)' % (entry.name, entry.number, entry.showtype())
                                print
[/code]

when I instantiate and run it with:

[code]
menu = MenuInput()
menu.addName()
[/code]

and enter the information asked, I am given this runtime error:

[error]
To add a name, please input he following information:
Name: Bryan
Number: 1234567
What type of number is this? (choose one):
 1. Home:
 2. Work:
 3. Cell:
 : 1
Traceback (most recent call last):
  File "examples\testpy\my_object_modified.py", line 101, in <module>
    menu.addName()
  File "examples\testpy\my_object_modified.py", line 85, in addName
    self.type = numberType(self.get)
  File "examples\testpy\my_object_modified.py", line 74, in numberType
    if self.get == 1:
AttributeError: 'int' object has no attribute 'get'
>>>
[/error]

I "think" that this has something to do with passing the results or possibly my functions are not properly calling (proper terminology?) each other.

Now what/where am I wrong?  As this is part of an object oriented programming class, I wanted the menu constructed inherent to the class.

Thank you in advance.  --Bryan


      ____________________________________________________________________________________
Get easy, one-click access to your favorites. 
Make Yahoo! your homepage.
http://www.yahoo.com/r/hs 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071114/843617eb/attachment.htm 
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: modified.py
Url: http://mail.python.org/pipermail/tutor/attachments/20071114/843617eb/attachment.txt 
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: original.py
Url: http://mail.python.org/pipermail/tutor/attachments/20071114/843617eb/attachment-0001.txt 

From wesbrooks at gmail.com  Wed Nov 14 12:49:58 2007
From: wesbrooks at gmail.com (Wesley Brooks)
Date: Wed, 14 Nov 2007 11:49:58 +0000
Subject: [Tutor] Interactive Menu Woes
In-Reply-To: <224108.54779.qm@web36702.mail.mud.yahoo.com>
References: <224108.54779.qm@web36702.mail.mud.yahoo.com>
Message-ID: <eec9f8ee0711140349x3cc60d87j741395c8a0ec8eb2@mail.gmail.com>

In the middle of your addName function you have defined another
function that requires 'self' and you've got a default argument
'get=1';

def numberType(self, get = 1):

You call this further down the function with the line;

self.type = numberType(self.get)

This should have been;

self.type = numberType(self)

I would suggest moving the numberType function from inside the addName
function as follows;

class MenuInput:
    def addName(self):
        print "To add a name, please input he following information: "
        name = raw_input("Name: ")
        number = raw_input("Number: ")
        get = int(raw_input("What type of number is this? (choose
one): \n 1. Home:\n 2. Work:\n 3. Cell:\n : "))
        type = self.numberType(get)
        enter = phoneentry()
        enter(name, number, returnType)

    def numberType(self, get):
        if get == 1:
            returnType = HOME
        elif get == 2:
            returnType = WORK
        elif get == 3:
            returnType = FAX
        return returnType

If you use self in a function all functions can see the value without
having to have it in the function definition.

For example;

class a:
    def a(self):
        self.get = 1
    def b(self):
        print self.get

>>> aa = a()
>>> aa.a()
>>> aa.b()
1
>>>

Default arguments in the function definition work as follows:

class a:
    def a(self):
        self.get = 1
    def b(self, get="Using default argument"):
        print get

>>> aa = a()
>>> aa.a()
>>> aa.b()
"Using default argument"
>>> aa.b(1)
1
>>>

Cheers,

Wes.

On 14/11/2007, Bryan Magalski <bryan_magalski at yahoo.com> wrote:
>
> Greetings all!!
>
> This is my first post and I am going to probably be vague at first, but, I
> will try my best to be specific.  I am a very GREEN scripter/programmer, so
> please be as descriptive as possible.  Ok, enough excuses, on with my
> question!
>
> Here is my issue:
>
> I am trying to build a menu for the following script to make it more "user
> friendly".  Nothing fancy, just a simple add data and look up the entered
> results.
>
> The problem is that when I run my modified version with this snippet (please
> see attachment for original and my modified versions):
>
> [code]
> class MenuInput:
>
>  # ask user to input data and store to be passed to manageable variables.
>         def addName(self):
>                 print "To add a name, please input he following information:
> "
>                 self.enter = phoneentry()
>                 self.name = raw_input("Name: ")
>                 self.number = raw_input("Number: ")
>                 self.get = int(raw_input("What type of number is this?
> (choose one): \n 1. Home:\n 2. Work:\n 3. Cell:\n : "))
>                 def numberType(self, get = 1):
>                         if self.get == 1:
>                                 self.returnType = HOME
>                                 #return self.getType
>                         elif self.gete == 2:
>                                 self.returnType = WORK
>                                 #return self.getType
>                         elif self.get == 3:
>                                 self.returnType = FAX
>                                 #return self.getType
>                         return self.returnType
>
>                 self.type = numberType(self.get)
>                 self.enter(self.name, self.number, self.returnType)
>
>         def display(self):
>                 print "Enter a name to look up: (leave blank to exit)"
>                 self.Name = str(raw_input("Name: "))
>                 print "%s has the following information: " % self.Name
>                 if self.Name != "":
>                         foo = phonedb()
>                         for entry in foo.lookup(self.Name):
>                                 print '%-40s %s (%s)' % (entry.name,
> entry.number, entry.showtype())
>                                 print
> [/code]
>
> when I instantiate and run it with:
>
> [code]
> menu = MenuInput()
> menu.addName()
> [/code]
>
> and enter the information asked, I am given this runtime error:
>
> [error]
> To add a name, please input he following information:
> Name: Bryan
> Number: 1234567
> What type of number is this? (choose one):
>  1. Home:
>  2. Work:
>  3. Cell:
>  : 1
> Traceback (most recent call last):
>   File "examples\testpy\my_object_modified.py", line 101,
> in <module>
>     menu.addName()
>   File "examples\testpy\my_object_modified.py", line 85, in
> addName
>     self.type = numberType(self.get)
>   File "examples\testpy\my_object_modified.py", line 74, in
> numberType
>     if self.get == 1:
> AttributeError: 'int' object has no attribute 'get'
> >>>
> [/error]
>
> I "think" that this has something to do with passing the results or possibly
> my functions are not properly calling (proper terminology?) each other.
>
> Now what/where am I wrong?  As this is part of an object oriented
> programming class, I wanted the menu constructed inherent to the class.
>
> Thank you in advance.  --Bryan
>  ________________________________
> Be a better sports nut! Let your teams follow you with Yahoo Mobile. Try it
> now.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>

From roychenlei at gmail.com  Wed Nov 14 13:04:00 2007
From: roychenlei at gmail.com (Roy Chen)
Date: Wed, 14 Nov 2007 21:04:00 +0900
Subject: [Tutor] Obtaining image date of creation
Message-ID: <729B8306-8039-44C5-8EDB-702E5A542B2D@gmail.com>

Hello,

I would like to write a simple script that would rename a bunch of  
photos according to their creation date, i.e. the date which the  
photo was taken.

Is there a way to use Python to obtain that information from the  
image file, or is that information not stored in the file?

Thanks,
Roy Chen

From evert.rol at gmail.com  Wed Nov 14 13:28:45 2007
From: evert.rol at gmail.com (Evert Rol)
Date: Wed, 14 Nov 2007 12:28:45 +0000
Subject: [Tutor] Interactive Menu Woes
In-Reply-To: <224108.54779.qm@web36702.mail.mud.yahoo.com>
References: <224108.54779.qm@web36702.mail.mud.yahoo.com>
Message-ID: <A46A457C-5B43-4B85-8664-B4F53556DD05@gmail.com>

> I am trying to build a menu for the following script to make it  
> more "user friendly".  Nothing fancy, just a simple add data and  
> look up the entered results.
>
> The problem is that when I run my modified version with this  
> snippet (please see attachment for original and my modified versions):
>
> [code]
> class MenuInput:
>
>  # ask user to input data and store to be passed to manageable  
> variables.
>         def addName(self):
>                 print "To add a name, please input he following  
> information: "
>                 self.enter = phoneentry()
>                 self.name = raw_input("Name: ")
>                 self.number = raw_input("Number: ")
>                 self.get = int(raw_input("What type of number is  
> this? (choose one): \n 1. Home:\n 2. Work:\n 3. Cell:\n : "))
>                 def numberType(self, get = 1):
>                         if self.get == 1:
>                                 self.returnType = HOME
>                                 #return self.getType
>                         elif self.gete == 2:
>                                 self.returnType = WORK
>                                 #return self.getType
>                         elif self.get == 3:
>                                 self.returnType = FAX
>                                 #return self.getType
>                         return self.returnType
>
>                 self.type = numberType(self.get)
>                 self.enter(self.name, self.number, self.returnType)
>


Bypassing the whole 'function within function' problem, consider  
using a dictionary instead: somedict = {1: HOME, 2: WORK, 3: FAX},  
and self.type = somedict[self.get]. This also avoids endless if-elif- 
elif-elif sequences (looking at showtype() in your original script,  
where you can apply the same technique); it's often clearer, and  
certainly shorter.




From kent37 at tds.net  Wed Nov 14 13:53:45 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 14 Nov 2007 07:53:45 -0500
Subject: [Tutor] global is bad but ...
In-Reply-To: <BAY109-DAV378A316FA836F742D2347A3810@phx.gbl>
References: <BAY109-DAV378A316FA836F742D2347A3810@phx.gbl>
Message-ID: <473AEFD9.5000407@tds.net>

Dinesh B Vadhia wrote:
> Alan/Jim:
>  
> It's good to hear some pragmatic advice. 
>  
> This particular module has 8 small functions that share common data 
> (structures, primarily in arrays and vectors).  I tried passing array_G 
> as a parameter but that doesn't work because everything in the function 
> remains local and I cannot get back the altered data (unless you know 
> better?). 

That sounds like a good candidate for a class with array_G as an 
instance attribute and your 8 small functions as methods.

If you pass the array as a parameter, you can change the passed 
parameter in place and changes will be seen by other clients. 
Re-assigning the parameter will have only local effect. For example:

This function mutates the list passed in, so changes are visible externally:
In [23]: def in_place(lst):
    ....:     lst[0] = 1
    ....:
    ....:
In [24]: a = [3,4,5]
In [25]: in_place(a)
In [26]: a
Out[26]: [1, 4, 5]

This function assigns a new value to the local name, changes are not 
visible externally:
In [27]: def reassign(lst):
    ....:     lst = []
    ....:
    ....:
In [28]: reassign(a)
In [29]: a
Out[29]: [1, 4, 5]

This function replaces the contents of the list with a new list. This is 
a mutating function so the changes are visible externally.
In [30]: def replace(lst):
    ....:     lst[:] = [1,2,3]
    ....:
    ....:
In [31]: replace(a)
In [32]: a
Out[32]: [1, 2, 3]

> The 'global' route works a treat so far.

Yes, globals work and they appear to be a simple solution, that is why 
they are used at all! They also
- increase coupling
- hinder testing and reuse
- obscure the relationship between pieces of code

which leads experienced developers to conclude that in general globals 
are a bad idea and should be strenuously avoided.

Kent


From phpmoonlighter at yahoo.com  Wed Nov 14 13:43:28 2007
From: phpmoonlighter at yahoo.com (ted b)
Date: Wed, 14 Nov 2007 04:43:28 -0800 (PST)
Subject: [Tutor] class accessing another's updated property
Message-ID: <726588.86719.qm@web58814.mail.re1.yahoo.com>

I want class One to be able to access access class
Two's value property after its been updated. Everytime
I try (by running, say testTwo().value) I get the
__init__ value. The update method fro class Two is
called elsewhere in the program, and I want class
One's "getTwo" method to access class Two's updated
value and give me '9' but i get '1'

Here's the code:

class One:
   def __init__(self):
      self.value = 3
   def getTwo(self):
      print "testTwo's updated value", Two().value

class Two:
   def __init__(self):
      self.value = 1
   def update(self):
      self.value = 9

Thanks in advance!


      ____________________________________________________________________________________
Be a better sports nut!  Let your teams follow you 
with Yahoo Mobile. Try it now.  http://mobile.yahoo.com/sports;_ylt=At9_qDKvtAbMuh1G1SQtBI7ntAcJ

From kent37 at tds.net  Wed Nov 14 14:05:48 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 14 Nov 2007 08:05:48 -0500
Subject: [Tutor] Obtaining image date of creation
In-Reply-To: <729B8306-8039-44C5-8EDB-702E5A542B2D@gmail.com>
References: <729B8306-8039-44C5-8EDB-702E5A542B2D@gmail.com>
Message-ID: <473AF2AC.80207@tds.net>

Roy Chen wrote:
> Hello,
> 
> I would like to write a simple script that would rename a bunch of  
> photos according to their creation date, i.e. the date which the  
> photo was taken.
> 
> Is there a way to use Python to obtain that information from the  
> image file, or is that information not stored in the file?

os.path.getctime() works on Windows, I'm not clear what it reports on *nix.

Kent

From kent37 at tds.net  Wed Nov 14 14:10:07 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 14 Nov 2007 08:10:07 -0500
Subject: [Tutor] class accessing another's updated property
In-Reply-To: <726588.86719.qm@web58814.mail.re1.yahoo.com>
References: <726588.86719.qm@web58814.mail.re1.yahoo.com>
Message-ID: <473AF3AF.5060904@tds.net>

ted b wrote:
> I want class One to be able to access access class
> Two's value property after its been updated. Everytime
> I try (by running, say testTwo().value) I get the
> __init__ value. The update method fro class Two is
> called elsewhere in the program, and I want class
> One's "getTwo" method to access class Two's updated
> value and give me '9' but i get '1'
> 
> Here's the code:
> 
> class One:
>    def __init__(self):
>       self.value = 3
>    def getTwo(self):
>       print "testTwo's updated value", Two().value
> 
> class Two:
>    def __init__(self):
>       self.value = 1
>    def update(self):
>       self.value = 9

value is a property of instances of Two, not of the class itself. 
getTwo() is creating a new instance of Two and reading it's value. You 
don't show the code that calls update but if it is something like
   Two().update()
then this creates an instance of Two, changes its value and throws the 
instance away.

Two options ;-) :
- Create an instance of Two which you keep in a variable and pass to 
clients.
- If you really just want Two to be a container for globally-accessible 
values, then make value a class attribute rather than an instance attribute:
class Two:
   value = 1

to update:
   Two.value = 9

class One:
   ...
   def getTwo(self):
     print Two.value

Kent

From eric at abrahamsen.com  Wed Nov 14 15:03:00 2007
From: eric at abrahamsen.com (Eric Abrahamsen)
Date: Wed, 14 Nov 2007 22:03:00 +0800
Subject: [Tutor] Obtaining image date of creation
In-Reply-To: <473AF2AC.80207@tds.net>
References: <729B8306-8039-44C5-8EDB-702E5A542B2D@gmail.com>
	<473AF2AC.80207@tds.net>
Message-ID: <6D18DFD0-DACE-4417-8BBD-08409D29C86C@abrahamsen.com>


On Nov 14, 2007, at 9:05 PM, Kent Johnson wrote:
> Roy Chen wrote:
>> Hello,
>>
>> I would like to write a simple script that would rename a bunch of
>> photos according to their creation date, i.e. the date which the
>> photo was taken.
>>
>> Is there a way to use Python to obtain that information from the
>> image file, or is that information not stored in the file?
>
> os.path.getctime() works on Windows, I'm not clear what it reports  
> on *nix.
>

Or you can use the Python Imaging Library (http://www.pythonware.com/ 
products/pil/) and get ALL the information!

E

From remco at gerlich.nl  Wed Nov 14 15:19:58 2007
From: remco at gerlich.nl (Remco Gerlich)
Date: Wed, 14 Nov 2007 15:19:58 +0100
Subject: [Tutor] Obtaining image date of creation
In-Reply-To: <729B8306-8039-44C5-8EDB-702E5A542B2D@gmail.com>
References: <729B8306-8039-44C5-8EDB-702E5A542B2D@gmail.com>
Message-ID: <7ae3ca10711140619k3667e3abv245e8961a6845c14@mail.gmail.com>

Hi,

I'm assuming you don't want the last changed date you see on the file
on your PC, but the creation date that the camera stored when the
picture was taken.

Now I don't know much about that, but I thought it was interesting, so
I did some Googling :-)

I don't know whether it's always stored, but many cameras do. There
are several formats. One of them is EXIF, no idea how universal that
is, but it seems to be pretty wide spread.

Unfortunately, the most common Python library for image stuff (PIL)
doesn't handle this.

However, some more Googling led me to the PyExif library (
http//pyexif.sourceforge.net/ ) and this post by someone who did the
exact thing you want to do:
http://www.leancrew.com/all-this/2007/08/photo_file_renaming_again.html

Hope this helps :-)

Remco

On Nov 14, 2007 1:04 PM, Roy Chen <roychenlei at gmail.com> wrote:
> Hello,
>
> I would like to write a simple script that would rename a bunch of
> photos according to their creation date, i.e. the date which the
> photo was taken.
>
> Is there a way to use Python to obtain that information from the
> image file, or is that information not stored in the file?
>
> Thanks,
> Roy Chen
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From evert.rol at gmail.com  Wed Nov 14 15:47:07 2007
From: evert.rol at gmail.com (Evert Rol)
Date: Wed, 14 Nov 2007 14:47:07 +0000
Subject: [Tutor] Obtaining image date of creation
In-Reply-To: <7ae3ca10711140619k3667e3abv245e8961a6845c14@mail.gmail.com>
References: <729B8306-8039-44C5-8EDB-702E5A542B2D@gmail.com>
	<7ae3ca10711140619k3667e3abv245e8961a6845c14@mail.gmail.com>
Message-ID: <F0F61119-514D-41F3-8005-B354F4B3ED5E@gmail.com>

> I'm assuming you don't want the last changed date you see on the file
> on your PC, but the creation date that the camera stored when the
> picture was taken.
>
> Now I don't know much about that, but I thought it was interesting, so
> I did some Googling :-)
>
> I don't know whether it's always stored, but many cameras do. There
> are several formats. One of them is EXIF, no idea how universal that
> is, but it seems to be pretty wide spread.
>
> Unfortunately, the most common Python library for image stuff (PIL)
> doesn't handle this.

I think EXIF does what the OP wants; you may loose the exif  
information if you do too much editing on your image, but otherwise  
it'll be on RAW images and JPEG images. I'm not sure if PIL handles  
RAW images, so you may need to use JPEGs (perhaps you're already  
doing that).

And while I haven't tried it, this page (http://effbot.org/zone/pil- 
changes-114.htm) appears to indicate exif format is somewhat  
supported in PIL; perhaps pyexif does a better job though?


From marc.tompkins at gmail.com  Wed Nov 14 20:16:16 2007
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Wed, 14 Nov 2007 11:16:16 -0800
Subject: [Tutor] Obtaining image date of creation
Message-ID: <40af687b0711141116g29e12072h78bd2ebeb1793698@mail.gmail.com>

Thus spake Roy Chen:

> Hello,
>
> I would like to write a simple script that would rename a bunch of
> photos according to their creation date, i.e. the date which the
> photo was taken.
>
> Is there a way to use Python to obtain that information from the
> image file, or is that information not stored in the file?
>

What you're looking for is called EXIF, which stands for Exchangeable Image
File Format.
A good place to start would be http://www.exif.org  (or maybe Google, now
that you know the name of the format...)
Without having researched very far, I would guess that a lot of the familiar
MP3 tag-manipulation routines floating around out there could be easily
modified to read EXIF data instead - or, perhaps there are already Python
EXIF libraries?

Have fun with that!


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

From bryan_magalski at yahoo.com  Wed Nov 14 21:40:04 2007
From: bryan_magalski at yahoo.com (Bryan Magalski)
Date: Wed, 14 Nov 2007 12:40:04 -0800 (PST)
Subject: [Tutor] Interactive Menu Woes
Message-ID: <36477.53946.qm@web36707.mail.mud.yahoo.com>


Thank you for your suggestion.  I did not create the original script, so it will stay as is and my addition for the menu has been adjusted.  

Now that I can make a clear distinction of what I am returning, I am getting a new error that leads me that I am trying to call a function that cannot be seen when instantiated:

To add a name, please input he following information: 
Name: Bryan
Number: 1234567890
What type of number is this? (choose one): 
                     1. Home:
                     2. Work:
                     3. Cell:
                     : 1
Traceback (most recent call last):
  File "menu_modified.py", line 95, in <module>
    menu.addName()
  File "menu_modified.py", line 73, in addName
    enter(name, number, returnType)
AttributeError: phoneentry instance has no __call__ method

[code]
class MenuInput:

        # ask user to input data and store to be passed to manageable variables.
        def addName(self):
                print "To add a name, please input he following information: "
                name = raw_input("Name: ")
                number = raw_input("Number: ")
                get = int(raw_input("What type of number is this? (choose one): \n \
                    1. Home:\n \
                    2. Work:\n \
                    3. Cell:\n \
                    : "))
                returnType = self.numberType(get)
                               
                #print returnType
                enter = phoneentry()
                enter(name, number, returnType)
[/code]

I googled the __call__ method, but I am not getting to the meat of what all of the leads have to say.  I know it has to deal with when I instantiated phoneentry() within addName(), I just don't know how to fix it or "call" it properly.

Again, thanks in advance.

----- Original Message ----
From: Evert Rol <evert.rol at gmail.com>
To: Bryan Magalski <bryan_magalski at yahoo.com>
Cc: tutor at python.org
Sent: Wednesday, November 14, 2007 1:28:45 PM
Subject: Re: [Tutor] Interactive Menu Woes


> I am trying to build a menu for the following script to make it  
> more "user friendly".  Nothing fancy, just a simple add data and  
> look up the entered results.
>
> The problem is that when I run my modified version with this  
> snippet (please see attachment for original and my modified
 versions):
>
> [code]
> class MenuInput:
>
>  # ask user to input data and store to be passed to manageable  
> variables.
>         def addName(self):
>                 print "To add a name, please input he following  
> information: "
>                 self.enter = phoneentry()
>                 self.name = raw_input("Name: ")
>                 self.number = raw_input("Number: ")
>                 self.get = int(raw_input("What type of number is  
> this? (choose one): \n 1. Home:\n 2. Work:\n 3. Cell:\n : "))
>                 def
 numberType(self, get = 1):
>                         if self.get == 1:
>                                 self.returnType = HOME
>                                 #return self.getType
>                         elif self.gete == 2:
>                                 self.returnType = WORK
>                                 #return self.getType
>                         elif self.get == 3:
>       
                          self.returnType = FAX
>                                 #return self.getType
>                         return self.returnType
>
>                 self.type = numberType(self.get)
>                 self.enter(self.name, self.number, self.returnType)
>


Bypassing the whole 'function within function' problem, consider  
using a dictionary instead: somedict = {1: HOME, 2: WORK, 3: FAX},  
and self.type = somedict[self.get]. This also avoids endless if-elif- 
elif-elif sequences (looking at showtype() in your original script,  
where you can
 apply the same technique); it's often clearer, and  
certainly shorter.










      ____________________________________________________________________________________
Never miss a thing.  Make Yahoo your home page. 
http://www.yahoo.com/r/hs
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071114/7b793947/attachment-0001.htm 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: menu_modified.py
Type: text/x-python
Size: 2832 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20071114/7b793947/attachment-0001.py 

From dineshbvadhia at hotmail.com  Wed Nov 14 23:29:14 2007
From: dineshbvadhia at hotmail.com (Dinesh B Vadhia)
Date: Wed, 14 Nov 2007 14:29:14 -0800
Subject: [Tutor] global is bad but ... okay
References: <BAY109-DAV378A316FA836F742D2347A3810@phx.gbl>
	<473AEFD9.5000407@tds.net>
Message-ID: <BAY109-DAV748FCCAF0D227B528708CA3810@phx.gbl>

Kent et al

I reworked the code to pass parameters (mainly arrays)  to the functions.  It works and performs faster.  Thank-you all very much for the insights.

Dinesh


----- Original Message ----- 
From: Kent Johnson 
To: Dinesh B Vadhia 
Cc: tutor at python.org 
Sent: Wednesday, November 14, 2007 4:53 AM
Subject: Re: [Tutor] global is bad but ...


Dinesh B Vadhia wrote:
> Alan/Jim:
>  
> It's good to hear some pragmatic advice. 
>  
> This particular module has 8 small functions that share common data 
> (structures, primarily in arrays and vectors).  I tried passing array_G 
> as a parameter but that doesn't work because everything in the function 
> remains local and I cannot get back the altered data (unless you know 
> better?). 

That sounds like a good candidate for a class with array_G as an 
instance attribute and your 8 small functions as methods.

If you pass the array as a parameter, you can change the passed 
parameter in place and changes will be seen by other clients. 
Re-assigning the parameter will have only local effect. For example:

This function mutates the list passed in, so changes are visible externally:
In [23]: def in_place(lst):
    ....:     lst[0] = 1
    ....:
    ....:
In [24]: a = [3,4,5]
In [25]: in_place(a)
In [26]: a
Out[26]: [1, 4, 5]

This function assigns a new value to the local name, changes are not 
visible externally:
In [27]: def reassign(lst):
    ....:     lst = []
    ....:
    ....:
In [28]: reassign(a)
In [29]: a
Out[29]: [1, 4, 5]

This function replaces the contents of the list with a new list. This is 
a mutating function so the changes are visible externally.
In [30]: def replace(lst):
    ....:     lst[:] = [1,2,3]
    ....:
    ....:
In [31]: replace(a)
In [32]: a
Out[32]: [1, 2, 3]

> The 'global' route works a treat so far.

Yes, globals work and they appear to be a simple solution, that is why 
they are used at all! They also
- increase coupling
- hinder testing and reuse
- obscure the relationship between pieces of code

which leads experienced developers to conclude that in general globals 
are a bad idea and should be strenuously avoided.

Kent

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

From eric at abrahamsen.com  Thu Nov 15 03:18:00 2007
From: eric at abrahamsen.com (Eric Abrahamsen)
Date: Thu, 15 Nov 2007 10:18:00 +0800
Subject: [Tutor] Obtaining image date of creation
In-Reply-To: <F0F61119-514D-41F3-8005-B354F4B3ED5E@gmail.com>
References: <729B8306-8039-44C5-8EDB-702E5A542B2D@gmail.com>
	<7ae3ca10711140619k3667e3abv245e8961a6845c14@mail.gmail.com>
	<F0F61119-514D-41F3-8005-B354F4B3ED5E@gmail.com>
Message-ID: <428DAA1F-0ED3-4D2D-92BF-DB113D794509@abrahamsen.com>

> And while I haven't tried it, this page (http://effbot.org/zone/pil-
> changes-114.htm) appears to indicate exif format is somewhat
> supported in PIL; perhaps pyexif does a better job though?

PIL does a pretty job, though it's a pain.

from PIL import Image
from PIL.ExifTags import TAGS
def get_exif(fn):
     ret = {}
     i = Image.open(fn)
     info = i._getexif()
     for tag, value in info.items():
         decoded = TAGS.get(tag, tag)
         ret[decoded] = value
     return ret

I found this here: http://wolfram.kriesing.de/blog/index.php/2006/ 
reading-out-exif-data-via-python

From varsha.purohit at gmail.com  Thu Nov 15 03:30:58 2007
From: varsha.purohit at gmail.com (Varsha Purohit)
Date: Wed, 14 Nov 2007 18:30:58 -0800
Subject: [Tutor] [wxPython-users] Loading default values for text box and
	choice
Message-ID: <c2157c790711141830p15ecea0pa980a313c1d09e02@mail.gmail.com>

Hello,
    I wanted to know how to load text box with the default value....

Eg. In these lines there is a static text and a text box created ...
and if i want to load value '3' in the text box how can i do that ??

wx.StaticText(panel, -1, "Random Seed", (550,200))
 wx.TextCtrl(panel,-1,pos=(620,200),size=(50,20))

and also in the Choice box

simpleList2 = ['Unbiased Attitude         ','Biased Attitude']
wx.Choice(panel, -1, (670,570),choices=simpleList2)

if i want to load the first value of simplelist2 in the choice box by
default when the application runs...



thanks in advance,

-- 
Varsha Purohit,

From pyprog at easyconnect.fr  Thu Nov 15 04:17:59 2007
From: pyprog at easyconnect.fr (pyprog)
Date: Thu, 15 Nov 2007 04:17:59 +0100
Subject: [Tutor] Obtaining image date of creation
In-Reply-To: <40af687b0711141116g29e12072h78bd2ebeb1793698@mail.gmail.com>
References: <40af687b0711141116g29e12072h78bd2ebeb1793698@mail.gmail.com>
Message-ID: <1195096679.25217.11.camel@kubuntu1>

Hello,

I'm new here .

To read EXIF with Python Imaging Library :

>>> import Image
>>> ouv=Image.open('path_to_your_picture_with_exif_data__jpeg')
>>> exifdata=imgExif._getexif()
>>> # Here a personnal exemple
>>> for keyExif, valueExif in zip(exifdata.keys(), exifdata.values()):
...     print keyExif, str(valueExif)
...
36864 0220
37121
37122 (2, 1)
36867 2004:04:12 17:02:53
36868 2004:04:12 17:02:53
37381 (48, 10)
37510                                                                           
37383 5
37384 0
37385 24
37386 (174, 10)
40962 640
270 OLYMPUS DIGITAL CAMERA
271 OLYMPUS OPTICAL CO.,LTD
272 X200,D560Z,C350Z
274 1
531 2
41992 0
41988 (0, 100)
282 (72, 1)
283 (72, 1)
33434 (10, 1250)
41728
40965 1268
34850 2
40961 1
50341 PrintIM0250?

?
???????????     '
                 '?'''^'?'?'?!?????
34855 64
296 2
41987 0
41991 0
33437 (52, 10)
305 v751-81
306 2004:04:12 17:02:53
41993 0
41729
41994 0
41985 0
40960 0100
41990 0
40963 480
41986 0
34665 550
37500 OLYMP4??   L?ldd,?????????????SX751[pictureInfo] Resolution=1
[Camera Info] Type=SX751OLYMPUS DIGITAL CAMERA?????????a1
 (d?@0:P""""""""""""""""""""??|?Fp]R?a?|'?   ?%?
?m?"w?twwww%#%!%!?V                       P???1M????]XlYn??:    ?
?yU(b? ?"????%79?Fffff

Here are some details :

1. "ExifVersion : "          ||    str(exifdata[36864])
2. "DateTimeOriginal : "     ||    str(exifdata[36867])
3. "DateTimeDigitized : "    ||    str(exifdata[36868])
4. "DateTime : "             ||    str(exifdata[306]) 
5. "ExifImageWidth : "       ||    str(exifdata[40962])
6. "ExifImageHeight : "      ||    str(exifdata[40963])
7. "XResolution : "          ||    str(exifdata[282])
8. "YResolution : "          ||    str(exifdata[283])
9. "Make : "                 ||    str(exifdata[271])
10. "Model : "               ||    str(exifdata[272])
11. "MaxApertureValue : "    ||    str(exifdata[37381]) 
12. "ImageDescription : "    ||    str(exifdata[270]) 
13. "MeteringMode : "        ||    str(exifdata[37383]) 
14. "LightSource : "         ||    str(exifdata[37384]) 
15. "Flash : "               ||    str(exifdata[37385]) 
16. "FlashPixVersion : "     ||    str(exifdata[40960]) 
17. "FocalLength : "         ||    str(exifdata[37386]) 
18. "ExposureTime : "        ||    str(exifdata[33434]) 
19. "FNumber : "             ||    str(exifdata[33437]) 
20. "Software : "            ||    str(exifdata[305]) 
21. "ExifOffset : "          ||    str(exifdata[34665]) 


a+ ;)

-- 
Venez faire un tour ici :

http://ekd.tolosano.info
http://monsitt.irruption.net
http://irruption.net/progdudim


From nogentstanford at yahoo.fr  Thu Nov 15 04:06:31 2007
From: nogentstanford at yahoo.fr (pileux systeme)
Date: Thu, 15 Nov 2007 04:06:31 +0100 (CET)
Subject: [Tutor] retrieve data from an online database without knowing the
	url
Message-ID: <716900.53900.qm@web27310.mail.ukl.yahoo.com>

Hello,

I was wondering whether it was possible to write a program which could directly write some word in a box and click 'search' on a typical online database without using the url. (e.g. is there a way to write a program which would write some keyword, say 'tomato' on google and click 'google search' automatically and copy the page without having to know the url 'http://www.google.com/search?hl=en&sa=X&oi=spell&resnum=0&ct=result&cd=1&q=tomato&spell=1')
Thank you very much for any help you could provide,

N.


             
---------------------------------
 Ne gardez plus qu'une seule adresse mail ! Copiez vos mails vers Yahoo! Mail 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071115/d1a12e2d/attachment.htm 

From pydev at rscorp.ab.ca  Thu Nov 15 06:24:48 2007
From: pydev at rscorp.ab.ca (Scott SA)
Date: Wed, 14 Nov 2007 22:24:48 -0700
Subject: [Tutor] Obtaining image date of creation
Message-ID: <r02010500-1049-15C537E6933B11DC87F4001124DEBE0E@[192.168.69.99]>

On 11/14/07, Roy Chen (roychenlei at gmail.com) wrote:

>I would like to write a simple script that would rename a bunch of  
>photos according to their creation date, i.e. the date which the  
>photo was taken.
>
>Is there a way to use Python to obtain that information from the  
>image file, or is that information not stored in the file?

There are a couple of EXIF libraries dedicated to reading EXIF headers of JPEG images plus, as mentioned by others PIL. Another great imaging library is ImageMagick but last time I looked the wrapper for it was in disarray IIRC.

A really quick snoop 'round the web turned up this PIL snippet:

    from PIL import Image
    from PIL.ExifTags import TAGS
    
    def get_exif(fn):
        ret = {}
        i = Image.open(fn)
        info = i._getexif()
        for tag, value in info.items():
            decoded = TAGS.get(tag, tag)
            ret[decoded] = value
        return ret

Posted by 'Justin' here:
    <http://wolfram.kriesing.de/blog/index.php/2006/reading-out-exif-data-via-python>


There is also:
    <http://pyexif.sourceforge.net/> (recommends EXIF.py below)
    <http://www.emilas.com/jpeg/>
    <http://www.imagemagick.org> (py-magic is one library-wrapper)

EXIF.py is a possible choice for this task:
    <http://sourceforge.net/projects/exif-py>

Here's a sample of what I did to extract the tags I was interested in (I wanted _more_ than the dates ;-). I also wanted something that could handle the variances between manufacturers i.e. not using a particular tag. There _are_ tags missing in EXIF.py although it has been updated recently for some Nikon and Olympus stuff.

This is a portion of a class I wrote to wrap other tasks, I didn't do anything wonderful here with exception handling:

    import EXIF
    
    def fetch_exif(strPath):
        
        # dictionary of desired tags (I have it elsewhere in the class). 
        # Only one of a few ways to do this...
        exif_tags = {
            'EXIF DateTimeDigitized': '',
            'EXIF DateTimeOriginal': '',
            'EXIF ExifImageLength': '',
            'EXIF ExifImageWidth': '',
            'EXIF ExifVersion': '',
            'EXIF ExposureBiasValue': '',
            'EXIF ExposureProgram': '',
            'EXIF ExposureTime': '',
            'EXIF Flash': '',
            'EXIF FNumber': '',
            'EXIF FocalLength': '',
            'EXIF ISOSpeedRatings': '',
            'EXIF MaxApertureValue': '',
            'EXIF MeteringMode': '',
            'EXIF SceneType': '',
            'EXIF ShutterSpeedValue': '',
            'EXIF SubSecTime': '',
            'Image DateTime': '',
            'Image ImageDescription': '',
            'Image Make': '',
            'Image Model': '',
            'Image Orientation': '',
            'Image XResolution': '',
            'Image YResolution': '',
            'ImageType': '',
            'ImageNumber': '',
            'OwnerName': '',
            'SerialNumber': '',
            'FirmwareVersion': '',
            'InternalSerialNumber': '',
            }

        exif_keys = exif_tags.keys()
        
        # iterate the keys looking for desirable/desired tags
        try:
            image_file = open(strPath,'rb')
            image_tags = EXIF.process_file(image_file, details=False)
            image_file.close()
            image_keys = image_tags.keys()
            
            for key_name in exif_keys:
                if key_name in image_keys:
                    exif_tags[key_name] = image_tags[key_name]
            
        except:
            # typically caused by missing exif
            exif_tags = False
            image_file.close()
            
        return exif_tags


A more compact option would have been to iterate a simple list of _desired_ tags, then build the dictionary of the ones available.
    
    return_exif_dict = {}
    
    shopping_list = ['EXIF DateTimeDigitized', 'EXIF DateTimeOriginal', 
    'EXIF ExifImageLength', 'EXIF ExifImageWidth', 'EXIF ExifVersion', 
    'EXIF ExposureBiasValue', 'EXIF ExposureProgram', 'EXIF ExposureTime', 
    'EXIF Flash', 'EXIF FNumber', 'EXIF FocalLength', 'EXIF ISOSpeedRatings',       
    'EXIF MaxApertureValue', 'EXIF MeteringMode', 'EXIF SceneType', 
    'EXIF ShutterSpeedValue', 'EXIF SubSecTime', 'Image DateTime', 
    'Image ImageDescription', 'Image Make', 'Image Model', 
    'Image Orientation', 'Image XResolution', 'Image YResolution', 
    'ImageType', 'ImageNumber', 'OwnerName', 'SerialNumber', 
    'FirmwareVersion', 'InternalSerialNumber'] 
    
    try:
        image_file = open(strPath,'rb')
        image_tags = EXIF.process_file(image_file, details=False)
        image_file.close()
        image_keys = image_tags.keys()

        for key_name in exif_keys:
        if key_name in image_keys:
            return_exif_dict[key_name] = image_tags[key_name]
    ...


You should be aware that it _is_ possible for a DC to take more than one image per second - though with a consumer P&S it is unlikely. The solution I used was to capture the camera's original sequential number - had the added benefit of letting the photogs I was working with reference to their own libraries later.

There are lots of pages to be found discussing file renaming and date conversions, so that should not be a problem... just be sure to use file-system compatible characters (sorry, I don't know your python exp. - just covering a couple of bases).

HTH

Scott

From sith618 at yahoo.com  Thu Nov 15 08:07:43 2007
From: sith618 at yahoo.com (sith .)
Date: Wed, 14 Nov 2007 23:07:43 -0800 (PST)
Subject: [Tutor] parsing an array
Message-ID: <556218.56153.qm@web33201.mail.mud.yahoo.com>

a = [[1,2],[3,1.5],[5,6]]
  for i in a:
    print i
    if i[1]>i[0]:
        print "second index is larger"
    else:
        print "second index is smaller"
  [1, 2]
  second index is larger
  [3, 1.5]
  second index is small
er
[5, 6]
  second index is larger
  
What I'd like do is compare if 1.5 in i[1] is greater than 2 in i[0]; 
for time series, t(1)>t(0) and interate through the entire list - is 6 in i[2]>than 1.5 in i[1] etc?
Since the data is in columns in a text file or csv, I can't put 1.5 in the same sublist as 2, and 6 in the same sublist as 1.5 to make things easier.  What can I do?  
Thank you for your help.

       
---------------------------------
Get easy, one-click access to your favorites.  Make Yahoo! your homepage.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071114/2eb2406f/attachment-0001.htm 

From aditya.n.lal at gmail.com  Thu Nov 15 09:01:34 2007
From: aditya.n.lal at gmail.com (Aditya Lal)
Date: Thu, 15 Nov 2007 13:31:34 +0530
Subject: [Tutor] parsing an array
In-Reply-To: <556218.56153.qm@web33201.mail.mud.yahoo.com>
References: <556218.56153.qm@web33201.mail.mud.yahoo.com>
Message-ID: <5df213700711150001j19b6f3a1kecf1a78dcc78af93@mail.gmail.com>

On Nov 15, 2007 12:37 PM, sith . <sith618 at yahoo.com> wrote:

> a = [[1,2],[3,1.5],[5,6]]
> for i in a:
>     print i
>     if i[1]>i[0]:
>         print "second index is larger"
>     else:
>         print "second index is smaller"
> [1, 2]
> second index is larger
> [3, 1.5]
> second index is small
> er
> [5, 6]
> second index is larger
>
> What I'd like do is compare if 1.5 in i[1] is greater than 2 in i[0];
> for time series, t(1)>t(0) and interate through the entire list - is 6 in
> i[2]>than 1.5 in i[1] etc?
> Since the data is in columns in a text file or csv, I can't put 1.5 in the
> same sublist as 2, and 6 in the same sublist as 1.5 to make things
> easier.  What can I do?
> Thank you for your help.
>
> ------------------------------
>
>
for i in range(1,len(a)) :
  if a[i][1] > a[i-1][1] :
     print 'greater !!' # or whatever you want

-- 
Aditya
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071115/0b78752d/attachment.htm 

From sacharook at hotmail.co.uk  Thu Nov 15 09:50:16 2007
From: sacharook at hotmail.co.uk (sacha rook)
Date: Thu, 15 Nov 2007 08:50:16 +0000
Subject: [Tutor] CSV TO LDIF
Message-ID: <BAY111-W24B10F1C5B8D6241DA673BF3820@phx.gbl>

Hi
 
I have a csv of users that I want to update their records in edirectory.
 
I am quite happy to use the ldap import utility to pull an ldif file into edirectory to update information.
 
I am using the csv module to parse the csv, anyone got any suggestions for creating the ldif file from this?
 
Any help or pointers greatly appreciated.
 
Regards
 
S
_________________________________________________________________
Celeb spotting ? Play CelebMashup and win cool prizes
https://www.celebmashup.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071115/36028d6d/attachment.htm 

From evert.rol at gmail.com  Thu Nov 15 11:14:41 2007
From: evert.rol at gmail.com (Evert Rol)
Date: Thu, 15 Nov 2007 10:14:41 +0000
Subject: [Tutor] retrieve data from an online database without knowing
	the url
In-Reply-To: <716900.53900.qm@web27310.mail.ukl.yahoo.com>
References: <716900.53900.qm@web27310.mail.ukl.yahoo.com>
Message-ID: <EB472245-646E-4C2D-890F-28A70166411C@gmail.com>

> I was wondering whether it was possible to write a program which  
> could directly write some word in a box and click 'search' on a  
> typical online database without using the url. (e.g. is there a way  
> to write a program which would write some keyword, say 'tomato' on  
> google and click 'google search' automatically and copy the page  
> without having to know the url 'http://www.google.com/search? 
> hl=en&sa=X&oi=spell&resnum=0&ct=result&cd=1&q=tomato&spell=1')
> Thank you very much for any help you could provide,

I would use urllib & urllib2 (google around for some example code),  
but then you'll still have to know
- the names of the input search box and search button
- whether it's a get or post form
Some of this info can be gotten by first downloading the form and  
examine it for tags (such as 'action'), but possibly not all.

Other than that, I wouldn't really know.


From yoram.hekma at aoes.com  Thu Nov 15 11:13:35 2007
From: yoram.hekma at aoes.com (Yoram Hekma)
Date: Thu, 15 Nov 2007 11:13:35 +0100
Subject: [Tutor] retrieve data from an online database without
	knowing	the url
In-Reply-To: <716900.53900.qm@web27310.mail.ukl.yahoo.com>
References: <716900.53900.qm@web27310.mail.ukl.yahoo.com>
Message-ID: <20071115101335.GA23026@aoes.com>

On Thu, Nov 15, 2007 at 04:06:31AM +0100, pileux systeme wrote:
> Hello,
> 
> I was wondering whether it was possible to write a program which could directly write some word in a box and click 'search' on a typical online database without using the url. (e.g. is there a way to write a program which would write some keyword, say 'tomato' on google and click 'google search' automatically and copy the page without having to know the url 'http://www.google.com/search?hl=en&sa=X&oi=spell&resnum=0&ct=result&cd=1&q=tomato&spell=1')
> Thank you very much for any help you could provide,
> 
> N.
> 

Yes, this is possible. Have a look at urllib
(http://docs.python.org/lib/module-urllib.html) and within that page see
urlencode. The idea is that first you make a connection to google.com,
and then post the search values to the form. If you look at the form on
google.com (from source) you see the following:

<form action="/search" name="f">
    --snip--
    <input name="hl" value="nl" type="hidden">
    <input maxlength="2048" name="q" size="55" title="Google zoeken" value="">
    <input name="btnG" value="Google zoeken" type="submit"><input name="btnI" value="Ik doe een gok" type="submit">
    --snip--
</form>

For example:

import urllib
search_string = 'cars'
encoded_search_string = urllib.urlencode({'q': search_string})
reponse = urllib.urlopen('www.google.com', encoded_search_string)

To search for "cars"

Good luck!
-- 
Yoram Hekma
Unix Systems Administrator
CICT Department
AOES Netherlands B.V.
Haagse Schouwweg 6G
2332 KG Leiden, The Netherlands
Phone:  +31 (0)71 5795588
Fax:    +31 (0)71 5721277
e-mail: yoram.hekma at aoes.com
http://www.aoes.com

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://mail.python.org/pipermail/tutor/attachments/20071115/1b7c2115/attachment.pgp 

From evert.rol at gmail.com  Thu Nov 15 11:37:43 2007
From: evert.rol at gmail.com (Evert Rol)
Date: Thu, 15 Nov 2007 10:37:43 +0000
Subject: [Tutor] Interactive Menu Woes
In-Reply-To: <36477.53946.qm@web36707.mail.mud.yahoo.com>
References: <36477.53946.qm@web36707.mail.mud.yahoo.com>
Message-ID: <39D22CFE-B58C-4262-9A00-01A7DCC8DC07@gmail.com>

> Thank you for your suggestion.  I did not create the original  
> script, so it will stay as is and my addition for the menu has been  
> adjusted.
>
> Now that I can make a clear distinction of what I am returning, I  
> am getting a new error that leads me that I am trying to call a  
> function that cannot be seen when instantiated:
>
> To add a name, please input he following information:
> Name: Bryan
> Number: 1234567890
> What type of number is this? (choose one):
>                      1. Home:
>                      2. Work:
>                      3. Cell:
>                      : 1
> Traceback (most recent call last):
>   File "menu_modified.py", line 95, in <module>
>     menu.addName()
>   File "menu_modified.py", line 73, in addName
>     enter(name, number, returnType)
> AttributeError: phoneentry instance has no __call__ method


You're first creating a phoneentry object, and then calling the  
actual object. That doesn't work; it's somewhat similar to:
 >>> a = dict()
 >>> a(key=5)
which gives a slightly different error, but obviously the correct  
form is:
 >>> a = dict(key=5)
and also
 >>> phoneentry(name, number, returnType)

When creating an object (instantiating the class), the __init__  
method is automatically called, and you provide the arguments of the  
__init__ method when creating the object.
In your current script, the actual entry you create (enter =  
phoneenetry()) creates an entry with name & number 'Unknown' (default  
arguments), and types=UNKNOWN; then you want to assign the actual  
values to the entry. If you *really* want to do this (don't, though),  
you'd be doing:
entry = phoneentry()
entry.name = name
entry.number = number
entry.types = returnType

See the add() method in the phonedb class, where it is done correctly.


A few other thoughts:
- what does numberType return if 'n is not in typeDict'? It should  
return UNKNOWN I guess.
- why not remove that function, and put typeDict to addName? It's  
really only one extra line, and avoids the whole extra function call  
(replacing it with something one might call a 'dictionary call')
- I noticed you use tabs, while the original part of the code uses  
spaces. Try to avoid mixing them: at some point things will go wrong  
(spaces are preferred; for a good read on that and other stuff:  
http://www.python.org/doc/essays/styleguide.html )


   Evert


From pyprog at easyconnect.fr  Thu Nov 15 12:34:29 2007
From: pyprog at easyconnect.fr (pyprog)
Date: Thu, 15 Nov 2007 12:34:29 +0100
Subject: [Tutor] Obtaining image date of creation
In-Reply-To: <1195096679.25217.11.camel@kubuntu1>
References: <40af687b0711141116g29e12072h78bd2ebeb1793698@mail.gmail.com>
	<1195096679.25217.11.camel@kubuntu1>
Message-ID: <1195126469.26308.7.camel@kubuntu1>

On jeu, 2007-11-15 at 04:17 +0100, pyprog wrote:
> 
> >>> import Image
> >>> ouv=Image.open('path_to_your_picture_with_exif_data__jpeg')
> >>> exifdata=imgExif._getexif() 

A little error :


>>> import Image
>>> ouv=Image.open('path_to_your_picture_with_exif_data__jpeg')
>>> exifdata=ouv._getexif()
>>> ...

I'm EKD developper : http://ekd.tolosano.info and it work with EXIF. You
can download and test it if you want. It works with Tkinter nowadays and
in future he will work with PyQt4 .

http://ekd.tolosano.info/html_docs/fonctionnalites_ekd/images_pages_html/cop_ecr_interfac_ekd_exif_00.jpg  
http://ekd.tolosano.info/html_docs/fonctionnalites_ekd/exif/essai_exif_ekd_1.html

Excuse me for my bad english .

a+
-- 
Venez faire un tour ici :

http://ekd.tolosano.info
http://monsitt.irruption.net
http://irruption.net/progdudim


From yoram.hekma at aoes.com  Thu Nov 15 12:21:07 2007
From: yoram.hekma at aoes.com (Yoram Hekma)
Date: Thu, 15 Nov 2007 12:21:07 +0100
Subject: [Tutor] class accessing another's updated property
In-Reply-To: <726588.86719.qm@web58814.mail.re1.yahoo.com>
References: <726588.86719.qm@web58814.mail.re1.yahoo.com>
Message-ID: <20071115112107.GB23026@aoes.com>

On Wed, Nov 14, 2007 at 04:43:28AM -0800, ted b wrote:
> I want class One to be able to access access class
> Two's value property after its been updated. Everytime
> I try (by running, say testTwo().value) I get the
> __init__ value. The update method fro class Two is
> called elsewhere in the program, and I want class
> One's "getTwo" method to access class Two's updated
> value and give me '9' but i get '1'
> 
> Here's the code:
> 
> class One:
>    def __init__(self):
>       self.value = 3
>    def getTwo(self):
>       print "testTwo's updated value", Two().value
> 
> class Two:
>    def __init__(self):
>       self.value = 1
>    def update(self):
>       self.value = 9
> 
> Thanks in advance!

I think you want to update an instance of a class, not the class itself.
If you do:

class Two:
   def __init__(self):
      self.value = 1
   def update(self):
      self.value = 9

class One:
    def __init__(self):
        self.value = 3
        instance_of_Two = Two()
    def getTwo(self):
        print "testTwo's value", instance_of_Two().value
        instance_of_Two.update()
        print "testTwo's updated value", instance_of_Two().value

HTH
Yoram

-- 
Yoram Hekma
Unix Systems Administrator
CICT Department
AOES Netherlands B.V.
Haagse Schouwweg 6G
2332 KG Leiden, The Netherlands
Phone:  +31 (0)71 5795588
Fax:    +31 (0)71 5721277
e-mail: yoram.hekma at aoes.com
http://www.aoes.com

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://mail.python.org/pipermail/tutor/attachments/20071115/0ba9e200/attachment.pgp 

From kent37 at tds.net  Thu Nov 15 13:20:21 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 15 Nov 2007 07:20:21 -0500
Subject: [Tutor] retrieve data from an online database without knowing
 the	url
In-Reply-To: <716900.53900.qm@web27310.mail.ukl.yahoo.com>
References: <716900.53900.qm@web27310.mail.ukl.yahoo.com>
Message-ID: <473C3985.5020802@tds.net>

pileux systeme wrote:
> Hello,
> 
> I was wondering whether it was possible to write a program which could 
> directly write some word in a box and click 'search' on a typical online 
> database without using the url. (e.g. is there a way to write a program 
> which would write some keyword, say 'tomato' on google and click 'google 
> search' automatically and copy the page without having to know the url 
> 'http://www.google.com/search?hl=en&sa=X&oi=spell&resnum=0&ct=result&cd=1&q=tomato&spell=1')

Maybe ClientForm is what you want:
http://wwwsearch.sourceforge.net/ClientForm/

Kent

From bryan_magalski at yahoo.com  Thu Nov 15 13:20:43 2007
From: bryan_magalski at yahoo.com (Bryan Magalski)
Date: Thu, 15 Nov 2007 04:20:43 -0800 (PST)
Subject: [Tutor] Interactive Menu Woes
Message-ID: <309916.88639.qm@web36701.mail.mud.yahoo.com>

Awesome, awesome, awesome.  I will check my script when I get home from work, but your explanation is top notch!  I think I understand it now.  Thank you.

I will post my corrected script and the answers when I get home from work tonight.

Many thanks!


----- Original Message ----
From: Evert Rol <evert.rol at gmail.com>
To: Bryan Magalski <bryan_magalski at yahoo.com>
Cc: tutor at python.org
Sent: Thursday, November 15, 2007 11:37:43 AM
Subject: Re: [Tutor] Interactive Menu Woes

> Thank you for your suggestion.  I did not create the original  
> script, so it will stay as is and my addition for the menu has been  
> adjusted.
>
> Now that I can make a clear distinction of what I am returning, I  
> am getting a new error that leads me that I am trying to call a  
> function that cannot be seen when instantiated:
>
> To add a name, please input he following information:
> Name: Bryan
> Number: 1234567890
> What type of number is this? (choose one):
>                      1. Home:
>                      2. Work:
>                      3. Cell:
>                      : 1
> Traceback (most recent call last):
>  File "menu_modified.py", line 95, in <module>
>    menu.addName()
>  File "menu_modified.py", line 73, in addName
>    enter(name, number, returnType)
> AttributeError: phoneentry instance has no __call__ method


You're first creating a phoneentry object, and then calling the  
actual object. That doesn't work; it's somewhat similar to:
>>> a = dict()
>>> a(key=5)
which gives a slightly different error, but obviously the correct  
form is:
>>> a = dict(key=5)
and also
>>> phoneentry(name, number, returnType)

When creating an object (instantiating the class), the __init__  
method is automatically called, and you provide the arguments of the  
__init__ method when creating the object.
In your current script, the actual entry you create (enter =  
phoneenetry()) creates an entry with name & number 'Unknown' (default  
arguments), and types=UNKNOWN; then you want to assign the actual  
values to the entry. If you *really* want to do this (don't, though),  
you'd be doing:
entry = phoneentry()
entry.name = name
entry.number = number
entry.types = returnType

See the add() method in the phonedb class, where it is done correctly.


A few other thoughts:
- what does numberType return if 'n is not in typeDict'? It should  
return UNKNOWN I guess.
- why not remove that function, and put typeDict to addName? It's  
really only one extra line, and avoids the whole extra function call  
(replacing it with something one might call a 'dictionary call')
- I noticed you use tabs, while the original part of the code uses  
spaces. Try to avoid mixing them: at some point things will go wrong  
(spaces are preferred; for a good read on that and other stuff:  
http://www.python.org/doc/essays/styleguide.html )


  Evert


      ____________________________________________________________________________________
Be a better sports nut!  Let your teams follow you 
with Yahoo Mobile. Try it now.  http://mobile.yahoo.com/sports;_ylt=At9_qDKvtAbMuh1G1SQtBI7ntAcJ
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071115/412135d3/attachment.htm 

From phpmoonlighter at yahoo.com  Thu Nov 15 12:23:13 2007
From: phpmoonlighter at yahoo.com (ted b)
Date: Thu, 15 Nov 2007 03:23:13 -0800 (PST)
Subject: [Tutor] selecting elements from a list that do not meet selection
	criteria
Message-ID: <354807.46236.qm@web58806.mail.re1.yahoo.com>

Is there a way i can select all elements from a list
that do not meet selection criteria. I want to be able
to select elements that have values of, say, < 1 but
only if at least one of the elements has a value of >
0.

What i mean is, for example, in the code below, if one
of the elements of "list 'a'" has a value greater than
1, then i want to print all the other elements in the
list (i.e., class One and class Three) and to do
otherStuff associated with those classes. Right now,
it prints those elements that *do* have values of > 0,
(i.e. class Two). But in situations where all of the
classes have values set to 0, then i don't want
anything selected. 

I don't want to just use something like "if x.value()
!= 0" or "if x.value() < 1" since those would give
results if all elements were less than 1, and i only
want to select elements of the list that are less than
1 if at least one of the elements is > 1.

Here's the sample code:

class One:
   def value(self):
      return 0
      
class Two:
   def value(self):
      return 1

class Three:
   def value(self):
      return 0

a = [One(), Two(), Three()]

for x in a:
   if x.value() > 0:
      print x
      x.otherStuff()

Thanks in advance!!! :)))


      ____________________________________________________________________________________
Be a better pen pal. 
Text or chat with friends inside Yahoo! Mail. See how.  http://overview.mail.yahoo.com/

From kent37 at tds.net  Thu Nov 15 13:23:06 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 15 Nov 2007 07:23:06 -0500
Subject: [Tutor] CSV TO LDIF
In-Reply-To: <BAY111-W24B10F1C5B8D6241DA673BF3820@phx.gbl>
References: <BAY111-W24B10F1C5B8D6241DA673BF3820@phx.gbl>
Message-ID: <473C3A2A.8060905@tds.net>

sacha rook wrote:

> I am using the csv module to parse the csv, anyone got any suggestions 
> for creating the ldif file from this?

http://python-ldap.sourceforge.net/doc/python-ldap/ldif-example.html

Kent

From bryan_magalski at yahoo.com  Thu Nov 15 13:25:12 2007
From: bryan_magalski at yahoo.com (Bryan Magalski)
Date: Thu, 15 Nov 2007 04:25:12 -0800 (PST)
Subject: [Tutor] Interactive Menu Woes
Message-ID: <289596.10273.qm@web36707.mail.mud.yahoo.com>

I wish I would have read your response before posting to Evert Rol's response.  They compliment each other in both explanation and detail.  I thank you as well for your contribution, as I said in my response to Evert, I will post my script completed when I get home.

Thank you.


--Bryan


----- Original Message ----
From: Wesley Brooks <wesbrooks at gmail.com>
To: Bryan Magalski <bryan_magalski at yahoo.com>
Sent: Thursday, November 15, 2007 10:12:26 AM
Subject: Re: [Tutor] Interactive Menu Woes

No worries, I'm still learning myself - be it four years down the
line. Don't think you ever really finsh learning these languages,
there's always new tricks to learn!

The __init__ functions are called when you create an instance of a
class, and are optional.

class a:
    def __init__(self, text):
        self.text = text

    def PrintText(self):
        print self.text

>>> aa = a("Testing __init__")
>>> aa.PrintText()
Testing __init__
>>>

More useful for the telephone number example would be an init function
that created a dictionary to contain your name/number information;

class Directory:
    def __init__(self):
        self.directory = {}

    def AddNumber(self, name, number):
        # name should be a string,
        # number can be string or integer.
        self.directory[name] = number

    def RetrieveNumber(self, name):
        nameList = self.directory.keys() # Returns a list of all the
names in the dictionary
        if name not in nameList: # Checks to make sure the name is in the list
                                            # if this check was not
made an error would be raised
                                            # if you tried to get the
name from the dictionary.
            print "Sorry, do not have that persons name!"
        else:
            return self.directory[name]

>>> telObj = Directory()
>>> telObj.AddNumber("Damion", 666)
>>> telObj.RetrieveNumber("Eric")
Sorry, do not have that persons name!
>>> telObj.RetrieveNumber("Damion")
666

However you would like to give these people different types of numbers
etc so you could create a new dictionary to store various details
inplace of the numbers:

class Directory:
    def __init__(self):
        self.directory = {}

    def AddDetail(self, name, type, data):
        if name not in self.directory.keys():
            self.directory[name] = {}
        personDetails = self.directory[name]
        personDetails[type] = data

    def RetrieveDetail(self, name, type):
        nameList = self.directory.keys()
        if name not in nameList:
            print "Sorry, do not have that persons name!"
        else:
            personDetails = self.directory[name]
            storedDetailTypes = personDetails.keys()
            if type not in storedDetailTypes:
                print "Sorry, do not have those details for that person"
            else:
                return personDetails[type]

>>> telObj = Directory()
>>> telObj.AddDetail("Damion", "HomeTel", 666)
>>> telObj.RetrieveDetail("Damion", "Mobile")
Sorry, do not have those details for that person
>>> telObj.RetrieveDetail("Damion", "HomeTel")
666

You can take this a further still. Instead of creating a dictionary,
you could create a new instance of an object that inherits the
dictionary class, and that way you can override the functions that add
data to, and retrieve data from the personalDetails object. This is a
little more advanced, and I guess you've got a fair bit to digest
above!

Hope that helps.

Cheers,

Wes.

On 14/11/2007, Bryan Magalski <bryan_magalski at yahoo.com> wrote:
>
> Thank you very much for the prompt reply.
>
> I believe the way you explained my inability to grasp the concept really
> helped and I think I understand it better now.  It just proves that I need
> to practice more.
>
> If you have the time, I have another question pertaining to objects.   There
> is a ton of information on the web about how to use __init__ and self when
> creating functions within an object.  I simply "aped" the code from the
> millions of examples out there without really understanding them totally,
> (maybe now I am script kiddie?).  As I really cannot digest this, can you
> help me and elaborate on the reason of their existence and when it is
> appropriate for their use?
>
>
> Again, excellent explanation and thank you very much.  I hope that I am not
> burdening you by bombarding you with these questions.
>
>
> --Bryan
>
>
> Wesley Brooks <wesbrooks at gmail.com> wrote:
> In the middle of your addName function you have defined another
> function that requires 'self' and you've got a default argument
> 'get=1';
>
> def numberType(self, get = 1):
>
> You call this further down the function with the line;
>
> self.type = numberType(self.get)
>
> This should have been;
>
> self.type = numberType(self)
>
> I would suggest moving the numberType function from inside the addName
> function as follows;
>
> class MenuInput:
> def addName(self):
> print "To add a name, please input he following information: "
> name = raw_input("Name: ")
> number = raw_input("Number: ")
> get = int(raw_input("What type of number is this? (choose
> one): \n 1. Home:\n 2. Work:\n 3. Cell:\n : "))
> type = self.numberType(get)
> enter = phoneentry()
> enter(name, number, returnType)
>
> def numberType(self, get):
> if get == 1:
> returnType = HOME
> elif get == 2:
> returnType = WORK
> elif get == 3:
> returnType = FAX
> return returnType
>
> If you use self in a function all functions can see the value without
> having to have it in the function definition.
>
> For example;
>
> class a:
> def a(self):
> self.get = 1
> def b(self):
> print self.get
>
> >>> aa = a()
> >>> aa.a()
> >>> aa.b()
> 1
> >>>
>
> Default arguments in the function definition work as follows:
>
> class a:
> def a(self):
> self.get = 1
> def b(self, get="Using default argument"):
> print get
>
> >>> aa = a()
> >>> aa.a()
> >>> aa.b()
> "Using default argument"
> >>> aa.b(1)
> 1
> >>>
>
> Cheers,
>
> Wes.
>
> On 14/11/2007, Bryan Magalski wrote:
> >
> > Greetings all!!
> >
> > This is my first post and I am going to probably be vague at first, but, I
> > will try my best to be specific. I am a very GREEN scripter/programmer, so
> > please be as descriptive as possible. Ok, enough excuses, on with my
> > question!
> >
> > Here is my issue:
> >
> > I am trying to build a menu for the following script to make it more "user
> > friendly". Nothing fancy, just a simple add data and look up the entered
> > results.
> >
> > The problem is that when I run my modified version with this snippet
> (please
> > see attachment for original and my modified versions):
> >
> > [code]
> > class MenuInput:
> >
> > # ask user to input data and store to be passed to manageable variables.
> > def addName(self):
> > print "To add a name, please input he following information:
> > "
> > self.enter = phoneentry()
> > self.name = raw_input("Name: ")
> > self.number = raw_input("Number: ")
> > self.get = int(raw_input("What type of number is this?
> > (choose one): \n 1. Home:\n 2. Work:\n 3. Cell:\n : "))
> > def numberType(self, get = 1):
> > if self.get == 1:
> > self.returnType = HOME
> > #return self.getType
> > elif self.gete == 2:
> > self.returnType = WORK
> > #return self.getType
> > elif self.get == 3:
> > self.returnType = FAX
> > #return self.getType
> > return self.returnType
> >
> > self.type = numberType(self.get)
> > self.enter(self.name, self.number, self.returnType)
> >
> > def display(self):
> > print "Enter a name to look up: (leave blank to exit)"
> > self.Name = str(raw_input("Name: "))
> > print "%s has the following information: " % self.Name
> > if self.Name != "":
> > foo = phonedb()
> > for entry in foo.lookup(self.Name):
> > print '%-40s %s (%s)' % (entry.name,
> > entry.number, entry.showtype())
> > print
> > [/code]
> >
> > when I instantiate and run it with:
> >
> > [code]
> > menu = MenuInput()
> > menu.addName()
> > [/code]
> >
> > and enter the information asked, I am given this runtime error:
> >
> > [error]
> > To add a name, please input he following information:
> > Name: Bryan
> > Number: 1234567
> > What type of number is this? (choose one):
> > 1. Home:
> > 2. Work:
> > 3. Cell:
> > : 1
> > Traceback (most recent call last):
> > File "examples\testpy\my_object_modified.py", line 101,
> > in
> > menu.addName()
> > File "examples\testpy\my_object_modified.py", line 85, in
> > addName
> > self.type = numberType(self.get)
> > File "examples\testpy\my_object_modified.py", line 74, in
> > numberType
> > if self.get == 1:
> > AttributeError: 'int' object has no attribute 'get'
> > >>>
> > [/error]
> >
> > I "think" that this has something to do with passing the results or
> possibly
> > my functions are not properly calling (proper terminology?) each other.
> >
> > Now what/where am I wrong? As this is part of an object oriented
> > programming class, I wanted the menu constructed inherent to the class.
> >
> > Thank you in advance. --Bryan
> > ________________________________
> > Be a better sports nut! Let your teams follow you with Yahoo Mobile. Try
> it
> > now.
> > _______________________________________________
> > Tutor maillist - Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
> >
>
>
>  ________________________________
> Be a better pen pal. Text or chat with friends inside Yahoo! Mail. See how.


      ____________________________________________________________________________________
Be a better pen pal. 
Text or chat with friends inside Yahoo! Mail. See how.  http://overview.mail.yahoo.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071115/0f0eb17a/attachment-0001.htm 

From kent37 at tds.net  Thu Nov 15 13:31:40 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 15 Nov 2007 07:31:40 -0500
Subject: [Tutor] selecting elements from a list that do not meet
 selection criteria
In-Reply-To: <354807.46236.qm@web58806.mail.re1.yahoo.com>
References: <354807.46236.qm@web58806.mail.re1.yahoo.com>
Message-ID: <473C3C2C.6090701@tds.net>

ted b wrote:
> Is there a way i can select all elements from a list
> that do not meet selection criteria. I want to be able
> to select elements that have values of, say, < 1 but
> only if at least one of the elements has a value of >
> 0.

I'm not sure if you mean > 0 or >1, you seem to say both at different times.

> I don't want to just use something like "if x.value()
> != 0" or "if x.value() < 1" since those would give
> results if all elements were less than 1, and i only
> want to select elements of the list that are less than
> 1 if at least one of the elements is > 1.

Use any():
   if any(x.value() > 0 for x in a):
     for x in a:
      if x.value() > 0:
        print x
        x.otherStuff()

> Here's the sample code:
> 
> class One:
>    def value(self):
>       return 0

BTW this style of programming - using getter methods to access values - 
is not idiomatic Python. Better would be to use a value attribute directly:

class One:
   def __init__(self):
     self.value = 0

Then refer to One().value instead of One().value()

Kent

From sanelson at gmail.com  Thu Nov 15 14:26:30 2007
From: sanelson at gmail.com (Stephen Nelson-Smith)
Date: Thu, 15 Nov 2007 13:26:30 +0000
Subject: [Tutor] [OT] Vacancy - python systems programmer
Message-ID: <b6131fdc0711150526u78721e3cra196f93e778a8233@mail.gmail.com>

All,

I may shortly be in the position of being able to hire a python
systems programmer for a short contract (1-2 days initially to spike
an ongoing project).

The ideal person will have the following:

* Solid experience of Python for systems programming and database interaction
* Familiarity with MySQL 5 - inserting and querying medium-sized
databases with Python
* Systems experience on RHEL or equivalent clone
* Sysadmin experience on Unix / Linux with patching and package
management systems
* Experience in a high-availability environment, eg managed hosting.
* Experience of working in an agile environment (test first, pairing)

This is, of course, a shopping list, but is intended to give a sense
of the sort of background I'm after.

If this sounds like the sort of thing you'd be interested in, please
contact me off list.

Thanks,

S.

From sith618 at yahoo.com  Thu Nov 15 15:36:59 2007
From: sith618 at yahoo.com (sith .)
Date: Thu, 15 Nov 2007 06:36:59 -0800 (PST)
Subject: [Tutor] parsing an array
Message-ID: <527819.73974.qm@web33208.mail.mud.yahoo.com>

a = [[1,1],[3,1.5],[5,0]]
  for i in range(len(a)) :
    if a[i][1] > a[i-1][1] :
        print 'greater !!'
    else:
        print "smaller"
  greater !!
  greater !!
  smaller
  
Thanks for taking the time to help me Aditya.  I tried the code but have encountered a problem.  In this new list,
[1,    1]
[3,    1.5]
[5,    0]
  only the second and third "greater" and "smaller" output are correct as 1.5 is larger than 1 and 0 is smaller than 1.5.  What is i[1] greater than?  
  I also tried using + for next item instread, but that produced an error.  Why?
    if a[i][1] > a[i+1][1] 

       
---------------------------------
Be a better sports nut! Let your teams follow you with Yahoo Mobile. Try it now.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071115/ec206ba6/attachment.htm 

From sith618 at yahoo.com  Thu Nov 15 15:46:23 2007
From: sith618 at yahoo.com (sith .)
Date: Thu, 15 Nov 2007 06:46:23 -0800 (PST)
Subject: [Tutor] parsing an array
Message-ID: <226442.82177.qm@web33202.mail.mud.yahoo.com>

greater !!
  greater !!
  smaller
  
  only the second and third "greater" and "smaller" output are correct as 1.5 is larger than 1 and 0 is smaller than 1.5.  
   
  What is i[1] greater than?  <----------------------------sorry this is wrong.
  Should be:
  What is the i[0,1] greater than?  There is no number before it in the list.
  Thank you.
  
 

       
---------------------------------
Never miss a thing.   Make Yahoo your homepage.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071115/6582e809/attachment.htm 

From kent37 at tds.net  Thu Nov 15 16:08:38 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 15 Nov 2007 10:08:38 -0500
Subject: [Tutor] parsing an array
In-Reply-To: <527819.73974.qm@web33208.mail.mud.yahoo.com>
References: <527819.73974.qm@web33208.mail.mud.yahoo.com>
Message-ID: <473C60F6.9030807@tds.net>

sith . wrote:
> a = [[1,1],[3,1.5],[5,0]]
> for i in range(len(a)) :

This should use range(1, len(a)). You don't want i to take on the value 0.

>     if a[i][1] > a[i-1][1] :

When i==0 this compares a[0] to a[-1] which is the *last* element of the 
list; a[0][1] > a[-1][1] so it prints 'greater !!'.

Kent

PS Please reply to the original post rather than starting a new thread.

From aymchaos at yahoo.com  Thu Nov 15 16:25:29 2007
From: aymchaos at yahoo.com (Mihai Iacob)
Date: Thu, 15 Nov 2007 07:25:29 -0800 (PST)
Subject: [Tutor] How to import modules using the input() command
Message-ID: <356507.59532.qm@web32715.mail.mud.yahoo.com>

Hello,

I was wondering if there is a way to import modules
using the input() command. If i try to do it directly
it gives me an error:

>>> input()
import time

Traceback (most recent call last):
  File "<pyshell#168>", line 1, in <module>
    input()
  File "<string>", line 1
    import time
         ^
SyntaxError: invalid syntax
>>> 


Is there another way in which i can import modules
with the input() command?





      ____________________________________________________________________________________
Never miss a thing.  Make Yahoo your home page. 
http://www.yahoo.com/r/hs

From kent37 at tds.net  Thu Nov 15 16:53:19 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 15 Nov 2007 10:53:19 -0500
Subject: [Tutor] How to import modules using the input() command
In-Reply-To: <356507.59532.qm@web32715.mail.mud.yahoo.com>
References: <356507.59532.qm@web32715.mail.mud.yahoo.com>
Message-ID: <473C6B6F.8030200@tds.net>

Mihai Iacob wrote:
> Hello,
> 
> I was wondering if there is a way to import modules
> using the input() command. If i try to do it directly
> it gives me an error:
> 
>>>> input()
> import time
> 
> Traceback (most recent call last):
>   File "<pyshell#168>", line 1, in <module>
>     input()
>   File "<string>", line 1
>     import time
>          ^
> SyntaxError: invalid syntax

import is a statement, not an expression, that is why it fails with 
input(). You could input the name of the module and then import it 
yourself with __import__(), or you could type '__import__("time")' to 
input() though that won't bind the module to a name.

Why do you want to do this? It is an unusual request.

Kent

From bgailer at alum.rpi.edu  Thu Nov 15 16:56:51 2007
From: bgailer at alum.rpi.edu (bob gailer)
Date: Thu, 15 Nov 2007 10:56:51 -0500
Subject: [Tutor] How to import modules using the input() command
In-Reply-To: <356507.59532.qm@web32715.mail.mud.yahoo.com>
References: <356507.59532.qm@web32715.mail.mud.yahoo.com>
Message-ID: <473C6C43.9030507@alum.rpi.edu>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071115/a324cdd9/attachment.htm 

From remco at gerlich.nl  Thu Nov 15 16:52:22 2007
From: remco at gerlich.nl (Remco Gerlich)
Date: Thu, 15 Nov 2007 16:52:22 +0100
Subject: [Tutor] How to import modules using the input() command
In-Reply-To: <356507.59532.qm@web32715.mail.mud.yahoo.com>
References: <356507.59532.qm@web32715.mail.mud.yahoo.com>
Message-ID: <7ae3ca10711150752w5a9d52a1x959f1950d29f1d16@mail.gmail.com>

The input() function calls eval() on the value you give it. Eval() can
evaluate any _expression_. That's generally insecure and not
recommended - people could type in anything, as you're trying to do
:-)

But anyway, that is why 'import ...' directly doesn't work, import is
a statement, not an expression.

However, you can use the built-in function __import__(), that imports
the module and returns it. That loads it into memory, but it doesn't
add the module to the current namespace.

What do you need this for?

Remco Gerlich

On Nov 15, 2007 4:25 PM, Mihai Iacob <aymchaos at yahoo.com> wrote:
> Hello,
>
> I was wondering if there is a way to import modules
> using the input() command. If i try to do it directly
> it gives me an error:
>
> >>> input()
> import time
>
> Traceback (most recent call last):
>   File "<pyshell#168>", line 1, in <module>
>     input()
>   File "<string>", line 1
>     import time
>          ^
> SyntaxError: invalid syntax
> >>>
>
>
> Is there another way in which i can import modules
> with the input() command?
>
>
>
>
>
>       ____________________________________________________________________________________
> Never miss a thing.  Make Yahoo your home page.
> http://www.yahoo.com/r/hs
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From bart.cramer at gmail.com  Thu Nov 15 16:56:59 2007
From: bart.cramer at gmail.com (Bart Cramer)
Date: Thu, 15 Nov 2007 16:56:59 +0100
Subject: [Tutor] Memory consumption question
Message-ID: <2f75e6460711150756i61f245ady6a00cc0f0fe9fc5@mail.gmail.com>

Dear all,

I have a question... :

>>> class A: pass
...
>>> class B(object) : pass
...
>>> dir(A)
['__doc__', '__module__']
>>> dir(B)
['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__',
'__hash__', '__init__', '__module__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__']

What is the difference between classes A and B? The funny thing is, when I
put these things into an array of length, say, a million, it turns out that
class A eats about 184 bytes per instantiation, and class B a lot less
(sic!): plm 50 bytes. How come?

Best,

Bart.

-- 
Bart Cramer

Dudweilerstrasse 31
66111 Saarbrucken, Germany
0049 1577 6806119 (NEW!)

Bedumerstraat 25
9716 BB Groningen, the Netherlands
0031 6 42440326

bart.cramer at gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071115/8fa226ec/attachment-0001.htm 

From bryan.fodness at gmail.com  Mon Nov 12 20:43:19 2007
From: bryan.fodness at gmail.com (Bryan Fodness)
Date: Mon, 12 Nov 2007 14:43:19 -0500
Subject: [Tutor] manipulating data
In-Reply-To: <fh94m5$1h6$1@ger.gmane.org>
References: <fbf64d2b0711061154v4f6547bcx133c342f2d5aac27@mail.gmail.com>
	<4731C327.6000704@tds.net> <47330268.1080304@bigfoot.com>
	<fbf64d2b0711111702g7161a4bal2b3bc83bb6761d84@mail.gmail.com>
	<fh94m5$1h6$1@ger.gmane.org>
Message-ID: <fbf64d2b0711121143o12fff941p4028a10acdaaa5b6@mail.gmail.com>

I try this,

f = open('TEST1.MLC')

fields = {}

for line in f:
    if line.split()[0] == 'Field':
        field = int(line.split()[-1])
    elif line.split()[0] == 'Leaf':
        fields[field] = line.split()[-1]
    else:
        line = f.next()

and get,

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    line.split()[0]
IndexError: list index out of range

I have attached my data file.
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: TEST1.MLC
Url: http://mail.python.org/pipermail/tutor/attachments/20071112/70da63cf/attachment.txt 

From kent37 at tds.net  Thu Nov 15 17:59:45 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 15 Nov 2007 11:59:45 -0500
Subject: [Tutor] manipulating data
In-Reply-To: <fbf64d2b0711121143o12fff941p4028a10acdaaa5b6@mail.gmail.com>
References: <fbf64d2b0711061154v4f6547bcx133c342f2d5aac27@mail.gmail.com>	<4731C327.6000704@tds.net>
	<47330268.1080304@bigfoot.com>	<fbf64d2b0711111702g7161a4bal2b3bc83bb6761d84@mail.gmail.com>	<fh94m5$1h6$1@ger.gmane.org>
	<fbf64d2b0711121143o12fff941p4028a10acdaaa5b6@mail.gmail.com>
Message-ID: <473C7B01.2070209@tds.net>

Bryan Fodness wrote:
> I try this,
> 
> f = open('TEST1.MLC')
> 
> fields = {}
> 
> for line in f:
>     if line.split()[0] == 'Field':
>         field = int(line.split()[-1])
>     elif line.split()[0] == 'Leaf':
>         fields[field] = line.split()[-1]
>     else:
>         line = f.next()
> 
> and get,
> 
> Traceback (most recent call last):
>   File "<pyshell#1>", line 1, in <module>
>     line.split()[0]
> IndexError: list index out of range

For blank lines, line.split() is [] so there is no line.split()[0]. Try 
skipping blank lines before you split.

Kent

From marc.tompkins at gmail.com  Thu Nov 15 18:03:11 2007
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Thu, 15 Nov 2007 09:03:11 -0800
Subject: [Tutor] Memory consumption question
Message-ID: <40af687b0711150903pe9e61fbx2f3925ff52d0388a@mail.gmail.com>

Thus spake Bart Cramer:

> I have a question... :
>
> >>> class A: pass
> ...
> >>> class B(object) : pass
> ...
> >>> dir(A)
> ['__doc__', '__module__']
> >>> dir(B)
> ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__',
> '__hash__', '__init__', '__module__', '__new__', '__reduce__',
> '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__']
>
> What is the difference between classes A and B? The funny thing is, when I
> put these things into an array of length, say, a million, it turns out
> that
> class A eats about 184 bytes per instantiation, and class B a lot less
> (sic!): plm 50 bytes. How come?
>

class B is a "new-style' class, meaning that it inherits from a base,
pre-existing class (in this case "object", which is as basic and generic as
you can get!).  class A has to start from nothing, which is why it consumes
more memory yet has less functionality.  (As a very, very rough analogy,
imagine that you have thirty seconds to paint a sign.  Which would be more
efficient - freehand or a stencil?  Given time, you can achieve more
artistic results freehand, but the stencil gets you quick results.)

As I understand it, in Python 3000 (aka 3.0), new-style classes will be
mandatory.  As you can already see, they give you more bang for the buck, so
you might as well get used to using them now!

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

From goldwamh at slu.edu  Thu Nov 15 18:04:16 2007
From: goldwamh at slu.edu (Michael H. Goldwasser)
Date: Thu, 15 Nov 2007 11:04:16 -0600
Subject: [Tutor] manipulating data
In-Reply-To: <fbf64d2b0711121143o12fff941p4028a10acdaaa5b6@mail.gmail.com>
References: <fbf64d2b0711061154v4f6547bcx133c342f2d5aac27@mail.gmail.com>
	<4731C327.6000704@tds.net> <47330268.1080304@bigfoot.com>
	<fbf64d2b0711111702g7161a4bal2b3bc83bb6761d84@mail.gmail.com>
	<fh94m5$1h6$1@ger.gmane.org>
	<fbf64d2b0711121143o12fff941p4028a10acdaaa5b6@mail.gmail.com>
Message-ID: <18236.31760.851972.350228@euclid.slu.edu>


On Monday November 12, 2007, Bryan Fodness wrote: 

>    I try this,
>    
>    f = open('TEST1.MLC')
>    
>    fields = {}
>    
>    for line in f:
>        if line.split()[0] == 'Field':
>            field = int(line.split()[-1])
>        elif line.split()[0] == 'Leaf':
>            fields[field] = line.split()[-1]
>        else:
>            line = f.next()
>    
>    and get,
>    
>    Traceback (most recent call last):
>      File "<pyshell#1>", line 1, in <module>
>        line.split()[0]
>    IndexError: list index out of range

Bryan,

There are some blank lines in your file.  When those lines are
reached, line.split() returns an empty list, and therefore
line.split()[0] is an IndexError.   One way to rewrite this is as
follows (untested):

    for line in f:
        pieces = line.split()
        if pieces:                      # non-empty line
            if pieces[0] == 'Field':
                field = int(pieces[-1])
            elif pieces[0] == 'Leaf':
                fields[field] = pieces[-1]
            else:
                line = f.next()         # I've left this here, but not sure
                                        # why you have it.  The for loop
                                        # already advances from line to line

Note as well that it is better to perform the split once per line
(rather than recomputing it as you do in your original code).

With regard,
Michael


From kent37 at tds.net  Thu Nov 15 18:32:29 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 15 Nov 2007 12:32:29 -0500
Subject: [Tutor] Memory consumption question
In-Reply-To: <40af687b0711150903pe9e61fbx2f3925ff52d0388a@mail.gmail.com>
References: <40af687b0711150903pe9e61fbx2f3925ff52d0388a@mail.gmail.com>
Message-ID: <473C82AD.9000603@tds.net>

Marc Tompkins wrote:

> class B is a "new-style' class, meaning that it inherits from a base, 
> pre-existing class (in this case "object", which is as basic and generic 
> as you can get!).  class A has to start from nothing, which is why it 
> consumes more memory yet has less functionality.

I don't think it is really accurate to say that an old-style class 
"starts from nothing". It doesn't have an explicit base class but it 
does have all the old-style class machinery which is built in to Python.

I don't know why new-style classes are smaller though. My guess is that 
it is because there was an opportunity to streamline the class structure 
based on experience.

Kent

From tavspamnofwd at googlemail.com  Thu Nov 15 19:35:49 2007
From: tavspamnofwd at googlemail.com (Tom)
Date: Thu, 15 Nov 2007 18:35:49 +0000
Subject: [Tutor] Little subclass understanding problem
Message-ID: <ca43e5230711151035r2c468ef8j993f15b432e82d9c@mail.gmail.com>

I am trying to understand what happens in the following scenario:

class Sub_class(Base_class):
    def __init__(self, data):
        Base_class.__init__(self, data)

as in:

# snippet from http://viner.tv/go?set
class Set(list):
    def __init__(self, value = []):
        list.__init__([])


The last line is the one I don't understand. Nothing appears to be
assigned or instantiated.

I have just re-read the relevant part of Wesley Chun's 'Core' book,
again, and think I *may* understand.

Base_class.__init__(self, data)

is *kind of* like saying:

self.Base_class.__init__(data)

i.e. it's doing something *to* self. But then the 2nd example above
doesn't make sense! It looks like list.__init__([]) is doing something
special just because of where it is, i.e. in the class definition of a
subclass of list.

Help!

If anyone has a better way of explaining this / thinking about this, I
would be most grateful!

From marc.tompkins at gmail.com  Thu Nov 15 20:03:12 2007
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Thu, 15 Nov 2007 11:03:12 -0800
Subject: [Tutor] Memory consumption question
In-Reply-To: <473C82AD.9000603@tds.net>
References: <40af687b0711150903pe9e61fbx2f3925ff52d0388a@mail.gmail.com>
	<473C82AD.9000603@tds.net>
Message-ID: <40af687b0711151103s19f7916eu12f35d39898ee325@mail.gmail.com>

I didn't mean that exactly literally - for goodness' sake, this is a
high-level, object-oriented, interpreted language!  We're not writing
machine language here.

What I did mean, and will probably still not express as clearly as I'd like,
is that when you create a "classic" class, lots of options remain unresolved
- slots vs. dict comes to mind - and Python needs to reserve extra space
accordingly.   About 134 extra bytes, it would appear.

On Nov 15, 2007 9:32 AM, Kent Johnson <kent37 at tds.net> wrote:

> Marc Tompkins wrote:
>
> > class B is a "new-style' class, meaning that it inherits from a base,
> > pre-existing class (in this case "object", which is as basic and generic
> > as you can get!).  class A has to start from nothing, which is why it
> > consumes more memory yet has less functionality.
>
> I don't think it is really accurate to say that an old-style class
> "starts from nothing". It doesn't have an explicit base class but it
> does have all the old-style class machinery which is built in to Python.
>
> I don't know why new-style classes are smaller though. My guess is that
> it is because there was an opportunity to streamline the class structure
> based on experience.
>
> Kent
>



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

From goldwamh at slu.edu  Thu Nov 15 20:05:36 2007
From: goldwamh at slu.edu (Michael H. Goldwasser)
Date: Thu, 15 Nov 2007 13:05:36 -0600
Subject: [Tutor]  Little subclass understanding problem
In-Reply-To: <ca43e5230711151035r2c468ef8j993f15b432e82d9c@mail.gmail.com>
References: <ca43e5230711151035r2c468ef8j993f15b432e82d9c@mail.gmail.com>
Message-ID: <18236.39040.363816.393685@euclid.slu.edu>


On Thursday November 15, 2007, Tom wrote: 

>    I am trying to understand what happens in the following scenario:
>    
>    class Sub_class(Base_class):
>        def __init__(self, data):
>            Base_class.__init__(self, data)
>    
>    as in:
>    
>    # snippet from http://viner.tv/go?set
>    class Set(list):
>        def __init__(self, value = []):
>            list.__init__([])


Tom,

  Indeed, that first line of the Set constructor body is invoking the
  constructor for the base class (list, in this case).  The reason
  that the value parameter is NOT being directly sent to the base
  class is that there is a desire to avoid allowing potentially
  duplicate elements into something that is representing a set. 

  However, it was entirely unnecessary for them to send an empty list
  as a parameter.  It would suffice to have written

             list.__init__()

  It is important to have the call to the base class initializer
  because we need to allow for the internal state of the underlying
  list to be properly intitialized. 

  Please note that the original source for this from viner.tv
  has an important fourth line:

    class Set(list):
        def __init__(self, value = []):
            list.__init__([])
            self.concat(value)              # copies mutable default

  That fourth line uses a custom method defined later to insert
  designated values into the set while making sure to avoid
  duplicates.

With regard,
Michael


From goldwamh at slu.edu  Thu Nov 15 20:16:53 2007
From: goldwamh at slu.edu (Michael H. Goldwasser)
Date: Thu, 15 Nov 2007 13:16:53 -0600
Subject: [Tutor]   Little subclass understanding problem
In-Reply-To: <18236.39040.363816.393685@euclid.slu.edu>
References: <ca43e5230711151035r2c468ef8j993f15b432e82d9c@mail.gmail.com>
	<18236.39040.363816.393685@euclid.slu.edu>
Message-ID: <18236.39717.746037.677973@euclid.slu.edu>



Oops...

Just finished sending my earlier response and realize that I overlooked an issue.

The code from http://viner.tv/go?set is potentially errant.  When
invoking the base class constructor, self should have been explcitly
sent as a parameter, using the syntax

        class Set(list):
            def __init__(self, value = []):
                list.__init__(self)
                self.concat(value)              # copies mutable default

I had gotten sidetracked by the issue of why value was not being
explicitly sent. This explains in part why the original author used
the syntax 
                list.__init__([])

with an empty list as the parameter to __init__.  That makes such a
command legal, but the call is entirely pointless, as it invokes the
initializer on a different instance than the one that we are currently
responsible for initializing.

I suspect that the code as written is faulty because the internal
state of the list is not necessarily properly initialized.   However,
since list is a built-in class, it is possible that the author of this
code is getting lucky because initialization of a Python list may be
happening by other means than list.__init__

This example is certainly not a proper use of inheritance.

With regard,
Michael



On Thursday November 15, 2007, Michael H. Goldwasser wrote: 

>    
>    On Thursday November 15, 2007, Tom wrote: 
>    
>    >    I am trying to understand what happens in the following scenario:
>    >    
>    >    class Sub_class(Base_class):
>    >        def __init__(self, data):
>    >            Base_class.__init__(self, data)
>    >    
>    >    as in:
>    >    
>    >    # snippet from http://viner.tv/go?set
>    >    class Set(list):
>    >        def __init__(self, value = []):
>    >            list.__init__([])
>    
>    
>    Tom,
>    
>      Indeed, that first line of the Set constructor body is invoking the
>      constructor for the base class (list, in this case).  The reason
>      that the value parameter is NOT being directly sent to the base
>      class is that there is a desire to avoid allowing potentially
>      duplicate elements into something that is representing a set. 
>    
>      However, it was entirely unnecessary for them to send an empty list
>      as a parameter.  It would suffice to have written
>    
>                 list.__init__()
>    
>      It is important to have the call to the base class initializer
>      because we need to allow for the internal state of the underlying
>      list to be properly intitialized. 
>    
>      Please note that the original source for this from viner.tv
>      has an important fourth line:
>    
>        class Set(list):
>            def __init__(self, value = []):
>                list.__init__([])
>                self.concat(value)              # copies mutable default
>    
>      That fourth line uses a custom method defined later to insert
>      designated values into the set while making sure to avoid
>      duplicates.
>    
>    With regard,
>    Michael
>    
>    _______________________________________________
>    Tutor maillist  -  Tutor at python.org
>    http://mail.python.org/mailman/listinfo/tutor


From kent37 at tds.net  Thu Nov 15 20:22:37 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 15 Nov 2007 14:22:37 -0500
Subject: [Tutor] Memory consumption question
In-Reply-To: <40af687b0711151103s19f7916eu12f35d39898ee325@mail.gmail.com>
References: <40af687b0711150903pe9e61fbx2f3925ff52d0388a@mail.gmail.com>	
	<473C82AD.9000603@tds.net>
	<40af687b0711151103s19f7916eu12f35d39898ee325@mail.gmail.com>
Message-ID: <473C9C7D.3020304@tds.net>

Marc Tompkins wrote:
> I didn't mean that exactly literally - for goodness' sake, this is a 
> high-level, object-oriented, interpreted language!  We're not writing 
> machine language here.

Yes, I was thinking I should re-word my email, it was worded a bit too 
strongly...

> What I did mean, and will probably still not express as clearly as I'd 
> like, is that when you create a "classic" class, lots of options remain 
> unresolved - slots vs. dict comes to mind - and Python needs to reserve 
> extra space accordingly.   About 134 extra bytes, it would appear.

Still not sure I know what you mean. AFAIK old-style classes don't 
support slots, at least not user-defined slots. I do remember talk of 
new-style classes and properties allowing a much cleaner implementation 
of the class mechanisms, and it seems plausible that such generalization 
would lead to fewer options and streamlining of the class structure, but 
I don't know enough about the specifics to know if that is right.

I poked around a bit in the source to see if I could figure it out but 
got tired of trying to sift through the header files...

Kent
> 
> On Nov 15, 2007 9:32 AM, Kent Johnson <kent37 at tds.net 
> <mailto:kent37 at tds.net>> wrote:
> 
>     Marc Tompkins wrote:
> 
>      > class B is a "new-style' class, meaning that it inherits from a base,
>      > pre-existing class (in this case "object", which is as basic and
>     generic
>      > as you can get!).  class A has to start from nothing, which is why it
>      > consumes more memory yet has less functionality.
> 
>     I don't think it is really accurate to say that an old-style class
>     "starts from nothing". It doesn't have an explicit base class but it
>     does have all the old-style class machinery which is built in to Python.
> 
>     I don't know why new-style classes are smaller though. My guess is that
>     it is because there was an opportunity to streamline the class structure
>     based on experience.
> 
>     Kent
> 
> 
> 
> 
> -- 
> www.fsrtechnologies.com <http://www.fsrtechnologies.com>


From kent37 at tds.net  Thu Nov 15 20:26:55 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 15 Nov 2007 14:26:55 -0500
Subject: [Tutor] Little subclass understanding problem
In-Reply-To: <ca43e5230711151035r2c468ef8j993f15b432e82d9c@mail.gmail.com>
References: <ca43e5230711151035r2c468ef8j993f15b432e82d9c@mail.gmail.com>
Message-ID: <473C9D7F.3030801@tds.net>

Tom wrote:
> I am trying to understand what happens in the following scenario:
> 
> class Sub_class(Base_class):
>     def __init__(self, data):
>         Base_class.__init__(self, data)
> 
> as in:
> 
> # snippet from http://viner.tv/go?set
> class Set(list):
>     def __init__(self, value = []):
>         list.__init__([])

This is a bug, it should be
   list.__init__(self, value)

> I have just re-read the relevant part of Wesley Chun's 'Core' book,
> again, and think I *may* understand.
> 
> Base_class.__init__(self, data)
> 
> is *kind of* like saying:
> 
> self.Base_class.__init__(data)
> 
> i.e. it's doing something *to* self. 

Yes, that is more or less correct.

In general, if c is an instance of class C, a method call
   c.foo()

can also be written as
   C.foo(c)

When you want to call a base class method, you have to use the second 
form. That is what
   Base_class.__init__(self)
is doing.

Kent

From samrobertsmith at gmail.com  Thu Nov 15 21:17:30 2007
From: samrobertsmith at gmail.com (linda.s)
Date: Thu, 15 Nov 2007 12:17:30 -0800
Subject: [Tutor] selection
Message-ID: <1d987df30711151217y5cd81105o278adf1d86ca9ab4@mail.gmail.com>

Hi,
I wonder how to hold the ctrl key and button-1 to do multiple
selection of the following items?
Thanks,
Linda

import Tkinter

s = Tkinter.Scrollbar()
L = Tkinter.Listbox()

s.pack(side=Tkinter.RIGHT, fill=Tkinter.Y)
L.pack(side=Tkinter.LEFT, fill=Tkinter.Y)

s.config(command=L.yview)
L.config(yscrollcommand=s.set)

for i in range(30):
   L.insert(Tkinter.END, str(i)*3)

Tkinter.mainloop()

From samrobertsmith at gmail.com  Thu Nov 15 22:40:43 2007
From: samrobertsmith at gmail.com (linda.s)
Date: Thu, 15 Nov 2007 13:40:43 -0800
Subject: [Tutor] width
Message-ID: <1d987df30711151340x1bd0efbeg8d51fafc16444483@mail.gmail.com>

I wonder why the widths are different for the three labels?
Thanks,
Linda

from Tkinter import *

root = Tk()

w = Label(root, text="Red", bg="red", fg="white")
w.pack()
w = Label(root, text="Green", bg="green", fg="white")
w.pack()
w = Label(root, text="Blue", bg="blue", fg="white")
w.pack()

mainloop()

From marc.tompkins at gmail.com  Thu Nov 15 22:42:13 2007
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Thu, 15 Nov 2007 13:42:13 -0800
Subject: [Tutor] Memory consumption question
In-Reply-To: <473C9C7D.3020304@tds.net>
References: <40af687b0711150903pe9e61fbx2f3925ff52d0388a@mail.gmail.com>
	<473C82AD.9000603@tds.net>
	<40af687b0711151103s19f7916eu12f35d39898ee325@mail.gmail.com>
	<473C9C7D.3020304@tds.net>
Message-ID: <40af687b0711151342i31df6458w4645f7c918a72d78@mail.gmail.com>

I thought of an analogy I like better than my sign-painting one: ordering a
sandwich.
Imagine: you're at the deli, and your waitron asks what you want.  (Granted,
this is a silly example.)
  "Classic" order: "I'd like a sandwich with two slices of rye bread,
Russian dressing, corned beef, and Swiss cheese.  Oh, and I'd like that
grilled."
  "New-style" order: "Reuben, please."

Now, I speak not of the time and materials required to construct the
above-mentioned tasty treat - in my analogy, Python is the long-suffering
waitron, not the cook - but I gotta figure that the second option will take
less space to write on the check.  Perhaps about 134 bytes' worth.

For some reason I'm hungry now...

On Nov 15, 2007 11:22 AM, Kent Johnson <kent37 at tds.net> wrote:

> Marc Tompkins wrote:
> > I didn't mean that exactly literally - for goodness' sake, this is a
> > high-level, object-oriented, interpreted language!  We're not writing
> > machine language here.
>
> Yes, I was thinking I should re-word my email, it was worded a bit too
> strongly...
>
> > What I did mean, and will probably still not express as clearly as I'd
> > like, is that when you create a "classic" class, lots of options remain
> > unresolved - slots vs. dict comes to mind - and Python needs to reserve
> > extra space accordingly.   About 134 extra bytes, it would appear.
>
> Still not sure I know what you mean. AFAIK old-style classes don't
> support slots, at least not user-defined slots. I do remember talk of
> new-style classes and properties allowing a much cleaner implementation
> of the class mechanisms, and it seems plausible that such generalization
> would lead to fewer options and streamlining of the class structure, but
> I don't know enough about the specifics to know if that is right.
>
> I poked around a bit in the source to see if I could figure it out but
> got tired of trying to sift through the header files...
>
> Kent
> >
> > On Nov 15, 2007 9:32 AM, Kent Johnson <kent37 at tds.net
> > <mailto:kent37 at tds.net>> wrote:
> >
> >     Marc Tompkins wrote:
> >
> >      > class B is a "new-style' class, meaning that it inherits from a
> base,
> >      > pre-existing class (in this case "object", which is as basic and
> >     generic
> >      > as you can get!).  class A has to start from nothing, which is
> why it
> >      > consumes more memory yet has less functionality.
> >
> >     I don't think it is really accurate to say that an old-style class
> >     "starts from nothing". It doesn't have an explicit base class but it
> >     does have all the old-style class machinery which is built in to
> Python.
> >
> >     I don't know why new-style classes are smaller though. My guess is
> that
> >     it is because there was an opportunity to streamline the class
> structure
> >     based on experience.
> >
> >     Kent
> >
> >
> >
> >
> > --
> > www.fsrtechnologies.com <http://www.fsrtechnologies.com>
>
>


-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071115/1596f702/attachment-0001.htm 

From alan.gauld at btinternet.com  Thu Nov 15 23:10:19 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 15 Nov 2007 22:10:19 -0000
Subject: [Tutor] class accessing another's updated property
References: <726588.86719.qm@web58814.mail.re1.yahoo.com>
Message-ID: <fhig4c$hu1$1@ger.gmane.org>

"ted b" <phpmoonlighter at yahoo.com> wrote

>I want class One to be able to access access class
> Two's value property after its been updated. Everytime
> I try (by running, say testTwo().value) I get the
> __init__ value.

Others have explained that you need to use instances
or class attributes.

I'll tackle the woder issue of synchronising
classes/instances. If you have a class (or classes) that
depend on another it is common to set up a publish/subscribe
mechanism so that the owner of the data notifies the subscribed
classesof changes. This can be a simple boolean flag to indicate
that something has changed or it can contain a list of the
published attributes that have changed(usually as a list of
name/value pairs or a dictionary)

This allows the subscribed objects to fetch the updated value
(or update their copy) whenever the master object changes value.
This is particularly common in the Model View architectures
used in GUIs where the model data may change and all
dependant views in the GUI need to be updated in synch.

To implement this requires that you create a publish/subscribe
method pair in the master class and then call publish every time
any of the public data changes. Client classes need to subscribe
to the master when created - ie in the init method. One common
way to do this with an established data class is via inheritance
and overloaded opertators, like so:

class Master:
    def __init__(self, v1,v2,v3):
       self.v1 = v1
       self.v2 = v2
       self.v3 = v3
    def m1(self): self.v1 = 42
    def m1(self): self.v2 = 66
    def m1(self): self.v3 = 27

class PublishedMaster(Master):
    def __init__(self,v1,v2,v3):
        Master.__init__(self,v1,v2,v3)
        self.subs = []
    def subscribe(self.obj):
        self.subs.append(obj)
    def publish(self):
        for obj in self.subs:
            obj.update(self)    # notify subscriber of change
    def m2(self):
        Master.m2(self)
        self.publish()
    def m3(self):
        Master.m3(self)
        self.publish()

class client:
    def __init__(self, master):
        self.myVal = master.v2
        master.subscribe(self)   # register interest in updates
    def update(self.publisher):
        self.v2 = publisher.v2

This allows the subscriber classes to be informed of any changes
to either v2 or v3. The client class is only interested in v2 so 
updates
its local copy when it receives the update message from the master.

Much more sophisticated regimes can be created but for simple
scenarios this suffices.Take care to avoid infinite loops caused by
calling a master method in client.update that results in the masdter
sending updates!

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 Nov 15 23:17:07 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 15 Nov 2007 22:17:07 -0000
Subject: [Tutor] How to import modules using the input() command
References: <356507.59532.qm@web32715.mail.mud.yahoo.com>
	<473C6C43.9030507@alum.rpi.edu>
Message-ID: <fhigh4$jcg$1@ger.gmane.org>

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

> modname = raw_input()
> exec "import " + modname
> 
> That can be a security risk, in that a use could 
> enter "time; import os; os.rmdir('some_valuable_directory')"

Even more risky is the fact that modules can contain executable 
code that is run when the module is imported. If someone wrote 
such a module they would only need to type the filename and 
the exec would result in the rogue code being executed. If the 
rogue code had the same name as a standard module it would 
be extremely hard to detect. All of which are good reasons 
for not doing this unless you intend to build an IDE or 
somesuch - and even then there are better solutions!

HTH,

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


From bhaaluu at gmail.com  Thu Nov 15 23:19:26 2007
From: bhaaluu at gmail.com (bhaaluu)
Date: Thu, 15 Nov 2007 17:19:26 -0500
Subject: [Tutor] width
In-Reply-To: <1d987df30711151340x1bd0efbeg8d51fafc16444483@mail.gmail.com>
References: <1d987df30711151340x1bd0efbeg8d51fafc16444483@mail.gmail.com>
Message-ID: <ea979d70711151419k67817387kbcc77980eba3a717@mail.gmail.com>

In pack() add:
expand=YES, fill=X,
expand=YES, fill=Y
or
expand=YES, fill=BOTH

Example:

from Tkinter import *
root = Tk()
Button(root, text='Red', bg="red", fg="white",
command=root.quit).pack(expand=YES,fill=X)
Button(root, text='Green', bg="green", fg="white",
command=root.quit).pack(expand=YES,fill=Y)
Button(root, text='Blue', bg="blue", fg="white",
command=root.quit).pack(expand=YES,fill=BOTH)
root.mainloop()


On Nov 15, 2007 4:40 PM, linda.s <samrobertsmith at gmail.com> wrote:
> I wonder why the widths are different for the three labels?
> Thanks,
> Linda
>
> from Tkinter import *
>
> root = Tk()
>
> w = Label(root, text="Red", bg="red", fg="white")
> w.pack()
> w = Label(root, text="Green", bg="green", fg="white")
> w.pack()
> w = Label(root, text="Blue", bg="blue", fg="white")
> w.pack()
>
> mainloop()
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
b h a a l u u at g m a i l dot c o m
http://www.geocities.com/ek.bhaaluu/index.html

From bhaaluu at gmail.com  Thu Nov 15 23:23:00 2007
From: bhaaluu at gmail.com (bhaaluu)
Date: Thu, 15 Nov 2007 17:23:00 -0500
Subject: [Tutor] width
In-Reply-To: <1d987df30711151340x1bd0efbeg8d51fafc16444483@mail.gmail.com>
References: <1d987df30711151340x1bd0efbeg8d51fafc16444483@mail.gmail.com>
Message-ID: <ea979d70711151423o51e35e74n3ea15acb41339a7b@mail.gmail.com>

As to the WHY it works like it does?

http://effbot.org/tkinterbook/pack.htm

On Nov 15, 2007 4:40 PM, linda.s <samrobertsmith at gmail.com> wrote:
> I wonder why the widths are different for the three labels?
> Thanks,
> Linda
>
> from Tkinter import *
>
> root = Tk()
>
> w = Label(root, text="Red", bg="red", fg="white")
> w.pack()
> w = Label(root, text="Green", bg="green", fg="white")
> w.pack()
> w = Label(root, text="Blue", bg="blue", fg="white")
> w.pack()
>
> mainloop()
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
b h a a l u u at g m a i l dot c o m
http://www.geocities.com/ek.bhaaluu/index.html

From keridee at jayco.net  Thu Nov 15 23:44:32 2007
From: keridee at jayco.net (Tiger12506)
Date: Thu, 15 Nov 2007 17:44:32 -0500
Subject: [Tutor] manipulating data
References: <fbf64d2b0711061154v4f6547bcx133c342f2d5aac27@mail.gmail.com><4731C327.6000704@tds.net>
	<47330268.1080304@bigfoot.com><fbf64d2b0711111702g7161a4bal2b3bc83bb6761d84@mail.gmail.com><fh94m5$1h6$1@ger.gmane.org>
	<fbf64d2b0711121143o12fff941p4028a10acdaaa5b6@mail.gmail.com>
Message-ID: <01c901c827d9$1aa708c0$6bfce004@jslaptop>

If you run this code

#
f = open('test1.mlc')
for line in f:
    print f.split()
#

You will see that about halfway through the file there is an empty list. I
assume that there was nothing on that line, in which case, there is no [0]
value.
In which case, you need to put in a try: except IndexError:  block like
this~

f = open('test1.mlc')
fields={}
for line in f:
    try:
        words = line.split()
        firstword = words[0]
    except IndexError: continue

    if firstword == 'Field':
        field = int(words[-1])
    elif firstword == 'Leaf':
        fields[field] = words[-1]


You will notice I made a few other changes. I changed it so line.split() is
assigned to a variable. That means I don't have to make the split() call
every time I want to check for a different word. The try except block just
fixes the problem you encountered. Also, I took out the last block-the else
block-because it is not necessary, and in fact will cause what you would
consider an error in the program. Calling f.next() will increment the line,
yes, but that is exactly for what the "for loop" is intended. The natural
conclusion of the for block is "finish the elif test and its block, then
execute code after it. Since there is no code after it indented to that
level, it automatically increments 'line' (line = f.next())

HTH,
JS


----- Original Message ----- 
From: "Bryan Fodness" <bryan.fodness at gmail.com>
To: "Alan Gauld" <alan.gauld at btinternet.com>
Cc: <tutor at python.org>
Sent: Monday, November 12, 2007 2:43 PM
Subject: Re: [Tutor] manipulating data


>I try this,
>
> f = open('TEST1.MLC')
>
> fields = {}
>
> for line in f:
>    if line.split()[0] == 'Field':
>        field = int(line.split()[-1])
>    elif line.split()[0] == 'Leaf':
>        fields[field] = line.split()[-1]
>    else:
>        line = f.next()
>
> and get,
>
> Traceback (most recent call last):
>  File "<pyshell#1>", line 1, in <module>
>    line.split()[0]
> IndexError: list index out of range
>
> I have attached my data file.
>


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


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


From alan.gauld at btinternet.com  Fri Nov 16 01:22:54 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 16 Nov 2007 00:22:54 -0000
Subject: [Tutor] class accessing another's updated property
References: <726588.86719.qm@web58814.mail.re1.yahoo.com>
	<fhig4c$hu1$1@ger.gmane.org>
Message-ID: <fhinsv$9nb$1@ger.gmane.org>

"Alan Gauld" <alan.gauld at btinternet.com> wrote 
> 
> class Master:
> 
> class PublishedMaster(Master):
> 
> class client:
> 
> This allows the subscriber classes to be informed of any changes

I should have pointed out that the code I posted was not tested
and should be treated as pseudo code - albeit very close to 
real code! 

Alan G.


From marc.tompkins at gmail.com  Fri Nov 16 01:59:45 2007
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Thu, 15 Nov 2007 16:59:45 -0800
Subject: [Tutor] Memory consumption question
In-Reply-To: <40af687b0711151342i31df6458w4645f7c918a72d78@mail.gmail.com>
References: <40af687b0711150903pe9e61fbx2f3925ff52d0388a@mail.gmail.com>
	<473C82AD.9000603@tds.net>
	<40af687b0711151103s19f7916eu12f35d39898ee325@mail.gmail.com>
	<473C9C7D.3020304@tds.net>
	<40af687b0711151342i31df6458w4645f7c918a72d78@mail.gmail.com>
Message-ID: <40af687b0711151659j37bc28c3kb2307578a7cfd404@mail.gmail.com>

And here's another reason to use new-style:  I forgot the sauerkraut!  Oh,
the horror!

On Nov 15, 2007 1:42 PM, Marc Tompkins <marc.tompkins at gmail.com> wrote:

> I thought of an analogy I like better than my sign-painting one: ordering
> a sandwich.
> Imagine: you're at the deli, and your waitron asks what you want.
> (Granted, this is a silly example.)
>   "Classic" order: "I'd like a sandwich with two slices of rye bread,
> Russian dressing, corned beef, and Swiss cheese.  Oh, and I'd like that
> grilled."
>   "New-style" order: "Reuben, please."
>
> Now, I speak not of the time and materials required to construct the
> above-mentioned tasty treat - in my analogy, Python is the long-suffering
> waitron, not the cook - but I gotta figure that the second option will take
> less space to write on the check.  Perhaps about 134 bytes' worth.
>
> For some reason I'm hungry now...
>
>
> On Nov 15, 2007 11:22 AM, Kent Johnson <kent37 at tds.net> wrote:
>
> > Marc Tompkins wrote:
> > > I didn't mean that exactly literally - for goodness' sake, this is a
> > > high-level, object-oriented, interpreted language!  We're not writing
> > > machine language here.
> >
> > Yes, I was thinking I should re-word my email, it was worded a bit too
> > strongly...
> >
> > > What I did mean, and will probably still not express as clearly as I'd
> > > like, is that when you create a "classic" class, lots of options
> > remain
> > > unresolved - slots vs. dict comes to mind - and Python needs to
> > reserve
> > > extra space accordingly.   About 134 extra bytes, it would appear.
> >
> > Still not sure I know what you mean. AFAIK old-style classes don't
> > support slots, at least not user-defined slots. I do remember talk of
> > new-style classes and properties allowing a much cleaner implementation
> > of the class mechanisms, and it seems plausible that such generalization
> >
> > would lead to fewer options and streamlining of the class structure, but
> > I don't know enough about the specifics to know if that is right.
> >
> > I poked around a bit in the source to see if I could figure it out but
> > got tired of trying to sift through the header files...
> >
> > Kent
> > >
> > > On Nov 15, 2007 9:32 AM, Kent Johnson <kent37 at tds.net
> > > <mailto:kent37 at tds.net>> wrote:
> > >
> > >     Marc Tompkins wrote:
> > >
> > >      > class B is a "new-style' class, meaning that it inherits from a
> > base,
> > >      > pre-existing class (in this case "object", which is as basic
> > and
> > >     generic
> > >      > as you can get!).  class A has to start from nothing, which is
> > why it
> > >      > consumes more memory yet has less functionality.
> > >
> > >     I don't think it is really accurate to say that an old-style class
> > >     "starts from nothing". It doesn't have an explicit base class but
> > it
> > >     does have all the old-style class machinery which is built in to
> > Python.
> > >
> > >     I don't know why new-style classes are smaller though. My guess is
> > that
> > >     it is because there was an opportunity to streamline the class
> > structure
> > >     based on experience.
> > >
> > >     Kent
> > >
> > >
> > >
> > >
> > > --
> > > www.fsrtechnologies.com < http://www.fsrtechnologies.com>
> >
> >
>
>
> --
> www.fsrtechnologies.com




-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071115/458a383e/attachment-0001.htm 

From brunson at brunson.com  Fri Nov 16 03:26:36 2007
From: brunson at brunson.com (Eric Brunson)
Date: Thu, 15 Nov 2007 19:26:36 -0700
Subject: [Tutor] Memory consumption question
In-Reply-To: <40af687b0711151659j37bc28c3kb2307578a7cfd404@mail.gmail.com>
References: <40af687b0711150903pe9e61fbx2f3925ff52d0388a@mail.gmail.com>	<473C82AD.9000603@tds.net>	<40af687b0711151103s19f7916eu12f35d39898ee325@mail.gmail.com>	<473C9C7D.3020304@tds.net>	<40af687b0711151342i31df6458w4645f7c918a72d78@mail.gmail.com>
	<40af687b0711151659j37bc28c3kb2307578a7cfd404@mail.gmail.com>
Message-ID: <473CFFDC.3030304@brunson.com>


I'm sorry, but a Reuben with no 'kraut is just a corned beef sandwich.  :-)

Marc Tompkins wrote:
> And here's another reason to use new-style:  I forgot the sauerkraut!  
> Oh, the horror!
>
> On Nov 15, 2007 1:42 PM, Marc Tompkins <marc.tompkins at gmail.com 
> <mailto:marc.tompkins at gmail.com>> wrote:
>
>     I thought of an analogy I like better than my sign-painting one:
>     ordering a sandwich. 
>     Imagine: you're at the deli, and your waitron asks what you want. 
>     (Granted, this is a silly example.)
>       "Classic" order: "I'd like a sandwich with two slices of rye
>     bread, Russian dressing, corned beef, and Swiss cheese.  Oh, and
>     I'd like that grilled." 
>       "New-style" order: "Reuben, please."
>
>     Now, I speak not of the time and materials required to construct
>     the above-mentioned tasty treat - in my analogy, Python is the
>     long-suffering waitron, not the cook - but I gotta figure that the
>     second option will take less space to write on the check.  Perhaps
>     about 134 bytes' worth.
>
>     For some reason I'm hungry now...
>
>
>     On Nov 15, 2007 11:22 AM, Kent Johnson <kent37 at tds.net
>     <mailto:kent37 at tds.net> > wrote:
>
>         Marc Tompkins wrote:
>         > I didn't mean that exactly literally - for goodness' sake,
>         this is a
>         > high-level, object-oriented, interpreted language!  We're
>         not writing
>         > machine language here.
>
>         Yes, I was thinking I should re-word my email, it was worded a
>         bit too
>         strongly...
>
>         > What I did mean, and will probably still not express as
>         clearly as I'd
>         > like, is that when you create a "classic" class, lots of
>         options remain
>         > unresolved - slots vs. dict comes to mind - and Python needs
>         to reserve
>         > extra space accordingly.   About 134 extra bytes, it would
>         appear.
>
>         Still not sure I know what you mean. AFAIK old-style classes
>         don't
>         support slots, at least not user-defined slots. I do remember
>         talk of
>         new-style classes and properties allowing a much cleaner
>         implementation
>         of the class mechanisms, and it seems plausible that such
>         generalization
>         would lead to fewer options and streamlining of the class
>         structure, but
>         I don't know enough about the specifics to know if that is right.
>
>         I poked around a bit in the source to see if I could figure it
>         out but
>         got tired of trying to sift through the header files...
>
>         Kent
>         >
>         > On Nov 15, 2007 9:32 AM, Kent Johnson <kent37 at tds.net
>         <mailto:kent37 at tds.net>
>         > <mailto:kent37 at tds.net <mailto:kent37 at tds.net>>> wrote:
>         >
>         >     Marc Tompkins wrote:
>         >
>         >      > class B is a "new-style' class, meaning that it
>         inherits from a base,
>         >      > pre-existing class (in this case "object", which is
>         as basic and
>         >     generic
>         >      > as you can get!).  class A has to start from nothing,
>         which is why it
>         >      > consumes more memory yet has less functionality.
>         >
>         >     I don't think it is really accurate to say that an
>         old-style class
>         >     "starts from nothing". It doesn't have an explicit base
>         class but it
>         >     does have all the old-style class machinery which is
>         built in to Python.
>         >
>         >     I don't know why new-style classes are smaller though.
>         My guess is that
>         >     it is because there was an opportunity to streamline the
>         class structure
>         >     based on experience.
>         >
>         >     Kent
>         >
>         >
>         >
>         >
>         > --
>         > www.fsrtechnologies.com <http://www.fsrtechnologies.com> <
>         http://www.fsrtechnologies.com>
>
>
>
>
>     -- 
>     www.fsrtechnologies.com <http://www.fsrtechnologies.com> 
>
>
>
>
> -- 
> www.fsrtechnologies.com <http://www.fsrtechnologies.com>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From kent37 at tds.net  Fri Nov 16 03:50:16 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 15 Nov 2007 21:50:16 -0500
Subject: [Tutor] Memory consumption question
In-Reply-To: <40af687b0711151342i31df6458w4645f7c918a72d78@mail.gmail.com>
References: <40af687b0711150903pe9e61fbx2f3925ff52d0388a@mail.gmail.com>	
	<473C82AD.9000603@tds.net>	
	<40af687b0711151103s19f7916eu12f35d39898ee325@mail.gmail.com>	
	<473C9C7D.3020304@tds.net>
	<40af687b0711151342i31df6458w4645f7c918a72d78@mail.gmail.com>
Message-ID: <473D0568.7080504@tds.net>

OK, the analogy is cute, but I really don't know what it means in 
Python. Can you give an example? What are the parts of an old-style 
class that have to be 'ordered' separately? How do you 'order' them 
concisely with a new-style class?

Thanks,
Kent

Marc Tompkins wrote:
> I thought of an analogy I like better than my sign-painting one: 
> ordering a sandwich. 
> Imagine: you're at the deli, and your waitron asks what you want.  
> (Granted, this is a silly example.)
>   "Classic" order: "I'd like a sandwich with two slices of rye bread, 
> Russian dressing, corned beef, and Swiss cheese.  Oh, and I'd like that 
> grilled." 
>   "New-style" order: "Reuben, please."
> 
> Now, I speak not of the time and materials required to construct the 
> above-mentioned tasty treat - in my analogy, Python is the 
> long-suffering waitron, not the cook - but I gotta figure that the 
> second option will take less space to write on the check.  Perhaps about 
> 134 bytes' worth.

From marc.tompkins at gmail.com  Fri Nov 16 04:24:28 2007
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Thu, 15 Nov 2007 19:24:28 -0800
Subject: [Tutor] Memory consumption question
In-Reply-To: <473D0568.7080504@tds.net>
References: <40af687b0711150903pe9e61fbx2f3925ff52d0388a@mail.gmail.com>
	<473C82AD.9000603@tds.net>
	<40af687b0711151103s19f7916eu12f35d39898ee325@mail.gmail.com>
	<473C9C7D.3020304@tds.net>
	<40af687b0711151342i31df6458w4645f7c918a72d78@mail.gmail.com>
	<473D0568.7080504@tds.net>
Message-ID: <40af687b0711151924q422cc0f6h5605a6939b26d244@mail.gmail.com>

Referring to the original post:

> >>> dir(B)
> ['__doc__', '__module__']
> >>> dir(B)
> ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__',
> '__hash__', '__init__', '__module__', '__new__', '__reduce__',
> '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__']
>
>

On Nov 15, 2007 6:50 PM, Kent Johnson <kent37 at tds.net> wrote:

> OK, the analogy is cute, but I really don't know what it means in
> Python. Can you give an example? What are the parts of an old-style
> class that have to be 'ordered' separately? How do you 'order' them
> concisely with a new-style class?
>
> Thanks,
> Kent
>
> Marc Tompkins wrote:
> > I thought of an analogy I like better than my sign-painting one:
> > ordering a sandwich.
> > Imagine: you're at the deli, and your waitron asks what you want.
> > (Granted, this is a silly example.)
> >   "Classic" order: "I'd like a sandwich with two slices of rye bread,
> > Russian dressing, corned beef, and Swiss cheese.  Oh, and I'd like that
> > grilled."
> >   "New-style" order: "Reuben, please."
> >
> > Now, I speak not of the time and materials required to construct the
> > above-mentioned tasty treat - in my analogy, Python is the
> > long-suffering waitron, not the cook - but I gotta figure that the
> > second option will take less space to write on the check.  Perhaps about
> > 134 bytes' worth.
>



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

From marc.tompkins at gmail.com  Fri Nov 16 04:26:07 2007
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Thu, 15 Nov 2007 19:26:07 -0800
Subject: [Tutor] Memory consumption question
In-Reply-To: <40af687b0711151924q422cc0f6h5605a6939b26d244@mail.gmail.com>
References: <40af687b0711150903pe9e61fbx2f3925ff52d0388a@mail.gmail.com>
	<473C82AD.9000603@tds.net>
	<40af687b0711151103s19f7916eu12f35d39898ee325@mail.gmail.com>
	<473C9C7D.3020304@tds.net>
	<40af687b0711151342i31df6458w4645f7c918a72d78@mail.gmail.com>
	<473D0568.7080504@tds.net>
	<40af687b0711151924q422cc0f6h5605a6939b26d244@mail.gmail.com>
Message-ID: <40af687b0711151926v68ef89b3ge064eedb44cea750@mail.gmail.com>

Sorry, sloppy cutting and pasting.  Should be:

Referring to the original post:
>
> > >>> dir(A)
> > ['__doc__', '__module__']
> > >>> dir(B)
> > ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__',
> > '__hash__', '__init__', '__module__', '__new__', '__reduce__',
> > '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__']
> >
> >
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071115/37d7c135/attachment.htm 

From phpmoonlighter at yahoo.com  Fri Nov 16 08:54:14 2007
From: phpmoonlighter at yahoo.com (ted b)
Date: Thu, 15 Nov 2007 23:54:14 -0800 (PST)
Subject: [Tutor] affecting all classes if one class is affected by an event
	- pygame
Message-ID: <37998.94842.qm@web58802.mail.re1.yahoo.com>

I am trying to figure out how to make a class instance
respond the same way as another class instance if the
other is affected by some event. I have been playing
around with inheritance, and have tried other stuff,
but i am somewhat of a newbie and I have been having
difficulty (but you guys, particularly Kent, have
really been helping me a lot :))))

For example, in the pygame code below, i have set it
up so that the boxes will stop if they are above the
barrier and hit it. Well, that's what i want to
happen, but if one of the boxes hits the barrier, the
other box keeps going. Is there a way i can have both
boxes stop if either of them hit the barrier. I was
hoping there was a way that i could have the info from
one class get passed to the other classes so i could
stop the other box (or stop all  or only some other
boxes if i add lots more). Should i make another
class? Another method? Globals?

Here's the code:

#/usr/bin/env python

import pygame

from pygame.locals import *

pygame.init()

class testBox1(pygame.sprite.Sprite):
   def __init__(self):
      pygame.sprite.Sprite.__init__(self)
      self.image=pygame.Surface((25,25))
      self.image.fill((255,0,0))
      self.rect=self.image.get_rect()
      self.rect.center = (30,90)

   def update(self):
      # check for user input and move left, right, up
or down
      keys = pygame.key.get_pressed()
      if keys[pygame.K_w]:
         self.rect.center = (self.rect.centerx,
self.rect.centery-4)
      if keys[pygame.K_s]:
         self.rect.center = (self.rect.centerx,
self.rect.centery+4)
      if keys[pygame.K_a]:
         self.rect.center = (self.rect.centerx-4,
self.rect.centery)
      if keys[pygame.K_d]:
         self.rect.center = (self.rect.centerx+4,
self.rect.centery)
      # see if the rect hit the barrier
      self.checkPos()

   def checkPos(self):
      # if box rect moves below barrier's rect, halt
box's position
      if ((self.rect.bottom > testBarrier().rect.top)
and (self.rect.top < testBarrier().rect.top)):
         if ((testBarrier().rect.right >
self.rect.right > testBarrier().rect.left) or
(testBarrier().rect.right > self.rect.left >
testBarrier().rect.left)):
            self.rect.bottom = testBarrier().rect.top
     
class testBox2(testBox1):
   def __init__(self):
      pygame.sprite.Sprite.__init__(self)
      self.image=pygame.Surface((25,25))
      self.image.fill((0,0,255))
      self.rect=self.image.get_rect()
      self.rect.center = (80,50)

class testBarrier(pygame.sprite.Sprite):
   def __init__(self):
      pygame.sprite.Sprite.__init__(self)
      self.image=pygame.Surface((30,4))
      self.image.fill((0,0,0))
      self.rect=self.image.get_rect()
      self.rect.center = (50,150)

def main():
   screen = pygame.display.set_mode((100,300))

   pygame.display.set_caption("testing")

   background=pygame.Surface(screen.get_size())
   background=background.convert()
   background.fill((255,255,255))
   screen.blit(background, (0,0))

   box1=testBox1()
   box2=testBox2()
   barrier=testBarrier()

   allSprites=pygame.sprite.Group(box1, box2, barrier)
   
   clock=pygame.time.Clock()
   keepGoing=True
   while keepGoing:
      clock.tick(30)
      for event in pygame.event.get():
         if event.type==pygame.QUIT:
            keepGoing=False

      allSprites.clear(screen, background)
      allSprites = pygame.sprite.OrderedUpdates
(barrier, box1, box2)
      allSprites.update()
      allSprites.draw(screen)
      
      pygame.display.flip()

if __name__ == "__main__":
   main()

Thanks for all your help!!! :)))))
-ted


      ____________________________________________________________________________________
Be a better sports nut!  Let your teams follow you 
with Yahoo Mobile. Try it now.  http://mobile.yahoo.com/sports;_ylt=At9_qDKvtAbMuh1G1SQtBI7ntAcJ

From kuiper at jpl.nasa.gov  Fri Nov 16 09:15:24 2007
From: kuiper at jpl.nasa.gov (kuiper at jpl.nasa.gov)
Date: Fri, 16 Nov 2007 00:15:24 -0800
Subject: [Tutor] widget value initialization
Message-ID: <20071116001524.egrnh3lmaskg4sss@webmail.jpl.nasa.gov>

Radiobuttons and entries in child windows do not display their initial  
state.  Try the attached example.  (Notice some attempted remedies  
commented out because they didn't work.)

If anyone can make this work I'd be very grateful.

Regards

Tom Kuiper
-------------- next part --------------
#!/usr/bin/python

# This is an extension of an example (first part) in An Introduction to
# Tkinter by Fred Lundh
# From http://www-acc.kek.jp/WWW-ACC-exp/KEKB/control/Activity/Python/TkIntro/introduction/button.htm
# See also http://www.pythonware.com/library/tkinter/introduction/x6969-patterns.htm

from Tkinter import *

master = Tk()

MODES = [
    ("Monochrome", "1"),
    ("Grayscale", "L"),
    ("True color", "RGB"),
    ("Color separation", "CMYK")
]

def make_buttons():
	global v
	f = Frame(master)
	f.pack()
	v = StringVar()
	v.set("L") # initialize

	for text, mode in MODES:
		b = Radiobutton(f, text=text,
               		        variable=v, value=mode)
		b.pack(anchor=W)
	make_radio()
	# child.mainloop()
	child.update_idletasks

def make_radio():
	global w
	global child
	child = Tk()
	w = StringVar()
	w.set("N") # initialize
	g = Frame(child)
	g.pack()

	y = Radiobutton(g, text="Yes", variable=w, value="Y")
	y.pack(side=LEFT)
	n = Radiobutton(g, text="No", variable=w, value="N")
	n.pack(side=LEFT)

make_buttons()
master.mainloop()


From kent37 at tds.net  Fri Nov 16 13:36:31 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 16 Nov 2007 07:36:31 -0500
Subject: [Tutor] affecting all classes if one class is affected by an
 event	- pygame
In-Reply-To: <37998.94842.qm@web58802.mail.re1.yahoo.com>
References: <37998.94842.qm@web58802.mail.re1.yahoo.com>
Message-ID: <473D8ECF.1020000@tds.net>

ted b wrote:
> I am trying to figure out how to make a class instance
> respond the same way as another class instance if the
> other is affected by some event. I have been playing
> around with inheritance, and have tried other stuff,
> but i am somewhat of a newbie and I have been having
> difficulty (but you guys, particularly Kent, have
> really been helping me a lot :))))
> 
> For example, in the pygame code below, i have set it
> up so that the boxes will stop if they are above the
> barrier and hit it. Well, that's what i want to
> happen, but if one of the boxes hits the barrier, the
> other box keeps going. Is there a way i can have both
> boxes stop if either of them hit the barrier. I was
> hoping there was a way that i could have the info from
> one class get passed to the other classes so i could
> stop the other box (or stop all  or only some other
> boxes if i add lots more). Should i make another
> class? Another method? Globals?

I don't understand what in the code below makes the box stop - does it 
just hit the barrier and stick there? And you want the other box to stop 
wherever it is at the time?

Here are some suggestions:
You only need one class for the boxes, the only difference is the 
initialization parameters; these can be passed in as parameters. For 
example,

class Box(pygame.sprite.Sprite):
    def __init__(self, color, center):
       pygame.sprite.Sprite.__init__(self)
       self.image=pygame.Surface((25,25))
       self.image.fill(color)
       self.rect=self.image.get_rect()
       self.rect.center = center

box1=Box((255,0,0), (30,90))
box2=Box((0,0,255), (80,50))

To stop all the boxes, maybe you want a Box class attribute which is a flag:

class Box(...):
   moving = True

Then in the Box methods you can refer to Box.moving.

HTH,
Kent

> 
> Here's the code:
> 
> #/usr/bin/env python
> 
> import pygame
> 
> from pygame.locals import *
> 
> pygame.init()
> 
> class testBox1(pygame.sprite.Sprite):
>    def __init__(self):
>       pygame.sprite.Sprite.__init__(self)
>       self.image=pygame.Surface((25,25))
>       self.image.fill((255,0,0))
>       self.rect=self.image.get_rect()
>       self.rect.center = (30,90)
> 
>    def update(self):
>       # check for user input and move left, right, up
> or down
>       keys = pygame.key.get_pressed()
>       if keys[pygame.K_w]:
>          self.rect.center = (self.rect.centerx,
> self.rect.centery-4)
>       if keys[pygame.K_s]:
>          self.rect.center = (self.rect.centerx,
> self.rect.centery+4)
>       if keys[pygame.K_a]:
>          self.rect.center = (self.rect.centerx-4,
> self.rect.centery)
>       if keys[pygame.K_d]:
>          self.rect.center = (self.rect.centerx+4,
> self.rect.centery)
>       # see if the rect hit the barrier
>       self.checkPos()
> 
>    def checkPos(self):
>       # if box rect moves below barrier's rect, halt
> box's position
>       if ((self.rect.bottom > testBarrier().rect.top)
> and (self.rect.top < testBarrier().rect.top)):
>          if ((testBarrier().rect.right >
> self.rect.right > testBarrier().rect.left) or
> (testBarrier().rect.right > self.rect.left >
> testBarrier().rect.left)):
>             self.rect.bottom = testBarrier().rect.top
>      
> class testBox2(testBox1):
>    def __init__(self):
>       pygame.sprite.Sprite.__init__(self)
>       self.image=pygame.Surface((25,25))
>       self.image.fill((0,0,255))
>       self.rect=self.image.get_rect()
>       self.rect.center = (80,50)
> 
> class testBarrier(pygame.sprite.Sprite):
>    def __init__(self):
>       pygame.sprite.Sprite.__init__(self)
>       self.image=pygame.Surface((30,4))
>       self.image.fill((0,0,0))
>       self.rect=self.image.get_rect()
>       self.rect.center = (50,150)
> 
> def main():
>    screen = pygame.display.set_mode((100,300))
> 
>    pygame.display.set_caption("testing")
> 
>    background=pygame.Surface(screen.get_size())
>    background=background.convert()
>    background.fill((255,255,255))
>    screen.blit(background, (0,0))
> 
>    box1=testBox1()
>    box2=testBox2()
>    barrier=testBarrier()
> 
>    allSprites=pygame.sprite.Group(box1, box2, barrier)
>    
>    clock=pygame.time.Clock()
>    keepGoing=True
>    while keepGoing:
>       clock.tick(30)
>       for event in pygame.event.get():
>          if event.type==pygame.QUIT:
>             keepGoing=False
> 
>       allSprites.clear(screen, background)
>       allSprites = pygame.sprite.OrderedUpdates
> (barrier, box1, box2)
>       allSprites.update()
>       allSprites.draw(screen)
>       
>       pygame.display.flip()
> 
> if __name__ == "__main__":
>    main()
> 
> Thanks for all your help!!! :)))))
> -ted
> 
> 
>       ____________________________________________________________________________________
> Be a better sports nut!  Let your teams follow you 
> with Yahoo Mobile. Try it now.  http://mobile.yahoo.com/sports;_ylt=At9_qDKvtAbMuh1G1SQtBI7ntAcJ
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


From lavendula6654 at yahoo.com  Fri Nov 16 17:17:26 2007
From: lavendula6654 at yahoo.com (Elaine)
Date: Fri, 16 Nov 2007 08:17:26 -0800 (PST)
Subject: [Tutor] Guest at Foothill College?
Message-ID: <791860.18633.qm@web31709.mail.mud.yahoo.com>

     Would you be able to come talk to beginning
Python students at Foothill College, Middlefield
campus in Palo Alto? The students are working on a
real world project and can really benefit from a guest
from industry who can critique their work and answer
questions about your career. 
      You would not have to prepare anything, just a
10 minute phone conversation with me will bring you up
to speed on their project and enable you to give the
students good feedback when you watch their
presentations. Then, you could just respond to their
questions about Python and your career. The whole
thing shouldn't take more than an hour.

Here are the dates you could choose from:

Wednesdays at Middlefield campus in Palo Alto
21 Nov, 6 pm    design/architecural review
28 Nov, 6 pm     code review
5 Dec, 6 pm       code review
12 Dec, 6 pm     code review

      Let me know as soon as possible if you are
interested, and don't hesitate to ask me for more
details. Thanks so much for considering this!
               -Elaine Haight
                 faculty, CTIS
                 haightElaine at foothill.edu


      ____________________________________________________________________________________
Never miss a thing.  Make Yahoo your home page. 
http://www.yahoo.com/r/hs

From marc.tompkins at gmail.com  Fri Nov 16 20:10:14 2007
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Fri, 16 Nov 2007 11:10:14 -0800
Subject: [Tutor] Read-ahead for large fixed-width binary files?
Message-ID: <40af687b0711161110y31f289aej7977fce7bb8cb945@mail.gmail.com>

I've been writing a lot of utility programs for my clients who are
users of a certain legacy database application - exporting, reporting,
pretty label printing, etc.  The database is normalized into 45 files,
each of which contains fixed-length records (ranging from 80 bytes to
1024).  A few of those files contain relatively few records, while
others - depending how long the users have worked with the application
- may contain millions of records; the transaction file is generally
the largest and consists of 256-byte records.

(Before anybody asks, yes!  I know that the best way to do this would
be to use the database engine that created the files.  Unfortunately,
that's not really an option.)
I am NOT writing back to the data file.

I seem to have two alternatives - read the file one record at a time
(which means I spend a ridiculous amount of time waiting for the
disk), or read the whole thing at once and process it in memory
(which, depending on the user's machine, will probably choke on a
250MB transaction file.)

My question is this: does anybody know of an equivalent to
"readlines(sizehint)" for non-delimited, binary files?  I've Googled
and Googled until I'm groggy, but I don't seem to find what I want.

Thanks!

-- 
www.fsrtechnologies.com

From marc.tompkins at gmail.com  Fri Nov 16 20:15:40 2007
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Fri, 16 Nov 2007 11:15:40 -0800
Subject: [Tutor] Read-ahead for large fixed-width binary files?
In-Reply-To: <40af687b0711161110y31f289aej7977fce7bb8cb945@mail.gmail.com>
References: <40af687b0711161110y31f289aej7977fce7bb8cb945@mail.gmail.com>
Message-ID: <40af687b0711161115r4556a040i829530ba8093b0c2@mail.gmail.com>

OK, I feel quite foolish... almost immediately after hitting 'send' I
realized I can implement this myself, using 'read(bigsize)' -
currently I'm using 'read(recordsize)'; I just need to add an extra
loop around my record reads.  Please disregard...

On Nov 16, 2007 11:10 AM, Marc Tompkins <marc.tompkins at gmail.com> wrote:
> I've been writing a lot of utility programs for my clients who are
> users of a certain legacy database application - exporting, reporting,
> pretty label printing, etc.  The database is normalized into 45 files,
> each of which contains fixed-length records (ranging from 80 bytes to
> 1024).  A few of those files contain relatively few records, while
> others - depending how long the users have worked with the application
> - may contain millions of records; the transaction file is generally
> the largest and consists of 256-byte records.
>
> (Before anybody asks, yes!  I know that the best way to do this would
> be to use the database engine that created the files.  Unfortunately,
> that's not really an option.)
> I am NOT writing back to the data file.
>
> I seem to have two alternatives - read the file one record at a time
> (which means I spend a ridiculous amount of time waiting for the
> disk), or read the whole thing at once and process it in memory
> (which, depending on the user's machine, will probably choke on a
> 250MB transaction file.)
>
> My question is this: does anybody know of an equivalent to
> "readlines(sizehint)" for non-delimited, binary files?  I've Googled
> and Googled until I'm groggy, but I don't seem to find what I want.
>
> Thanks!
>
> --
> www.fsrtechnologies.com
>



-- 
www.fsrtechnologies.com

From dave6502 at googlemail.com  Fri Nov 16 22:08:33 2007
From: dave6502 at googlemail.com (dave selby)
Date: Fri, 16 Nov 2007 21:08:33 +0000
Subject: [Tutor] Q1: Any way for script to intercept a HUP signal ?
Message-ID: <f52017b60711161308t1c4f0cd4h7260785616cc9176@mail.gmail.com>

Is there a way for a Python script to intercept a HUP signal sent to it ?

Cheers

Dave

-- 

Please avoid sending me Word or PowerPoint attachments.
See http://www.gnu.org/philosophy/no-word-attachments.html

From dave6502 at googlemail.com  Fri Nov 16 22:09:27 2007
From: dave6502 at googlemail.com (dave selby)
Date: Fri, 16 Nov 2007 21:09:27 +0000
Subject: [Tutor] Q2: logging not working as expected
Message-ID: <f52017b60711161309x195517c0k9cc9664328db52a9@mail.gmail.com>

I am trying to use the python logging module. At first glance it looks
pretty complicated but having Ggooled a lot I have come up with a
trial script of  ...

logging.config.fileConfig("logging.conf")
logger = logging.getLogger()
logger.critical("Test Message")

Where 'loggin.conf' contains ...

[loggers]
keys=root,hdk1,hkd2

[handlers]
keys=SysLog,hand02

[formatters]
keys=SysLog

[logger_root]
level=NOTSET
handlers=SysLog

[logger_hkd1]
level=DEBUG
propagate=1
qualname=hkd1
handlers=SysLog
channel=hkd1
parent=(root)

[logger_hkd2]
level=DEBUG
propagate=1
qualname=hkd2
handlers=hand02
channel=hkd2
parent=(root)

[handler_hand02]
class=FileHandler
level=DEBUG
formatter=SysLog
args=('python.log', 'w')

[handler_SysLog]
class=handlers.SysLogHandler
level=DEBUG
formatter=SysLog
args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)

[formatter_SysLog]
format=%(filename)s[%(process)d]: %(levelname)s: %(message)s

I was trying to get logging to report to Syslog, that failed so I
changed it to write to a file 'python.log' .  When I execute my test
script 'python.log' appears but contains no messages and no error
messages are generated.

Anybody any ideas as to what I am doing wrong ?

Cheers

Dave

-- 

Please avoid sending me Word or PowerPoint attachments.
See http://www.gnu.org/philosophy/no-word-attachments.html

From brunson at brunson.com  Fri Nov 16 22:15:11 2007
From: brunson at brunson.com (Eric Brunson)
Date: Fri, 16 Nov 2007 14:15:11 -0700
Subject: [Tutor] Q1: Any way for script to intercept a HUP signal ?
In-Reply-To: <f52017b60711161308t1c4f0cd4h7260785616cc9176@mail.gmail.com>
References: <f52017b60711161308t1c4f0cd4h7260785616cc9176@mail.gmail.com>
Message-ID: <473E085F.8040801@brunson.com>

dave selby wrote:
> Is there a way for a Python script to intercept a HUP signal sent to it ?
>
> Cheers
>
> Dave
>
>   
Yes, using a signal handler:

http://docs.python.org/lib/module-signal.html

Let us know if you need clarification on anything after you read the 
section.


From brunson at brunson.com  Fri Nov 16 22:23:07 2007
From: brunson at brunson.com (Eric Brunson)
Date: Fri, 16 Nov 2007 14:23:07 -0700
Subject: [Tutor] Q2: logging not working as expected
In-Reply-To: <f52017b60711161309x195517c0k9cc9664328db52a9@mail.gmail.com>
References: <f52017b60711161309x195517c0k9cc9664328db52a9@mail.gmail.com>
Message-ID: <473E0A3B.4010509@brunson.com>


I can't get the python 2.5.1 logging module to use your logging.conf, 
can you create a simpler example?

dave selby wrote:
> I am trying to use the python logging module. At first glance it looks
> pretty complicated but having Ggooled a lot I have come up with a
> trial script of  ...
>
> logging.config.fileConfig("logging.conf")
> logger = logging.getLogger()
> logger.critical("Test Message")
>
> Where 'loggin.conf' contains ...
>
> [loggers]
> keys=root,hdk1,hkd2
>
> [handlers]
> keys=SysLog,hand02
>
> [formatters]
> keys=SysLog
>
> [logger_root]
> level=NOTSET
> handlers=SysLog
>
> [logger_hkd1]
> level=DEBUG
> propagate=1
> qualname=hkd1
> handlers=SysLog
> channel=hkd1
> parent=(root)
>
> [logger_hkd2]
> level=DEBUG
> propagate=1
> qualname=hkd2
> handlers=hand02
> channel=hkd2
> parent=(root)
>
> [handler_hand02]
> class=FileHandler
> level=DEBUG
> formatter=SysLog
> args=('python.log', 'w')
>
> [handler_SysLog]
> class=handlers.SysLogHandler
> level=DEBUG
> formatter=SysLog
> args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
>
> [formatter_SysLog]
> format=%(filename)s[%(process)d]: %(levelname)s: %(message)s
>
> I was trying to get logging to report to Syslog, that failed so I
> changed it to write to a file 'python.log' .  When I execute my test
> script 'python.log' appears but contains no messages and no error
> messages are generated.
>
> Anybody any ideas as to what I am doing wrong ?
>
> Cheers
>
> Dave
>
>   


From kent37 at tds.net  Fri Nov 16 22:27:48 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 16 Nov 2007 16:27:48 -0500
Subject: [Tutor] Q2: logging not working as expected
In-Reply-To: <f52017b60711161309x195517c0k9cc9664328db52a9@mail.gmail.com>
References: <f52017b60711161309x195517c0k9cc9664328db52a9@mail.gmail.com>
Message-ID: <473E0B54.2000607@tds.net>

dave selby wrote:
> I was trying to get logging to report to Syslog, that failed so I
> changed it to write to a file 'python.log' .  When I execute my test
> script 'python.log' appears but contains no messages and no error
> messages are generated.
> 
> Anybody any ideas as to what I am doing wrong ?

The root logger is still logging only to Syslog. What if you make the 
root logger just output to hand02?

You might try cutting your config down to just the root logger and file 
handler, get that working, then expand.

Kent

From brunson at brunson.com  Fri Nov 16 22:33:00 2007
From: brunson at brunson.com (Eric Brunson)
Date: Fri, 16 Nov 2007 14:33:00 -0700
Subject: [Tutor] Q2: logging not working as expected
In-Reply-To: <473E0B54.2000607@tds.net>
References: <f52017b60711161309x195517c0k9cc9664328db52a9@mail.gmail.com>
	<473E0B54.2000607@tds.net>
Message-ID: <473E0C8C.2010409@brunson.com>

Kent Johnson wrote:
> dave selby wrote:
>   
>> I was trying to get logging to report to Syslog, that failed so I
>> changed it to write to a file 'python.log' .  When I execute my test
>> script 'python.log' appears but contains no messages and no error
>> messages are generated.
>>
>> Anybody any ideas as to what I am doing wrong ?
>>     
>
> The root logger is still logging only to Syslog. What if you make the 
> root logger just output to hand02?
>
> You might try cutting your config down to just the root logger and file 
> handler, get that working, then expand.
>   

Good advice, Kent.  When in doubt, simplify.

Sometimes I find the answer to my problems just trying to reduce it down 
to a simple test case to post to a forum like this.  :-)

e.

From titleistfour at gmail.com  Fri Nov 16 22:50:48 2007
From: titleistfour at gmail.com (jay)
Date: Fri, 16 Nov 2007 15:50:48 -0600
Subject: [Tutor] Q2: logging not working as expected
In-Reply-To: <f52017b60711161309x195517c0k9cc9664328db52a9@mail.gmail.com>
References: <f52017b60711161309x195517c0k9cc9664328db52a9@mail.gmail.com>
Message-ID: <7c25bb490711161350y20f141fcu64bd38230780bafb@mail.gmail.com>

Dave,

Fix your typo here

> [loggers]
> keys=root,hdk1,hkd2

Should be hkd1 I believe, otherwise the config file is rejected by the
logging module.

> args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)

LOG_USER is not a defined priority by default in syslog, unless it is
something you have custom defined.  I would suggest using one of the
LOCAL[1-6] levels instead.


> logging.config.fileConfig("logging.conf")
> logger = logging.getLogger('hkd1')
> logger.info('Test Messages')

Finally, call using the qualified name 'hkd1'.


It works for me after that...

Although I agree with others, simplification does wonders for debugging.

Jay


On Nov 16, 2007 3:09 PM, dave selby <dave6502 at googlemail.com> wrote:
> I am trying to use the python logging module. At first glance it looks
> pretty complicated but having Ggooled a lot I have come up with a
> trial script of  ...
>
> logging.config.fileConfig("logging.conf")
> logger = logging.getLogger()
> logger.critical("Test Message")
>
> Where 'loggin.conf' contains ...
>
> [loggers]
> keys=root,hdk1,hkd2
>
> [handlers]
> keys=SysLog,hand02
>
> [formatters]
> keys=SysLog
>
> [logger_root]
> level=NOTSET
> handlers=SysLog
>
> [logger_hkd1]
> level=DEBUG
> propagate=1
> qualname=hkd1
> handlers=SysLog
> channel=hkd1
> parent=(root)
>
> [logger_hkd2]
> level=DEBUG
> propagate=1
> qualname=hkd2
> handlers=hand02
> channel=hkd2
> parent=(root)
>
> [handler_hand02]
> class=FileHandler
> level=DEBUG
> formatter=SysLog
> args=('python.log', 'w')
>
> [handler_SysLog]
> class=handlers.SysLogHandler
> level=DEBUG
> formatter=SysLog
> args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
>
> [formatter_SysLog]
> format=%(filename)s[%(process)d]: %(levelname)s: %(message)s
>
> I was trying to get logging to report to Syslog, that failed so I
> changed it to write to a file 'python.log' .  When I execute my test
> script 'python.log' appears but contains no messages and no error
> messages are generated.
>
> Anybody any ideas as to what I am doing wrong ?
>
> Cheers
>
> Dave
>
> --
>
> Please avoid sending me Word or PowerPoint attachments.
> See http://www.gnu.org/philosophy/no-word-attachments.html
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From ricaraoz at gmail.com  Fri Nov 16 14:16:47 2007
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Fri, 16 Nov 2007 10:16:47 -0300
Subject: [Tutor] selecting elements from a list that do not meet
 selection criteria
In-Reply-To: <354807.46236.qm@web58806.mail.re1.yahoo.com>
References: <354807.46236.qm@web58806.mail.re1.yahoo.com>
Message-ID: <473D983F.5040704@bigfoot.com>

ted b wrote:
> Is there a way i can select all elements from a list
> that do not meet selection criteria. I want to be able
> to select elements that have values of, say, < 1 but
> only if at least one of the elements has a value of >
> 0.
> 
> What i mean is, for example, in the code below, if one
> of the elements of "list 'a'" has a value greater than
> 1, then i want to print all the other elements in the
> list (i.e., class One and class Three) and to do
> otherStuff associated with those classes. Right now,
> it prints those elements that *do* have values of > 0,
> (i.e. class Two). But in situations where all of the
> classes have values set to 0, then i don't want
> anything selected. 
> 
> I don't want to just use something like "if x.value()
> != 0" or "if x.value() < 1" since those would give
> results if all elements were less than 1, and i only
> want to select elements of the list that are less than
> 1 if at least one of the elements is > 1.
> 
> Here's the sample code:
> 
> class One:
>    def value(self):
>       return 0
>       
> class Two:
>    def value(self):
>       return 1
> 
> class Three:
>    def value(self):
>       return 0
> 
> a = [One(), Two(), Three()]
> 
> for x in a:
>    if x.value() > 0:
>       print x
>       x.otherStuff()
> 
> Thanks in advance!!! :)))
> 



>>> doit = [1,2,0,-1,-3,-5,-7]
>>> dont = [0,-1,-3,-5,-7,-9,-11]
>>> [i for i in dont if max(dont) > 0 and i < 1]
[]
>>> [i for i in doit if max(doit) > 0 and i < 1]
[0, -1, -3, -5, -7]


HTH






From marc.tompkins at gmail.com  Fri Nov 16 23:49:05 2007
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Fri, 16 Nov 2007 14:49:05 -0800
Subject: [Tutor] affecting all classes if one class is affected by an
	event - pygame
Message-ID: <40af687b0711161449l316edf0ft1a27bf17a7fd0c4@mail.gmail.com>

Thus spake ted b:

I am trying to figure out how to make a class instance respond the same way
> as another class instance if the other is affected by some event. I have
> been playing around with inheritance, and have tried other stuff, but i am
> somewhat of a newbie and I have been having difficulty (but you guys,
> particularly Kent, have really been helping me a lot :))))
>
> For example, in the pygame code below, i have set it up so that the boxes
> will stop if they are above the barrier and hit it. Well, that's what i want
> to happen, but if one of the boxes hits the barrier, the other box keeps
> going. Is there a way i can have both boxes stop if either of them hit the
> barrier. I was hoping there was a way that i could have the info from one
> class get passed to the other classes so i could stop the other box (or stop
> all  or only some other boxes if i add lots more). Should i make another
> class? Another method? Globals?
>

You need to have some way for information to be passed around between
objects, or communicated to them by some central authority (which is much,
much simpler to implement.)  You're already collecting your objects into
"allSprites"; go ahead and use that.

This needs tuning, but off the top of my head I'd say:

1) add a bool attribute (let's call it "collided") to your sprites; in
 __init__ for each object add:
  self.collided = False

2) in your checkPos method, if there was a collision, set self.collided =
True
  Also, don't do the actual reversal / stopping here - add another method to
do it, like so:
def oopsie(self):
    pass # replace this with whatever you want to have happen

3) put this somewhere in your "while KeepGoing:" loop:
collision - False
for sprite in AllSprites:  # run through the list of sprites once to check
   if sprite.collided:
      collision = True
      sprite.collided = False # reset this sprite's flag for next time
if collision:  # if there was a collision,
    for sprite in AllSprites:  # then run through the list of sprites again
and update them
       sprite.oopsie()

I agree with Kent - don't derive Box2 from Box1; use parameters to
initialize them.

I've never looked at pygame - some of this might already be built-in, but
this is how I'd go about it.

Enjoy!
-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071116/6c85415a/attachment.htm 

From keridee at jayco.net  Fri Nov 16 23:56:35 2007
From: keridee at jayco.net (Tiger12506)
Date: Fri, 16 Nov 2007 17:56:35 -0500
Subject: [Tutor] Memory consumption question
References: <40af687b0711150903pe9e61fbx2f3925ff52d0388a@mail.gmail.com>	<473C82AD.9000603@tds.net>	<40af687b0711151103s19f7916eu12f35d39898ee325@mail.gmail.com>	<473C9C7D.3020304@tds.net><40af687b0711151342i31df6458w4645f7c918a72d78@mail.gmail.com>
	<473D0568.7080504@tds.net>
Message-ID: <000801c828a3$f51985d0$8cfce004@jslaptop>

> OK, the analogy is cute, but I really don't know what it means in
> Python. Can you give an example? What are the parts of an old-style
> class that have to be 'ordered' separately? How do you 'order' them
> concisely with a new-style class?
>
> Thanks,
> Kent

He is setting up the analogy so that python is the waiter (or waitress)
taking the order.
A "Reuben" in this case is a new-style class, whereas the whole list of
sandwich components
is also a reuben but expressed in old style class language. So, basically,
he's saying that new
style classes have more initial components but take up less room than old
style classes because the
waitress has less to write on her notepad.

As for what has to be ordered seperately, he is treating the concept of a
class abstractly as a
sandwich. So he's saying that python has to "write less on the order pad" in
order to create a
new-style class because it's been restructured like that, whereas python
writes all the stuff down,
even for an empty class. Whether that's actually true or not, i do not know.
I personally cannot imagine
that a simple restructuring of classes can make that drastic a change.

Here's the only way I can imagine it - in C++. C++ comes with virtual
methods, i.e. methods of a base
class that can function properly if the child does not provide that method
in its definition. So I presume
that he is thinking along the lines of old-style classes are C-structured
based, whereas new-style classes
are C++ based (even if they're not written in C++) with virtual methods -
where you only need one copy
of the methods in memory for all new-style classes.

Maybe I'm way out in left field. I do not know. That is one explanation that
I have provided myself so that
I feel I have an understanding. Interpret it as you will.

JS


From alan.gauld at btinternet.com  Sat Nov 17 01:36:27 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 17 Nov 2007 00:36:27 -0000
Subject: [Tutor] Read-ahead for large fixed-width binary files?
References: <40af687b0711161110y31f289aej7977fce7bb8cb945@mail.gmail.com>
	<40af687b0711161115r4556a040i829530ba8093b0c2@mail.gmail.com>
Message-ID: <fhld2d$9db$1@ger.gmane.org>


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

> realized I can implement this myself, using 'read(bigsize)' -
> currently I'm using 'read(recordsize)'; I just need to add an extra
> loop around my record reads.  Please disregard...

If you just want to navigate to a specific record then it might be
easier to use seek(), that will save you having to read all the 
previous records into memory.

HTH,


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


From python at mrfab.info  Sat Nov 17 07:01:15 2007
From: python at mrfab.info (Michael)
Date: Sat, 17 Nov 2007 15:01:15 +0900
Subject: [Tutor] repeat
Message-ID: <473E83AB.8020209@mrfab.info>

Hi All

This has probably been asked before but can I get some clarification on 
why Python does not have a repeat...until statement, and does that mean 
repeat...until is bad practice? I was trying to get Python on the 
standard langauge list for my state secondary school system but they say 
a langauge must have a test last structure in it to be considered.

Thanks

Michael

From pydev at rscorp.ab.ca  Sat Nov 17 09:01:09 2007
From: pydev at rscorp.ab.ca (Scott SA)
Date: Sat, 17 Nov 2007 01:01:09 -0700
Subject: [Tutor] repeat
In-Reply-To: <473E83AB.8020209@mrfab.info>
Message-ID: <r02010500-1049-425F9D7E94E311DC87F4001124DEBE0E@[192.168.69.99]>

On 11/17/07, Michael (python at mrfab.info) wrote:

>This has probably been asked before but can I get some clarification on 
>why Python does not have a repeat...until statement, and does that mean 
>repeat...until is bad practice? I was trying to get Python on the 
>standard langauge list for my state secondary school system but they say 
>a langauge must have a test last structure in it to be considered.

While you may feel your assertion to be true, it will persist until discovered  false... 

    <http://docs.python.org/ref/while.html>

... to date has satisfied my needs for the task. 8^)


Like many things in Python there are alternates, even to this (I expect to be learning more of them myself for a good long time 8^)

More examples and detail can be found at:
    <http://www.diveintopython.org/>
    <http://www.pasteur.fr/formation/infobio/python/ch10s03.html>
    <http://www.freenetpages.co.uk/hp/alan.gauld/tutloops.htm>


Simply put:
    
    while [test]:
        do something

 or
    
    while True:
        do something
        if [test]:
            break

    x = 0
    
    while x < 100:
        x += 1

    print x
    100

Still, the links can elaborate more than I can.

HTH

Scott

From alan.gauld at btinternet.com  Sat Nov 17 09:41:38 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 17 Nov 2007 08:41:38 -0000
Subject: [Tutor] repeat
References: <473E83AB.8020209@mrfab.info>
Message-ID: <fhm9g4$lt$1@ger.gmane.org>

"Michael" <python at mrfab.info> wrote

> This has probably been asked before but can I get some clarification 
> on
> why Python does not have a repeat...until statement,

Because Guido didn't put one in

repeat/until is never needed it is only ever a nice to have.
Indeed some languages don't even have a for loop for the same
reason (Oberon being an example). Some don't even
have any explicit loops since recursion can be used
instead - some Lisp dialects for example.

The important concept here is looping not the syntax
of the loop structure. However in Python the space
sensitive nature of the language does make a do/while
style loop a little harder to implement without breaking
good indentation practice. For example:

repeat:
     # code here
     # more code
     until condition

Now the until is visually part of the block - not nice!
(And if your school board don't understand that then
they have much bigger problems to worry about than
the syntax of loops!)

Whereas

repeat:
     # code
     # code
until condition

Is better structure but completely inconsistent with
every other Python construction (aside from try/except?)

You could of course introduce block markers to define
the block in the manner of Tcl or ruby etc but that too
would be completely inconsistent with Python style.

So instead we have the common Python idiom of

while True
    # code
    # code
    if condition: break

> repeat...until is bad practice?

No, just a variation on a theme that Python does not support
directly. There are plenty other loop structures that Python
(and other languages) does not support, for example ADAs
loop with exit:

loop:
   # code
   # code
   exit when condition
   # code
   # code
end loop

But again that can be modelled using while/break

> a langauge must have a test last structure in it to be considered.

That's a bizarre requirement that rules out many significant
languages from which important lessons can be learnt.

As a matter of interest, how would they view COBOL which
has many more loop constructs than Python but they are all
done via a single command(PERFORM) which requires the
body of the loop to be a list of functions (aka paragraphs
in COBOL).
eg

FOR loop:
PERFORM paragraph val TIMES
PERFORM paragraph VARYING variable FROM val BY val UNTIL condition.

WHILE loop
PERFORM paragraph IF condition

REPEAT
PERFORM paragraph until condition

We can also modify these case to use
WITH TEST BEFORE or WITH TEST AFTER
clauses. All very powerful but very different syntactically from
Java/Pascal/VB etc.

Also, do they have any requirements on languages to support
functional programming constructs or anonymous functions/blocks?
All very important concepts.

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



From dave6502 at googlemail.com  Sat Nov 17 12:43:53 2007
From: dave6502 at googlemail.com (dave selby)
Date: Sat, 17 Nov 2007 11:43:53 +0000
Subject: [Tutor] More logging probs ...
Message-ID: <f52017b60711170343md8b2d42j289f66dd66a5b98c@mail.gmail.com>

Im having a bad day. The logging module refused to send anything to
syslog no matter what I did, so discovering the syslog module &
thought, for what I need I will write a simple class to do the job.

 class kmotion_logger:

    def __init__(self, ident, min_priority):
        # min_priority must be one of ...
        # EMERG, ALERT, CRIT, ERR, WARNING, NOTICE, INFO, DEBUG

        self.case = {'EMERG': syslog.LOG_EMERG,
                            'ALERT': syslog.LOG_ALERT,
                            'CRIT': syslog.LOG_CRIT,
                            'ERR': syslog.LOG_ERR,
                            'WARNING': syslog.LOG_WARNING,
                            'NOTICE': syslog.LOG_NOTICE,
                            'INFO': syslog.LOG_INFO,
                            'DEBUG': syslog.LOG_DEBUG}

        self.ident = ident
        print 'log up to & inclusive of ... ', self.case[min_priority]
        syslog.setlogmask(syslog.LOG_UPTO(self.case[min_priority]))

    def log(self, msg, priority):
        print 'sending message at level ...',  self.case[priority]
        syslog.openlog(self.ident , syslog.LOG_PID,
(self.case[priority] | syslog.LOG_USER))
        syslog.syslog(msg)
        syslog.closelog()

And call it with ...

import kmotion_logger
# EMERG, ALERT, CRIT, ERR, WARNING, NOTICE, INFO, DEBUG
logger = kmotion_logger.kmotion_logger("kmotion", "DEBUG")
logger.log("TESTING", "ALERT")

And it worked as I wanted, it logs to syslog (cheers, jumps for joy) :)

Then I noticed several inconsistencys, the following also works AOK ...

import kmotion_logger
# EMERG, ALERT, CRIT, ERR, WARNING, NOTICE, INFO, DEBUG
logger = kmotion_logger.kmotion_logger("kmotion", "INFO")
logger.log("TESTING", "ALERT")

But the next one fails to log ...

import kmotion_logger
# EMERG, ALERT, CRIT, ERR, WARNING, NOTICE, INFO, DEBUG
logger = kmotion_logger.kmotion_logger("kmotion", "NOTICE")
logger.log("TESTING", "ALERT")
ALERT is above NOTICE & should log .... I am suspicious of
'(self.case[priority] | syslog.LOG_USER)' although it looks right and
have tried LOG_LOCAL6 etc but still no joy

I have even tried explaining it to my cat, no joy

Any ideas anyone ?

Cheers

A very log frustrated programmer

Dave




-- 

Please avoid sending me Word or PowerPoint attachments.
See http://www.gnu.org/philosophy/no-word-attachments.html

From kent37 at tds.net  Sat Nov 17 13:35:27 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 17 Nov 2007 07:35:27 -0500
Subject: [Tutor] More logging probs ...
In-Reply-To: <f52017b60711170343md8b2d42j289f66dd66a5b98c@mail.gmail.com>
References: <f52017b60711170343md8b2d42j289f66dd66a5b98c@mail.gmail.com>
Message-ID: <473EE00F.50404@tds.net>

dave selby wrote:
> Im having a bad day. The logging module refused to send anything to
> syslog no matter what I did, so discovering the syslog module &
> thought, for what I need I will write a simple class to do the job.
> 
>  class kmotion_logger:
> 
>     def __init__(self, ident, min_priority):
>         # min_priority must be one of ...
>         # EMERG, ALERT, CRIT, ERR, WARNING, NOTICE, INFO, DEBUG
> 
>         self.case = {'EMERG': syslog.LOG_EMERG,
>                             'ALERT': syslog.LOG_ALERT,
>                             'CRIT': syslog.LOG_CRIT,
>                             'ERR': syslog.LOG_ERR,
>                             'WARNING': syslog.LOG_WARNING,
>                             'NOTICE': syslog.LOG_NOTICE,
>                             'INFO': syslog.LOG_INFO,
>                             'DEBUG': syslog.LOG_DEBUG}
> 
>         self.ident = ident
>         print 'log up to & inclusive of ... ', self.case[min_priority]
>         syslog.setlogmask(syslog.LOG_UPTO(self.case[min_priority]))
> 
>     def log(self, msg, priority):
>         print 'sending message at level ...',  self.case[priority]
>         syslog.openlog(self.ident , syslog.LOG_PID,
> (self.case[priority] | syslog.LOG_USER))

| is a bit-wise or, not a logical or.

Logical or is not correct here anyway because self.case[priority] will 
raise KeyError for an unknown priority. Try
   self.case.get(priority, syslog.LOG_USER)
if you want to provide a default value for unknown keys.

Kent

>         syslog.syslog(msg)
>         syslog.closelog()
> 
> And call it with ...
> 
> import kmotion_logger
> # EMERG, ALERT, CRIT, ERR, WARNING, NOTICE, INFO, DEBUG
> logger = kmotion_logger.kmotion_logger("kmotion", "DEBUG")
> logger.log("TESTING", "ALERT")
> 
> And it worked as I wanted, it logs to syslog (cheers, jumps for joy) :)
> 
> Then I noticed several inconsistencys, the following also works AOK ...
> 
> import kmotion_logger
> # EMERG, ALERT, CRIT, ERR, WARNING, NOTICE, INFO, DEBUG
> logger = kmotion_logger.kmotion_logger("kmotion", "INFO")
> logger.log("TESTING", "ALERT")
> 
> But the next one fails to log ...
> 
> import kmotion_logger
> # EMERG, ALERT, CRIT, ERR, WARNING, NOTICE, INFO, DEBUG
> logger = kmotion_logger.kmotion_logger("kmotion", "NOTICE")
> logger.log("TESTING", "ALERT")
> ALERT is above NOTICE & should log .... I am suspicious of
> '(self.case[priority] | syslog.LOG_USER)' although it looks right and
> have tried LOG_LOCAL6 etc but still no joy
> 
> I have even tried explaining it to my cat, no joy
> 
> Any ideas anyone ?
> 
> Cheers
> 
> A very log frustrated programmer
> 
> Dave
> 
> 
> 
> 


From bgailer at alum.rpi.edu  Sat Nov 17 14:03:45 2007
From: bgailer at alum.rpi.edu (bob gailer)
Date: Sat, 17 Nov 2007 08:03:45 -0500
Subject: [Tutor] repeat
In-Reply-To: <473E83AB.8020209@mrfab.info>
References: <473E83AB.8020209@mrfab.info>
Message-ID: <473EE6B1.8060807@alum.rpi.edu>

Michael wrote:
> Hi All
>
> This has probably been asked before but can I get some clarification on 
> why Python does not have a repeat...until statement, and does that mean 
> repeat...until is bad practice? I was trying to get Python on the 
> standard langauge list for my state secondary school system but they say 
> a langauge must have a test last structure in it to be considered.
>   
That rules out FORTRAN!

And I would point out (as one of us already did):

while True:
  blahblah
  if condition: break

Is a test-last structure.

Of course some purists will object to "break" since it is a "goto in 
disguise".

From dave6502 at googlemail.com  Sat Nov 17 14:07:34 2007
From: dave6502 at googlemail.com (dave selby)
Date: Sat, 17 Nov 2007 13:07:34 +0000
Subject: [Tutor] More logging probs ...
In-Reply-To: <f52017b60711170343md8b2d42j289f66dd66a5b98c@mail.gmail.com>
References: <f52017b60711170343md8b2d42j289f66dd66a5b98c@mail.gmail.com>
Message-ID: <f52017b60711170507n2ff3b9ddha17c4f7f3babc49b@mail.gmail.com>

OK so to condense the problem the following works at LOG_INFO default
priority ...

    def log(self, msg, priority):
        syslog.openlog(self.ident , syslog.LOG_PID)
        syslog.syslog('testing message')
        syslog.closelog()

But as soon as I try to set a priority API syslog docs, it fails to log ...

    def log(self, msg, priority):
        syslog.openlog(self.ident , syslog.LOG_PID)
        syslog.syslog((syslog.LOG_ALERT | syslog.LOG_USER), 'testing message')
        syslog.closelog()

PS tried LOG_LOCAL6 etc, same result.

Trying to change the priority in openlog() logs but does not appear to
change the priority since syslog.setlogmask() indicate it is stuck at
LOG_INFO

    def log(self, msg, priority):
        syslog.openlog(self.ident , syslog.LOG_PID, (syslog.LOG_ALERT
| syslog.LOG_LOCAL6))
        syslog.syslog('testing message')
        syslog.closelog()

Still stuck

Dave

From goldwamh at slu.edu  Sat Nov 17 16:20:37 2007
From: goldwamh at slu.edu (Michael H. Goldwasser)
Date: Sat, 17 Nov 2007 09:20:37 -0600
Subject: [Tutor]  repeat
In-Reply-To: <473E83AB.8020209@mrfab.info>
References: <473E83AB.8020209@mrfab.info>
Message-ID: <18239.1733.236390.796165@euclid.slu.edu>


On Saturday November 17, 2007, Michael wrote: 

>    Hi All
>    
>    This has probably been asked before but can I get some clarification on 
>    why Python does not have a repeat...until statement, and does that mean 
>    repeat...until is bad practice? I was trying to get Python on the 
>    standard langauge list for my state secondary school system but they say 
>    a langauge must have a test last structure in it to be considered.


That is quite an arbitrary rule for a state to use when adopting a
programming language.  In any event, if they are also uncomfortable
with the while(True)/break combination that has been suggested by
others, you can alternatively mimic the repeat/until by using a
well-named boolean variable, as follows.


repeating = True
while repeating:

    # ...


    if (exitCondition):
        repeating = False



or in a negated form (if that reads better), as


done = False
while not done:

    # ...

    if (exitCondition):
        done = True



Perhaps these kinds of examples might help ease their concerns.

With regard,
Michael



From dineshbvadhia at hotmail.com  Sat Nov 17 18:14:10 2007
From: dineshbvadhia at hotmail.com (Dinesh B Vadhia)
Date: Sat, 17 Nov 2007 09:14:10 -0800
Subject: [Tutor] Web programming
Message-ID: <BAY109-DAV48A3CD9BFEB668C095304A37C0@phx.gbl>

Hi!  I want to create (for testing purposes) a straightforward web application consisting of a client that makes simple queries to a backend which returns data from a database (initially pysqlite3).  That's it - really!   I don't need a professional web server (eg. Apache) per se.

Are the Python urlparse, urllib, urllib2, httplib, BaseHTTPServer, SimpleHTTPServer etc. modules sufficient for the task.  The number of queries per second will initially be low, in the 10's/second.

Dinesh



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

From scott at rscorp.ab.ca  Sat Nov 17 18:51:02 2007
From: scott at rscorp.ab.ca (Scott Sandeman-Allen)
Date: Sat, 17 Nov 2007 10:51:02 -0700
Subject: [Tutor] repeat
In-Reply-To: <473EE6B1.8060807@alum.rpi.edu>
Message-ID: <r02010500-1049-AA4B1B66953511DC87F4001124DEBE0E@[192.168.69.99]>

On 11/17/07, bob gailer (bgailer at alum.rpi.edu) wrote:

>Michael wrote:
>> Hi All
>>
>> This has probably been asked before but can I get some clarification on 
>> why Python does not have a repeat...until statement, and does that mean 
>> repeat...until is bad practice? I was trying to get Python on the 
>> standard langauge list for my state secondary school system but they say 
>> a langauge must have a test last structure in it to be considered.
>>   
>That rules out FORTRAN!
>
>And I would point out (as one of us already did):
>
>while True:
>  blahblah
>  if condition: break
>
>Is a test-last structure.

If one considers the "repeat" statement to have an _implied_ truthfulness there is even less difference _except_ for the nesting syntax which IMO is arbitrary and therefore moot.

    repeat [while true]
        perform task
    until [proven false by] condition

or  
    do [while true]
        blah blah blah
        
VS the explicitly stated

    >while True:
    >  blahblah
    >  if condition: break
    
Python is a very rich language and provides a great deal of flexibility, even with this single flow-control statement i.e.
    
    while [state | condition] maintains truthfulness:
        perform task [intrinsically modify state | argument(s)]
        [test argument(s) & exit | modify state]

Python is a modern and full-featured language. The test of its sutability should be based upon its clarity and capability rather than an arbitrary syntactical (sp?) construct.

Can the language clearly perform looping constructs: yes, in many ways.
Does the language have a reasonable level of flow-control: yes.
...

I could see a language like PHP being excluded because of its dependence upon environment. But if I were to teach a language to a student, Python would probably be one of my first choices as opposed to C/Java/Perl/VB/AppleScript and such.

Ultimately, what is the objective of the programming programme? Is it to teach students to consider application development at a high-level or incumber them with unnecessary syntax at a low level i.e. 
    
    def some_variable as some_type
    
    test some_variable then
        ...
    end test

IMO, the def, then and end are unnecessary cluter; totally superfluious!

Personally, I would rather my students (if I had any) be less incumbered with "verbosity" and more focussed on planning and understanding. Letting the language work for them rather than enslaving them.

"When the only tool you have is a hammer, all of your problems start looking like nails" is a favorite quote of mine (unknown origin). Python is one heck of a hammer to have in the bag.

Scott

PS. Interesting thing about Python: in minutes a student could be working with the language i.e. 'Hello world', and understand it. Within days they can be writing functional code with reasonable complexity. The kicker is, the language is deep enough that new approaches can still appear many months and even years of regular use. Not only is it tasty, it's nutritious too ;^)

From varsha.purohit at gmail.com  Sat Nov 17 21:44:41 2007
From: varsha.purohit at gmail.com (Varsha Purohit)
Date: Sat, 17 Nov 2007 12:44:41 -0800
Subject: [Tutor] [wxPython-users] How to save file name of file opened from
	wx.FileDialog ?
Message-ID: <c2157c790711171244q2074ceaal99caf59ec697b6ed@mail.gmail.com>

Hello Everyone,
        In my application i need to select a file using open dialog
box. And then i dont need to open the file. I just need to display the
name of the selected file in a text control. And then open the file in
later part of the program.  But i am not able to get the file name and
display it in the text control. Here is the sample code.

import wx
import os

Fname = '' #Global variable to hold the file name.
class ScrolledWindow(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(350, 300))
        panel = wx.Panel(self, -1)
        txt1 = wx.TextCtrl(panel, -1, pos=(30, 100), size=(150, 20))
        button11 = wx.Button(panel, -1, "Open", pos=(200,100))
        self.Bind(wx.EVT_BUTTON, self.OnOpen, button11)
        txt1.write(Fname)

        self.Centre()
        self.Show()

    def OnOpen(self,event):
        self.dirname = ''
        dlg = wx.FileDialog(self, "Choose a file", self.dirname,"",
"*.*", wx.OPEN)
        if dlg.ShowModal()==wx.ID_OK:
            self.filename=dlg.GetFilename()
            Fname = self.filename
            self.dirname=dlg.GetDirectory()
        dlg.Destroy()

app = wx.App()
ScrolledWindow(None, -1, 'Aliens')
app.MainLoop()


Any help is appreciated....

thanks,
-- 
Varsha Purohit,
Graduate Student

From alan.gauld at btinternet.com  Sun Nov 18 00:32:01 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 17 Nov 2007 23:32:01 -0000
Subject: [Tutor] Web programming
References: <BAY109-DAV48A3CD9BFEB668C095304A37C0@phx.gbl>
Message-ID: <fhntlj$emp$1@ger.gmane.org>

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

> web application consisting of a client that makes simple queries
> to a backend which returns data from a database (initially 
> pysqlite3).

When you say a client do you mean a robotic browser?
Or do you mean the web application will be a client/server 
architecture?

> Are the Python urlparse, urllib, urllib2,

These will build a robotic client of that's what you need.

> httplib,

You probably won't need this if it's just a simple app.

> BaseHTTPServer, SimpleHTTPServer etc.

These are OK to start with but you will also need the
cgi module to create the server code

> The number of queries per second will initially be low, in the 
> 10's/second.

tens per second is quite high for a simple CGI app
accessing a database. Up to 10 per second should be fine but
if you get up to 20,30 or more I'd consider using a real web
server (Apache or a simpler one like Xitami) and you may even
want to investigate fastCGI or some of the simpler web
frameworks like CherryPy.

Finally watch out for locking issues around the database
if your transactions are writing as well as reading data.

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  Sun Nov 18 00:35:51 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 17 Nov 2007 23:35:51 -0000
Subject: [Tutor] [wxPython-users] How to save file name of file opened
	fromwx.FileDialog ?
References: <c2157c790711171244q2074ceaal99caf59ec697b6ed@mail.gmail.com>
Message-ID: <fhntsq$f65$1@ger.gmane.org>


"Varsha Purohit" <varsha.purohit at gmail.com> wrote

> later part of the program.  But i am not able to get the file name 
> and
> display it in the text control. Here is the sample code.
>
> Fname = '' #Global variable to hold the file name.

You don't need this since its stored in self.filename.

> class ScrolledWindow(wx.Frame):
>    def __init__(self, parent, id, title):
>        txt1 = wx.TextCtrl(panel, -1, pos=(30, 100), size=(150, 20))

If you want to write to it you need to store it in the object so this
should be self.txt1

>        txt1.write(Fname)

You can't write the filename yet as it hasn't been fetched

>
>    def OnOpen(self,event):
>        self.dirname = ''
>        dlg = wx.FileDialog(self, "Choose a file", self.dirname,"",
> "*.*", wx.OPEN)
>        if dlg.ShowModal()==wx.ID_OK:
>            self.filename=dlg.GetFilename()

Here you get the filename but don't write it to the text control

HTH,

Alan G. 



From kent37 at tds.net  Sun Nov 18 00:48:13 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 17 Nov 2007 18:48:13 -0500
Subject: [Tutor] Web programming
In-Reply-To: <BAY109-DAV48A3CD9BFEB668C095304A37C0@phx.gbl>
References: <BAY109-DAV48A3CD9BFEB668C095304A37C0@phx.gbl>
Message-ID: <473F7DBD.2030405@tds.net>

Dinesh B Vadhia wrote:
> Hi!  I want to create (for testing purposes) a straightforward web 
> application consisting of a client that makes simple queries to a 
> backend which returns data from a database (initially pysqlite3).  
> That's it - really!   I don't need a professional web server (eg. 
> Apache) per se.

I did something like this once with CherryPy, it worked quite well.

Kent

From mlangford.cs03 at gtalumni.org  Sun Nov 18 01:10:41 2007
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Sat, 17 Nov 2007 19:10:41 -0500
Subject: [Tutor] Web programming
In-Reply-To: <BAY109-DAV48A3CD9BFEB668C095304A37C0@phx.gbl>
References: <BAY109-DAV48A3CD9BFEB668C095304A37C0@phx.gbl>
Message-ID: <82b4f5810711171610r4c7c0c69jbc3808d92a04db73@mail.gmail.com>

While CherryPy is suited to what you're doing, I personally think
Mod_Python and Apache are easier to use for this sort of thing. Here
is an article showing how to set it up:
http://modpython.org/live/current/doc-html/installation.html

And a good first quick program that clearly explains what errors mean
when you're trying to get it up and going:
http://www.dscpl.com.au/wiki/ModPython/Articles/GettingModPythonWorking

I was amazed how helpful that second page was on setting things up. I
think it took me about 20-25 min.

   --Michael

On Nov 17, 2007 12:14 PM, Dinesh B Vadhia <dineshbvadhia at hotmail.com> wrote:
>
>
> Hi!  I want to create (for testing purposes) a straightforward web
> application consisting of a client that makes simple queries to a backend
> which returns data from a database (initially pysqlite3).  That's it -
> really!   I don't need a professional web server (eg. Apache) per se.
>
> Are the Python urlparse, urllib, urllib2, httplib, BaseHTTPServer,
> SimpleHTTPServer etc. modules sufficient for the task.  The number of
> queries per second will initially be low, in the 10's/second.
>
> Dinesh
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>



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

From varsha.purohit at gmail.com  Sun Nov 18 03:09:51 2007
From: varsha.purohit at gmail.com (Varsha Purohit)
Date: Sat, 17 Nov 2007 18:09:51 -0800
Subject: [Tutor] [wxPython-users] How to save file name of file opened
	fromwx.FileDialog ?
In-Reply-To: <fhntsq$f65$1@ger.gmane.org>
References: <c2157c790711171244q2074ceaal99caf59ec697b6ed@mail.gmail.com>
	<fhntsq$f65$1@ger.gmane.org>
Message-ID: <c2157c790711171809u4e29b069j37f371177552a36d@mail.gmail.com>

Hi Alan,
    I am actually calling the binding function and then writing it
into the text value... i tried using simple print in the openfile
function and it shows the filename. I am trying to return the file
name value but even that is not responding...

class ScrolledWindow(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(350, 300))
        panel = wx.Panel(self, -1)
        txt1 = wx.TextCtrl(panel, -1, pos=(30, 100), size=(150, 20))
        button11 = wx.Button(panel, -1, "Open", pos=(200,100))
        name = self.Bind(wx.EVT_BUTTON, self.OnOpen, button11)
        txt1.write(name)

        self.Centre()
        self.Show()

    def OnOpen(self,event):
        self.dirname = ''
        dlg = wx.FileDialog(self, "Choose a file", self.dirname,"",
"*.*", wx.OPEN)
        if dlg.ShowModal()==wx.ID_OK:
            self.filename=dlg.GetFilename()
            Fname = self.filename
            self.dirname=dlg.GetDirectory()
            #f=open(os.path.join(self.dirname, self.filename),'r')
            #self.control.SetValue(f.read())
           # self.txt1.WriteText(Fname)
            f.close()

        dlg.Destroy()
        return Fname

app = wx.App()
ScrolledWindow(None, -1, 'Aliens')
app.MainLoop()

I donno the alternative to this now... :(

On Nov 17, 2007 3:35 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> "Varsha Purohit" <varsha.purohit at gmail.com> wrote
>
> > later part of the program.  But i am not able to get the file name
> > and
> > display it in the text control. Here is the sample code.
> >
> > Fname = '' #Global variable to hold the file name.
>
> You don't need this since its stored in self.filename.
>
> > class ScrolledWindow(wx.Frame):
> >    def __init__(self, parent, id, title):
> >        txt1 = wx.TextCtrl(panel, -1, pos=(30, 100), size=(150, 20))
>
> If you want to write to it you need to store it in the object so this
> should be self.txt1
>
> >        txt1.write(Fname)
>
> You can't write the filename yet as it hasn't been fetched
>
> >
> >    def OnOpen(self,event):
> >        self.dirname = ''
> >        dlg = wx.FileDialog(self, "Choose a file", self.dirname,"",
> > "*.*", wx.OPEN)
> >        if dlg.ShowModal()==wx.ID_OK:
> >            self.filename=dlg.GetFilename()
>
> Here you get the filename but don't write it to the text control
>
> HTH,
>
> Alan G.
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Varsha Purohit

From varsha.purohit at gmail.com  Sun Nov 18 03:31:26 2007
From: varsha.purohit at gmail.com (Varsha Purohit)
Date: Sat, 17 Nov 2007 18:31:26 -0800
Subject: [Tutor] [wxPython-users] How to save file name of file opened
	from wx.FileDialog ?
In-Reply-To: <c2157c790711171244q2074ceaal99caf59ec697b6ed@mail.gmail.com>
References: <c2157c790711171244q2074ceaal99caf59ec697b6ed@mail.gmail.com>
Message-ID: <c2157c790711171831i22bb7e78k1b4ddce3276fe86a@mail.gmail.com>

HI Alan,
    Thanks for suggestion its working now....

import wx
import os

class ScrolledWindow(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(350, 300))
        panel = wx.Panel(self, -1)
        self.txt1 = wx.TextCtrl(panel, -1, pos=(30, 100), size=(150, 20))
        self.button11 = wx.Button(panel, -1, "Open", pos=(200,100))
        self.button11.Bind(wx.EVT_BUTTON, self.OnOpen)

        self.Centre()
        self.Show()

    def OnOpen(self,event):
        self.dirname = ''
        dlg = wx.FileDialog(self, "Choose a file", self.dirname,"",
"*.*", wx.OPEN)
        if dlg.ShowModal()==wx.ID_OK:
            self.filename=dlg.GetFilename()
           self.dirname=dlg.GetDirectory()

            self.txt1.write(self.filename)
        dlg.Destroy()


app = wx.App()
ScrolledWindow(None, -1, 'Aliens')
app.MainLoop()

On Nov 17, 2007 12:44 PM, Varsha Purohit <varsha.purohit at gmail.com> wrote:
> Hello Everyone,
>         In my application i need to select a file using open dialog
> box. And then i dont need to open the file. I just need to display the
> name of the selected file in a text control. And then open the file in
> later part of the program.  But i am not able to get the file name and
> display it in the text control. Here is the sample code.
>
> import wx
> import os
>
> Fname = '' #Global variable to hold the file name.
> class ScrolledWindow(wx.Frame):
>     def __init__(self, parent, id, title):
>         wx.Frame.__init__(self, parent, id, title, size=(350, 300))
>         panel = wx.Panel(self, -1)
>         txt1 = wx.TextCtrl(panel, -1, pos=(30, 100), size=(150, 20))
>         button11 = wx.Button(panel, -1, "Open", pos=(200,100))
>         self.Bind(wx.EVT_BUTTON, self.OnOpen, button11)
>         txt1.write(Fname)
>
>         self.Centre()
>         self.Show()
>
>     def OnOpen(self,event):
>         self.dirname = ''
>         dlg = wx.FileDialog(self, "Choose a file", self.dirname,"",
> "*.*", wx.OPEN)
>         if dlg.ShowModal()==wx.ID_OK:
>             self.filename=dlg.GetFilename()
>             Fname = self.filename
>             self.dirname=dlg.GetDirectory()
>         dlg.Destroy()
>
> app = wx.App()
> ScrolledWindow(None, -1, 'Aliens')
> app.MainLoop()
>
>
> Any help is appreciated....
>
> thanks,
> --
> Varsha Purohit,
> Graduate Student
>

From marc.tompkins at gmail.com  Sun Nov 18 04:10:10 2007
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Sat, 17 Nov 2007 19:10:10 -0800
Subject: [Tutor] Read-ahead for large fixed-width binary files?
Message-ID: <40af687b0711171910o121038d3w7e2a3f9c63667e2c@mail.gmail.com>

Alan Gauld wrote:

"Marc Tompkins" <marc.tompkins at gmail.com> wrote
> realized I can implement this myself, using 'read(bigsize)' -
> currently I'm using 'read(recordsize)'; I just need to add an extra
> loop around my record reads.  Please disregard...
If you just want to navigate to a specific record then it might be
easier to use seek(), that will save you having to read all the
previous records into memory.


No, I need to parse the entire file, checking records as I go.  Here's the
solution I came up with - I'm sure it could be optimized, but it's already
about six times faster than going record-by-record:

def loadInsurance(self):
    header = ('Code', 'Name')
    Global.Ins.append(header)
    obj = Insurance()
    recLen = obj.RecordLength
    for offNum, offPath in Global.offices.iteritems():
        if (offPath.Ref == ''):
            offPath.Ref = offPath.Default
        with open(offPath.Ref + obj.TLA + '.dat','rb') as inFile:
            tmpIn = inFile.read(recLen)                 # throw away the
header record
            tmpIn = inFile.read(recLen*4096)
            while not (len(tmpIn) < recLen):
                buf = StringIO.StringIO(tmpIn)
                inRec = buf.read(recLen)
                while not (len(inRec) < recLen):
                    obj = Insurance(inRec)
                    if (obj.Valid):
                        Global.Ins.append(obj.ID, obj.Name)
                    inRec = buf.read(recLen)
                buf.close()
                tmpIn = inFile.read(recLen*4096)

Obviously this is taken out of context, and I'm afraid I'm too lazy to
sanitize it (much) for posting right now, so here's a brief summary instead.

1-  I don't want my calling code to need to know many details.  So if I
create an object with no parameters, it provides me with the record length
(files vary from 80-byte records up to 1024) and the TLA portion of the
filename (the data files are named in the format xxTLA.dat, where xx is the
2-digit office number and TLA is the three-letter acronym for what the file
contains - e.g. INS for insurance.)

2-  Using the information I just obtained, I then read through the file one
record-length chunk at a time, creating an object out of each chunk and
reading the attributes of that object.  In the next version of my class
library, I'll move the whole list-generation logic inside the classes so I
can just pass in a filename and receive a list... but that's one for my
copious free time.

3-  Each file contains a header record, which is pure garbage.  I read it in
and throw it away before I even begin.  (I could seek to just past it
instead - would it really be more efficient?)

4-  Now here's where the read-ahead buffer comes in - I (attempt to) read
4096 records' worth of data, and store it in a StringIO file-like object.
(4096 is just a number I pulled out of the air, but I've tried increasing
and decreasing it, and it seems good.  If I have the time, I may benchmark
to find the best number for each record length, and retrieve that number
along with the record length and TLA.  Of course, the optimal number
probably varies per machine, so maybe I won't bother.)

5-  Now I go through the buffer, one record's worth at a time, and do
whatever I'm doing with the records - in this case, I'm making a list of
insurance company IDs and names to display in a wx.CheckListCtrl.

6-  If I try to read past the end of the file, there's no error - so I need
to check the size of what's returned.  If it's smaller than recLen, I know
I've hit the end.
 6a- When I hit the end of the buffer, I close it and read in another 4096
records.
 6b- When I try to read 4096 records, and end up with less than recLen, I
know I've hit the end of the file.

I've only tested on a few machines/client databases so far, but when I added
step 4, processing a 250MB transaction table (256-byte records) went from
nearly 30 seconds down to about 3.5 seconds.  Other results have varied, but
they've all shown improvement.

If anybody sees any glaring inefficiencies, let me know; OTOH if anybody
else needs to do something similar... here's one way to do it.

-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071117/8e50138e/attachment-0001.htm 

From kent37 at tds.net  Sun Nov 18 05:14:17 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 17 Nov 2007 23:14:17 -0500
Subject: [Tutor] Read-ahead for large fixed-width binary files?
In-Reply-To: <40af687b0711161110y31f289aej7977fce7bb8cb945@mail.gmail.com>
References: <40af687b0711161110y31f289aej7977fce7bb8cb945@mail.gmail.com>
Message-ID: <473FBC19.205@tds.net>

Marc Tompkins wrote:
> My question is this: does anybody know of an equivalent to
> "readlines(sizehint)" for non-delimited, binary files?  I've Googled
> and Googled until I'm groggy, but I don't seem to find what I want.

Have you tried specifying a buffer size in the open() call?

Kent

From kent37 at tds.net  Sun Nov 18 05:20:09 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 17 Nov 2007 23:20:09 -0500
Subject: [Tutor] Read-ahead for large fixed-width binary files?
In-Reply-To: <40af687b0711171910o121038d3w7e2a3f9c63667e2c@mail.gmail.com>
References: <40af687b0711171910o121038d3w7e2a3f9c63667e2c@mail.gmail.com>
Message-ID: <473FBD79.1070004@tds.net>

I would wrap the record buffering into a generator function and probably 
use plain slicing to return the individual records instead of StringIO. 
I have a writeup on generators here:

http://personalpages.tds.net/~kent37/kk/00004.html

Kent

Marc Tompkins wrote:
> Alan Gauld wrote:
> 
>     "Marc Tompkins" <marc.tompkins at gmail.com
>     <mailto:marc.tompkins at gmail.com>> wrote
>      > realized I can implement this myself, using 'read(bigsize)' -
>      > currently I'm using 'read(recordsize)'; I just need to add an extra
>      > loop around my record reads.  Please disregard...
>     If you just want to navigate to a specific record then it might be
>     easier to use seek(), that will save you having to read all the
>     previous records into memory.
> 
> 
> No, I need to parse the entire file, checking records as I go.  Here's 
> the solution I came up with - I'm sure it could be optimized, but it's 
> already about six times faster than going record-by-record:
> 
> def loadInsurance(self):
>     header = ('Code', 'Name')
>     Global.Ins.append(header)
>     obj = Insurance()
>     recLen = obj.RecordLength
>     for offNum, offPath in Global.offices.iteritems():
>         if (offPath.Ref == ''):
>             offPath.Ref = offPath.Default
>         with open(offPath.Ref + obj.TLA + '.dat','rb') as inFile:
>             tmpIn = inFile.read(recLen)                 # throw away the 
> header record
>             tmpIn = inFile.read(recLen*4096)
>             while not (len(tmpIn) < recLen):
>                 buf = StringIO.StringIO (tmpIn)
>                 inRec = buf.read(recLen)
>                 while not (len(inRec) < recLen):
>                     obj = Insurance(inRec)
>                     if (obj.Valid):
>                         Global.Ins.append (obj.ID, obj.Name)
>                     inRec = buf.read(recLen)
>                 buf.close()
>                 tmpIn = inFile.read(recLen*4096)
> 
> Obviously this is taken out of context, and I'm afraid I'm too lazy to 
> sanitize it (much) for posting right now, so here's a brief summary 
> instead.
> 
> 1-  I don't want my calling code to need to know many details.  So if I 
> create an object with no parameters, it provides me with the record 
> length (files vary from 80-byte records up to 1024) and the TLA portion 
> of the filename (the data files are named in the format xxTLA.dat, where 
> xx is the 2-digit office number and TLA is the three-letter acronym for 
> what the file contains - e.g. INS for insurance.) 
> 
> 2-  Using the information I just obtained, I then read through the file 
> one record-length chunk at a time, creating an object out of each chunk 
> and reading the attributes of that object.  In the next version of my 
> class library, I'll move the whole list-generation logic inside the 
> classes so I can just pass in a filename and receive a list... but 
> that's one for my copious free time.
> 
> 3-  Each file contains a header record, which is pure garbage.  I read 
> it in and throw it away before I even begin.  (I could seek to just past 
> it instead - would it really be more efficient?)
> 
> 4-  Now here's where the read-ahead buffer comes in - I (attempt to) 
> read 4096 records' worth of data, and store it in a StringIO file-like 
> object.  (4096 is just a number I pulled out of the air, but I've tried 
> increasing and decreasing it, and it seems good.  If I have the time, I 
> may benchmark to find the best number for each record length, and 
> retrieve that number along with the record length and TLA.  Of course, 
> the optimal number probably varies per machine, so maybe I won't bother.)
> 
> 5-  Now I go through the buffer, one record's worth at a time, and do 
> whatever I'm doing with the records - in this case, I'm making a list of 
> insurance company IDs and names to display in a wx.CheckListCtrl .
> 
> 6-  If I try to read past the end of the file, there's no error - so I 
> need to check the size of what's returned.  If it's smaller than recLen, 
> I know I've hit the end.
>  6a- When I hit the end of the buffer, I close it and read in another 
> 4096 records. 
>  6b- When I try to read 4096 records, and end up with less than recLen, 
> I know I've hit the end of the file.
> 
> I've only tested on a few machines/client databases so far, but when I 
> added step 4, processing a 250MB transaction table (256-byte records) 
> went from nearly 30 seconds down to about 3.5 seconds.  Other results 
> have varied, but they've all shown improvement.
> 
> If anybody sees any glaring inefficiencies, let me know; OTOH if anybody 
> else needs to do something similar... here's one way to do it.
> 
> -- 
> www.fsrtechnologies.com <http://www.fsrtechnologies.com>
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


From marc.tompkins at gmail.com  Sun Nov 18 06:03:39 2007
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Sat, 17 Nov 2007 21:03:39 -0800
Subject: [Tutor] Read-ahead for large fixed-width binary files?
In-Reply-To: <473FBC19.205@tds.net>
References: <40af687b0711161110y31f289aej7977fce7bb8cb945@mail.gmail.com>
	<473FBC19.205@tds.net>
Message-ID: <40af687b0711172103k1fdb2ff8r5ac9341c5a6747f4@mail.gmail.com>

On Nov 17, 2007 8:14 PM, Kent Johnson <kent37 at tds.net> wrote:

> Marc Tompkins wrote:
> > My question is this: does anybody know of an equivalent to
> > "readlines(sizehint)" for non-delimited, binary files?  I've Googled
> > and Googled until I'm groggy, but I don't seem to find what I want.
>
> Have you tried specifying a buffer size in the open() call?
>
> Kent
>

Yes.
I compared:
-  no buffer size specified
-  any of a wide range of positive numbers (from 1 to 4M)
-  -1
and saw no noticeable difference - as opposed to adding the StringIO
buffering, which kicked things up by a notch of six or so.

By the way, this is really obscurely documented.  It took me a lot of
Googling to find even one mention of it - in Programming Python by Mark Lutz
- and I was very excited... until I tested it and found that it did nothing
for me.  Bummer.  Then I re-read the passage:

> *Buffer size*
>
> The open call also takes an optional third buffer size argument, which
> lets you control stdio buffering for the file -- the way that data is
> queued up before being transferred to boost performance. If passed, means
> file operations are unbuffered (data is transferred immediately), 1 means
> they are line buffered, any other positive value means use a buffer of
> approximately that size, and a negative value means to use the system
> default (which you get if no third argument is passed, and generally means
> buffering is enabled). The buffer size argument works on most platforms, but
> is currently ignored on platforms that don't provide the sevbuf system
> call.
>
I've only tested on Windows XP; is XP one of those that don't provide
sevbuf?  (Actually, I think that's a typo - I think it should be "setvbuf" -
but it exists in both the 2001 and 2006 editions of the book.)  Perhaps
someone who codes closer to the silicon can enlighten me on that score.

I just realized that the one thing I didn't try was passing a value of 0 to
turn buffering OFF -  if, as the above passage seems to suggest, it's always
on by default.  I might try that tomorrow.  But in any case it looks like
all it'll do is make things slower.

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

From marc.tompkins at gmail.com  Sun Nov 18 06:07:17 2007
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Sat, 17 Nov 2007 21:07:17 -0800
Subject: [Tutor] Read-ahead for large fixed-width binary files?
In-Reply-To: <40af687b0711172103k1fdb2ff8r5ac9341c5a6747f4@mail.gmail.com>
References: <40af687b0711161110y31f289aej7977fce7bb8cb945@mail.gmail.com>
	<473FBC19.205@tds.net>
	<40af687b0711172103k1fdb2ff8r5ac9341c5a6747f4@mail.gmail.com>
Message-ID: <40af687b0711172107l24790fe6l8e64ae4ad27a1a69@mail.gmail.com>

L'esprit d'escalier - once again I notice something only after hitting
Send.  How do you reconcile these phrases:

> If passed, means file operations are unbuffered

and

> the system default (which you get if no third argument is passed, and
> generally means buffering is enabled)
>

I think my head's going to explode - my negative capacity is overloaded!

On Nov 17, 2007 9:03 PM, Marc Tompkins <marc.tompkins at gmail.com> wrote:

> On Nov 17, 2007 8:14 PM, Kent Johnson <kent37 at tds.net> wrote:
>
> > Marc Tompkins wrote:
> > > My question is this: does anybody know of an equivalent to
> > > "readlines(sizehint)" for non-delimited, binary files?  I've Googled
> > > and Googled until I'm groggy, but I don't seem to find what I want.
> >
> > Have you tried specifying a buffer size in the open() call?
> >
> > Kent
> >
>
> Yes.
> I compared:
> -  no buffer size specified
> -  any of a wide range of positive numbers (from 1 to 4M)
> -  -1
> and saw no noticeable difference - as opposed to adding the StringIO
> buffering, which kicked things up by a notch of six or so.
>
> By the way, this is really obscurely documented.  It took me a lot of
> Googling to find even one mention of it - in Programming Python by Mark Lutz
> - and I was very excited... until I tested it and found that it did nothing
> for me.  Bummer.  Then I re-read the passage:
>
> > *Buffer size*
> >
> > The open call also takes an optional third buffer size argument, which
> > lets you control stdio buffering for the file -- the way that data is
> > queued up before being transferred to boost performance. If passed, means
> > file operations are unbuffered (data is transferred immediately), 1 means
> > they are line buffered, any other positive value means use a buffer of
> > approximately that size, and a negative value means to use the system
> > default (which you get if no third argument is passed, and generally means
> > buffering is enabled). The buffer size argument works on most platforms, but
> > is currently ignored on platforms that don't provide the sevbuf system
> > call.
> >
> I've only tested on Windows XP; is XP one of those that don't provide
> sevbuf?  (Actually, I think that's a typo - I think it should be "setvbuf" -
> but it exists in both the 2001 and 2006 editions of the book.)  Perhaps
> someone who codes closer to the silicon can enlighten me on that score.
>
> I just realized that the one thing I didn't try was passing a value of 0
> to turn buffering OFF -  if, as the above passage seems to suggest, it's
> always on by default.  I might try that tomorrow.  But in any case it looks
> like all it'll do is make things slower.
>
> --
> www.fsrtechnologies.com




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

From marc.tompkins at gmail.com  Sun Nov 18 06:39:49 2007
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Sat, 17 Nov 2007 21:39:49 -0800
Subject: [Tutor] Read-ahead for large fixed-width binary files?
In-Reply-To: <473FBD79.1070004@tds.net>
References: <40af687b0711171910o121038d3w7e2a3f9c63667e2c@mail.gmail.com>
	<473FBD79.1070004@tds.net>
Message-ID: <40af687b0711172139q7cc44b18jc02c7f4ad8485cbb@mail.gmail.com>

On Nov 17, 2007 8:20 PM, Kent Johnson <kent37 at tds.net> wrote:

> I would wrap the record buffering into a generator function and probably
> use plain slicing to return the individual records instead of StringIO.
> I have a writeup on generators here:
>
> http://personalpages.tds.net/~kent37/kk/00004.html<http://personalpages.tds.net/%7Ekent37/kk/00004.html>
>
> Kent
>

I can see the benefit of wrapping the buffering in a generator - after all,
a large point of the exercise is to make this and all future programs
simpler to write and to debug - but I don't understand the second part

> use plain slicing to return the individual records instead of StringIO.

I hope I'm not being obtuse, but could you clarify that?

Meditating further, I begin to see a way through... the generator reads in
chunks 4096 records long; an internal iterator keeps track of how far along
to slice the thing; I need to check to make sure I don't try to slice past
the end of the loaf...  I'm not sure I see how this makes my life better
than using StringIO (especially since I'm actually using cStringIO, with a
"just-in-case" fallback in the import section, and it seems to be pretty
fast.)
Of course, if I load the entire file into memory I only need to check the
size once, but several of my clients have transaction files (to name only
one file) that are larger than their physical RAM, so that approach would
seem... problematic.  I'm trying to enhance performance, not kill it.

Thanks in advance for your insight -

Marc
-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071117/5fe36af8/attachment-0001.htm 

From alan.gauld at btinternet.com  Sun Nov 18 10:03:15 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 18 Nov 2007 09:03:15 -0000
Subject: [Tutor] [wxPython-users] How to save file name of file
	openedfromwx.FileDialog ?
References: <c2157c790711171244q2074ceaal99caf59ec697b6ed@mail.gmail.com><fhntsq$f65$1@ger.gmane.org>
	<c2157c790711171809u4e29b069j37f371177552a36d@mail.gmail.com>
Message-ID: <fhov4m$fcs$1@ger.gmane.org>


"Varsha Purohit" <varsha.purohit at gmail.com> wrote

I note that you got it wotking but just to clarify...

>    I am actually calling the binding function and then writing it
> into the text value... 

> class ScrolledWindow(wx.Frame):
>    def __init__(self, parent, id, title):
>        txt1 = wx.TextCtrl(panel, -1, pos=(30, 100), size=(150, 20))
>        name = self.Bind(wx.EVT_BUTTON, self.OnOpen, button11)
>        txt1.write(name)

The Bind function does not execute the handler method 
it simply registers it within wxPython for future use when 
the button event is triggered. The return value from Bind 
is not the return value of the method being bound.

The method only gets called when the button is pressed, 
thats why you have to put the write() call in the event 
handler itself.

HTH,

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


From kent37 at tds.net  Sun Nov 18 13:57:16 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 18 Nov 2007 07:57:16 -0500
Subject: [Tutor] Read-ahead for large fixed-width binary files?
In-Reply-To: <40af687b0711172103k1fdb2ff8r5ac9341c5a6747f4@mail.gmail.com>
References: <40af687b0711161110y31f289aej7977fce7bb8cb945@mail.gmail.com>	
	<473FBC19.205@tds.net>
	<40af687b0711172103k1fdb2ff8r5ac9341c5a6747f4@mail.gmail.com>
Message-ID: <474036AC.4020209@tds.net>

Marc Tompkins wrote:
> On Nov 17, 2007 8:14 PM, Kent Johnson <kent37 at tds.net 
> <mailto:kent37 at tds.net>> wrote:
>     Have you tried specifying a buffer size in the open() call?
> 
> Yes. 
> I compared:
> -  no buffer size specified
> -  any of a wide range of positive numbers (from 1 to 4M)
> -  -1
> and saw no noticeable difference - as opposed to adding the StringIO 
> buffering, which kicked things up by a notch of six or so.
> 
> By the way, this is really obscurely documented.  

It is documented in the official docs of the open() function, that can't 
really be called obscure:
http://docs.python.org/lib/built-in-funcs.html#l2h-54

though I admit that this section of the docs itself is not as well-known 
as it should be. (I strongly recommend that all learning Pythonistas 
read sections 2.1 and 3 of the Library Reference.)

It took me a lot of
> Googling to find even one mention of it - in Programming Python by Mark 
> Lutz - and I was very excited... until I tested it and found that it did 
> nothing for me.  Bummer.  Then I re-read the passage:
> 
>     /Buffer size/
> 
>         The open call also takes an optional third buffer size argument,
>         which lets you control stdio buffering for the file -- the way
>         that data is queued up before being transferred to boost
>         performance. If passed, means file operations are unbuffered

Should read, "If 0 is passed"

> I've only tested on Windows XP; is XP one of those that don't provide 
> sevbuf?  (Actually, I think that's a typo - I think it should be 
> "setvbuf" - but it exists in both the 2001 and 2006 editions of the 
> book.) 

Yes, it is correctly spelled in the official docs:
http://docs.python.org/lib/built-in-funcs.html#foot1196

Kent

From kent37 at tds.net  Sun Nov 18 14:15:56 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 18 Nov 2007 08:15:56 -0500
Subject: [Tutor] Read-ahead for large fixed-width binary files?
In-Reply-To: <40af687b0711172139q7cc44b18jc02c7f4ad8485cbb@mail.gmail.com>
References: <40af687b0711171910o121038d3w7e2a3f9c63667e2c@mail.gmail.com>	
	<473FBD79.1070004@tds.net>
	<40af687b0711172139q7cc44b18jc02c7f4ad8485cbb@mail.gmail.com>
Message-ID: <47403B0C.4010400@tds.net>

Marc Tompkins wrote:
> On Nov 17, 2007 8:20 PM, Kent Johnson <kent37 at tds.net 
> <mailto:kent37 at tds.net>> wrote:
>     use plain slicing to return the individual records instead of StringIO.
> 
> I hope I'm not being obtuse, but could you clarify that? 

I think it will simplify the looping. A sketch, probably needs work:

def by_record(path, recsize):
   with open(path,'rb') as inFile:
     inFile.read(recLen)  # throw away the header record
     while True:
       buf = inFile.read(recLen*4096)
       if not buf:
         return
       for ix in range(0, len(buf), recLen):
         yield buf[ix:ix+recLen]

 > I'm not sure I see how this makes my
> life better than using StringIO (especially since I'm actually using 
> cStringIO, with a "just-in-case" fallback in the import section, and it 
> seems to be pretty fast.)

This version seems simpler and more readable to me.

Kent

From thorsten at thorstenkampe.de  Sun Nov 18 07:03:56 2007
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Sun, 18 Nov 2007 14:03:56 +0800
Subject: [Tutor] Installing modules via setuptools in a script
Message-ID: <fhpgaj$ohi$1@ger.gmane.org>

Hi,

can anyone give me a short code snippet how to install a missing 
module via setuptools (assuming setuptools is already installed)?!

Something like this:

try:
    import missing_module
except import_error
    import setuptools
    setuptools.whatever.install(missing_module)

Thorsten


From marc.tompkins at gmail.com  Sun Nov 18 18:09:20 2007
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Sun, 18 Nov 2007 09:09:20 -0800
Subject: [Tutor] Read-ahead for large fixed-width binary files?
In-Reply-To: <47403B0C.4010400@tds.net>
References: <40af687b0711171910o121038d3w7e2a3f9c63667e2c@mail.gmail.com>
	<473FBD79.1070004@tds.net>
	<40af687b0711172139q7cc44b18jc02c7f4ad8485cbb@mail.gmail.com>
	<47403B0C.4010400@tds.net>
Message-ID: <40af687b0711180909n53fc3594v13700122476334f5@mail.gmail.com>

On Nov 18, 2007 5:15 AM, Kent Johnson <kent37 at tds.net> wrote:

> Marc Tompkins wrote:
> > On Nov 17, 2007 8:20 PM, Kent Johnson <kent37 at tds.net
> > <mailto:kent37 at tds.net>> wrote:
> >     use plain slicing to return the individual records instead of
> StringIO.
> >
> > I hope I'm not being obtuse, but could you clarify that?
>
> I think it will simplify the looping. A sketch, probably needs work:
>
> def by_record(path, recsize):
>   with open(path,'rb') as inFile:
>     inFile.read(recLen)  # throw away the header record
>     while True:
>       buf = inFile.read(recLen*4096)
>       if not buf:
>         return
>       for ix in range(0, len(buf), recLen):
>         yield buf[ix:ix+recLen]
>
>  > I'm not sure I see how this makes my
> > life better than using StringIO (especially since I'm actually using
> > cStringIO, with a "just-in-case" fallback in the import section, and it
> > seems to be pretty fast.)
>
> This version seems simpler and more readable to me.
>
> Kent
>
It does look lean and mean, true.  I'll time this against the cStringIO
version. One thing, though - I think I need to do

> if len(buf) < recLen:
>         return
>
rather than

>       if not buf:
>         return
>
I'll have to experiment again to refresh my memory, but I believe I tried
that in one of my first iterations (about a year ago, so I may be
remembering wrong.)  If I remember correctly, read() was still returning a
result - but with a size that didn't evaluate to false.  As you can imagine,
hilarity ensued when I tried to slice the last record.

Of course, I may have hallucinated that while on an extended caffeine jag,
so feel free to disregard!
-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071118/65f1e23c/attachment.htm 

From kent37 at tds.net  Sun Nov 18 19:28:35 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 18 Nov 2007 13:28:35 -0500
Subject: [Tutor] Read-ahead for large fixed-width binary files?
In-Reply-To: <40af687b0711180909n53fc3594v13700122476334f5@mail.gmail.com>
References: <40af687b0711171910o121038d3w7e2a3f9c63667e2c@mail.gmail.com>	
	<473FBD79.1070004@tds.net>	
	<40af687b0711172139q7cc44b18jc02c7f4ad8485cbb@mail.gmail.com>	
	<47403B0C.4010400@tds.net>
	<40af687b0711180909n53fc3594v13700122476334f5@mail.gmail.com>
Message-ID: <47408453.2090306@tds.net>

Marc Tompkins wrote:
> though - I think I need to do
> 
>     if len(buf) < recLen:
>             return
> 
> rather than
> 
>           if not buf:
>             return
> 
> I'll have to experiment again to refresh my memory, but I believe I 
> tried that in one of my first iterations (about a year ago, so I may be 
> remembering wrong.)  If I remember correctly, read() was still returning 
> a result - but with a size that didn't evaluate to false.  As you can 
> imagine, hilarity ensued when I tried to slice the last record.

Yes, there might be a partial record or a newline or some kind of cruft 
at the end of the file. If that is the case you will have to guard 
against yielding short records, too, e.g.

rec = buf[ix:ix+recLen]
if len(rec) == recLen:
   yield rec

which will make my version about as long as yours I think :-)

Kent

From mwalsh at groktech.org  Sun Nov 18 20:36:08 2007
From: mwalsh at groktech.org (Martin Walsh)
Date: Sun, 18 Nov 2007 13:36:08 -0600
Subject: [Tutor] subprocess help, nohup
In-Reply-To: <aaf235960711131340wda4ef16qbc8fb1cb05ab6c09@mail.gmail.com>
References: <aaf235960711131340wda4ef16qbc8fb1cb05ab6c09@mail.gmail.com>
Message-ID: <47409428.7080007@groktech.org>

John wrote:
> Hello,

Hi John,

I didn't see a response to your question, so I'll make an attempt ...

>  
> I've written a script which conducts several subprocess calls and then
> ultimately calls a shell script which runs even more programs... my
> script is using subprocess to execute a few sed calls, and then execute
> the script. I'm getting strange behavior:

Just a suggestion, if you find you are preforming sed replace operations
regularly, you might consider writing your own sed-like replace
function. This way you avoid spawning a subprocess altogether for
search/replace functionality, and as an added bonus you can re-use it in
future scripts. The following (untested) code should get you started, if
you choose to go this route:

import re

def sed_replace(search, replace, text):
    pattern = re.compile(search)
    return pattern.sub(replace, text)

def infile_sed_replace(search, replace, path):
    text = file(path).read()
    newtext = sed_replace(search, replace, text)
    file(path, 'w').write(newtext)

...
infile_sed_replace('RunMin=[0-9][0-9]*', 'RunMin=%s' % k, runFile)
...

> 
> You'll notice, the last subprocess call is commented out. Right now I'm
> just getting to that point to make sure everything is working. So, it
> seems to work, but I'm not sure how to get it to work if I change the
> command to nohup. I still want python to wait for it to return, in fact,
> I would like to set the python job running in the background as well...
> so what I'm looking at doing is:
>  
> % nohup myControl.py
>    ---> which will make several subprocess.call(s) including some that
> should be 'nohupped' as well...

This strikes me as nohup abuse, though I'm not entirely certain what you
are trying to accomplish. Since you plan to nohup *and* background your
script anyway, you might be better served by preemptively detaching from
the controlling terminal (or daemonizing) instead. If so, you may find
one or both of the following recipes useful:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012

Of course, you may need to handle logging a little differently.

HTH,
Marty

From pyth0nc0d3r at gmail.com  Mon Nov 19 19:01:16 2007
From: pyth0nc0d3r at gmail.com (Lamonte Harris)
Date: Mon, 19 Nov 2007 12:01:16 -0600
Subject: [Tutor] Is it possible to use sockets to login to a website that
	uses php?
Message-ID: <eb79828c0711191001v2cf4ff90x3743d02efbd597a9@mail.gmail.com>

I need to some how make a script that logs into a website from my desktop
and I can do the rest and grab the information on my on hopefully.  How
would I login to a website using sockets with python?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071119/e374b2ef/attachment.htm 

From cappy2112 at gmail.com  Mon Nov 19 21:16:28 2007
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Mon, 19 Nov 2007 12:16:28 -0800
Subject: [Tutor] Wrong version of Python being executed
In-Reply-To: <473665F0.2050704@tds.net>
References: <8249c4ac0711101723u44fd0352r8325db01443124f1@mail.gmail.com>
	<473665F0.2050704@tds.net>
Message-ID: <8249c4ac0711191216k58746f92l71d16721665bc2a8@mail.gmail.com>

I've found something interesting regarding this issue.

I went to Windows Explorer, Tools,Folder Options, File Types and
noticed that there are two different icons associated with .PY files.
The Icon for Python 2.5 is easy to recognize as compared with the icon
for Python 2.3.

So I've changed the association from the 2.3 icon to the 2.5 icon, and
now I can run my script from the command line as follows

python script.py, and the correct version of Python is invoked.

This is very disturbing because it means the path or other env vars
have no control (or very little) as to which version of Python is
invoked.


How do other people deal with having multiple versions of Python on
their system, and not run into this issue??



On Nov 10, 2007 6:16 PM, Kent Johnson <kent37 at tds.net> wrote:
>
> Tony Cappellini wrote:
> > When I run this python script, the following exception is thrown,
> > implying that it is being executed with Python 2.3
> > So I've added this print statement to the main function, which shows
> > the logging module is being imported from the Python 2.3 directory
> >
> > print"\nlogging.__file__ = %s" % logging.__file__
> >
> > logging.__file__ = C:\Python23\lib\logging\__init__.pyc
> >
> >
> >
> > Traceback (most recent call last):
> >   File "c:\Project\myscript.py", line 584, in
> > ?
> >     main(sys.argv)
> >   File "c:\Project\myscript.py", line 518, in
> > main
> >     logging.basicConfig(level=config.verbosity,format='%(message)s')
> > TypeError: basicConfig() takes no arguments (2 given)
> >
> >
> > The really odd thing is when I bring up the python interpreter at the
> > same command prompt where i ran the script above,
> > Python 2.5 is invoked, as seen by
> >
> >
> > Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
> > (Intel)] on win32
> > Type "help", "copyright", "credits" or "license" for more information.
> >>>> import sys
> >>>> sys.version
> > '2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)]'
> >
> >
> > How is it that running a script invokes Python 2.3, but running the
> > interpreter without the script invoked Python 2.5?
>
> A couple of possibilities...
> Is there a #! line at the start of the script that specifies Python 2.3
> (I'm not sure if those work in windows though...)
>
> How do you run the script? If you double-click it, perhaps the file
> association with .py files is to Python 2.3?
>
> Conceivably the Python 2.5 module path is incorrect and imports the
> wrong module. What happens if you import logging from the interpreter
> prompt and print its file? What do you get if you print sys.path from
> the interpreter?
>
> HTH,
> Kent
>

From srini_iyyer_bio at yahoo.com  Mon Nov 19 23:40:29 2007
From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer)
Date: Mon, 19 Nov 2007 14:40:29 -0800 (PST)
Subject: [Tutor] Windows - Linux based open() file handle mode
Message-ID: <68887.75120.qm@web38107.mail.mud.yahoo.com>

Dear group, 

I want to parse an file generated for windows.
My code works beautifully when I try to parse the same
file generated in Linux. 

I uses the following options with no success:

blast_out = open('C:\human\prb_blast.out','r')

blast_out = open('C:\human\prb_blast.out','rU')

blast_out = open('C:\human\prb_blast.out','U')

Are there any other ways to solve this problem. 

Since the question is more of biopython question I
posted detailed question on biopython forum. apologies
for any inconvenience. 

thanks
srini


      ____________________________________________________________________________________
Be a better sports nut!  Let your teams follow you 
with Yahoo Mobile. Try it now.  http://mobile.yahoo.com/sports;_ylt=At9_qDKvtAbMuh1G1SQtBI7ntAcJ

From kent37 at tds.net  Mon Nov 19 23:57:18 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 19 Nov 2007 17:57:18 -0500
Subject: [Tutor] Windows - Linux based open() file handle mode
In-Reply-To: <68887.75120.qm@web38107.mail.mud.yahoo.com>
References: <68887.75120.qm@web38107.mail.mud.yahoo.com>
Message-ID: <474214CE.10000@tds.net>

Srinivas Iyyer wrote:
> Dear group, 
> 
> I want to parse an file generated for windows.
> My code works beautifully when I try to parse the same
> file generated in Linux. 
> 
> I uses the following options with no success:
> 
> blast_out = open('C:\human\prb_blast.out','r')
> 
> blast_out = open('C:\human\prb_blast.out','rU')
> 
> blast_out = open('C:\human\prb_blast.out','U')

Presumably the file is a text file? What kind of error do you get? Have 
you looked at the file and compared it with the same file generated on 
Linux? Are you using a recent version of Python? (the U options were 
introduced in 2.3)

Kent

From bill at celestial.net  Tue Nov 20 00:30:01 2007
From: bill at celestial.net (Bill Campbell)
Date: Mon, 19 Nov 2007 15:30:01 -0800
Subject: [Tutor] Windows - Linux based open() file handle mode
In-Reply-To: <68887.75120.qm@web38107.mail.mud.yahoo.com>
References: <68887.75120.qm@web38107.mail.mud.yahoo.com>
Message-ID: <20071119233001.GA24250@ayn.mi.celestial.com>

On Mon, Nov 19, 2007, Srinivas Iyyer wrote:
>Dear group, 
>
>I want to parse an file generated for windows.
>My code works beautifully when I try to parse the same
>file generated in Linux. 
>
>I uses the following options with no success:
>
>blast_out = open('C:\human\prb_blast.out','r')
>
>blast_out = open('C:\human\prb_blast.out','rU')
>
>blast_out = open('C:\human\prb_blast.out','U')
>
>Are there any other ways to solve this problem. 

Try blast_out = open('C:/human/prb_blast.out', 'U') instead of
the $DEITY/Awful DOSish backwacks.

If you're really enamoured of backslashes, add an r before the
single quotes to get what you want.

blast_out = open(r'C:\human\prb_blast.out','U')

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

There is nothing as stupid as an educated man if you get him off the
thing he was educated in.
    Will Rogers

From alan.gauld at btinternet.com  Tue Nov 20 02:04:57 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 20 Nov 2007 01:04:57 -0000
Subject: [Tutor] Windows - Linux based open() file handle mode
References: <68887.75120.qm@web38107.mail.mud.yahoo.com>
	<20071119233001.GA24250@ayn.mi.celestial.com>
Message-ID: <fhtbrt$7nq$1@ger.gmane.org>


"Bill Campbell" <bill at celestial.net> wrote

>>blast_out = open('C:\human\prb_blast.out','U')
>>
>>Are there any other ways to solve this problem.
>
> Try blast_out = open('C:/human/prb_blast.out', 'U') instead of
> the $DEITY/Awful DOSish backwacks.
>
> If you're really enamoured of backslashes, add an r before the
> single quotes to get what you want.

And the reason is that \ is the escape character in Python strings
so \h is seen as just h and \p as p. if you had a \t it would be seen
as a tab character etc. So to avoid that either tell Python to ignore
the escapes by using r(raw string) or use forward slashes which
work just as well in Windows as in Linux...

You'll find more on this in the side bar in my File Handling topic,
about 1/3 of the way down the page.

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  Tue Nov 20 02:08:59 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 20 Nov 2007 01:08:59 -0000
Subject: [Tutor] Wrong version of Python being executed
References: <8249c4ac0711101723u44fd0352r8325db01443124f1@mail.gmail.com><473665F0.2050704@tds.net>
	<8249c4ac0711191216k58746f92l71d16721665bc2a8@mail.gmail.com>
Message-ID: <fhtc3f$8c4$1@ger.gmane.org>

"Tony Cappellini" <cappy2112 at gmail.com> wrote

> So I've changed the association from the 2.3 icon to the 2.5 icon, 
> and
> now I can run my script from the command line as follows
>
> python script.py, and the correct version of Python is invoked.
>
> This is very disturbing because it means the path or other env vars
> have no control (or very little) as to which version of Python is
> invoked.

There are multiple mechanisms.
The PATH and env vars should take precedence inside a DOS
box but from Explorer or from Start-Run its the registry settings
that matter.

> How do other people deal with having multiple versions of Python on
> their system, and not run into this issue??

By using one under cygwin and the other under Windows.
I currently have 2.5 installed in cygwin but 2.4 in Windows...
(and 2.5 and 2.3 installed in MacOS - and 2.2 on Linux!)

Alan G 



From alan.gauld at btinternet.com  Tue Nov 20 09:26:52 2007
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Tue, 20 Nov 2007 08:26:52 +0000 (GMT)
Subject: [Tutor] Fw:  Wrong version of Python being executed
Message-ID: <110607.96775.qm@web86709.mail.ird.yahoo.com>

Forwarding to the list...

----- Forwarded Message ----
From: Doug Glenn <doug at foruminfosystems.com>
To: Alan Gauld <alan.gauld at btinternet.com>
Sent: Tuesday, 20 November, 2007 4:08:12 AM
Subject: Re: [Tutor] Wrong version of Python being executed

Hrrrm, I thought you did that last week when I asked you about it.

It is a bit odd since normally Pythons installation mechinism only
does it for the PY file on install.  You may have clicked on it
sometime in the past and then selected "run with" and it remembered
the association.

File associations are checked first, then it will check the path if
there is no association.  This is default windows behavior.

Glad you got it sussed out!

-- 
Doug Glenn
FORUM Information Systems, LLC
http://foruminfosystems.com




From dglenn99 at gmail.com  Tue Nov 20 13:34:50 2007
From: dglenn99 at gmail.com (Douglas Glenn)
Date: Tue, 20 Nov 2007 07:34:50 -0500
Subject: [Tutor] Fw: Wrong version of Python being executed
In-Reply-To: <110607.96775.qm@web86709.mail.ird.yahoo.com>
References: <110607.96775.qm@web86709.mail.ird.yahoo.com>
Message-ID: <fab8e70d0711200434t5ce376ceu73462b4e19a2de82@mail.gmail.com>

Darn, I thought I sent this to Tony.  I had seen about 20 odd
exchanges about it and had not seen anyone ask about File
associations.  For some reasons my messages bounce, probably because I
had used my alias mail addressing from gmail.

Thanks Alan.

On Nov 20, 2007 3:26 AM, ALAN GAULD <alan.gauld at btinternet.com> wrote:
> Forwarding to the list...
>
> ----- Forwarded Message ----
> From: Doug Glenn <doug at foruminfosystems.com>
> To: Alan Gauld <alan.gauld at btinternet.com>
> Sent: Tuesday, 20 November, 2007 4:08:12 AM
> Subject: Re: [Tutor] Wrong version of Python being executed
>
>
> Hrrrm, I thought you did that last week when I asked you about it.
>
> It is a bit odd since normally Pythons installation mechinism only
> does it for the PY file on install.  You may have clicked on it
> sometime in the past and then selected "run with" and it remembered
> the association.
>
> File associations are checked first, then it will check the path if
> there is no association.  This is default windows behavior.
>
> Glad you got it sussed out!
>
> --
> Doug Glenn
> FORUM Information Systems, LLC
> http://foruminfosystems.com
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Doug Glenn
FORUM Information Systems, LLC
http://foruminfosystems.com

From varsha.purohit at gmail.com  Tue Nov 20 16:31:59 2007
From: varsha.purohit at gmail.com (Varsha Purohit)
Date: Tue, 20 Nov 2007 07:31:59 -0800
Subject: [Tutor] [wxPython-users] How to save file name of file
	openedfromwx.FileDialog ?
In-Reply-To: <fhov4m$fcs$1@ger.gmane.org>
References: <c2157c790711171244q2074ceaal99caf59ec697b6ed@mail.gmail.com>
	<fhntsq$f65$1@ger.gmane.org>
	<c2157c790711171809u4e29b069j37f371177552a36d@mail.gmail.com>
	<fhov4m$fcs$1@ger.gmane.org>
Message-ID: <c2157c790711200731j829307dg81d7e149fb749dd2@mail.gmail.com>

Hello Alan,

What i want is i just need a file picker to chooose the file and
display the file name in the text box. I need to open about 4 files
like that. That is the front end work. In the back end i am making a
list variable to which i have to send the information about the
selected files. And that list is read and files are opened in another
script. So, i guess i need to improve the code more to choose the
file, display just the file information and may be send whole file
path to the list.  I need to work more on that i guess.....Thanks for
reminding me...

-Varsha


On Nov 18, 2007 1:03 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> "Varsha Purohit" <varsha.purohit at gmail.com> wrote
>
> I note that you got it wotking but just to clarify...
>
> >    I am actually calling the binding function and then writing it
> > into the text value...
>
> > class ScrolledWindow(wx.Frame):
> >    def __init__(self, parent, id, title):
> >        txt1 = wx.TextCtrl(panel, -1, pos=(30, 100), size=(150, 20))
> >        name = self.Bind(wx.EVT_BUTTON, self.OnOpen, button11)
> >        txt1.write(name)
>
> The Bind function does not execute the handler method
> it simply registers it within wxPython for future use when
> the button event is triggered. The return value from Bind
> is not the return value of the method being bound.
>
> The method only gets called when the button is pressed,
> thats why you have to put the write() call in the event
> handler itself.
>
> 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 cappy2112 at gmail.com  Tue Nov 20 19:03:02 2007
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Tue, 20 Nov 2007 10:03:02 -0800
Subject: [Tutor] Tutor Digest, Vol 45, Issue 58
In-Reply-To: <mailman.25.1195556405.32514.tutor@python.org>
References: <mailman.25.1195556405.32514.tutor@python.org>
Message-ID: <8249c4ac0711201003w72e0f42bkc1f2b4e2f53a0e81@mail.gmail.com>

----- Forwarded Message ----
From: Doug Glenn <doug at foruminfosystems.com>
To: Alan Gauld <alan.gauld at btinternet.com>
Sent: Tuesday, 20 November, 2007 4:08:12 AM
Subject: Re: [Tutor] Wrong version of Python being executed

>>It is a bit odd since normally Pythons installation mechinism only
>>does it for the PY file on install.  You may have clicked on it
>>sometime in the past and then selected "run with" and it remembered
>>the association.

I'm pretty sure every time I've installed Python that the associations
get changed. However, since the executable is the same name for all
versions of python (but the path is different), this doesn't help when
you want to use one version instead of another.

File associations are checked first, then it will check the path if
there is no association.  This is default windows behavior.

>>Glad you got it sussed out!
I know the reason of the strange behaviour, but not a solution at this point.
I have a library which only works for Python2.3. When I start working
on that project again, I 'll have to re-associate .py with 2.3.
This isn't convenient (and it's likely I will have forgotten all about
this by then) :-)

From keridee at jayco.net  Tue Nov 20 22:19:01 2007
From: keridee at jayco.net (Tiger12506)
Date: Tue, 20 Nov 2007 16:19:01 -0500
Subject: [Tutor] Fw: Wrong version of Python being executed
References: <110607.96775.qm@web86709.mail.ird.yahoo.com>
	<fab8e70d0711200434t5ce376ceu73462b4e19a2de82@mail.gmail.com>
Message-ID: <001001c82bbb$00323bf0$3ffce004@jslaptop>

I haven't seen anybody write down the full picture so that we are not
misled. Windows chooses which python to use in this manner.

1) If you double click on a .py file in windows, it looks in the registry
for the command string that pertains to "open".
    The .py extension has a default value that tells which type of file it
is, this 'type' has it's own seperate command for "open"
    (So 'txtfile' will have a different open command than 'mp3file', for
example.)

    If in the command interpreter (sometimes inaccurately called a dos box)
you type the name of the .py file (WITHOUT typing python),
    then windows will open it with whatever value is in the registry, just
as if you had double clicked it in explorer.

2) However, if you type python before the script name, then windows checks
first
     a) in the directory that the prompt is at
     b) checks in each directory in the PATH environment variable for an
executable named python.exe and uses that

I have not found that the PYTHONPATH environment variable has any effect
(which i doubt it would, as windows does not make a
special case to check it before hand, and I doubt that python.exe will check
that environ var and spawn the proper version before it runs the script)
I am absolutely certain that the #! at the beginning of the python file does
NOT work in windows, it is strictly a *nix thing.

There are many solutions to this, my favorite being where one adds an extra
entry to the sub menu of the .py file.
Effectively what happens is that another key and value is added to the
registry, providing an alternate command string for "open"

If you go to control panel->folder options->file associations and choose py
file and click advanced, there should be an option to add
another "verb" i believe they call it. So add one and call it open w/23 or
something to distinguish it from regular "open" and put in the
command box the full path of the python exe, followed by "%1" with quotes,
so that when you choose that menu option it will run
that particular python and send the name of the file through %1 so it is
passed in as the argument. Then, when you want to run it with
your default python, you right-click->open. When you want to run it with the
different version, right-click->open w/23 or whatever you
called it.

hope this helps
JS


From kent37 at tds.net  Tue Nov 20 22:27:32 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 20 Nov 2007 16:27:32 -0500
Subject: [Tutor] Fw: Wrong version of Python being executed
In-Reply-To: <001001c82bbb$00323bf0$3ffce004@jslaptop>
References: <110607.96775.qm@web86709.mail.ird.yahoo.com>	<fab8e70d0711200434t5ce376ceu73462b4e19a2de82@mail.gmail.com>
	<001001c82bbb$00323bf0$3ffce004@jslaptop>
Message-ID: <47435144.3090507@tds.net>

Tiger12506 wrote:
> I have not found that the PYTHONPATH environment variable has any effect

No, it wouldn't. Windows doesn't know about PYTHONPATH; it is used 
internally by the Python interpreter when searching for imported modules 
and packages.

Kent

From trey at opmstech.org  Wed Nov 21 06:05:11 2007
From: trey at opmstech.org (Trey Keown)
Date: Tue, 20 Nov 2007 23:05:11 -0600 (CST)
Subject: [Tutor] Python on T-Mobile Wing???
Message-ID: <61480.68.191.136.241.1195621511.squirrel@webmail.opmstech.org>

Hey all,
I just got a brand new T-Mobile Wing, and, as you might guess, I want to
install python on it. Well, I tried both the pythonce main build (with the
.exe), and the build for the smartphone (also used .exe), but once I
downloaded them, when I tried to run them, a dialog comes up saying that
this is not a valid pocket pc app. Any ideas?

Note- the wing uses windows mobile 6. The specs can be found at-
http://www.t-mobile.com/shop/phones/Detail.aspx?device=acc8102d-4506-4eaa-bc2f-9c7b8ec1b1e0


From mwalsh at groktech.org  Wed Nov 21 14:08:11 2007
From: mwalsh at groktech.org (Martin Walsh)
Date: Wed, 21 Nov 2007 07:08:11 -0600
Subject: [Tutor] Python on T-Mobile Wing???
In-Reply-To: <61480.68.191.136.241.1195621511.squirrel@webmail.opmstech.org>
References: <61480.68.191.136.241.1195621511.squirrel@webmail.opmstech.org>
Message-ID: <47442DBB.2010107@groktech.org>

Trey Keown wrote:
> Hey all,
> I just got a brand new T-Mobile Wing, and, as you might guess, I want to
> install python on it. Well, I tried both the pythonce main build (with the
> .exe), and the build for the smartphone (also used .exe), but once I
> downloaded them, when I tried to run them, a dialog comes up saying that
> this is not a valid pocket pc app. Any ideas?
> 

I think the exe installer is for running on a windows pc with activesync
-- you would need the cab version to install directly on a windows
mobile device.

>From the pythonce wiki:
http://pythonce.sourceforge.net/Wikka/Installing
http://pythonce.sourceforge.net/Wikka/Downloading

> Note- the wing uses windows mobile 6. The specs can be found at-
> http://www.t-mobile.com/shop/phones/Detail.aspx?device=acc8102d-4506-4eaa-bc2f-9c7b8ec1b1e0
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


From srini_iyyer_bio at yahoo.com  Wed Nov 21 18:02:47 2007
From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer)
Date: Wed, 21 Nov 2007 09:02:47 -0800 (PST)
Subject: [Tutor] ElementTree - reading large XML files as file handles
Message-ID: <85529.50830.qm@web38105.mail.mud.yahoo.com>

Dear tutors, 

I use ElementTree for XML works. I have a 1.3GB file
to parse. 


I takes a lot of time to open my input XML file. 

Is that because of my hardware limitation or am I
using a blunt method to load the file.

my computer config:
Inte(R)
Pentium(R)4 CPU 2.80GHz
2.79GHz, 0.99GB of RAM

from elementtree import ElementTree
myfile = open('myXML.out','r')

Do you suggest any tip to circumvent the file opening
problem. 

thanks
Srini



      ____________________________________________________________________________________
Be a better sports nut!  Let your teams follow you 
with Yahoo Mobile. Try it now.  http://mobile.yahoo.com/sports;_ylt=At9_qDKvtAbMuh1G1SQtBI7ntAcJ

From kent37 at tds.net  Wed Nov 21 18:21:23 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 21 Nov 2007 12:21:23 -0500
Subject: [Tutor] ElementTree - reading large XML files as file handles
In-Reply-To: <85529.50830.qm@web38105.mail.mud.yahoo.com>
References: <85529.50830.qm@web38105.mail.mud.yahoo.com>
Message-ID: <47446913.4060703@tds.net>

Srinivas Iyyer wrote:
> Dear tutors, 
> 
> I use ElementTree for XML works. I have a 1.3GB file
> to parse. 
> 
> 
> I takes a lot of time to open my input XML file. 
> 
> Is that because of my hardware limitation or am I
> using a blunt method to load the file.
> 
> my computer config:
> Inte(R)
> Pentium(R)4 CPU 2.80GHz
> 2.79GHz, 0.99GB of RAM
> 
> from elementtree import ElementTree
> myfile = open('myXML.out','r')

Reading a 1.3 GB file on a machine with .99 GB RAM is certainly pushing 
things. To parse it into an ElementTree will probably double or triple 
your memory requirements.
> 
> Do you suggest any tip to circumvent the file opening
> problem. 

Do you need the whole parsed tree at once or can you process it a little 
at a time? If not, maybe this will help:
http://effbot.org/zone/element-iterparse.htm

Kent

From dkuhlman at rexx.com  Wed Nov 21 18:54:23 2007
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Wed, 21 Nov 2007 09:54:23 -0800
Subject: [Tutor] ElementTree - reading large XML files as file handles
In-Reply-To: <85529.50830.qm@web38105.mail.mud.yahoo.com>
References: <85529.50830.qm@web38105.mail.mud.yahoo.com>
Message-ID: <20071121175423.GB74184@cutter.rexx.com>

On Wed, Nov 21, 2007 at 09:02:47AM -0800, Srinivas Iyyer wrote:
> Dear tutors, 
> 
> I use ElementTree for XML works. I have a 1.3GB file
> to parse. 
> 
> 
> I takes a lot of time to open my input XML file. 
> 
> Is that because of my hardware limitation or am I
> using a blunt method to load the file.
> 
> my computer config:
> Inte(R)
> Pentium(R)4 CPU 2.80GHz
> 2.79GHz, 0.99GB of RAM
> 
> from elementtree import ElementTree
> myfile = open('myXML.out','r')
> 
> Do you suggest any tip to circumvent the file opening
> problem. 

If time is the problem, you might want to look at:

- cElementTree -- See notes about cElementTree on this page:
  http://effbot.org/zone/elementtree-13-intro.htm

- lxml -- http://codespeak.net/lxml/

If size/resources/memory are the issue, as must be the case for
you, then SAX can be a solution.  But, switching to SAX requires a
very radical redesign of your application.

You might also want to investigate pulldom.  It's in the Python
standard library.  A quote:

    "PullDOM has 80% of the speed of SAX and 80% of the convenience
    of the DOM. There are still circumstances where you might need
    SAX (speed freak!) or DOM (complete random access). But IMO
    there are a lot more circumstances where the PullDOM middle
    ground is exactly what you need."

The Python standard documentation on pulldom is next to none, but
here are several links:

  http://www.prescod.net/python/pulldom.html
  http://www.ibm.com/developerworks/xml/library/x-tipulldom.html
  http://www.idealliance.org/papers/dx_xml03/papers/06-02-03/06-02-03.html
  http://www.idealliance.org/papers/dx_xml03/papers/06-02-03/06-02-03.html#pull

Hope this helps.

Dave

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

From kent37 at tds.net  Wed Nov 21 19:18:11 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 21 Nov 2007 13:18:11 -0500
Subject: [Tutor] ElementTree - reading large XML files as file handles
In-Reply-To: <85529.50830.qm@web38105.mail.mud.yahoo.com>
References: <85529.50830.qm@web38105.mail.mud.yahoo.com>
Message-ID: <47447663.8090200@tds.net>

Srinivas Iyyer wrote:
> Dear tutors, 
> 
> I use ElementTree for XML works. I have a 1.3GB file
> to parse. 
> 
> 
> I takes a lot of time to open my input XML file. 
> 
> Is that because of my hardware limitation or am I
> using a blunt method to load the file.
> 
> my computer config:
> Inte(R)
> Pentium(R)4 CPU 2.80GHz
> 2.79GHz, 0.99GB of RAM
> 
> from elementtree import ElementTree
> myfile = open('myXML.out','r')

Reading a 1.3 GB file on a machine with .99 GB RAM is certainly pushing 
things. To parse it into an ElementTree will probably double or triple 
your memory requirements.
> 
> Do you suggest any tip to circumvent the file opening
> problem. 

Do you need the whole parsed tree at once or can you process it a little 
at a time? If not, maybe this will help:
http://effbot.org/zone/element-iterparse.htm

Kent

From iapythonman at gmail.com  Fri Nov 23 09:23:53 2007
From: iapythonman at gmail.com (Le Van)
Date: Fri, 23 Nov 2007 15:23:53 +0700
Subject: [Tutor] Display Vietnamese characters with GnoChm
Message-ID: <31cceb570711230023m719870fbsdbd1337a1c500672@mail.gmail.com>

Hi all,
I'm using CHM Viewer 0.9.11 running in Ubuntu 7.10. When open an .chm
file, I got this warning
"Your Python installation does not support Vietnamese (Vietnamese -
None). It is like that the characters
in the navigation tabs will not be correctly displayed."
Then it does not display text correctly. The file displays correctly in Windows.
I tried to open another file. CHM Viewer displays Vietnamese characters well.
So what is the problem. Does my machine miss some fonts ?
What does it mean "Your Python installation does not support Vietnamese"
I'm using Python 2.5.1
Thanks in advance,
Van

From ebrosh at nana10.co.il  Fri Nov 23 14:39:50 2007
From: ebrosh at nana10.co.il (Eli Brosh)
Date: Fri, 23 Nov 2007 15:39:50 +0200
Subject: [Tutor] 2-D array to string
Message-ID: <957526FB6E347743AAB42B212AB54FDA95BA64@NANAMAILBACK1.nanamail.co.il>


Hello
I am starting to use pylab/numpy/scipy instead of MATLAB.
I now have a real beginners question (I think it is not really related to numpy)
I have a two-dimensional array
a=[[1,2,3],[4, 5, 6],[7,8,9]]

Is there a simple way to turn it into a multiline string ?

That is, turn a into:
s='''1 2 3 \n 4 5 6 \n 7 8 9'''

Thanks
Eli
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071123/ed14f7a2/attachment.htm 

From evert.rol at gmail.com  Fri Nov 23 15:24:03 2007
From: evert.rol at gmail.com (Evert Rol)
Date: Fri, 23 Nov 2007 14:24:03 +0000
Subject: [Tutor] 2-D array to string
In-Reply-To: <957526FB6E347743AAB42B212AB54FDA95BA64@NANAMAILBACK1.nanamail.co.il>
References: <957526FB6E347743AAB42B212AB54FDA95BA64@NANAMAILBACK1.nanamail.co.il>
Message-ID: <7CEE50CA-2FF1-4342-97A9-62C99144CBD6@gmail.com>

> I am starting to use pylab/numpy/scipy instead of MATLAB.
> I now have a real beginners question (I think it is not really  
> related to numpy)
> I have a two-dimensional array
> a=[[1,2,3],[4, 5, 6],[7,8,9]]
>
> Is there a simple way to turn it into a multiline string ?
>
> That is, turn a into:
> s='''1 2 3 \n 4 5 6 \n 7 8 9'''
>

Not a really easy way that I know of, but several solutions I can  
think of:
- turning the Python double list into a numpy array gives a multiline  
string, although differently formatted:
 >>> repr(numpy.array(a))
'array([[1, 2, 3],\n       [4, 5, 6],\n       [7, 8, 9]])'

- Using a double list comprehension can work:
 >>> '\n'.join([' '.join(str(aaa) for aaa in aa) for aa in a])
'1 2 3\n4 5 6\n7 8 9'

- You could use a regular expression to alter the numpy  
representation or the default Python representation into what you want.

- you could subclass the (numpy) array object and alter the __str__  
or __repr__ functions for convenience, although this may be bit overdone

There's probably a few more, perhaps even more elegant, that other  
people on the list may come up with.

But is there a specific reason you'd want it in this format, and not  
the default Python or numpy format? Perhaps you're writing data to a  
file?


From ebrosh at nana10.co.il  Fri Nov 23 16:43:21 2007
From: ebrosh at nana10.co.il (Eli Brosh)
Date: Fri, 23 Nov 2007 17:43:21 +0200
Subject: [Tutor] 2-D array to string
References: <957526FB6E347743AAB42B212AB54FDA95BA64@NANAMAILBACK1.nanamail.co.il>
	<7CEE50CA-2FF1-4342-97A9-62C99144CBD6@gmail.com>
Message-ID: <957526FB6E347743AAB42B212AB54FDA95BA65@NANAMAILBACK1.nanamail.co.il>


Thank you very much Evert.
Starting from your advice, I used:
a=numpy.array([[100,2,3],[4,5,6],[7,8,9]])
s=repr(a).replace('array',' ')
s='      '+''.join([ c for c in s if c not in ('(', ')','[',']',',')])
print s

This gave the correct result.
So, the problem is solved.

The reason I wanted the array to be converted to string format is that I use such strings as an input to another program. 
The easiest thing so far, was to copy them from the MATLAB console.
Now, I have the same functionality in python, without '[' that appear if I just use:
print a

Thanks
Eli

-----????? ??????-----
???: Evert Rol [mailto:evert.rol at gmail.com]
????: ? 11/23/2007 16:24
??: Eli Brosh
???? ??????: tutor at python.org
????: Re: [Tutor] 2-D array to string
 
> I am starting to use pylab/numpy/scipy instead of MATLAB.
> I now have a real beginners question (I think it is not really  
> related to numpy)
> I have a two-dimensional array
> a=[[1,2,3],[4, 5, 6],[7,8,9]]
>
> Is there a simple way to turn it into a multiline string ?
>
> That is, turn a into:
> s='''1 2 3 \n 4 5 6 \n 7 8 9'''
>

Not a really easy way that I know of, but several solutions I can  
think of:
- turning the Python double list into a numpy array gives a multiline  
string, although differently formatted:
 >>> repr(numpy.array(a))
'array([[1, 2, 3],\n       [4, 5, 6],\n       [7, 8, 9]])'

- Using a double list comprehension can work:
 >>> '\n'.join([' '.join(str(aaa) for aaa in aa) for aa in a])
'1 2 3\n4 5 6\n7 8 9'

- You could use a regular expression to alter the numpy  
representation or the default Python representation into what you want.

- you could subclass the (numpy) array object and alter the __str__  
or __repr__ functions for convenience, although this may be bit overdone

There's probably a few more, perhaps even more elegant, that other  
people on the list may come up with.

But is there a specific reason you'd want it in this format, and not  
the default Python or numpy format? Perhaps you're writing data to a  
file?


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

From johnpatrick at gerdeman.de  Fri Nov 23 18:06:38 2007
From: johnpatrick at gerdeman.de (John Gerdeman)
Date: Fri, 23 Nov 2007 18:06:38 +0100
Subject: [Tutor] python 2.4 reading files - unexpected behaviour
Message-ID: <1195837598.5262.13.camel@forellle92>

Hello, 

I got a csv file, in which I have to count the occurrences of certain
numbers in columns. I can do this for one arbitrary column, but not for
all.

The problem I encountered is as follows. Iterating through the rows of a
file works, but as soon as I try to iterate through the same file again,
it seems it returns nothing.

Code-example
------------
import csv
file = csv.reader(open("some.csv", "rb"))
for i in file:
	print i

for i in file:
	print i

some.csv:
3, 4, 5
4, 3, 2

The above program only returns:
['3', ' 4', ' 5']
['4', ' 3', ' 2']

instead of:
['3', ' 4', ' 5']
['4', ' 3', ' 2']
['3', ' 4', ' 5']
['4', ' 3', ' 2']

Any help would be welcome.

John
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Dies ist ein digital signierter Nachrichtenteil
Url : http://mail.python.org/pipermail/tutor/attachments/20071123/dfd4b46c/attachment.pgp 

From bgailer at alum.rpi.edu  Fri Nov 23 20:35:27 2007
From: bgailer at alum.rpi.edu (bob gailer)
Date: Fri, 23 Nov 2007 14:35:27 -0500
Subject: [Tutor] python 2.4 reading files - unexpected behaviour
In-Reply-To: <1195837598.5262.13.camel@forellle92>
References: <1195837598.5262.13.camel@forellle92>
Message-ID: <47472B7F.7090501@alum.rpi.edu>

John Gerdeman wrote:
> Hello, 
>
> I got a csv file, in which I have to count the occurrences of certain
> numbers in columns. I can do this for one arbitrary column, but not for
> all.
>
> The problem I encountered is as follows. Iterating through the rows of a
> file works, but as soon as I try to iterate through the same file again,
> it seems it returns nothing.
>
> Code-example
> ------------
> import csv
> file = csv.reader(open("some.csv", "rb"))
>   
It is not a good idea to use "file" as a variable name since that hides 
the built-in function. But that is not the reason you get what you do.
> for i in file:
> 	print i
>   
The file is now at end-of-file. Any attempts to read it now just keep it 
at end-of-file.  Either re-open it or file.seek(0) to rewind it to the 
beginning.
> for i in file:
> 	print i
>
>   


From hunter92383 at gmail.com  Fri Nov 23 23:31:30 2007
From: hunter92383 at gmail.com (elis aeris)
Date: Fri, 23 Nov 2007 14:31:30 -0800
Subject: [Tutor] network - send one line of text
Message-ID: <674d5ce60711231431h7c3adc95xefcfb474f1f72fc5@mail.gmail.com>

is it possible to do this with python?


a server script to listen for

a client script, it sends a line of text to server when a given criteria is
met.


i just need to send text alone, and then code it best kept simple,

is this possible to do with python?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071123/16b4ad1f/attachment.htm 

From bgailer at alum.rpi.edu  Sat Nov 24 00:35:57 2007
From: bgailer at alum.rpi.edu (bob gailer)
Date: Fri, 23 Nov 2007 18:35:57 -0500
Subject: [Tutor] network - send one line of text
In-Reply-To: <674d5ce60711231431h7c3adc95xefcfb474f1f72fc5@mail.gmail.com>
References: <674d5ce60711231431h7c3adc95xefcfb474f1f72fc5@mail.gmail.com>
Message-ID: <474763DD.8050208@alum.rpi.edu>

elis aeris wrote:
> is it possible to do this with python?
>
>
> a server script to listen for
>
> a client script, it sends a line of text to server when a given 
> criteria is met.
>
>
> i just need to send text alone, and then code it best kept simple,
>
> is this possible to do with python?
see the socket module for starters


From alan.gauld at btinternet.com  Sat Nov 24 01:13:29 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 24 Nov 2007 00:13:29 -0000
Subject: [Tutor] network - send one line of text
References: <674d5ce60711231431h7c3adc95xefcfb474f1f72fc5@mail.gmail.com>
Message-ID: <fi7qba$bp9$1@ger.gmane.org>


"elis aeris" <hunter92383 at gmail.com> wrote

> a server script to listen for
>
> a client script, it sends a line of text to server when a given 
> criteria is
> met.
>
> is this possible to do with python?

Yes its standard socket programming.

Take a look at my tutorial, specifically the Network Programming topic
for more info and an example.

There is also an excellent How-To document for sockets
on the Python web site.

HTH,

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



From mlangford.cs03 at gtalumni.org  Sat Nov 24 02:06:40 2007
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Fri, 23 Nov 2007 20:06:40 -0500
Subject: [Tutor] network - send one line of text
In-Reply-To: <674d5ce60711231431h7c3adc95xefcfb474f1f72fc5@mail.gmail.com>
References: <674d5ce60711231431h7c3adc95xefcfb474f1f72fc5@mail.gmail.com>
Message-ID: <82b4f5810711231706k7e55d69bhc34fb3915a9ce83a@mail.gmail.com>

On 11/23/07, elis aeris <hunter92383 at gmail.com> wrote:
> is it possible to do this with python?
>
>
> a server script to listen for
>
> a client script, it sends a line of text to server when a given criteria is
> met.

Sounds like python may not be simplest path to solving your problem.
If you're on a unix-like OS, use netcat:

http://netcat.sourceforge.net/

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

From steve at alchemy.com  Sat Nov 24 02:42:42 2007
From: steve at alchemy.com (Steve Willoughby)
Date: Fri, 23 Nov 2007 17:42:42 -0800
Subject: [Tutor] network - send one line of text
In-Reply-To: <82b4f5810711231706k7e55d69bhc34fb3915a9ce83a@mail.gmail.com>
References: <674d5ce60711231431h7c3adc95xefcfb474f1f72fc5@mail.gmail.com>
	<82b4f5810711231706k7e55d69bhc34fb3915a9ce83a@mail.gmail.com>
Message-ID: <47478192.10703@alchemy.com>

Michael Langford wrote:
> On 11/23/07, elis aeris <hunter92383 at gmail.com> wrote:
>> is it possible to do this with python?
>>
>>
>> a server script to listen for
>>
>> a client script, it sends a line of text to server when a given criteria is
>> met.
> 
> Sounds like python may not be simplest path to solving your problem.
> If you're on a unix-like OS, use netcat:

Depending on the criteria you want to watch for, "expect" may be the 
ideal solution.  I'd recommend checking that out as well.

http://expect.nist.gov


From detroit371 at gmail.com  Sat Nov 24 06:27:43 2007
From: detroit371 at gmail.com (Lawrence Shafer)
Date: Fri, 23 Nov 2007 23:27:43 -0600
Subject: [Tutor] comparing dates
Message-ID: <4747B64F.10102@gmail.com>

How would I compare these two dates and extract the difference in H:M:S??

22 Nov 2007 18:54:07
23 Nov 2007 23:24:23

Cheers,

Lawrence

From shantanoo at gmail.com  Sat Nov 24 06:37:36 2007
From: shantanoo at gmail.com (Shantanoo Mahajan)
Date: Sat, 24 Nov 2007 11:07:36 +0530
Subject: [Tutor] comparing dates
In-Reply-To: <4747B64F.10102@gmail.com>
References: <4747B64F.10102@gmail.com>
Message-ID: <CC2E7982-2C2F-47EC-9CF9-7F6343254A61@gmail.com>


On 24-Nov-07, at 10:57 AM, Lawrence Shafer wrote:

> How would I compare these two dates and extract the difference in  
> H:M:S??
>
> 22 Nov 2007 18:54:07
> 23 Nov 2007 23:24:23

You can try, 'datetime' module.
'http://pleac.sourceforge.net/pleac_python/datesandtimes.html' may be  
useful.

regards,
shantanoo

From steve at alchemy.com  Sat Nov 24 06:39:29 2007
From: steve at alchemy.com (Steve Willoughby)
Date: Fri, 23 Nov 2007 21:39:29 -0800
Subject: [Tutor] comparing dates
In-Reply-To: <4747B64F.10102@gmail.com>
References: <4747B64F.10102@gmail.com>
Message-ID: <4747B911.9000105@alchemy.com>

Lawrence Shafer wrote:
> How would I compare these two dates and extract the difference in H:M:S??
> 
> 22 Nov 2007 18:54:07
> 23 Nov 2007 23:24:23

Look at the datetime module's timedelta operations.


From cbc at unc.edu  Sat Nov 24 06:58:39 2007
From: cbc at unc.edu (Chris Calloway)
Date: Sat, 24 Nov 2007 00:58:39 -0500
Subject: [Tutor] comparing dates
In-Reply-To: <4747B64F.10102@gmail.com>
References: <4747B64F.10102@gmail.com>
Message-ID: <3A2998FA-6D7F-47A1-91D3-01A17FDA8354@unc.edu>

On Nov 24, 2007, at 12:27 AM, Lawrence Shafer wrote:
> How would I compare these two dates and extract the difference in  
> H:M:S??

http://docs.python.org/lib/module-datetime.html
http://docs.python.org/lib/datetime-timedelta.html

> 22 Nov 2007 18:54:07
> 23 Nov 2007 23:24:23

 >>> import datetime
 >>> a = datetime.datetime(2007,11,22,18,54,7)
 >>> b = datetime.datetime(2007,11,23,23,24,23)
 >>> c = b - a
 >>> hours = (c.seconds / (60*60))
 >>> minutes = (c.seconds - (hours * 60*60)) / 60
 >>> seconds = c.seconds - (hours * 60*60) - (minutes * 60)
 >>> print str((c.days*24) + hours) + ":" + str(minutes) + ":" + str 
(seconds)
28:30:16
 >>>

--
Sincerely,

Chris Calloway
http://www.seacoos.org
office: 332 Chapman Hall cell: (919) 599-3530
mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599


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

From dave6502 at googlemail.com  Sat Nov 24 14:49:41 2007
From: dave6502 at googlemail.com (dave selby)
Date: Sat, 24 Nov 2007 13:49:41 +0000
Subject: [Tutor] unexpected signal behaviour
Message-ID: <f52017b60711240549u69120675sd428eee8a83e1a6b@mail.gmail.com>

Hi all,

I have written a daemon as part of a larger project, if it recieves a
SIGHUP signal it needs to re-read its config file. It works in that I
get 'signal HUP detected, re-reading config file' in syslog but then
the script exits ... mmm .... first time I have used signal catching
... thought it would continue its infinate loop. Any idea anyone ?

Cheers

Dave




import os,  sys, time, signal, ConfigParser, kmotion_logger

class Kmotion_Hkd2:

    def __init__(self):
        self.snap_init = [ 0 for i in xrange(16) ]
        self.snap_count = [ 0 for i in xrange(16) ]
        self.video_dir = ''
        self.motion_feeds = ''
        self.logger = kmotion_logger.Logger('kmotion_hdk2', 'DEBUG')
        signal.signal(signal.SIGHUP, self.signal_hup)
        self.read_config()

    def start_daemon(self):
        self.logger.log('daemon starting ...', 'DEBUG')
        """" Start the house keeping 2 daemon """
        while(True):
            target_date = time.strftime('%Y%m%d')
            # Scan the feeds
            for feed in xrange(self.motion_feeds):
                target_tmp = '%s/%s/%02i/tmp/' % (self.video_dir,
target_date, (feed + 1))
                target_video = '%s/%s/%02i/video/' % (self.video_dir,
target_date, (feed + 1))

                # If target_date or target_tmp don't exist they will
shortly as motion auto generates them
                # If target_video doesn't exist, could be just no
motion so add dir
                if not(os.path.isdir(self.video_dir + '/' +
target_date)) or not(os.path.isdir(target_tmp)): continue
                if not(os.path.isdir(target_video)): os.mkdir(target_video)

                jpeg_list = os.listdir(target_tmp)
                jpeg_list.sort()

                while (len(jpeg_list) >= 3):
                    jpeg = jpeg_list[:1][0]
                    self.snap_count[feed] = self.snap_count[feed] - 1

                    if  self.snap_count[feed]:
                        # Still counting down the snap_count[], so
delete the snapshot
                        self.logger.log('deleteing snapshot %s' %
(target_tmp + jpeg), 'DEBUG')
                        os.remove(target_tmp + jpeg)

                    else:  # snap_count[] = 0, reset it & do something
with the snapshot
                        self.snap_count[feed] = self.snap_init[feed]

                        if os.path.isdir(target_video + jpeg[:-4]) or
not(self.snap_init[feed]):
                            # If there is a video file dir or if
snap_init[feed] = 0, we dont need a snapshot so remove it
                            self.logger.log('remove snapshot due to
video clash %s/tmp/%s' % (self.video_dir, jpeg), 'DEBUG')
                            os.remove(target_tmp + jpeg)

                        else:  # No video file dir, move the snapshot
                            self.logger.log('rename %s %s' %
(target_tmp + jpeg, target_video + jpeg), 'DEBUG')
                            os.rename(target_tmp + jpeg, target_video + jpeg)

                    jpeg_list = jpeg_list[1:]
            time.sleep(2)

    def read_config(self):
        """ Read config file from '~/.kde/share/apps/kmotion/kmotion.rc' """
        parser = ConfigParser.SafeConfigParser()
        parsed =
parser.read(os.path.expanduser('~/.kde/share/apps/kmotion/kmotion.rc'))
        if parsed[0][-10:] != 'kmotion.rc':
            emsg = 'Can\'t open config file %s - killing motion & all
daemon processes' % (parsed[0][-10:])
            self.logger.log(emsg, 'CRIT')
            self.kill_daemons()
            sys.exit()

        try:
            self.video_dir = parser.get('misc', 'video_dir')
            self.motion_feeds = 0  # Get ready to count the live feeds
            for i in xrange(0, 16):
                self.snap_init[i] = int(parser.get('feed%s' %
(str(i)), 'snapshot_interval'))
                if parser.get('feed%s' % (str(i)), 'live') == "yes" :
self.motion_feeds = self.motion_feeds + 1
        except:
            emsg = 'Corrupt config %s - Killing motion & all daemons
processes' %  (sys.exc_info()[1])
            self.logger.log(emsg, 'CRIT')
            self.kill_daemons()
            sys.exit()

        for i in xrange(16):  # Force an immediate snapshot on all feeds
            self.snap_count[i] = 1

    def kill_daemons(self):
        """ Kill motion & all daemons """
        os.system('killall -q motion')
        os.system('pkill -f \'python.+kmotion_hkd1.py\'')

    def signal_hup(self, signum, frame):
            """ Re-read the config file on SIGHUP """
            self.logger.log('signal HUP detected, re-reading config
file', 'DEBUG')
            self.read_config()

if __name__ == '__main__':
    Hkd2 = Kmotion_Hkd2()
    Hkd2.start_daemon()



-- 

Please avoid sending me Word or PowerPoint attachments.
See http://www.gnu.org/philosophy/no-word-attachments.html

From dineshbvadhia at hotmail.com  Sun Nov 25 02:35:54 2007
From: dineshbvadhia at hotmail.com (Dinesh B Vadhia)
Date: Sat, 24 Nov 2007 17:35:54 -0800
Subject: [Tutor] error binding parameter 1
Message-ID: <BAY109-DAV98187314008B619064B2AA3740@phx.gbl>

Hello!  Can anyone see what the problem with this code snippet is?

Dinesh


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

            image_filename = str(dir_list[i])
            image_file = dir_path + image_filename
            image_blob = open(image_file, 'rb')
[L40]   cursor.execute("Insert into image_table values (?, ?)", (image_filename, image_blob))

Traceback (most recent call last):
  File "C:\storage management.py", line 40, in <module>
    cursor.execute("Insert into image_table values (?, ?)", (image_filename, image_blob))
InterfaceError: Error binding parameter 1 - probably unsupported type.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071124/d501aec3/attachment.htm 

From bgailer at alum.rpi.edu  Sun Nov 25 02:55:23 2007
From: bgailer at alum.rpi.edu (bob gailer)
Date: Sat, 24 Nov 2007 20:55:23 -0500
Subject: [Tutor] error binding parameter 1
In-Reply-To: <BAY109-DAV98187314008B619064B2AA3740@phx.gbl>
References: <BAY109-DAV98187314008B619064B2AA3740@phx.gbl>
Message-ID: <4748D60B.7020006@alum.rpi.edu>

Dinesh B Vadhia wrote:
> Hello!  Can anyone see what the problem with this code snippet is?
>  
> Dinesh
>  
> ------------------------------------------------------------------------
>             image_filename = str(dir_list[i])
>             image_file = dir_path + image_filename
>             image_blob = open(image_file, 'rb')
Should that be
image_blob = open(image_file, 'rb').read()?
> [L40]   cursor.execute("Insert into image_table values (?, ?)", 
> (image_filename, image_blob))
>  
> Traceback (most recent call last):
>   File "C:\storage management.py", line 40, in <module>
>     cursor.execute("Insert into image_table values (?, ?)", 
> (image_filename, image_blob))
> InterfaceError: Error binding parameter 1 - probably unsupported type.
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From dineshbvadhia at hotmail.com  Sun Nov 25 03:18:40 2007
From: dineshbvadhia at hotmail.com (Dinesh B Vadhia)
Date: Sat, 24 Nov 2007 18:18:40 -0800
Subject: [Tutor] error binding parameter 1
References: <BAY109-DAV98187314008B619064B2AA3740@phx.gbl>
	<4748D60B.7020006@alum.rpi.edu>
Message-ID: <BAY109-DAV506897D6F69692CE35585A3740@phx.gbl>

Yes, it should be: image_blob = open(image_file, 'rb').read()

Thank-you!


----- Original Message ----- 
From: bob gailer 
To: Dinesh B Vadhia 
Cc: tutor at python.org 
Sent: Saturday, November 24, 2007 5:55 PM
Subject: Re: [Tutor] error binding parameter 1


Dinesh B Vadhia wrote:
> Hello!  Can anyone see what the problem with this code snippet is?
>  
> Dinesh
>  
> ------------------------------------------------------------------------
>             image_filename = str(dir_list[i])
>             image_file = dir_path + image_filename
>             image_blob = open(image_file, 'rb')
Should that be
image_blob = open(image_file, 'rb').read()?
> [L40]   cursor.execute("Insert into image_table values (?, ?)", 
> (image_filename, image_blob))
>  
> Traceback (most recent call last):
>   File "C:\storage management.py", line 40, in <module>
>     cursor.execute("Insert into image_table values (?, ?)", 
> (image_filename, image_blob))
> InterfaceError: Error binding parameter 1 - probably unsupported type.
> ------------------------------------------------------------------------
>
> _______________________________________________
> 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/20071124/a4c5b34f/attachment.htm 

From oclbdk at gmail.com  Sun Nov 25 07:15:57 2007
From: oclbdk at gmail.com (Johnston Jiaa)
Date: Sun, 25 Nov 2007 01:15:57 -0500
Subject: [Tutor] Tkinter Grid Layout Problems
Message-ID: <4E1444C8-8509-452B-924B-E40A7C45C077@gmail.com>

I'm trying to get the left part of a window to look like this:
http://img.photobucket.com/albums/v228/gaypig123ABC/PB240055.jpg

I tried using sticky's, but nothing seems to work correctly.

This is my attempt, without the sticky's..
         self.lt_lbl = Label(frame, text="Left label")
         self.lt_lbl.grid(row=0, column=0)

         self.lt_add_btn = Button(frame, text="Left add button")
         self.lt_add_btn.grid(row=0, column=1)
         self.lt_rem_btn = Button(frame, text="Left remove button")
         self.lt_rem_btn.grid(row=0, column=2)

         self.lt_lstbx = Listbox(frame)
         self.lt_lstbx.grid(row=1, column=0)
         self.lt_scrlbr = Scrollbar(frame)
         self.lt_scrlbr.grid(row=1, column=1)

How do I get everything aligned properly?


Thanks,
Johnston Jiaa

From alan.gauld at btinternet.com  Sun Nov 25 10:59:44 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 25 Nov 2007 09:59:44 -0000
Subject: [Tutor] unexpected signal behaviour
References: <f52017b60711240549u69120675sd428eee8a83e1a6b@mail.gmail.com>
Message-ID: <fibh2j$ig2$1@ger.gmane.org>

I can't see anything obvious.

Try putting some debug messages into read_config
and the main loop.

Also you could try catching the SystemExit exception at
the top level and dumping a stacktrace to see exactly
where it is exiting.

HTH,

Alan G.


"dave selby" <dave6502 at googlemail.com> wrote in message 
news:f52017b60711240549u69120675sd428eee8a83e1a6b at mail.gmail.com...
> Hi all,
>
> I have written a daemon as part of a larger project, if it recieves 
> a
> SIGHUP signal it needs to re-read its config file. It works in that 
> I
> get 'signal HUP detected, re-reading config file' in syslog but then
> the script exits ... mmm .... first time I have used signal catching
> ... thought it would continue its infinate loop. Any idea anyone ?
>
> Cheers
>
> Dave
>
>
>
>
> import os,  sys, time, signal, ConfigParser, kmotion_logger
>
> class Kmotion_Hkd2:
>
>    def __init__(self):
>        self.snap_init = [ 0 for i in xrange(16) ]
>        self.snap_count = [ 0 for i in xrange(16) ]
>        self.video_dir = ''
>        self.motion_feeds = ''
>        self.logger = kmotion_logger.Logger('kmotion_hdk2', 'DEBUG')
>        signal.signal(signal.SIGHUP, self.signal_hup)
>        self.read_config()
>
>    def start_daemon(self):
>        self.logger.log('daemon starting ...', 'DEBUG')
>        """" Start the house keeping 2 daemon """
>        while(True):
>            target_date = time.strftime('%Y%m%d')
>            # Scan the feeds
>            for feed in xrange(self.motion_feeds):
>                target_tmp = '%s/%s/%02i/tmp/' % (self.video_dir,
> target_date, (feed + 1))
>                target_video = '%s/%s/%02i/video/' % (self.video_dir,
> target_date, (feed + 1))
>
>                # If target_date or target_tmp don't exist they will
> shortly as motion auto generates them
>                # If target_video doesn't exist, could be just no
> motion so add dir
>                if not(os.path.isdir(self.video_dir + '/' +
> target_date)) or not(os.path.isdir(target_tmp)): continue
>                if not(os.path.isdir(target_video)): 
> os.mkdir(target_video)
>
>                jpeg_list = os.listdir(target_tmp)
>                jpeg_list.sort()
>
>                while (len(jpeg_list) >= 3):
>                    jpeg = jpeg_list[:1][0]
>                    self.snap_count[feed] = self.snap_count[feed] - 1
>
>                    if  self.snap_count[feed]:
>                        # Still counting down the snap_count[], so
> delete the snapshot
>                        self.logger.log('deleteing snapshot %s' %
> (target_tmp + jpeg), 'DEBUG')
>                        os.remove(target_tmp + jpeg)
>
>                    else:  # snap_count[] = 0, reset it & do 
> something
> with the snapshot
>                        self.snap_count[feed] = self.snap_init[feed]
>
>                        if os.path.isdir(target_video + jpeg[:-4]) or
> not(self.snap_init[feed]):
>                            # If there is a video file dir or if
> snap_init[feed] = 0, we dont need a snapshot so remove it
>                            self.logger.log('remove snapshot due to
> video clash %s/tmp/%s' % (self.video_dir, jpeg), 'DEBUG')
>                            os.remove(target_tmp + jpeg)
>
>                        else:  # No video file dir, move the snapshot
>                            self.logger.log('rename %s %s' %
> (target_tmp + jpeg, target_video + jpeg), 'DEBUG')
>                            os.rename(target_tmp + jpeg, target_video 
> + jpeg)
>
>                    jpeg_list = jpeg_list[1:]
>            time.sleep(2)
>
>    def read_config(self):
>        """ Read config file from 
> '~/.kde/share/apps/kmotion/kmotion.rc' """
>        parser = ConfigParser.SafeConfigParser()
>        parsed =
> parser.read(os.path.expanduser('~/.kde/share/apps/kmotion/kmotion.rc'))
>        if parsed[0][-10:] != 'kmotion.rc':
>            emsg = 'Can\'t open config file %s - killing motion & all
> daemon processes' % (parsed[0][-10:])
>            self.logger.log(emsg, 'CRIT')
>            self.kill_daemons()
>            sys.exit()
>
>        try:
>            self.video_dir = parser.get('misc', 'video_dir')
>            self.motion_feeds = 0  # Get ready to count the live 
> feeds
>            for i in xrange(0, 16):
>                self.snap_init[i] = int(parser.get('feed%s' %
> (str(i)), 'snapshot_interval'))
>                if parser.get('feed%s' % (str(i)), 'live') == "yes" :
> self.motion_feeds = self.motion_feeds + 1
>        except:
>            emsg = 'Corrupt config %s - Killing motion & all daemons
> processes' %  (sys.exc_info()[1])
>            self.logger.log(emsg, 'CRIT')
>            self.kill_daemons()
>            sys.exit()
>
>        for i in xrange(16):  # Force an immediate snapshot on all 
> feeds
>            self.snap_count[i] = 1
>
>    def kill_daemons(self):
>        """ Kill motion & all daemons """
>        os.system('killall -q motion')
>        os.system('pkill -f \'python.+kmotion_hkd1.py\'')
>
>    def signal_hup(self, signum, frame):
>            """ Re-read the config file on SIGHUP """
>            self.logger.log('signal HUP detected, re-reading config
> file', 'DEBUG')
>            self.read_config()
>
> if __name__ == '__main__':
>    Hkd2 = Kmotion_Hkd2()
>    Hkd2.start_daemon()
>
>
>
> -- 
>
> Please avoid sending me Word or PowerPoint attachments.
> See http://www.gnu.org/philosophy/no-word-attachments.html
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



From hunter92383 at gmail.com  Sun Nov 25 18:30:00 2007
From: hunter92383 at gmail.com (elis aeris)
Date: Mon, 26 Nov 2007 01:30:00 +0800
Subject: [Tutor] use my own code
Message-ID: <674d5ce60711250930x6c99f79bw967100dc42a9e244@mail.gmail.com>

I have some .py files that have things I need to use,  sometimes it's the
functions and sometimes it's the whole .py (they have no functions)


how do I use them in my other .py codes?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071126/55e52092/attachment.htm 

From evert.rol at gmail.com  Sun Nov 25 18:42:31 2007
From: evert.rol at gmail.com (Evert Rol)
Date: Sun, 25 Nov 2007 17:42:31 +0000
Subject: [Tutor] use my own code
In-Reply-To: <674d5ce60711250930x6c99f79bw967100dc42a9e244@mail.gmail.com>
References: <674d5ce60711250930x6c99f79bw967100dc42a9e244@mail.gmail.com>
Message-ID: <B32F032D-1C50-40EA-A619-8575EF74966C@gmail.com>

> I have some .py files that have things I need to use,  sometimes  
> it's the functions and sometimes it's the whole .py (they have no  
> functions)
>
> how do I use them in my other .py codes?

Import them at the top of your other .py file(s):

import <yourfile>

(without the .py extension).
If they're in the current directory, you're fine. Otherwise you may  
need to set the PYTHONPATH variable.
See chapter 6 in the Python tutorial, especially section 6.1.1:  
http://docs.python.org/tut/node8.html#SECTION008110000000000000000

  Evert


From hunter92383 at gmail.com  Sun Nov 25 18:43:48 2007
From: hunter92383 at gmail.com (elis aeris)
Date: Mon, 26 Nov 2007 01:43:48 +0800
Subject: [Tutor] use my own code
In-Reply-To: <B32F032D-1C50-40EA-A619-8575EF74966C@gmail.com>
References: <674d5ce60711250930x6c99f79bw967100dc42a9e244@mail.gmail.com>
	<B32F032D-1C50-40EA-A619-8575EF74966C@gmail.com>
Message-ID: <674d5ce60711250943h143c2afdv914c7901cbe7f961@mail.gmail.com>

ok, i can import them.


how do I use them though?





On Nov 26, 2007 1:42 AM, Evert Rol <evert.rol at gmail.com> wrote:

> > I have some .py files that have things I need to use,  sometimes
> > it's the functions and sometimes it's the whole .py (they have no
> > functions)
> >
> > how do I use them in my other .py codes?
>
> Import them at the top of your other .py file(s):
>
> import <yourfile>
>
> (without the .py extension).
> If they're in the current directory, you're fine. Otherwise you may
> need to set the PYTHONPATH variable.
> See chapter 6 in the Python tutorial, especially section 6.1.1:
> http://docs.python.org/tut/node8.html#SECTION008110000000000000000
>
>  Evert
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071126/f2595698/attachment.htm 

From evert.rol at gmail.com  Sun Nov 25 18:49:40 2007
From: evert.rol at gmail.com (Evert Rol)
Date: Sun, 25 Nov 2007 17:49:40 +0000
Subject: [Tutor] use my own code
In-Reply-To: <674d5ce60711250943h143c2afdv914c7901cbe7f961@mail.gmail.com>
References: <674d5ce60711250930x6c99f79bw967100dc42a9e244@mail.gmail.com>
	<B32F032D-1C50-40EA-A619-8575EF74966C@gmail.com>
	<674d5ce60711250943h143c2afdv914c7901cbe7f961@mail.gmail.com>
Message-ID: <A212BE7E-FED6-43F7-89DF-7190BCAC418B@gmail.com>

> ok, i can import them.
>
> how do I use them though?

That's also in the tutorial; if there are variables (constants)  
instead of functions in your module, it works just the same.


> > I have some .py files that have things I need to use,  sometimes
> > it's the functions and sometimes it's the whole .py (they have no
> > functions)
> >
> > how do I use them in my other .py codes?
>
> Import them at the top of your other .py file(s):
>
> import <yourfile>
>
> (without the .py extension).
> If they're in the current directory, you're fine. Otherwise you may
> need to set the PYTHONPATH variable.
> See chapter 6 in the Python tutorial, especially section 6.1.1:
> http://docs.python.org/tut/node8.html#SECTION008110000000000000000
>
>  Evert
>
>


From hunter92383 at gmail.com  Sun Nov 25 18:57:27 2007
From: hunter92383 at gmail.com (elis aeris)
Date: Mon, 26 Nov 2007 01:57:27 +0800
Subject: [Tutor] pipeline - what is it and how do I use it?
Message-ID: <674d5ce60711250957w45a1518fydc82df2b1d93ff13@mail.gmail.com>

I need to keep a bit of python code ready to run at anytime, in the ram, but
this is what I need to do

I am using two languages at the same time, because python doesn't really
have any effective way of simulating keyboard and mouse events,

so I need to run auto it 3, and then call my python code to perform a little
bit of work, it only takes 0.1 seconds to run, but it takes almost a second
to start the code,
if i I can keep the code alive in the ram waiting for the cue, then it
should run fast enough.

but how do I pass information from one code to the other?

in fact - another language.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071126/4f81b4cb/attachment.htm 

From evert.rol at gmail.com  Sun Nov 25 19:38:11 2007
From: evert.rol at gmail.com (Evert Rol)
Date: Sun, 25 Nov 2007 18:38:11 +0000
Subject: [Tutor] pipeline - what is it and how do I use it?
In-Reply-To: <674d5ce60711250957w45a1518fydc82df2b1d93ff13@mail.gmail.com>
References: <674d5ce60711250957w45a1518fydc82df2b1d93ff13@mail.gmail.com>
Message-ID: <C48FC0F0-F290-4F29-91E1-4CCD6F26B15D@gmail.com>

> I need to keep a bit of python code ready to run at anytime, in the  
> ram, but this is what I need to do
>
> I am using two languages at the same time, because python doesn't  
> really have any effective way of simulating keyboard and mouse events,

Well, not the language itself, but there may be some library out  
there that has this functionality. But I guess it'll indeed be hard  
to find though.


> so I need to run auto it 3, and then call my python code to perform  
> a little bit of work, it only takes 0.1 seconds to run, but it  
> takes almost a second to start the code,
> if i I can keep the code alive in the ram waiting for the cue, then  
> it should run fast enough.
>
> but how do I pass information from one code to the other?
>
> in fact - another language.

It's the virtual machine you want to keep around in memory (together  
with the code), not so much the code itself.
The quickest thing I can think of right now is having a daemon  
program running, and communicate with it through signals or sockets.  
But that doesn't feel very (thread)safe.
Depending on your problem, you may want to go at it in another way.  
In fact, if speed is a concern, you may be better off writing your  
time essential code in C or something, and compile it to machine  
code. Less fun & easy than to code in Python probably.


btw: odd subject line, when relating it to the actual question ;-)


From hunter92383 at gmail.com  Sun Nov 25 19:40:06 2007
From: hunter92383 at gmail.com (elis aeris)
Date: Mon, 26 Nov 2007 02:40:06 +0800
Subject: [Tutor] pipeline - what is it and how do I use it?
In-Reply-To: <C48FC0F0-F290-4F29-91E1-4CCD6F26B15D@gmail.com>
References: <674d5ce60711250957w45a1518fydc82df2b1d93ff13@mail.gmail.com>
	<C48FC0F0-F290-4F29-91E1-4CCD6F26B15D@gmail.com>
Message-ID: <674d5ce60711251040n310d10f2m184441de5bb9fff3@mail.gmail.com>

thanks for the reply

On Nov 26, 2007 2:38 AM, Evert Rol <evert.rol at gmail.com> wrote:

> > I need to keep a bit of python code ready to run at anytime, in the
> > ram, but this is what I need to do
> >
> > I am using two languages at the same time, because python doesn't
> > really have any effective way of simulating keyboard and mouse events,
>
> Well, not the language itself, but there may be some library out
> there that has this functionality. But I guess it'll indeed be hard
> to find though.
>
>
> > so I need to run auto it 3, and then call my python code to perform
> > a little bit of work, it only takes 0.1 seconds to run, but it
> > takes almost a second to start the code,
> > if i I can keep the code alive in the ram waiting for the cue, then
> > it should run fast enough.
> >
> > but how do I pass information from one code to the other?
> >
> > in fact - another language.
>
> It's the virtual machine you want to keep around in memory (together
> with the code), not so much the code itself.
> The quickest thing I can think of right now is having a daemon
> program running, and communicate with it through signals or sockets.
> But that doesn't feel very (thread)safe.
> Depending on your problem, you may want to go at it in another way.
> In fact, if speed is a concern, you may be better off writing your
> time essential code in C or something, and compile it to machine
> code. Less fun & easy than to code in Python probably.
>
>
> btw: odd subject line, when relating it to the actual question ;-)
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071126/329bacdb/attachment.htm 

From bgailer at alum.rpi.edu  Sun Nov 25 19:41:45 2007
From: bgailer at alum.rpi.edu (bob gailer)
Date: Sun, 25 Nov 2007 13:41:45 -0500
Subject: [Tutor] pipeline - what is it and how do I use it?
In-Reply-To: <674d5ce60711250957w45a1518fydc82df2b1d93ff13@mail.gmail.com>
References: <674d5ce60711250957w45a1518fydc82df2b1d93ff13@mail.gmail.com>
Message-ID: <4749C1E9.4010100@alum.rpi.edu>

elis aeris wrote:
> I need to keep a bit of python code ready to run at anytime, in the 
> ram, but this is what I need to do
>
> I am using two languages at the same time, because python doesn't 
> really have any effective way of simulating keyboard and mouse events,
>
> so I need to run auto it 3, and then call my python code to perform a 
> little bit of work, it only takes 0.1 seconds to run, but it takes 
> almost a second to start the code,
> if i I can keep the code alive in the ram waiting for the cue, then it 
> should run fast enough.
>
> but how do I pass information from one code to the other?
See the signal and socket modules.

Also I sorta recall there are modules that enable Python to simulate 
keyboard and mouse events.

From hunter92383 at gmail.com  Sun Nov 25 19:42:36 2007
From: hunter92383 at gmail.com (elis aeris)
Date: Mon, 26 Nov 2007 02:42:36 +0800
Subject: [Tutor] pipeline - what is it and how do I use it?
In-Reply-To: <4749C1E9.4010100@alum.rpi.edu>
References: <674d5ce60711250957w45a1518fydc82df2b1d93ff13@mail.gmail.com>
	<4749C1E9.4010100@alum.rpi.edu>
Message-ID: <674d5ce60711251042v6bae74e6m7d93d6bd591160ff@mail.gmail.com>

any specific leads?
any ready code would rock

thankyou for responding

On Nov 26, 2007 2:41 AM, bob gailer <bgailer at alum.rpi.edu> wrote:

> elis aeris wrote:
> > I need to keep a bit of python code ready to run at anytime, in the
> > ram, but this is what I need to do
> >
> > I am using two languages at the same time, because python doesn't
> > really have any effective way of simulating keyboard and mouse events,
> >
> > so I need to run auto it 3, and then call my python code to perform a
> > little bit of work, it only takes 0.1 seconds to run, but it takes
> > almost a second to start the code,
> > if i I can keep the code alive in the ram waiting for the cue, then it
> > should run fast enough.
> >
> > but how do I pass information from one code to the other?
> See the signal and socket modules.
>
> Also I sorta recall there are modules that enable Python to simulate
> keyboard and mouse events.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071126/de1894a8/attachment-0001.htm 

From ricaraoz at gmail.com  Sun Nov 25 20:27:21 2007
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Sun, 25 Nov 2007 16:27:21 -0300
Subject: [Tutor] pipeline - what is it and how do I use it?
In-Reply-To: <674d5ce60711250957w45a1518fydc82df2b1d93ff13@mail.gmail.com>
References: <674d5ce60711250957w45a1518fydc82df2b1d93ff13@mail.gmail.com>
Message-ID: <4749CC99.6010205@bigfoot.com>

elis aeris wrote:
> I need to keep a bit of python code ready to run at anytime, in the ram,
> but this is what I need to do
> 
> I am using two languages at the same time, because python doesn't really
> have any effective way of simulating keyboard and mouse events,
> 

Check PyWinAuto, it might provide what you need.
You can find it at : http://www.openqa.org/pywinauto/

HTH

From bere6944 at blue.unco.edu  Sun Nov 25 19:59:16 2007
From: bere6944 at blue.unco.edu (Christina Margaret Berens)
Date: Sun, 25 Nov 2007 11:59:16 -0700
Subject: [Tutor] altering a list of lists
Message-ID: <709176e101.6e10170917@blue.unco.edu>

I am supposed to make a very simple gameboard where a person is to 
find the gold by moving up, down, left, or right.  I have most of the 
math worked out and am trying to place the person on the game board.  
We were to make a list of lists for the board, but to place the person 
or gold on the board, I have to change one of the spaces to a '+', but 
when I do it, it changes all the elements in that position in each 
list.

# set up of board
Board = [['- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 -']]
width = ['|']
for i in range(30):
    for j in range(1):
        width.append('  ')
width.append('|')

for i in range(30):
    Board.append(width)

Board.append(['- - - - - - - - - - - - - - - - - - - - - - - - - - - -
 - - -'])
for i in range(32):
    print ''.join(Board[i])

# changing '  ' to '+'
Board[2][3] = '+'

but when I print Board in IDLE, I get this
[['- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -'], 
['|', '  ', '  ', '+', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', 
'  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ',
 '  ', '  ', '  ', '  ', '  ', '  ', '  ', '|'], 
['|', '  ', '  ', '+', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', 
'  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ',
 '  ', '  ', '  ', '  ', '  ', '  ', '  ', '|'], 
['|', '  ', '  ', '+', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', 
'  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ',
 '  ', '  ', '  ', '  ', '  ', '  ', '  ', '|'], 
['|', '  ', '  ', '+', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', 
'  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ',
 '  ', '  ', '  ', '  ', '  ', '  ', '  ', '|'], 
['|', '  ', '  ', '+', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', 
'  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ',
 '  ', '  ', '  ', '  ', '  ', '  ', '  ', '|'], 
['|', '  ', '  ', '+', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', 
'  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ',
 '  ', '  ', '  ', '  ', '  ', '  ', '  ', '|'], 
['|', '  ', '  ', '+', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', 
'  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ',
 '  ', '  ', '  ', '  ', '  ', '  ', '  ', '|'], 
['|', '  ', '  ', '+', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', 
'  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ',
 '  ', '  ', '  ', '  ', '  ', '  ', '  ', '|'], 
['|', '  ', '  ', '+', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', 
'  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ',
 '  ', '  ', '  ', '  ', '  ', '  ', '  ', '|'], 
['|', '  ', '  ', '+', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', 
'  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ',
 '  ', '  ', '  ', '  ', '  ', '  ', '  ', '|'], 
['|', '  ', '  ', '+', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', 
'  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ',
 '  ', '  ', '  ', '  ', '  ', '  ', '  ', '|'], 
['|', '  ', '  ', '+', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', 
'  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ',
 '  ', '  ', '  ', '  ', '  ', '  ', '  ', '|'], 
['|', '  ', '  ', '+', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', 
'  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ',
 '  ', '  ', '  ', '  ', '  ', '  ', '  ', '|'], 
['|', '  ', '  ', '+', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', 
'  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ',
 '  ', '  ', '  ', '  ', '  ', '  ', '  ', '|'], 
['|', '  ', '  ', '+', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', 
'  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ',
 '  ', '  ', '  ', '  ', '  ', '  ', '  ', '|'], 
['|', '  ', '  ', '+', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', 
'  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ',
 '  ', '  ', '  ', '  ', '  ', '  ', '  ', '|'], 
['|', '  ', '  ', '+', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', 
'  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ',
 '  ', '  ', '  ', '  ', '  ', '  ', '  ', '|'], 
['|', '  ', '  ', '+', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', 
'  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ',
 '  ', '  ', '  ', '  ', '  ', '  ', '  ', '|'], 
['|', '  ', '  ', '+', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', 
'  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ',
 '  ', '  ', '  ', '  ', '  ', '  ', '  ', '|'], 
['|', '  ', '  ', '+', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', 
'  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ',
 '  ', '  ', '  ', '  ', '  ', '  ', '  ', '|'], 
['|', '  ', '  ', '+', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', 
'  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ',
 '  ', '  ', '  ', '  ', '  ', '  ', '  ', '|'], 
['|', '  ', '  ', '+', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', 
'  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ',
 '  ', '  ', '  ', '  ', '  ', '  ', '  ', '|'], 
['|', '  ', '  ', '+', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', 
'  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ',
 '  ', '  ', '  ', '  ', '  ', '  ', '  ', '|'], 
['|', '  ', '  ', '+', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', 
'  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ',
 '  ', '  ', '  ', '  ', '  ', '  ', '  ', '|'], 
['|', '  ', '  ', '+', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', 
'  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ',
 '  ', '  ', '  ', '  ', '  ', '  ', '  ', '|'], 
['|', '  ', '  ', '+', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', 
'  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ',
 '  ', '  ', '  ', '  ', '  ', '  ', '  ', '|'], 
['|', '  ', '  ', '+', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', 
'  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ',
 '  ', '  ', '  ', '  ', '  ', '  ', '  ', '|'], 
['|', '  ', '  ', '+', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', 
'  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ',
 '  ', '  ', '  ', '  ', '  ', '  ', '  ', '|'], 
['|', '  ', '  ', '+', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', 
'  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ',
 '  ', '  ', '  ', '  ', '  ', '  ', '  ', '|'], 
['|', '  ', '  ', '+', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', 
'  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ',
 '  ', '  ', '  ', '  ', '  ', '  ', '  ', '|'], ['- - - - - - - - - -
 - - - - - - - - - - - - - - - - - - - - -']]

From john at fouhy.net  Sun Nov 25 23:02:21 2007
From: john at fouhy.net (John Fouhy)
Date: Mon, 26 Nov 2007 11:02:21 +1300
Subject: [Tutor] altering a list of lists
In-Reply-To: <709176e101.6e10170917@blue.unco.edu>
References: <709176e101.6e10170917@blue.unco.edu>
Message-ID: <5e58f2e40711251402v1b89e7b4gafae95a20e5f918e@mail.gmail.com>

On 26/11/2007, Christina Margaret Berens <bere6944 at blue.unco.edu> wrote:
> I am supposed to make a very simple gameboard where a person is to
> find the gold by moving up, down, left, or right.  I have most of the
> math worked out and am trying to place the person on the game board.
> We were to make a list of lists for the board, but to place the person
> or gold on the board, I have to change one of the spaces to a '+', but
> when I do it, it changes all the elements in that position in each
> list.
[...]

Here is something for you to try:

>>> x = [3]
>>> y = [x, x, x]
>>> print y
>>> y[1].append(2)
>>> print y
>>> print x

Does anything you see here surprise you?  Can you explain what is going on?

-- 
John.

From ricaraoz at gmail.com  Mon Nov 26 00:54:37 2007
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Sun, 25 Nov 2007 20:54:37 -0300
Subject: [Tutor] altering a list of lists
In-Reply-To: <709176e101.6e10170917@blue.unco.edu>
References: <709176e101.6e10170917@blue.unco.edu>
Message-ID: <474A0B3D.30208@bigfoot.com>

Christina Margaret Berens wrote:
> I am supposed to make a very simple gameboard where a person is to 
> find the gold by moving up, down, left, or right.  I have most of the 
> math worked out and am trying to place the person on the game board.  
> We were to make a list of lists for the board, but to place the person 
> or gold on the board, I have to change one of the spaces to a '+', but 
> when I do it, it changes all the elements in that position in each 
> list.
> 
> # set up of board
> Board = [['- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
>  -']]
> width = ['|']
> for i in range(30):
>     for j in range(1):
>         width.append('  ')
> width.append('|')
> 

width here is only ONE object

> for i in range(30):
>     Board.append(width)

Here all your lines are the same object (not copies).
It will work ok if you do :
for i in range(30):
    Board.append(width[:])
                 here ^^^ you are assigning a COPY of width

Or you might check :

Board = [['- ' * 30 + '-']]
for line in xrange(30):
    Board.append(['|']+[' ' for i in xrange(59)] + ['|'])
Board.append(['- ' * 30 + '-'])
Board[2][3] = '+'
for i in range(32):
    print ''.join(Board[i])

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|                                                           |
|  +                                                        |
|                                                           |
|                                                           |
|                                                           |
|                                                           |
|                                                           |
|                                                           |
|                                                           |
|                                                           |
|                                                           |
|                                                           |
|                                                           |
|                                                           |
|                                                           |
|                                                           |
|                                                           |
|                                                           |
|                                                           |
|                                                           |
|                                                           |
|                                                           |
|                                                           |
|                                                           |
|                                                           |
|                                                           |
|                                                           |
|                                                           |
|                                                           |
|                                                           |
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

From mobiledreamers at gmail.com  Mon Nov 26 01:08:16 2007
From: mobiledreamers at gmail.com (mobiledreamers at gmail.com)
Date: Sun, 25 Nov 2007 16:08:16 -0800
Subject: [Tutor] image rendering in python
Message-ID: <c1870d60711251608y59762c7fu676e7a162667ed08@mail.gmail.com>

http://cdnll.i.imagechef.com/ic/templimg2/Shaved%20Head.jpg
Do u know how to make such images using PIL

or other tools in python
thanks a lot for your kind help
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071125/b17a438e/attachment.htm 

From alan.gauld at btinternet.com  Mon Nov 26 01:15:36 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 26 Nov 2007 00:15:36 -0000
Subject: [Tutor] use my own code
References: <674d5ce60711250930x6c99f79bw967100dc42a9e244@mail.gmail.com><B32F032D-1C50-40EA-A619-8575EF74966C@gmail.com>
	<674d5ce60711250943h143c2afdv914c7901cbe7f961@mail.gmail.com>
Message-ID: <fid37a$44c$1@ger.gmane.org>


"elis aeris" <hunter92383 at gmail.com> wrote 

> ok, i can import them.
> 
> how do I use them though?

When you import the module the code is executed. 
If you have executable code rather than function or 
class definitions then it will be executed (print 
statements etc). Thats why its always good practice 
to wrap stuff in functions and then use an

if __name__ == "__main__":
    main()

Type construct to execute it, it makres reuse later 
much easier.

But to access the functions and variables you just 
call them with the module prefix as usual

import sys, mymodule

mymodule.doSomething()
sys.exit()

See? exactly the same as you would use sys...

There's a lot more on this in the Modules and Functions 
topic in my tutorial.

-- 
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 Nov 26 01:23:40 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 26 Nov 2007 00:23:40 -0000
Subject: [Tutor] pipeline - what is it and how do I use it?
References: <674d5ce60711250957w45a1518fydc82df2b1d93ff13@mail.gmail.com>
Message-ID: <fid3mf$54q$1@ger.gmane.org>

"elis aeris" <hunter92383 at gmail.com> wrote

>I need to keep a bit of python code ready to run at anytime, in the 
>ram, but
> this is what I need to do
>
> I am using two languages at the same time, because python doesn't 
> really
> have any effective way of simulating keyboard and mouse events,

This depends a lot on what the other language offers in the way of
inter-process communications. If it can send signals then a simple
signal and file sharing scheme may work. Or if it can use sockets
you can very simply get the two processes communicating.

If it can do http calls to a web server you could run your python
code under a simple web server and use that.

There are lots of options but it depernds on what your other language
can do, it might be easier to endure the pain of using Python to read
the keyboard and events, depending on how complex the events are,
but I agree its not the easiest thing to do.

It might even be easier to get the other language to do what Python
does?! But again it depends on how powerful that language is.

> so I need to run auto it 3,

Never heard of it so can't comment on specifics.

> if i I can keep the code alive in the ram waiting for the cue, then 
> it
> should run fast enough.

Keeping a process running in memory is not difficult. Assuming you
are on Windows google for Windows Services. But you could just
keep a user app running iconified if you prefer.

> but how do I pass information from one code to the other?

As above,. there are lots of ways from sharing a file or database
table through to inter process calls via sockets or web services.

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 Nov 26 01:25:53 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 26 Nov 2007 00:25:53 -0000
Subject: [Tutor] pipeline - what is it and how do I use it?
References: <674d5ce60711250957w45a1518fydc82df2b1d93ff13@mail.gmail.com>
	<4749CC99.6010205@bigfoot.com>
Message-ID: <fid3qk$5dt$1@ger.gmane.org>


"Ricardo Ar?oz" <ricaraoz at gmail.com> wrote

>
> Check PyWinAuto, it might provide what you need.
> You can find it at : http://www.openqa.org/pywinauto/
>

Nice link thanks, I've not seen that before.

Using ctypes/winall and PostMessage is not friendly.

Alan G. 



From alan.gauld at btinternet.com  Mon Nov 26 01:29:59 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 26 Nov 2007 00:29:59 -0000
Subject: [Tutor] altering a list of lists
References: <709176e101.6e10170917@blue.unco.edu>
Message-ID: <fid42a$5u8$1@ger.gmane.org>


"Christina Margaret Berens" <bere6944 at blue.unco.edu> wrote

> or gold on the board, I have to change one of the spaces to a '+', 
> but
> when I do it, it changes all the elements in that position in each
> list.

This is a classic sign that you have 5reated your nested list
by using the same list instead of copying it...


> # set up of board
> Board = 
> [['- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
> -']]
> width = ['|']
> for i in range(30):
>    for j in range(1):
>        width.append('  ')
> width.append('|')
>
> for i in range(30):
>    Board.append(width)

And here it is, you just assin the same sublist for eah row,
you need to create a new copy for each one.

We can do that with slicing, thus:

    Board.append(width[:])

Which should fix the problem.


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



From orsenthil at gmail.com  Mon Nov 26 01:47:28 2007
From: orsenthil at gmail.com (O.R.Senthil Kumaran)
Date: Mon, 26 Nov 2007 06:17:28 +0530
Subject: [Tutor] pipeline - what is it and how do I use it?
In-Reply-To: <4749CC99.6010205@bigfoot.com>
References: <674d5ce60711250957w45a1518fydc82df2b1d93ff13@mail.gmail.com>
	<4749CC99.6010205@bigfoot.com>
Message-ID: <20071126004728.GA3454@gmail.com>

> elis aeris wrote:
> > I need to keep a bit of python code ready to run at anytime, in the ram,
> > but this is what I need to do
> > 
> > I am using two languages at the same time, because python doesn't really
> > have any effective way of simulating keyboard and mouse events,
> > 
> 
> Check PyWinAuto, it might provide what you need.
> You can find it at : http://www.openqa.org/pywinauto/
> 

Sendkeys module can also be used for the same purpose. Unlike pywinauto, which is for a simulation of actions, sendkeys as the name suggests would just send the keystrokes to the application.

http://www.rutherfurd.net/python/sendkeys/


-- 
O.R.Senthil Kumaran
http://uthcode.sarovar.org

From mlangford.cs03 at gtalumni.org  Mon Nov 26 02:29:09 2007
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Sun, 25 Nov 2007 20:29:09 -0500
Subject: [Tutor] pipeline - what is it and how do I use it?
In-Reply-To: <674d5ce60711250957w45a1518fydc82df2b1d93ff13@mail.gmail.com>
References: <674d5ce60711250957w45a1518fydc82df2b1d93ff13@mail.gmail.com>
Message-ID: <82b4f5810711251729m1b1eaad9t5f5fb423deaffedf@mail.gmail.com>

On 11/25/07, elis aeris <hunter92383 at gmail.com> wrote:
> I need to keep a bit of python code ready to run at anytime, in the ram, but
> this is what I need to do

You have several options. You can use sockets to talk to a local
program that has opened a server port. You can batch out commands to a
file. You can directly call most likely from whatever other language
you're using. You can do what I have below.

> I am using two languages at the same time, because python doesn't really
> have any effective way of simulating keyboard and mouse events,

I'm sure it does. I think you're talking about...watsup and
dogtail....http://www.tizmoi.net/watsup/intro.html does it for windows
and http://www.redhat.com/magazine/020jun06/features/dogtail/ does it
for GTK apps. There are surely more for other windowing systems. If
you mentioned what windowing system you were on, we could possibly
help

> but how do I pass information from one code to the other?

If you insist on passing it back and forth, you can either write it
out over the network using the python sockets api and whatever the
other language can do with networking can read it in (or vice versa).

Otherwise, you can write out the data to a file and use that as the
medium between the languages. You can use a scheme such as the
following:

##Shell Script to run your foo program
Foo.sh > /tmp/data1
echo /tmp/data1 > /var/jobs

##Python program (which I've not run, but should work)
while not os.path.isfile("/var/jobs"):
      datafile = file("/var/jobs")
      map(myFileProcessingFunc,datafile.readlines())
      datafile.close()
      os.remove("/var/jobs")

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

From tpc247 at gmail.com  Mon Nov 26 02:56:04 2007
From: tpc247 at gmail.com (tpc247 at gmail.com)
Date: Sun, 25 Nov 2007 17:56:04 -0800
Subject: [Tutor] adding a new folder to Python's importable modules search
	path
Message-ID: <bae1efdf0711251756m56c40b55rdef81f131ba7ad9@mail.gmail.com>

Dear fellow Python enthusiasts,

I trust your Thanksgiving holiday has been a relaxing one.  A quick question
for you: I have a script that attempts to import my_module from a folder
that is not in Python's importable modules search path.  In my script, that
I run from the command line, I have the following lines:

import os
import sys

PATH_TO_MODULE = os.path.join('path', 'to', 'my', 'module')
sys.append(PATH_TO_MODULE)

import my_module

When I attempt to run the script, I get the following error message:

ImportError: No module named my_module

In Python IDLE when I perform the aforementioned steps in the order
indicated I can import my_module successfully.  My assumption is Python's
importable modules search path is in sys.path.  In both cases I identify the
path to the folder containing my module, I append said path to sys.path, and
when I attempt to import my_module by either running from the command line
or in IDLE, I get different behavior.  I read the information here again:

http://docs.python.org/tut/node8.html

so I believe I am doing everything correctly.  Am I doing something wrong ?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071125/4a255c9d/attachment.htm 

From rdm at rcblue.com  Mon Nov 26 03:53:30 2007
From: rdm at rcblue.com (Dick Moores)
Date: Sun, 25 Nov 2007 18:53:30 -0800
Subject: [Tutor] Caching for speed
Message-ID: <20071126025334.A9A0C1E4005@bag.python.org>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071125/ba313b11/attachment.htm 

From kent37 at tds.net  Mon Nov 26 04:09:44 2007
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 25 Nov 2007 22:09:44 -0500
Subject: [Tutor] adding a new folder to Python's importable modules
 search path
In-Reply-To: <bae1efdf0711251756m56c40b55rdef81f131ba7ad9@mail.gmail.com>
References: <bae1efdf0711251756m56c40b55rdef81f131ba7ad9@mail.gmail.com>
Message-ID: <474A38F8.2000909@tds.net>

tpc247 at gmail.com wrote:
> Dear fellow Python enthusiasts,
> 
> I trust your Thanksgiving holiday has been a relaxing one.  A quick 
> question for you: I have a script that attempts to import my_module from 
> a folder that is not in Python's importable modules search path.  In my 
> script, that I run from the command line, I have the following lines:
> 
> import os
> import sys
> 
> PATH_TO_MODULE = os.path.join('path', 'to', 'my', 'module')
> sys.append(PATH_TO_MODULE)

Should be sys.path.append(...)

Kent

> 
> import my_module
> 
> When I attempt to run the script, I get the following error message:
> 
> ImportError: No module named my_module
> 
> In Python IDLE when I perform the aforementioned steps in the order 
> indicated I can import my_module successfully.  My assumption is 
> Python's importable modules search path is in sys.path.  In both cases I 
> identify the path to the folder containing my module, I append said path 
> to sys.path, and when I attempt to import my_module by either running 
> from the command line or in IDLE, I get different behavior.  I read the 
> information here again:
> 
> http://docs.python.org/tut/node8.html
> 
> so I believe I am doing everything correctly.  Am I doing something wrong ?
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


From tpc247 at gmail.com  Mon Nov 26 06:00:24 2007
From: tpc247 at gmail.com (tpc247 at gmail.com)
Date: Sun, 25 Nov 2007 21:00:24 -0800
Subject: [Tutor] adding a new folder to Python's importable modules
	search path
In-Reply-To: <474A38F8.2000909@tds.net>
References: <bae1efdf0711251756m56c40b55rdef81f131ba7ad9@mail.gmail.com>
	<474A38F8.2000909@tds.net>
Message-ID: <bae1efdf0711252100o44090255iaaa979af524d2ff6@mail.gmail.com>

On 11/25/07, Kent Johnson <kent37 at tds.net> wrote:
>
>
>
> Should be sys.path.append(...)
>
> Kent



yes, I'm sorry, in my posting I did have a  typographical error, but my code
has the following seemingly correct lines:

            sys.path.append(PATH_TO_MODULE)
            print "Path added: ", PATH_TO_MODULE

so when I run my script from the command line, the folder does seem to be
added to Python's importable modules search path.  When I attempt to import
my_module I get the error:

ImportError: No module named my_module
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071125/9c5bd14e/attachment.htm 

From jeff at drinktomi.com  Mon Nov 26 08:14:47 2007
From: jeff at drinktomi.com (Jeff Younker)
Date: Sun, 25 Nov 2007 23:14:47 -0800
Subject: [Tutor] adding a new folder to Python's importable modules
	search path
In-Reply-To: <bae1efdf0711252100o44090255iaaa979af524d2ff6@mail.gmail.com>
References: <bae1efdf0711251756m56c40b55rdef81f131ba7ad9@mail.gmail.com>
	<474A38F8.2000909@tds.net>
	<bae1efdf0711252100o44090255iaaa979af524d2ff6@mail.gmail.com>
Message-ID: <37B6A238-3D68-4F31-B958-1E4384F28130@drinktomi.com>


> so when I run my script from the command line, the folder does seem  
> to be added to Python's importable modules search path.  When I  
> attempt to import my_module I get the error:
>
> ImportError: No module named my_module

Do your module directories have an __init__.py file
in them?

- Jeff Younker - jeff at drinktomi.com -


On Nov 25, 2007, at 9:00 PM, tpc247 at gmail.com wrote:


From alan.gauld at btinternet.com  Mon Nov 26 09:39:00 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 26 Nov 2007 08:39:00 -0000
Subject: [Tutor] Caching for speed
References: <20071126025334.A9A0C1E4005@bag.python.org>
Message-ID: <fie0n7$2vp$1@ger.gmane.org>

Dick,

While the speed up due to caching is interesting I'm not sure
what your code is supposed to be doing but it looks to me
like you are effectively doing this:

from mpmath import pi
# long pause
print pi

Which will be faster than 0.1 seconds I suspect!
Or am I missing something?

Alan G.



"Dick Moores" <rdm at rcblue.com> wrote in message 
news:20071126025334.A9A0C1E4005 at bag.python.org...
> Caching for speed is a concept brand new to me, and there's a 
> remarkable example in a thread on the python-list. I thought some 
> readers of this list might find it instructive. However, to run the 
> scripts you'll need mpmath. < http://code.google.com/p/mpmath/>
>
> Begin by jumping in toward the end of the thread:
>
> < 
> http://mail.python.org/pipermail/python-list/2007-November/466662.html >
>
> Note Fredrik Johansson's function f() that he suggests could greatly 
> speed up my demo of the amazing Chudnovsky algorithm for pi, at < 
> http://python.pastebin.com/f4410f3dc>.
>
> I didn't understand what to do with it, so I ask, < 
> http://mail.python.org/pipermail/python-list/2007-November/467148.html 
>  >. But see the revision I did make, < 
> http://py77.python.pastebin.com/f48e4151c>
>
> And his revision of that, < 
> http://py77.python.pastebin.com/m6b2b34b7>.
>
> As for the speed-up on my computer due to the caching done by f(): < 
> http://py77.python.pastebin.com/f48e4151c> takes 151 secs for 2000 
> digits of pi; < http://py77.python.pastebin.com/m6b2b34b7> takes 0.4 
> secs!
>
> Dick Moores
>


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


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



From tuiagcs at hotmail.com  Mon Nov 26 09:30:54 2007
From: tuiagcs at hotmail.com (anuchit thiam-uan)
Date: Mon, 26 Nov 2007 08:30:54 +0000
Subject: [Tutor] Can I create 3D game with python ?
Message-ID: <BLU111-W878E74ACE0A59D23E4799B1750@phx.gbl>


I interested in 3D game programming and I want to create my own some kind of it.But I'm Just Beginner of Python,please give me some idea 
thank you
????????????????????????? ? ??????? ???????????????...
_________________________________________________________________
??????????????????????????????????????????????????????? Photo Gallery
http://www.get.live.com/wl/all
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071126/f9e0f68a/attachment.htm 

From alan.gauld at btinternet.com  Mon Nov 26 10:05:07 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 26 Nov 2007 09:05:07 -0000
Subject: [Tutor] Tkinter Grid Layout Problems
References: <4E1444C8-8509-452B-924B-E40A7C45C077@gmail.com>
Message-ID: <fie286$7kr$1@ger.gmane.org>


"Johnston Jiaa" <oclbdk at gmail.com> wrote

> I'm trying to get the left part of a window to look like this:
> http://img.photobucket.com/albums/v228/gaypig123ABC/PB240055.jpg
>
> I tried using sticky's, but nothing seems to work correctly.
>
I did it this way:
#####################
from Tkinter import *

listItems = """first second third
               fourth fifth sixth
               seventh eighth ninth
               tenth eleventh twelth""".split()

class App:
   def __init__(self, parent):
      self.lt_lbl = Label(parent, text="Left label")
      self.lt_lbl.grid(row=0, column=0)
      self.lt_add_btn = Button(parent, text="Left add button")
      self.lt_add_btn.grid(row=0, column=1)
      self.lt_rem_btn = Button(parent, text="Left remove button")
      self.lt_rem_btn.grid(row=0, column=2)

      scrollList = Frame(parent)
      self.lt_lstbx = Listbox(scrollList)
      self.lt_lstbx.pack(side=LEFT)
      self.lt_scrlbr = Scrollbar(scrollList)
      self.lt_scrlbr.pack(side=RIGHT, fill="y" )
      scrollList.grid(row=1, column=0)

      for item in listItems:
         self.lt_lstbx.insert(END,item)

tk = Tk()
app = App(tk)
tk.mainloop()

Note that I created a frame to hold both list box and scrollbar and 
used
the packer to put them together.

> How do I get everything aligned properly?

However I would personally use the packer rather than the grid for the
whole GUI.
I'd create a frame for your buttons and label and pack them with
the label on the left and buttons on the right, then another frame
for the scrolled list as above then simply pack the two frames into
the root window.

YMMV,

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



From rabidpoobear at gmail.com  Mon Nov 26 10:35:26 2007
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 26 Nov 2007 03:35:26 -0600
Subject: [Tutor] Can I create 3D game with python ?
In-Reply-To: <BLU111-W878E74ACE0A59D23E4799B1750@phx.gbl>
References: <BLU111-W878E74ACE0A59D23E4799B1750@phx.gbl>
Message-ID: <474A935E.6000908@gmail.com>

anuchit thiam-uan wrote:
>
> I interested in 3D game programming and I want to create my own some 
> kind of it.But I'm Just Beginner of Python,please give me some idea
> thank you
Yes, you can.  It'll be hard to do in Python with just the standard library.
Luckily there are a few other (3rd-party) libraries already made that 
you can use.
Depending on how low-level you want to get, here are the libraries I've 
heard of,
in roughly the order of lowest to highest level.

Pyglet
Pygame + OpenGL
Soya
Panda3D
Blender
Alice

Those are the only 3d libraries I am aware of.  There are many more 2d 
libraries than that, and I suspect the same is true of 3D libraries..
Just ask Google for more information about each of these.
Feel free to ask us more questions, but if they're specific to a certain 
external library, you may not get the same caliber of response as you 
would if you asked on a message board specifically designed for that 
library.  For example, asking on pygame-users at seul.org is a good idea 
for pygame-related questions.
Hope that helps,
-Luke

From bhaaluu at gmail.com  Mon Nov 26 11:18:43 2007
From: bhaaluu at gmail.com (bhaaluu)
Date: Mon, 26 Nov 2007 05:18:43 -0500
Subject: [Tutor] Can I create 3D game with python ?
In-Reply-To: <BLU111-W878E74ACE0A59D23E4799B1750@phx.gbl>
References: <BLU111-W878E74ACE0A59D23E4799B1750@phx.gbl>
Message-ID: <ea979d70711260218o1c48cdf7lc139b84a4bfbbbfb@mail.gmail.com>

Sawatdee,
Look at these books which are all Python game programming books:

1*) Easiest book for beginners just learning Python. Start here.
Python Programming for the Absolute Beginner, Second Edition.
Michael Dawson. ISBN-13: 978-1598631128

2*) Next step, learn Python PyGame 2D game programming.
Game Programming, The L Line, The Express Line to Learning.
Andy Harris. ISBN-13: 978-0470068229

3*) Now you're totally prepared to learn how to write 3D games in Python!
Beginning Game Development with Python and Pygame: From Novice to
Professional. Will McGugan. ISBN-13: 978-1590598726

*1) This book takes you from the most fundamental Python concepts
    through learning classes/OOP while programming simple text-based
    games. The last couple of games are graphical, using the LiveWires
    pygame wrapper.

*2) This book is about 2D game programming with Python and Pygame.
    The book shows you how to create your own graphics, using GIMP, a
    free graphical image manipulation program; your own sound FX, using
    Audacity, a free music editor; and do all the things you need to do to
    create a 2D arcade-style game using Python and the PyGame module.

*3) This book covers 3D game programming with Python, PyGame, and the
    author's free GameObjects module. There are a couple of free chapters
    to download here: http://www.willmcgugan.com/category/tech/python/page/2/
    The GameObjects module is here: http://code.google.com/p/gameobjects/
    and the TOC:
ttp://www.willmcgugan.com/2007/10/07/table-of-contents-for-pygame-book/
    There's a lot of other stuff on McGugan's blog, so take a look.

You can also check out http://www.pygame.org/ for more pygame info.
-- 
b h a a l u u at g m a i l dot c o m


On Nov 26, 2007 3:30 AM, anuchit thiam-uan <tuiagcs at hotmail.com> wrote:
>
>
> I interested in 3D game programming and I want to create my own some kind of
> it.But I'm Just Beginner of Python,please give me some idea
>  thank you
>  ????????????????????????? ? ??????? ???????????????...
>
> ________________________________
> ???????????????????????????? Window Live services! ???????????
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>

From rdm at rcblue.com  Mon Nov 26 11:22:26 2007
From: rdm at rcblue.com (Dick Moores)
Date: Mon, 26 Nov 2007 02:22:26 -0800
Subject: [Tutor] Caching for speed
In-Reply-To: <fie0n7$2vp$1@ger.gmane.org>
References: <20071126025334.A9A0C1E4005@bag.python.org>
	<fie0n7$2vp$1@ger.gmane.org>
Message-ID: <20071126102232.BDAD41E4006@bag.python.org>

At 12:39 AM 11/26/2007, Alan Gauld wrote:
>Dick,
>
>While the speed up due to caching is interesting I'm not sure
>what your code is supposed to be doing but it looks to me
>like you are effectively doing this:
>
>from mpmath import pi
># long pause
>print pi
>
>Which will be faster than 0.1 seconds I suspect!
>Or am I missing something?
>
>Alan G.

I should have explained that "print pi" line.
Using <http://py77.python.pastebin.com/m6b2b34b7>, here's the output 
for precision = 100:

=================================================
Enter a positive integer to set precision: 100
The result calculated from the first 8 terms of the series is:
3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068

pi to 100 digits is:
3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068
Time was 0 seconds
===================================================

The "print pi" line (line 42) is there to confirm to the user that 
the algorithm in fact does compute pi to the requested precision 
(i.e., number of digits). Remember, I wrote the script as a demo of 
the Chudnovsky algorithm for pi.

Dick



From dkuhlman at rexx.com  Mon Nov 26 17:15:47 2007
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Mon, 26 Nov 2007 08:15:47 -0800
Subject: [Tutor] adding a new folder to Python's importable modules
	search path
In-Reply-To: <37B6A238-3D68-4F31-B958-1E4384F28130@drinktomi.com>
References: <bae1efdf0711251756m56c40b55rdef81f131ba7ad9@mail.gmail.com>
	<474A38F8.2000909@tds.net>
	<bae1efdf0711252100o44090255iaaa979af524d2ff6@mail.gmail.com>
	<37B6A238-3D68-4F31-B958-1E4384F28130@drinktomi.com>
Message-ID: <20071126161547.GA1806@cutter.rexx.com>

On Sun, Nov 25, 2007 at 11:14:47PM -0800, Jeff Younker wrote:
> 
> > so when I run my script from the command line, the folder does seem  
> > to be added to Python's importable modules search path.  When I  
> > attempt to import my_module I get the error:
> >
> > ImportError: No module named my_module
> 
> Do your module directories have an __init__.py file
> in them?

Actually, you do not need an __init__.py file in directories that
are immediately in sys.path.  You *do* need that __init__.py file
in sub-directories (which you access via dot notation).  See:

    http://docs.python.org/ref/import.html  (and search for __init__)

Dave

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

From tpc247 at gmail.com  Mon Nov 26 23:17:07 2007
From: tpc247 at gmail.com (tpc247 at gmail.com)
Date: Mon, 26 Nov 2007 14:17:07 -0800
Subject: [Tutor] adding a new folder to Python's importable modules
	search path
In-Reply-To: <20071126161547.GA1806@cutter.rexx.com>
References: <bae1efdf0711251756m56c40b55rdef81f131ba7ad9@mail.gmail.com>
	<474A38F8.2000909@tds.net>
	<bae1efdf0711252100o44090255iaaa979af524d2ff6@mail.gmail.com>
	<37B6A238-3D68-4F31-B958-1E4384F28130@drinktomi.com>
	<20071126161547.GA1806@cutter.rexx.com>
Message-ID: <bae1efdf0711261417x1dbdce7dgcc3b916cf6aa22af@mail.gmail.com>

hey guys, thanks a lot for your insight (or lack thereof) which convinced me
to try further investigation on what I might have left out.  One significant
point of correction: for purposes of simplification, I neglected to include
for your review the fact that when I attempted to add my path to Python's
importable modules search path, I did the following:

<paste>
import os
import sys

folder_1 = os.path.join('x', 'y', 'z', 'w', 's')
folder_2 = os.path.join('x', 'y', 'z', 't', 'm', 'n', 'a', 'b', 'c', 'd')
folders = [folder_1, folder_2]

for a_path in folders:
    sys.path.append(os.path.join("F://", a_path) + os.sep)

import My_Module

ImportError: No module named TableParse

sys.path.append(os.path.join("F://", folder_1) + os.sep)
sys.path.append(os.path.join("F://", folder_2) + os.sep)

import My_Module

ImportError: No module named TableParse
</paste>

apparently the interpreter does not like the os.sep at the end of the search
path.  Once I removed it, everything was gravy.

On 11/26/07, Dave Kuhlman <dkuhlman at rexx.com> wrote:
>
> On Sun, Nov 25, 2007 at 11:14:47PM -0800, Jeff Younker wrote:
> >
> > > so when I run my script from the command line, the folder does seem
> > > to be added to Python's importable modules search path.  When I
> > > attempt to import my_module I get the error:
> > >
> > > ImportError: No module named my_module
> >
> > Do your module directories have an __init__.py file
> > in them?
>
> Actually, you do not need an __init__.py file in directories that
> are immediately in sys.path.  You *do* need that __init__.py file
> in sub-directories (which you access via dot notation).  See:
>
>     http://docs.python.org/ref/import.html  (and search for __init__)
>
> Dave
>
> --
> Dave Kuhlman
> http://www.rexx.com/~dkuhlman
> _______________________________________________
> 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/20071126/c5dcac93/attachment.htm 

From tpc247 at gmail.com  Mon Nov 26 23:18:55 2007
From: tpc247 at gmail.com (tpc247 at gmail.com)
Date: Mon, 26 Nov 2007 14:18:55 -0800
Subject: [Tutor] adding a new folder to Python's importable modules
	search path
In-Reply-To: <bae1efdf0711261417x1dbdce7dgcc3b916cf6aa22af@mail.gmail.com>
References: <bae1efdf0711251756m56c40b55rdef81f131ba7ad9@mail.gmail.com>
	<474A38F8.2000909@tds.net>
	<bae1efdf0711252100o44090255iaaa979af524d2ff6@mail.gmail.com>
	<37B6A238-3D68-4F31-B958-1E4384F28130@drinktomi.com>
	<20071126161547.GA1806@cutter.rexx.com>
	<bae1efdf0711261417x1dbdce7dgcc3b916cf6aa22af@mail.gmail.com>
Message-ID: <bae1efdf0711261418hd59c22nca12ef8f4216feff@mail.gmail.com>

and for purposes of continuity TableParse should be replaced with My_Module
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071126/429bd6a9/attachment.htm 

From timmichelsen at gmx-topmail.de  Tue Nov 27 01:24:08 2007
From: timmichelsen at gmx-topmail.de (Tim Michelsen)
Date: Tue, 27 Nov 2007 01:24:08 +0100
Subject: [Tutor] detecting a change in a iterable object (list, array, etc.)
Message-ID: <fifo3d$6no$1@ger.gmane.org>

Hello,
would like to ask for your help on the following issue:
What procedure can I use to detect if there's a change when iterating 
over a list?

For instance if I want to extract the years 1997 and 1998 from the table 
below and save them into separate files?
How do I build the average only on the 1997-year values?
Or how do find out that there is three successive values 3*2 and 3*2 in 
the volume column?

I already tried a for-loop in connection with a last_value == current 
value comparison but wasn't successful at all.

Therefore, I highly appreaciate any hint or pointer!


Example data:

Year	month	volume
1997	1	2
1997	2	2
1997	3	2
1997	4	5
1997	5	2
1997	7	1
1998	1	2
1998	2	6
1998	3	3
1998	4	3
1998	5	3
1998	6	1

Thanks and kind regards,
Tim Michelsen


From ricaraoz at gmail.com  Mon Nov 26 17:40:22 2007
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Mon, 26 Nov 2007 13:40:22 -0300
Subject: [Tutor] pipeline - what is it and how do I use it?
In-Reply-To: <fid3qk$5dt$1@ger.gmane.org>
References: <674d5ce60711250957w45a1518fydc82df2b1d93ff13@mail.gmail.com>	<4749CC99.6010205@bigfoot.com>
	<fid3qk$5dt$1@ger.gmane.org>
Message-ID: <474AF6F6.10007@bigfoot.com>

Alan Gauld wrote:
> "Ricardo Ar?oz" <ricaraoz at gmail.com> wrote
> 
>> Check PyWinAuto, it might provide what you need.
>> You can find it at : http://www.openqa.org/pywinauto/
>>
> 
> Nice link thanks, I've not seen that before.
> 
> Using ctypes/winall and PostMessage is not friendly.
> 
> Alan G. 
> 

Never used it though. If somebody does it would be nice if he/she could
give us a short report.




From cutkiller1234 at yahoo.com  Tue Nov 27 01:10:37 2007
From: cutkiller1234 at yahoo.com (Chiar Nimeni)
Date: Mon, 26 Nov 2007 16:10:37 -0800 (PST)
Subject: [Tutor] opening a javascript window and reading its source
Message-ID: <907541.69092.qm@web90603.mail.mud.yahoo.com>

i basicly need python to open a certain javascript window ... then read it's source ... how do i do that?

-----------------------------
import urllib2
import cookielib

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))

url = opener.open("The url that has a javascript window toggled on click")
js = opener.open('javascript:toggleBackpack(null,2190551);')  # opening the JS window
js2 = opener.open("javascript:toggleBackpack('orb',2190551);") # toggleing another section on the JS window
source = js2.read()
print source
       
---------------------------------
Be a better pen pal. Text or chat with friends inside Yahoo! Mail. See how.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071126/1deba7e2/attachment.htm 

From kent37 at tds.net  Tue Nov 27 02:33:56 2007
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 26 Nov 2007 20:33:56 -0500
Subject: [Tutor] detecting a change in a iterable object (list, array,
 etc.)
In-Reply-To: <fifo3d$6no$1@ger.gmane.org>
References: <fifo3d$6no$1@ger.gmane.org>
Message-ID: <474B7404.6010309@tds.net>

Tim Michelsen wrote:
> Hello,
> would like to ask for your help on the following issue:
> What procedure can I use to detect if there's a change when iterating 
> over a list?
> 
> For instance if I want to extract the years 1997 and 1998 from the table 
> below and save them into separate files?

A list comprehension will work for this. If data is a list of triples of 
(year, month, volume) then this will give you a list of the 1997 triples:

data1997 = [ item for item in data if item[0]==1997 ]

> How do I build the average only on the 1997-year values?

Given the above data1997 list can you do this? Sum the third values and 
divide by the length of the list.

> Or how do find out that there is three successive values 3*2 and 3*2 in 
> the volume column?

itertools.groupby() is helpful for this. It's a bit tricky to understand 
though. Here is an extended example:
http://personalpages.tds.net/~kent37/blog/arch_m1_2005_12.html#e69

Here is an example that shows sequences of values of length 3 or more:

import itertools
def key(item):
     return item[2]

for k, g in itertools.groupby(data, key=key):
     g = list(g)
     if len(g) > 2:
         print k, 'occurs', len(g), 'times'

> 
> I already tried a for-loop in connection with a last_value == current 
> value comparison but wasn't successful at all.

If you show us what you have done so far it would be easier to make
suggestions.

Kent

From timmichelsen at gmx-topmail.de  Tue Nov 27 10:43:23 2007
From: timmichelsen at gmx-topmail.de (Tim Michelsen)
Date: Tue, 27 Nov 2007 09:43:23 +0000 (UTC)
Subject: [Tutor] detecting a change in a iterable object (list, array,
	etc.)
References: <fifo3d$6no$1@ger.gmane.org> <474B7404.6010309@tds.net>
Message-ID: <loom.20071127T093717-21@post.gmane.org>

Hello,
> If you show us what you have done so far it would be easier to make
> suggestions.
The thing is that I am working a lot with time series data and need to write
criteria based filters for that data.
There's already a start in SciPy Time Series package:
http://www.scipy.org/SciPyPackages/TimeSeries
But it is still in early development.

Your suggestions are exactly what I was looking for. A kick into the right
direction...

I found itertools when writing my code for the last list items:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/34c7398eec5a92cd/68f0aaef68e5ca0e?lnk=raot

I will keep you upodated it when I finshed investigating and incorporating your
tips.

Thanks so far,
Timmie


From globophobe at gmail.com  Tue Nov 27 10:57:53 2007
From: globophobe at gmail.com (Luis N)
Date: Tue, 27 Nov 2007 18:57:53 +0900
Subject: [Tutor] Help with modulus.
Message-ID: <c6e072940711270157l4fc6e1d0hb0148b767abfeb0@mail.gmail.com>

I'd like the below to be a single line if possible.

hours = metrics.totaltime/3600000
minutes = (metrics.totaltime - 3600000*hours)/60000
seconds = (metrics.totaltime - 3600000*hours - 60000*minutes)/1000

Would it be possible to simplify this with a generator expression e.g.

total_time = tuple((...))

From alan.gauld at btinternet.com  Tue Nov 27 11:28:45 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 27 Nov 2007 10:28:45 -0000
Subject: [Tutor] Help with modulus.
References: <c6e072940711270157l4fc6e1d0hb0148b767abfeb0@mail.gmail.com>
Message-ID: <figrh0$14p$1@ger.gmane.org>


"Luis N" <globophobe at gmail.com> wrote

> I'd like the below to be a single line if possible.

Beware compression for the sake of it. However we can simplify
a bit using divmod()

> hours = metrics.totaltime/3600000
> minutes = (metrics.totaltime - 3600000*hours)/60000
> seconds = (metrics.totaltime - 3600000*hours - 60000*minutes)/1000

hours,minutes = divmod(metrics.totaltime/1000, 3600) # get rid of the 
ms here
minutes.seconds = divmod(minutes, 60)

> Would it be possible to simplify this with a generator expression 
> e.g.
>
> total_time = tuple((...))

Possibly, but the above is simple enough for my tastes! :-)

Alan G. 



From remco at gerlich.nl  Tue Nov 27 11:57:39 2007
From: remco at gerlich.nl (Remco Gerlich)
Date: Tue, 27 Nov 2007 11:57:39 +0100
Subject: [Tutor] opening a javascript window and reading its source
In-Reply-To: <907541.69092.qm@web90603.mail.mud.yahoo.com>
References: <907541.69092.qm@web90603.mail.mud.yahoo.com>
Message-ID: <7ae3ca10711270257j241ebf2ei35c591093ead2ffe@mail.gmail.com>

Hi,

Python can't run Javascript functions. Note that "HTTPCookieProcessor"
is a HTTP thing, so it can handle  "http:" links, not "javascript:"
links.

Your best bet would probably be to download all the Javascript files
mentioned in the original HTML file, and try to find out what the
toggleBackpack() function does. If you can find out from that
Javascript function what the URL is that it opens in the new window,
then you can download that same URL from Python.

There is no such thing as a "Javascript window". Javascript can be
used to open perfectly normal windows, that contain normal HTML.

It's hard to give more help without knowing more about your problem.

Hope this helps a little,
Remco Gerlich

On Nov 27, 2007 1:10 AM, Chiar Nimeni <cutkiller1234 at yahoo.com> wrote:
> i basicly need python to open a certain javascript window ... then read it's
> source ... how do i do that?
>
> -----------------------------
> import urllib2
> import cookielib
>
> cj = cookielib.CookieJar()
> opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
>
> url = opener.open("The url that has a javascript window toggled on click")
> js = opener.open('javascript:toggleBackpack(null,2190551);')  # opening the
> JS window
> js2 = opener.open("javascript:toggleBackpack('orb',2190551);") # toggleing
> another section on the JS window
> source = js2.read()
> print source
>
>  ________________________________
> Be a better pen pal. Text or chat with friends inside Yahoo! Mail. See how.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>

From rfquerin at gmail.com  Tue Nov 27 15:52:26 2007
From: rfquerin at gmail.com (Richard Querin)
Date: Tue, 27 Nov 2007 09:52:26 -0500
Subject: [Tutor] Python CMS advice wanted
Message-ID: <7d81675b0711270652r5332c8b1u8ae53aa78c2c6daa@mail.gmail.com>

Hi,

I've got a site that is currently a static site. While not unmanageable at
the moment (it's still pretty young), we've been entertaining thoughts of
converting it to a CMS system. I'm looking for some good suggestions based
on some simple criteria:

- Python based - I have a rudimentary knowledge of Python and like it, so
I'd prefer to go this route
- Simple - Our needs are not very complex, we're really just thinking about
maintainability and expandability.
- We want to be able to customize the look and layout of the site to our
whim.

I'm a complete newbie when it comes to CMS systems so I'm not sure whether
or not it might be better just to go with something like an install of
Wordpress instead.

Just looking for some suggestions. The current site btw is
http://screencasters.heathenx.org

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

From jim at well.com  Tue Nov 27 16:10:57 2007
From: jim at well.com (jim stockford)
Date: Tue, 27 Nov 2007 07:10:57 -0800
Subject: [Tutor] Python CMS advice wanted
In-Reply-To: <7d81675b0711270652r5332c8b1u8ae53aa78c2c6daa@mail.gmail.com>
References: <7d81675b0711270652r5332c8b1u8ae53aa78c2c6daa@mail.gmail.com>
Message-ID: <b209bb029d9827946972a6975ecaac16@well.com>


IMO:
my experience with cms systems is that there's a big
learning curve. you might have more fun (and be more
productive and maybe more creative) if you use the
available appropriate python modules and cobble
together your own site.
    maintenance, especially by some one else, would
be an area to worry about: each cms system has its
own community of experts, a few of which are always
available to help. your custom code would present
new people a learning curve.
    expansion and extensibility would probably be as
problematic regardless of your choice: you can
expand/extend your code depending on available
modules and your imagination/skill. you can expand/
extend a packaged cms system depending on how
it presents an API and/or other means and limited
by what the people coding, managing, and releasing
the cms package choose to add (there'll sooner or
later be bloat in everything, you want your bloat or
some one else's?).



On Nov 27, 2007, at 6:52 AM, Richard Querin wrote:

> Hi,
>
> I've got a site that is currently a static site. While not 
> unmanageable at the moment (it's still pretty young), we've been 
> entertaining thoughts of converting it to a CMS system. I'm looking 
> for some good suggestions based on some simple criteria:
>
> - Python based - I have a rudimentary knowledge of Python and like it, 
> so I'd prefer to go this route
> - Simple - Our needs are not very complex, we're really just thinking 
> about maintainability and expandability.
> - We want to be able to customize the look and layout of the site to 
> our whim.
>
> I'm a complete newbie when it comes to CMS systems so I'm not sure 
> whether or not it might be better just to go with something like an 
> install of Wordpress instead.
>
> Just looking for some suggestions. The current site btw is 
> http://screencasters.heathenx.org
>
> RQ
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


From pacbaby27 at yahoo.com  Tue Nov 27 17:23:38 2007
From: pacbaby27 at yahoo.com (Latasha Marks)
Date: Tue, 27 Nov 2007 08:23:38 -0800 (PST)
Subject: [Tutor] (no subject)
Message-ID: <744872.94132.qm@web56410.mail.re3.yahoo.com>

Design a program to keep track of the scores of bowlers as they bowl a game. The program must prompt each bowler to bowl. The program begins by allowing the bowlers to enter their names. Each frame is tracked and properly displayed as the game progresses..
  Click Here for a see what the printed score sheet must look like as a game is bowled.
  Click Here  to get a little more information about the scoring scheme of bowling. 
   
  i'm having a hard time on how to print out each frame adding the score.

       
---------------------------------
Get easy, one-click access to your favorites.  Make Yahoo! your homepage.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071127/4f926926/attachment.htm 

From dkuhlman at rexx.com  Tue Nov 27 17:30:34 2007
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Tue, 27 Nov 2007 08:30:34 -0800
Subject: [Tutor] Python CMS advice wanted
In-Reply-To: <7d81675b0711270652r5332c8b1u8ae53aa78c2c6daa@mail.gmail.com>
References: <7d81675b0711270652r5332c8b1u8ae53aa78c2c6daa@mail.gmail.com>
Message-ID: <20071127163034.GA73271@cutter.rexx.com>

On Tue, Nov 27, 2007 at 09:52:26AM -0500, Richard Querin wrote:
> Hi,
> 
> I've got a site that is currently a static site. While not unmanageable at
> the moment (it's still pretty young), we've been entertaining thoughts of
> converting it to a CMS system. I'm looking for some good suggestions based
> on some simple criteria:
> 
> - Python based - I have a rudimentary knowledge of Python and like it, so
> I'd prefer to go this route
> - Simple - Our needs are not very complex, we're really just thinking about
> maintainability and expandability.
> - We want to be able to customize the look and layout of the site to our
> whim.
> 
> I'm a complete newbie when it comes to CMS systems so I'm not sure whether
> or not it might be better just to go with something like an install of
> Wordpress instead.
> 
> Just looking for some suggestions. The current site btw is
> http://screencasters.heathenx.org

If you are interested in a CMS, take a look at the following:

- Plone:  http://plone.org/

- Silva:  http://infrae.com/products/silva

Both of which are built on Zope: http://zope.org/

And, I do not know anything about this one, but it looks
interesting -- Skeletonz: http://orangoo.com/skeletonz/

You might also find helpful info at: http://www.cmsreview.com/

If you have success with one, please report back here with your
experience, suggestions, etc.

Dave


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

From kent37 at tds.net  Tue Nov 27 18:01:07 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 27 Nov 2007 12:01:07 -0500
Subject: [Tutor] Bowling program
In-Reply-To: <744872.94132.qm@web56410.mail.re3.yahoo.com>
References: <744872.94132.qm@web56410.mail.re3.yahoo.com>
Message-ID: <474C4D53.6070502@tds.net>

Latasha Marks wrote:
> Design a program to keep track of the scores of bowlers as they bowl a 
> game. The program must prompt each bowler to bowl. The program begins by 
> allowing the bowlers to enter their names. Each frame is tracked and 
> properly displayed as the game progresses..

This is obviously homework. We won't do your homework for you. We will 
help you when you get stuck.

> i'm having a hard time on how to print out each frame adding the score.

What do you have so far? Show us some code and tell us where you are 
stuck, or what you don't understand.

Kent

PS Please use a meaningful subject line.



From scott at rscorp.ab.ca  Tue Nov 27 17:39:55 2007
From: scott at rscorp.ab.ca (Scott Sandeman-Allen)
Date: Tue, 27 Nov 2007 09:39:55 -0700
Subject: [Tutor] Python CMS advice wanted
In-Reply-To: <b209bb029d9827946972a6975ecaac16@well.com>
Message-ID: <r02010500-1049-62CA6DD99D0711DC8B31001124DEBE0E@[192.168.69.99]>

On 11/27/07, jim stockford (jim at well.com) wrote:

>IMO:
>my experience with cms systems is that there's a big
>learning curve. you might have more fun (and be more
>productive and maybe more creative) if you use the
>available appropriate python modules and cobble
>together your own site.

Woah, I whole-heartedly disagree with this. Sorry!

>    maintenance, especially by some one else, would
>be an area to worry about: each cms system has its
>own community of experts, a few of which are always
>available to help. your custom code would present
>new people a learning curve.

This is why I disagree: maintenance. 

Oh yeah, how about: security!

Along with expediency, quality and a bunch of other things like maybe the OP would like a life too (i.e. not be a slave to supporting his own code).

Frankly, the OP (Richard) does not really need the 'full-meal' of a CMS. He's looking for a templating system (cheetah, myghty, kid) and a mechanism to organize code into a web application of sorts.

While there are some behemouth CMS options (Zope/Plone) there are some lighter ones (turbogears) and even ones that are not as much CMS but frameworks (django, pylons, even quixote).

Yes, some of the frameworks/CMS have small communities (quixote) but others (django, tubogears) are quite active. Still, each _do_ have a community and if th OP chooses one that has a critical mass (all of the above), he will find ample help to get over the humps & bumps.

I'm presently working with Django and am thoroughly enjoying it. While it isn't perfect, nothing is, it is very well documented and has a vigorous community. I have worked with Zope and Quixote (ridiculous to the sublime), Django is a nice blend of features with an intelligent API for my needs. Your mileage may vary.

>    expansion and extensibility would probably be as
>problematic regardless of your choice: you can
>expand/extend your code depending on available
>modules and your imagination/skill. you can expand/
>extend a packaged cms system depending on how
>it presents an API and/or other means and limited
>by what the people coding, managing, and releasing
>the cms package choose to add (there'll sooner or
>later be bloat in everything, you want your bloat or
>some one else's?).

Do you think a person with emerging skills is going to create clean, elegant code that optimizes Python's strengths? No aspersions toward's Richard's skills, just going by his own remark: "I have a rudimentary knowledge of Python"

If the OP had stated some really specific and very unique requirements, there may be justification but telling someone to 'roll their own'. It is like saying there are side-effects to the latest Flu shot so you better go create your own. 

I don't mean to be critical of you; taking the time to express your constructive opinion is a valuable act. However, in this case I don't believe it serves in the best interest in the OP's requirements.

There are some truths to what I believe you were trying to say. Some CMS/Frameworks like Zope are to be avoided, IMHO, unless they satisfy some specific requirements (the Zope sites I have are a bear to extend for reasons outside the scope of this thread). They are bloated or just non-starters, but thankfully they are not the only options.

To close, I strongly suggest the original poster Richard check out Django, TurboGears and Pylons. I don't have much exp. with the latter two, but there is a reason they are generally popular. While those reasons don't meet with my req. they may meet with his.

It is _always_ easier to engineer/re-engineer from a _good_ base of knowledge than it is to start fresh... though an open mind is equally important.

I hope this helps,

Scott

>On Nov 27, 2007, at 6:52 AM, Richard Querin wrote:
>
>> Hi,
>>
>> I've got a site that is currently a static site. While not 
>> unmanageable at the moment (it's still pretty young), we've been 
>> entertaining thoughts of converting it to a CMS system. I'm looking 
>> for some good suggestions based on some simple criteria:
>>
>>
>> I'm a complete newbie when it comes to CMS systems so I'm not sure 
>> whether or not it might be better just to go with something like an 
>> install of Wordpress instead.
>>
>> Just looking for some suggestions. The current site btw is 
>> http://screencasters.heathenx.org
>>
>> RQ
>> _______________________________________________
>> 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 pydev at rscorp.ab.ca  Tue Nov 27 18:40:51 2007
From: pydev at rscorp.ab.ca (Scott SA)
Date: Tue, 27 Nov 2007 10:40:51 -0700
Subject: [Tutor] Python CMS advice wanted
Message-ID: <r02010500-1049-E60A58C29D0F11DC8B31001124DEBE0E@[192.168.69.99]>

On 11/27/07, jim stockford (jim at well.com) wrote:

>IMO:
>my experience with cms systems is that there's a big
>learning curve. you might have more fun (and be more
>productive and maybe more creative) if you use the
>available appropriate python modules and cobble
>together your own site.

Woah, I whole-heartedly disagree with this. Sorry!

>    maintenance, especially by some one else, would
>be an area to worry about: each cms system has its
>own community of experts, a few of which are always
>available to help. your custom code would present
>new people a learning curve.

This is why I disagree: maintenance. 

Oh yeah, how about: security!

Along with expediency, quality and a bunch of other things like maybe the OP would like a life too (i.e. not be a slave to supporting his own code).

Frankly, the OP (Richard) does not really need the 'full-meal' of a CMS. He's looking for a templating system (cheetah, myghty, kid) and a mechanism to organize code into a web application of sorts.

While there are some behemouth CMS options (Zope/Plone) there are some lighter ones (turbogears) and even ones that are not as much CMS but frameworks (django, pylons, even quixote).

Yes, some of the frameworks/CMS have small communities (quixote) but others (django, tubogears) are quite active. Still, each _do_ have a community and if th OP chooses one that has a critical mass (all of the above), he will find ample help to get over the humps & bumps.

I'm presently working with Django and am thoroughly enjoying it. While it isn't perfect, nothing is, it is very well documented and has a vigorous community. I have worked with Zope and Quixote (ridiculous to the sublime), Django is a nice blend of features with an intelligent API for my needs. Your mileage may vary.

>    expansion and extensibility would probably be as
>problematic regardless of your choice: you can
>expand/extend your code depending on available
>modules and your imagination/skill. you can expand/
>extend a packaged cms system depending on how
>it presents an API and/or other means and limited
>by what the people coding, managing, and releasing
>the cms package choose to add (there'll sooner or
>later be bloat in everything, you want your bloat or
>some one else's?).

Do you think a person with emerging skills is going to create clean, elegant code that optimizes Python's strengths? No aspersions toward's Richard's skills, just going by his own remark: "I have a rudimentary knowledge of Python"

If the OP had stated some really specific and very unique requirements, there may be justification but telling someone to 'roll their own'. It is like saying there are side-effects to the latest Flu shot so you better go create your own. 

I don't mean to be critical of you; taking the time to express your constructive opinion is a valuable act. However, in this case I don't believe it serves in the best interest in the OP's requirements.

There are some truths to what I believe you were trying to say. Some CMS/Frameworks like Zope are to be avoided, IMHO, unless they satisfy some specific requirements (the Zope sites I have are a bear to extend for reasons outside the scope of this thread). They are bloated or just non-starters, but thankfully they are not the only options.

To close, I strongly suggest the original poster Richard check out Django, TurboGears and Pylons. I don't have much exp. with the latter two, but there is a reason they are generally popular. While those reasons don't meet with my req. they may meet with his.

It is _always_ easier to engineer/re-engineer from a _good_ base of knowledge than it is to start fresh... though an open mind is equally important.

I hope this helps,

Scott

>On Nov 27, 2007, at 6:52 AM, Richard Querin wrote:
>
>> Hi,
>>
>> I've got a site that is currently a static site. While not 
>> unmanageable at the moment (it's still pretty young), we've been 
>> entertaining thoughts of converting it to a CMS system. I'm looking 
>> for some good suggestions based on some simple criteria:
>>
>>
>> I'm a complete newbie when it comes to CMS systems so I'm not sure 
>> whether or not it might be better just to go with something like an 
>> install of Wordpress instead.
>>
>> Just looking for some suggestions. The current site btw is 
>> http://screencasters.heathenx.org
>>
>> RQ
>> _______________________________________________
>> 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 jim at well.com  Tue Nov 27 19:28:56 2007
From: jim at well.com (jim stockford)
Date: Tue, 27 Nov 2007 10:28:56 -0800
Subject: [Tutor] Python CMS advice wanted
In-Reply-To: <r02010500-1049-E60A58C29D0F11DC8B31001124DEBE0E@[192.168.69.99]>
References: <r02010500-1049-E60A58C29D0F11DC8B31001124DEBE0E@[192.168.69.99]>
Message-ID: <a9dde83f82e727c3c50e915118fc7d8c@well.com>


On Nov 27, 2007, at 9:40 AM, Scott SA wrote:

> On 11/27/07, jim stockford (jim at well.com) wrote:
>
>> IMO:
>> my experience with cms systems is that there's a big
>> learning curve. you might have more fun (and be more
>> productive and maybe more creative) if you use the
>> available appropriate python modules and cobble
>> together your own site.
>
> Woah, I whole-heartedly disagree with this. Sorry!
perfectly okay and somewhat hoped for. note the points
* "cms systems have a big learning curve": largely true
and often unsuspected how big.
* "might have more fun (and be more productive...":
depends on his talents and ambitions, some people
like coding despite the problems and responsibilities.

>>    maintenance, especially by some one else, would
>> be an area to worry about: each cms system has its
>> own community of experts, a few of which are always
>> available to help. your custom code would present
>> new people a learning curve.
>
> This is why I disagree: maintenance.
> Oh yeah, how about: security!
very good point, security.

> Along with expediency, quality and a bunch of other things like maybe 
> the OP would like a life too (i.e. not be a slave to supporting his 
> own code).
for sure one of the considerations, depends on his talent, ambition,
and build-or-buy proclivity.

> Frankly, the OP (Richard) does not really need the 'full-meal' of a 
> CMS. He's looking for a templating system (cheetah, myghty, kid) and a 
> mechanism to organize code into a web application of sorts.
what are the learning curves of cheetah, myghty, kid?
also,  http://screencasters.heathenx.org  seems at the lean end of the
richness spectrum (per looking for a templating system), so of all
possible python projects, his is within reasonable limits as a candidate
for building from available modules (i.e. from scratch).

> While there are some behemouth CMS options (Zope/Plone) there are some 
> lighter ones (turbogears) and even ones that are not as much CMS but 
> frameworks (django, pylons, even quixote).
>
> Yes, some of the frameworks/CMS have small communities (quixote) but 
> others (django, tubogears) are quite active. Still, each _do_ have a 
> community and if th OP chooses one that has a critical mass (all of 
> the above), he will find ample help to get over the humps & bumps.
evaluating the community around a framework/cms product
is an important part of evaluation.

> I'm presently working with Django and am thoroughly enjoying it. While 
> it isn't perfect, nothing is, it is very well documented and has a 
> vigorous community. I have worked with Zope and Quixote (ridiculous to 
> the sublime), Django is a nice blend of features with an intelligent 
> API for my needs. Your mileage may vary.
>
>>    expansion and extensibility would probably be as
>> problematic regardless of your choice: you can
>> expand/extend your code depending on available
>> modules and your imagination/skill. you can expand/
>> extend a packaged cms system depending on how
>> it presents an API and/or other means and limited
>> by what the people coding, managing, and releasing
>> the cms package choose to add (there'll sooner or
>> later be bloat in everything, you want your bloat or
>> some one else's?).
>
> Do you think a person with emerging skills is going to create clean, 
> elegant code that optimizes Python's strengths? No aspersions toward's 
> Richard's skills, just going by his own remark: "I have a rudimentary 
> knowledge of Python"
certainly not: experienced coders generally code much better
than in their pre-experienced state. Note the key issues are
* does he want to take on coding
* does his project reasonably permit his doing so (time to market)
* is there some special customization he has in mind

> If the OP had stated some really specific and very unique 
> requirements, there may be justification but telling someone to 'roll 
> their own'. It is like saying there are side-effects to the latest Flu 
> shot so you better go create your own.
>
> I don't mean to be critical of you; taking the time to express your 
> constructive opinion is a valuable act. However, in this case I don't 
> believe it serves in the best interest in the OP's requirements.
your comments are very informative. this is a build-or-buy issue, and
i hope what we're writing provides some helpful insights to those who
are considering python projects, including richard.

> There are some truths to what I believe you were trying to say. Some 
> CMS/Frameworks like Zope are to be avoided, IMHO, unless they satisfy 
> some specific requirements (the Zope sites I have are a bear to extend 
> for reasons outside the scope of this thread). They are bloated or 
> just non-starters, but thankfully they are not the only options.
it would be nice to have some comparative information
on these products: does anyone know of a web site or
other source that compares CMS/frameworks?

> To close, I strongly suggest the original poster Richard check out 
> Django, TurboGears and Pylons. I don't have much exp. with the latter 
> two, but there is a reason they are generally popular. While those 
> reasons don't meet with my req. they may meet with his.
>
> It is _always_ easier to engineer/re-engineer from a _good_ base of 
> knowledge than it is to start fresh... though an open mind is equally 
> important.
>
> I hope this helps,
>
> Scott
>
>> On Nov 27, 2007, at 6:52 AM, Richard Querin wrote:
>>
>>> Hi,
>>>
>>> I've got a site that is currently a static site. While not
>>> unmanageable at the moment (it's still pretty young), we've been
>>> entertaining thoughts of converting it to a CMS system. I'm looking
>>> for some good suggestions based on some simple criteria:
>>>
>>>
>>> I'm a complete newbie when it comes to CMS systems so I'm not sure
>>> whether or not it might be better just to go with something like an
>>> install of Wordpress instead.
>>>
>>> Just looking for some suggestions. The current site btw is
>>> http://screencasters.heathenx.org
>>>
>>> RQ
>>> _______________________________________________
>>> Tutor maillist  -  Tutor at python.org
>>> http://mail.python.org/mailman/listinfo/tutor
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


From pydev at rscorp.ab.ca  Tue Nov 27 21:30:36 2007
From: pydev at rscorp.ab.ca (Scott SA)
Date: Tue, 27 Nov 2007 13:30:36 -0700
Subject: [Tutor] Python CMS advice wanted
In-Reply-To: <a9dde83f82e727c3c50e915118fc7d8c@well.com>
Message-ID: <r02010500-1049-9D090E509D2711DC8B31001124DEBE0E@[192.168.69.99]>

First-off, I have to appologize to the list for an accidental re-send of my original post. I didn't want to spam the list with an 'oops' message, but it seems appropriate now. If the other version gets caught by a moderator, it can be deleted - thanks!

On 11/27/07, jim stockford (jim at well.com) wrote:

Jim, great reply with valid points - only the reader can choose how to weight them for their needs.

>> Woah, I whole-heartedly disagree with this. Sorry!
>perfectly okay and somewhat hoped for. note the points
>* "cms systems have a big learning curve": largely true
>and often unsuspected how big.

Agreed, something like Zope sounds promising but it can easily become a rats-nest due to the 'magic' factor in the background.

As previously noted that I don't believe he is looking for a CMS but that seemed to be a good frame of reference for starting his quest. Now that "Frameworks" are on the table, his options are broader, simpler and certainly less bloated.

>* "might have more fun (and be more productive...":
>depends on his talents and ambitions, some people
>like coding despite the problems and responsibilities.

Possibly, but unlikely. Before you can use a pencil sharpener, you need to know what a pencil is (with mechanical pencils these days, this is not as silly as it sounds).

My point is, this being a 'Tutor' list and the expressed level of knowledge, it would be more informative for someone to learn how/why a framework has certain features by working with them, than trying to discover they need a feature.

The other nice thing about a framework like Django, for exampe, is it can be started quite easily and with it's automatic forms a novice can get a pretty decent site working in a short period of time. All the while allowing that person to write custom 'business logic' in python without a lot of contortions.

It's a high-level approach allowing for the user to drill down as they need.

Essentially, this _is_ the difference in our approaches: which end do you start with?

>>>    maintenance, especially by some one else, would
>>> be an area to worry about: each cms system has its
>>> own community of experts, a few of which are always
>>> available to help. your custom code would present
>>> new people a learning curve.
>>
>> This is why I disagree: maintenance.
>> Oh yeah, how about: security!
>very good point, security.

I'd be a liar if I said I hadn't been bitten with this before... as would a lot of high-profile installations.

This is a double-edged sword. The gains you get from using a framework is the knowlege of others the sharp-bit is complexity which brings more opportunity to err.

>> Along with expediency, quality and a bunch of other things like maybe 
>> the OP would like a life too (i.e. not be a slave to supporting his 
>> own code).
>for sure one of the considerations, depends on his talent, ambition,
>and build-or-buy proclivity.

"proclivity", "a natural inclination", great word & thanks for introducing me to it... now back to the thread.

In my personal experience, the more a batch of code revolves arround _my_ view of the task, the more I become the sole point of support. It is a constant effort to make things clear, organzied and self-documenting. 

Having the separation of framework from customization is a reduction in volume of code to be maintained by the developer.

The sharp-pointy-bit to this is you are reliant on others sometimes for getting things fixed and exposed to the possibilty of breakage with upgrades. 

>> Frankly, the OP (Richard) does not really need the 'full-meal' of a 
>> CMS. He's looking for a templating system (cheetah, myghty, kid) and a 
>> mechanism to organize code into a web application of sorts.
>what are the learning curves of cheetah, myghty, kid?
>also,  http://screencasters.heathenx.org  seems at the lean end of the
>richness spectrum (per looking for a templating system), so of all
>possible python projects, his is within reasonable limits as a candidate
>for building from available modules (i.e. from scratch).

Hey, some things are better from scratch... like bread ;-)

My experience with Quixote was valuable from this perpsective. I got tired, though, of re-inventing things that already existed elsewhere. For example, we wanted to add breadcrumbs, not an arduous task, but we had to re-write it. That took resources, time to consider how it needed to work, code it then debug it.

>> Yes, some of the frameworks/CMS have small communities (quixote) but 
>> others (django, tubogears) are quite active. Still, each _do_ have a 
>> community and if th OP chooses one that has a critical mass (all of 
>> the above), he will find ample help to get over the humps & bumps.
>evaluating the community around a framework/cms product
>is an important part of evaluation.

... and everybody's measuring sticks are different. 

>> Do you think a person with emerging skills is going to create clean, 
>> elegant code that optimizes Python's strengths? No aspersions toward's 
>> Richard's skills, just going by his own remark: "I have a rudimentary 
>> knowledge of Python"
>certainly not: experienced coders generally code much better
>than in their pre-experienced state. Note the key issues are
>* does he want to take on coding
>* does his project reasonably permit his doing so (time to market)
>* is there some special customization he has in mind

Valid as a learning exercise, sure, or to maintain propriety, another reason. All good points but not necessarily a good _starting_ point. 

It helps knowing what you don't want as much as it helps knowing what you want. The evaluation of existing tools available can assist in both and only after that can one trully make an informed decision as to wether to build or buy, as you put it.

>> I don't mean to be critical of you; taking the time to express your 
>> constructive opinion is a valuable act. However, in this case I don't 
>> believe it serves in the best interest in the OP's requirements.
>your comments are very informative. this is a build-or-buy issue, and
>i hope what we're writing provides some helpful insights to those who
>are considering python projects, including richard.

Absolutely. If the least we've obtaind is the ability to ask better questions, then it is a net gain.

>> There are some truths to what I believe you were trying to say. Some 
>> CMS/Frameworks like Zope are to be avoided, IMHO, unless they satisfy 
>> some specific requirements (the Zope sites I have are a bear to extend 
>> for reasons outside the scope of this thread). They are bloated or 
>> just non-starters, but thankfully they are not the only options.
>it would be nice to have some comparative information
>on these products: does anyone know of a web site or
>other source that compares CMS/frameworks?

Ahh, now this is _where_ roll-your-own comes into play. Rough comparrisions i.e. "does it have xyz feature" are helpful in narrowing the range but a person really does have to take the leap and play with the tools. 

A really good starting point, IMO, is to scan the tutorials and documentation. Maybe watch a few videos and see which 'feels' the best. Then choose one that seems to fit the needs and dive into it with the tutorial or a small project.  Rinse and repeat as necessary.

Before I chose my current framework, I looked for comparative information. Since this is a moving target, it can only be a rough guide. I had to research more into the features available and see how they fit.

Some of the things I considered were how it interfaced with a DB. I'm an object-oriented guy so the ORM (object-relational model) was a consideration. The cost of that is performance as a site becomes more complex. If your db requirements are minimal then this may not be an issue or it may make the db interface so transparent you don't have to think about it anymore.

Another consideration was portability of code from one project to another - something I do frequently. How is that handled. If you don't move code, it doesn't matter as much.

Templating syntax and the separation of code from presentation was yet another consideration. Is it intelligently done and easy to work with? 

There are more things to think about, but I have run out of time for now.

HTH

Scott

From rfquerin at gmail.com  Tue Nov 27 22:37:52 2007
From: rfquerin at gmail.com (Richard Querin)
Date: Tue, 27 Nov 2007 16:37:52 -0500
Subject: [Tutor] List processing question - consolidating duplicate entries
Message-ID: <7d81675b0711271337o3c92fafga8f7d3392b71abfc@mail.gmail.com>

I'm trying to process a list and I'm stuck. Hopefully someone can help
me out here:

I've got a list that is formatted as follows:
[Name,job#,jobname,workcode,hours]

An example might be:

[Bob,07129,projectA,4001,5]
[Bob,07129,projectA,5001,2]
[Bob,07101,projectB,4001,1]
[Bob,07140,projectC,3001,3]
[Bob,07099,projectD,3001,2]
[Bob,07129,projectA,4001,4]
[Bob,07099,projectD,4001,3]
[Bob,07129,projectA,4001,2]

Now I'd like to consolidate entries that are duplicates. Duplicates
meaning entries that share the same Name, job#, jobname and workcode.
So for the list above, there are 3 entries for projectA which have a
workcode of 4001. (there is a fourth entry for projectA but it's
workcode is 5001 and not 4001).

So I'd like to end up with a list so that the three duplicate entries
are consolidated into one with their hours added up:

[Bob,07129,projectA,4001,11]
[Bob,07129,projectA,5001,2]
[Bob,07101,projectB,4001,1]
[Bob,07140,projectC,3001,3]
[Bob,07099,projectD,3001,2]
[Bob,07099,projectD,4001,3]

I've tried doing it with brute force by stepping through each item and
checking all the other items for matches, and then trying to build a
new list as I go, but that's still confusing me - for instance how can
I delete the items that I've already consolidated so they don't get
processed again?.

I'm not a programmer by trade so I'm sorry if this is a basic computer
science question.

RQ

From john at fouhy.net  Tue Nov 27 22:59:27 2007
From: john at fouhy.net (John Fouhy)
Date: Wed, 28 Nov 2007 10:59:27 +1300
Subject: [Tutor] List processing question - consolidating duplicate
	entries
In-Reply-To: <7d81675b0711271337o3c92fafga8f7d3392b71abfc@mail.gmail.com>
References: <7d81675b0711271337o3c92fafga8f7d3392b71abfc@mail.gmail.com>
Message-ID: <5e58f2e40711271359w4b5eb5advdb19ef360b06ecf7@mail.gmail.com>

On 28/11/2007, Richard Querin <rfquerin at gmail.com> wrote:
> I've got a list that is formatted as follows:
> [Name,job#,jobname,workcode,hours]
[...]
> Now I'd like to consolidate entries that are duplicates. Duplicates
> meaning entries that share the same Name, job#, jobname and workcode.
> So for the list above, there are 3 entries for projectA which have a
> workcode of 4001. (there is a fourth entry for projectA but it's
> workcode is 5001 and not 4001).

You use a dictionary: pull out the jobname and workcode as the dictionary key.

====
import operator

# if job is an element of the list, then jobKey(job) will be (jobname, workcode)
jobKey = operator.itemgetter(2, 3)

jobList = [...]  # the list of jobs

jobDict = {}

for job in jobList:
  try:
    jobDict[jobKey(job)][4] += job[4]
  except KeyError:
    jobDict[jobKey(job)] = job

(note that this will modify the jobs in your original list... if this
is Bad, you can replace the last line with "... = job[:]")

HTH!

-- 
John.

From bgailer at alum.rpi.edu  Tue Nov 27 23:00:54 2007
From: bgailer at alum.rpi.edu (bob gailer)
Date: Tue, 27 Nov 2007 17:00:54 -0500
Subject: [Tutor] (no subject)
In-Reply-To: <744872.94132.qm@web56410.mail.re3.yahoo.com>
References: <744872.94132.qm@web56410.mail.re3.yahoo.com>
Message-ID: <474C9396.3090802@alum.rpi.edu>

Latasha Marks wrote:
> Design a program to keep track of the scores of bowlers as they bowl a 
> game. The program must prompt each bowler to bowl. The program begins 
> by allowing the bowlers to enter their names. Each frame is tracked 
> and properly displayed as the game progresses.
I agree with Kent. His statement reflects the "policy" of the tutors.

So if you are just looking for someone to do the work for you this is 
not the right place.

However if you have some idea of where to start, show us what you have 
figured out and where exactly you are stuck.

Also in my "dictionary" design a program does not mean write one. So 
your design can be a flowchart or pseudocode or a narrative. BTW is 
Python involved in this assignment? If it is then the instructor has a 
different meaning for "design".

How did you get into a class that seems to expect you to be able to do 
this assignment and you find yourself not able?

Hope this helps. Please respond in some way.


From bgailer at alum.rpi.edu  Tue Nov 27 23:12:30 2007
From: bgailer at alum.rpi.edu (bob gailer)
Date: Tue, 27 Nov 2007 17:12:30 -0500
Subject: [Tutor] List processing question - consolidating duplicate
	entries
In-Reply-To: <7d81675b0711271337o3c92fafga8f7d3392b71abfc@mail.gmail.com>
References: <7d81675b0711271337o3c92fafga8f7d3392b71abfc@mail.gmail.com>
Message-ID: <474C964E.5020404@alum.rpi.edu>

Richard Querin wrote:
> I'm trying to process a list and I'm stuck. Hopefully someone can help
> me out here:
>
> I've got a list that is formatted as follows:
> [Name,job#,jobname,workcode,hours]
>
> An example might be:
>
> [Bob,07129,projectA,4001,5]
> [Bob,07129,projectA,5001,2]
> [Bob,07101,projectB,4001,1]
> [Bob,07140,projectC,3001,3]
> [Bob,07099,projectD,3001,2]
> [Bob,07129,projectA,4001,4]
> [Bob,07099,projectD,4001,3]
> [Bob,07129,projectA,4001,2]
>
> Now I'd like to consolidate entries that are duplicates. Duplicates
> meaning entries that share the same Name, job#, jobname and workcode.
> So for the list above, there are 3 entries for projectA which have a
> workcode of 4001. (there is a fourth entry for projectA but it's
> workcode is 5001 and not 4001).
>
> So I'd like to end up with a list so that the three duplicate entries
> are consolidated into one with their hours added up:
>
> [Bob,07129,projectA,4001,11]
> [Bob,07129,projectA,5001,2]
> [Bob,07101,projectB,4001,1]
> [Bob,07140,projectC,3001,3]
> [Bob,07099,projectD,3001,2]
> [Bob,07099,projectD,4001,3]
There are at least 2 more approaches.

1 - Use sqlite (or some other database), insert the data into the 
database, then run a sql statement to sum(hours) group by name, project, 
workcode.

2 - Sort the list. Create a new list with an entry for the first name, 
project, workcode. Step thru the list. Each time the name, project, 
workcode is the same, accumulate hours. When any of those change, create 
a list entry for the next name, project, workcode and again start 
accumulating hours.

The last is IMHO the most straightforward, and easiest to code.

From kent37 at tds.net  Tue Nov 27 23:40:41 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 27 Nov 2007 17:40:41 -0500
Subject: [Tutor] List processing question - consolidating
	duplicate	entries
In-Reply-To: <474C964E.5020404@alum.rpi.edu>
References: <7d81675b0711271337o3c92fafga8f7d3392b71abfc@mail.gmail.com>
	<474C964E.5020404@alum.rpi.edu>
Message-ID: <474C9CE9.9080807@tds.net>

bob gailer wrote:
> 2 - Sort the list. Create a new list with an entry for the first name, 
> project, workcode. Step thru the list. Each time the name, project, 
> workcode is the same, accumulate hours. When any of those change, create 
> a list entry for the next name, project, workcode and again start 
> accumulating hours.

This is a two-liner using itertools.groupby() and operator.itemgetter:

data = [['Bob', '07129', 'projectA', '4001',5],
['Bob', '07129', 'projectA', '5001',2],
['Bob', '07101', 'projectB', '4001',1],
['Bob', '07140', 'projectC', '3001',3],
['Bob', '07099', 'projectD', '3001',2],
['Bob', '07129', 'projectA', '4001',4],
['Bob', '07099', 'projectD', '4001',3],
['Bob', '07129', 'projectA', '4001',2]
]

import itertools, operator
for k, g in itertools.groupby(sorted(data), key=operator.itemgetter(0, 
1, 2, 3)):
   print k, sum(item[4] for item in g)

For some explanation see my recent post:
http://mail.python.org/pipermail/tutor/2007-November/058753.html

Kent

From rfquerin at gmail.com  Wed Nov 28 03:49:35 2007
From: rfquerin at gmail.com (Richard Querin)
Date: Tue, 27 Nov 2007 21:49:35 -0500
Subject: [Tutor] Python CMS advice wanted
In-Reply-To: <r02010500-1049-9D090E509D2711DC8B31001124DEBE0E@192.168.69.99>
References: <a9dde83f82e727c3c50e915118fc7d8c@well.com>
	<r02010500-1049-9D090E509D2711DC8B31001124DEBE0E@192.168.69.99>
Message-ID: <7d81675b0711271849t61c450bel2bc9f950960f4fbc@mail.gmail.com>

Whoa!. Lots of very good advice here. Thanks to all.

After reading it all I'm wondering if maybe a templating system like
Cheetah might be the way to go for us. I'll have to do a lot more
reading and exploring. I'd love to learn something like Django but
like it has been said, that's really a framework you'd use to build a
CMS. And this site is really a labour of love and not a business
venture so the time we invest into it at the moment is kind of in
short supply.

While we have less than 50 entries at the moment, adding each one is
still quite a hack. I've written a small wxpython app to take away
some of the pain of it, but it's still prone to corruption and still
too much work.

I think I'll have to watch some demo's to get a feel for how some of
these systems work before going down any specific path, because a lot
of it is still Greek to me.

Again sincere thanks for all the great info, and I'll try to check
back in on this thread once we get going on a solution.

RQ

From kent37 at tds.net  Wed Nov 28 04:16:39 2007
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 27 Nov 2007 22:16:39 -0500
Subject: [Tutor] Python CMS advice wanted
In-Reply-To: <7d81675b0711271849t61c450bel2bc9f950960f4fbc@mail.gmail.com>
References: <a9dde83f82e727c3c50e915118fc7d8c@well.com>	<r02010500-1049-9D090E509D2711DC8B31001124DEBE0E@192.168.69.99>
	<7d81675b0711271849t61c450bel2bc9f950960f4fbc@mail.gmail.com>
Message-ID: <474CDD97.8030804@tds.net>

Richard Querin wrote:

> While we have less than 50 entries at the moment, adding each one is
> still quite a hack. I've written a small wxpython app to take away
> some of the pain of it, but it's still prone to corruption and still
> too much work.

Have you looked at Firedrop2? It makes it pretty easy to generate a 
blog. I'm not sure if it would create your format though.
http://www.voidspace.org.uk/python/programs.shtml#firedrop

I think it would be pretty easy to put your site together in Django. 
Each entry could be a database item, you would use the admin interface 
to create them.

Kent

From jim at well.com  Wed Nov 28 04:48:23 2007
From: jim at well.com (jim stockford)
Date: Tue, 27 Nov 2007 19:48:23 -0800
Subject: [Tutor] Python CMS advice wanted
In-Reply-To: <7d81675b0711271849t61c450bel2bc9f950960f4fbc@mail.gmail.com>
References: <a9dde83f82e727c3c50e915118fc7d8c@well.com>
	<r02010500-1049-9D090E509D2711DC8B31001124DEBE0E@192.168.69.99>
	<7d81675b0711271849t61c450bel2bc9f950960f4fbc@mail.gmail.com>
Message-ID: <88178059882ad7cf5fcb161a0d62a2a8@well.com>


    I'd love to know scott's definition of "framework", especially
contrasting with full-blown CMS.
    Frameworks for Python:
CherryPy ? Django ? Karrigell ? Nevow ? Porcupine ? Pylons ? Spyce ? 
TurboGears ? TwistedWeb ? Webware ? Zope
    per  http://en.wikipedia.org/wiki/Django_(web_framework)

    Richard, i think from the (very) little investigation i did
following scott's last post, that you should investigate
Django. to me it looks like a pretty streamlined "framework"
that marries a database (your choice of a few) to a web
server (apache seems their choice) via mod_python.
    there's a learning curve, but that seems an inevitable
hurdle: you only get to choose which, so do a little
window shopping.
    the example sites look streamlined. django presents
an object-oriented API to whatever database you hook
to.  mod_python ensures near-optimum performance.
    If you take a look on the top-level page for django
http://www.djangoproject.com/
you should see a link for "DRY principle". Click it and
read and follow the links in the subsequent pages:
you'll find an easy-to-read, to-the-point set of links to
coders' wisdom (Don't Repeat Yourself,
OnceAndOnlyOnce, YouAren'tGonnaNeedIt, and more).


http://www.djangoproject.com/


On Nov 27, 2007, at 6:49 PM, Richard Querin wrote:

> Whoa!. Lots of very good advice here. Thanks to all.
>
> After reading it all I'm wondering if maybe a templating system like
> Cheetah might be the way to go for us. I'll have to do a lot more
> reading and exploring. I'd love to learn something like Django but
> like it has been said, that's really a framework you'd use to build a
> CMS. And this site is really a labour of love and not a business
> venture so the time we invest into it at the moment is kind of in
> short supply.
>
> While we have less than 50 entries at the moment, adding each one is
> still quite a hack. I've written a small wxpython app to take away
> some of the pain of it, but it's still prone to corruption and still
> too much work.
>
> I think I'll have to watch some demo's to get a feel for how some of
> these systems work before going down any specific path, because a lot
> of it is still Greek to me.
>
> Again sincere thanks for all the great info, and I'll try to check
> back in on this thread once we get going on a solution.
>
> RQ
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


From mlangford.cs03 at gtalumni.org  Wed Nov 28 06:10:19 2007
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Wed, 28 Nov 2007 00:10:19 -0500
Subject: [Tutor] List processing question - consolidating duplicate
	entries
In-Reply-To: <7d81675b0711271337o3c92fafga8f7d3392b71abfc@mail.gmail.com>
References: <7d81675b0711271337o3c92fafga8f7d3392b71abfc@mail.gmail.com>
Message-ID: <82b4f5810711272110x2ca9d885w621a178d2ff7c51d@mail.gmail.com>

What you want is a set of entries. Unfortunately, python lists are not
"hashable" which means you have to convert them to something hashable
before you can use the python set datatype.

What you'd like to do is add each to a set while converting them to a
tuple, then convert them back out of the set. In python that is:

#
# remove duplicate entries
#
#  myEntries is a list of lists,
#    such as [[1,2,3],[1,2,"foo"],[1,2,3]]
#
s=set()
[s.add(tuple(x)) for x in myEntries]
myEntries = [list(x) for x in list(s)]

List completions are useful for all sorts of list work, this included.

Do not use a database, that would be very ugly and time consuming too.

This is cleaner than the dict keys approach, as you'd *also* have to
convert to tuples for that.

If you need this in non-list completion form, I'd be happy to write
one if that's clearer to you on what's happening.

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

From pydev at rscorp.ab.ca  Wed Nov 28 08:34:00 2007
From: pydev at rscorp.ab.ca (Scott SA)
Date: Wed, 28 Nov 2007 00:34:00 -0700
Subject: [Tutor] Python CMS advice wanted
In-Reply-To: <7d81675b0711271849t61c450bel2bc9f950960f4fbc@mail.gmail.com>
Message-ID: <r02010500-1049-49A6CAEC9D8411DC8B31001124DEBE0E@[192.168.69.99]>

On 11/27/07, Richard Querin (rfquerin at gmail.com) wrote:

>After reading it all I'm wondering if maybe a templating system like
>Cheetah might be the way to go for us. I'll have to do a lot more
>reading and exploring.

Sure. Be wary of any system that allows the template to freely call python i.e. one system I've seen:
    <python: eval('unrestricted python code')/>

... 'nuf said.

>I'd love to learn something like Django but
>like it has been said, that's really a framework you'd use to build a
>CMS. And this site is really a labour of love and not a business
>venture so the time we invest into it at the moment is kind of in
>short supply.

There are a couple of 'screencasts' on 'showmedo.com', one of them is here:
    <http://showmedo.com/videos/video?name=1100000&fromSeriesID=110>

... it's the typical "Build a wiki in 20 minutes" dog 'n pony show, but you do get a feel for some of the key features.

There is a pretty direct line between the request and rendering a response. Everything arrives in a dictionary and is returned in a dictionary, usually with a template spec'd but can be direct too (this isn't totally unique to django, I'm just illustrating the concept).  URLs are parsed using regular expressions, a portable skill so it's not a framework-specific element and IMO doesn't count in the 'learning curve'.

A big difference between templating systems is how 'active content' is described. Some templating structures use embedded python within custom tags. This is not the case with django and for some that is a deal-breaker, others it is a deal-maker. It's pretty feature-rich, but _does_ have its own (well documented) syntax using curly-braces ie. {{ dict.item }} or {% ifequal %}.

The db interface is straightforward and much of it is managed for the developer, including the table creation; a single command-line call. There are a few gotcha's when you want to do some complex queries, but for most things it is straightforward and capable. There is the ability to use raw SQL, so the developer isn't 'trapped'.

Each table is defined as a python class with field-names as class-attributes and the class-name typically as the app & table-name i.e. 'thisap_apptable'. 

The developer can then define methods within each of the classes to do most table-related things i.e. custom type-chekcing, agregation of fields and so on. Quite pythonic indeed. (you could check out SQLObject for similar functionality in an independent library)tutor at python.org.

Again, much of the required skills are very portable and not framework specific. This was a selling point _for_me_, it feels natural to work with. It's automatic admin forms were another bonus, allowing the developer to focus on more important things. Did I mention the automatic forms???

It has a built-in server as well, typically for development and dead-simple to start/config. From the main project directory the call is:
    python manage.py runserver

... an optional port number can be added.

"manage.py" is a set of utility and maintenance scripts for creating the databases, seeing what SQL is generated and so on.

Still, as much as _I_ like this framework, I fully recognize there are good reasons why others exist and respect their capabilities. I don't want you or anyone else to use this because I said so, but because after review it is what meets your needs. 

All the best,

Scott

PS. In fact, I fully intend on exploring Pylons (and now Webpy) in the new year - nothing is perfect for all circumstances.


>While we have less than 50 entries at the moment, adding each one is
>still quite a hack. I've written a small wxpython app to take away
>some of the pain of it, but it's still prone to corruption and still
>too much work.
>
>I think I'll have to watch some demo's to get a feel for how some of
>these systems work before going down any specific path, because a lot
>of it is still Greek to me.
>
>Again sincere thanks for all the great info, and I'll try to check
>back in on this thread once we get going on a solution.


From pydev at rscorp.ab.ca  Wed Nov 28 08:39:19 2007
From: pydev at rscorp.ab.ca (Scott SA)
Date: Wed, 28 Nov 2007 00:39:19 -0700
Subject: [Tutor] Python CMS advice wanted
In-Reply-To: <88178059882ad7cf5fcb161a0d62a2a8@well.com>
Message-ID: <r02010500-1049-07A2A85E9D8511DC8B31001124DEBE0E@[192.168.69.99]>

On 11/27/07, jim stockford (jim at well.com) wrote:
>    I'd love to know scott's definition of "framework", especially
>contrasting with full-blown CMS.

Yes, when one compares something like Quixote to Zope, there is a _lot_ of middle-ground. They are all frameorks, just with incrementally larger feature-sets (a.k.a. bloat and learning curve). I just anecdotally draw anline in the sand when workflows and content start being managed extensively. With the two names above, I classify the first is a framework, the latter is hel^h^h^h a CMS.

    <http://en.wikipedia.org/wiki/Web_framework>

>    Frameworks for Python:
>CherryPy ? Django ? Karrigell ? Nevow ? Porcupine ? Pylons ? Spyce ? 
>TurboGears ? TwistedWeb ? Webware ? Zope

I just found a new-to-me rather lite framework:
    <http://webpy.org/>

There is also more related info here:
    <http://wiki.python.org/moin/WebProgramming>

A few years old, but still somewhat informative:
    <http://colorstudy.com/docs/shootout.html>
    <http://www.boddie.org.uk/python/web_frameworks.html>

>    Richard, i think from the (very) little investigation i did
>following scott's last post, that you should investigate
>Django. to me it looks like a pretty streamlined "framework"
>that marries a database (your choice of a few) to a web
>server (apache seems their choice) via mod_python.

FastCGI and WSGI are also supported, the latter looks promising. Has an integrated server as well.

>    If you take a look on the top-level page for django
>http://www.djangoproject.com/
>you should see a link for "DRY principle". Click it and
>read and follow the links in the subsequent pages:
>you'll find an easy-to-read, to-the-point set of links to
>coders' wisdom (Don't Repeat Yourself,
>OnceAndOnlyOnce, YouAren'tGonnaNeedIt, and more).
>
>http://www.djangoproject.com/

If nothing else, some of the documentation from the project does cover good general material, as you've pointed out. (I wish I could get my teen-aged kid to figure out the DRY principal... but I digress ;-)

Thanks for the good discussion, Jim. For my part, I think it's  about time for me to stick a fork in it 'cause it's done ;-)

Happy trails!

Scott

>On Nov 27, 2007, at 6:49 PM, Richard Querin wrote:
>
>> Whoa!. Lots of very good advice here. Thanks to all.
>>
>> After reading it all I'm wondering if maybe a templating system like
>> Cheetah might be the way to go for us. I'll have to do a lot more
>> reading and exploring. I'd love to learn something like Django but
>> like it has been said, that's really a framework you'd use to build a
>> CMS. And this site is really a labour of love and not a business
>> venture so the time we invest into it at the moment is kind of in
>> short supply.
>>
>> While we have less than 50 entries at the moment, adding each one is
>> still quite a hack. I've written a small wxpython app to take away
>> some of the pain of it, but it's still prone to corruption and still
>> too much work.
>>
>> I think I'll have to watch some demo's to get a feel for how some of
>> these systems work before going down any specific path, because a lot
>> of it is still Greek to me.
>>
>> Again sincere thanks for all the great info, and I'll try to check
>> back in on this thread once we get going on a solution.
>>
>> RQ
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>

From keridee at jayco.net  Wed Nov 28 13:43:32 2007
From: keridee at jayco.net (Tiger12506)
Date: Wed, 28 Nov 2007 07:43:32 -0500
Subject: [Tutor] List processing question - consolidating
	duplicateentries
References: <7d81675b0711271337o3c92fafga8f7d3392b71abfc@mail.gmail.com>
	<82b4f5810711272110x2ca9d885w621a178d2ff7c51d@mail.gmail.com>
Message-ID: <001601c831bc$4c869440$aefce004@jslaptop>

> s=set()
> [s.add(tuple(x)) for x in myEntries]
> myEntries = [list(x) for x in list(s)]

This could be written more concisely as...

s = set(tuple(x) for x in myEntries)
myEntries = [list(x) for x in list(s)]

Generator expressions are really cool.

Not what the OP asked for exactly. He wanted to eliminate duplicates by 
adding their last columns. He said the last column is a number of hours that 
pertain to the first four columns. When you apply your method, it will not 
get rid of duplicate projects, just circumstances where the number of hours 
is equivalent also, and of course, not add the hours like they should be. I 
like the dictionary approach for this personally...

di = {}
for x in myEntries:
    try: di[x[:3]]+=x[4]
    except KeyError: di[x[:3]] = x[4]

This can be written even smaller and cleaner if you use the default value 
method... 


From kent37 at tds.net  Wed Nov 28 13:52:02 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 28 Nov 2007 07:52:02 -0500
Subject: [Tutor] List processing question - consolidating
	duplicate	entries
In-Reply-To: <82b4f5810711272110x2ca9d885w621a178d2ff7c51d@mail.gmail.com>
References: <7d81675b0711271337o3c92fafga8f7d3392b71abfc@mail.gmail.com>
	<82b4f5810711272110x2ca9d885w621a178d2ff7c51d@mail.gmail.com>
Message-ID: <474D6472.3030908@tds.net>

Michael Langford wrote:
> What you want is a set of entries.

Not really; he wants to aggregate entries.

> # remove duplicate entries
> #
> #  myEntries is a list of lists,
> #    such as [[1,2,3],[1,2,"foo"],[1,2,3]]
> #
> s=set()
> [s.add(tuple(x)) for x in myEntries]

A set can be constructed directly from a sequence so this can be written as
  s=set(tuple(x) for x in myEntries)

BTW I personally think it is bad style to use a list comprehension just 
for the side effect of iteration, IMO it is clearer to write out the 
loop when you want a loop.

Kent

From spam.spam at hfbk-hamburg.de  Wed Nov 28 15:28:49 2007
From: spam.spam at hfbk-hamburg.de (sa9k063)
Date: Wed, 28 Nov 2007 15:28:49 +0100
Subject: [Tutor] Python CMS advice wanted
In-Reply-To: <7d81675b0711270652r5332c8b1u8ae53aa78c2c6daa@mail.gmail.com>
References: <7d81675b0711270652r5332c8b1u8ae53aa78c2c6daa@mail.gmail.com>
Message-ID: <474D7B21.7080300@hfbk-hamburg.de>

Richard Querin wrote:
> - Python based - I have a rudimentary knowledge of Python and like it, so
> I'd prefer to go this route
> - Simple - Our needs are not very complex, we're really just thinking about
> maintainability and expandability.
> - We want to be able to customize the look and layout of the site to our
> whim.

while not really being a CMS but nevertheless easily abusable as a CMS I
would recommend trac: http://trac.edgewall.org

the wiki gives easy editing of pages, the look can be customized with
css, it's of course python and can be extended with plugins.

apart from being simple I like its clean and well-structured user interface.

hth,

tee


From johnpatrick at gerdeman.de  Wed Nov 28 19:24:02 2007
From: johnpatrick at gerdeman.de (John Gerdeman)
Date: Wed, 28 Nov 2007 19:24:02 +0100
Subject: [Tutor] update a ws.ListBox
Message-ID: <1196274242.5261.13.camel@forellle92>

Hello,

I'm trying to create a gui using wxpython on ubuntu 6.10 (read, that
some functions of wx differ on different OS). 

I have two Listbox items, Listbox1 and Listbox2. I want to update
Listbox2 according to the choice made in Listbox1.
I already looked at the wx API doc, but only found methods to insert
items or (de)select.

I know I can update a textctrl, but I need a way to make a choice based
on the first.

Here a Minimal example:

#!/usr/bin/python

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition,
(550, 350))

        self.listbox1_items = [ 'item1', 'item2']
        self.listbox2_items = ['select a item from the right']

        hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        vbox = wx.BoxSizer(wx.VERTICAL)

        panel = wx.Panel(self, -1)

        self.listbox1 = wx.ListBox(panel, 1, wx.DefaultPosition, (170,
130), self.listbox1_items, wx.LB_SINGLE)
        self.listbox1.SetSelection(0)
        self.listbox2 = wx.ListBox(panel, 2, wx.DefaultPosition, (170,
130), self.listbox2_items, wx.LB_SINGLE)
        self.listbox2.SetSelection(0)
        hbox1.Add(self.listbox1, 0, wx.TOP, 40)
        hbox1.Add(self.listbox2, 0, wx.TOP, 40)
        vbox.Add(hbox1, 0, wx.ALIGN_CENTRE)
        panel.SetSizer(vbox)

        self.Bind(wx.EVT_LISTBOX, self.OnListBox1, id=1)
        self.Bind(wx.EVT_LISTBOX, self.OnListBox2, id=2)

    def OnListBox1(self, event):
		index = event.GetSelection()
		choice = self.listbox1_items[index]
		print "You chose " + str(choice)
		if choice == 'item1':
			ret = ['choice1', 'choice2']
		elif choice == 'item2':
			ret = ['choice3', 'choice4']
		else:
			ret = ['Ooops']
		print "Now I somehow need a way to pass to self.listbox2 I can set
self.listbox2_items to ret, but self.listbox2 doesn't get updated"
		print ret
    def OnListBox2(self, event):
	    return True


class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'minexample.py')
        frame.Centre()
        frame.Show(True)
        return True

app = MyApp(0)
app.MainLoop()

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Dies ist ein digital signierter Nachrichtenteil
Url : http://mail.python.org/pipermail/tutor/attachments/20071128/c2d0bf14/attachment.pgp 

From evert.rol at gmail.com  Wed Nov 28 19:23:57 2007
From: evert.rol at gmail.com (Evert Rol)
Date: Wed, 28 Nov 2007 18:23:57 +0000
Subject: [Tutor] distutils: how to include a header file belonging to an
	extension module
Message-ID: <CAF9E68A-9F3D-4851-BE82-8BF9FE24C43A@gmail.com>

(this may not be a py-tutor question, but well)

I have a small C-extension module, consisting of 3 files  
(ndcombine_module.c, combine.c & combine.h). I can build the  
extension find 'in place' using distutils, but when creating a  
distribution (with setup.py sdist), the combine.h header file  
seemingly gets lost and I cannot build it anywhere else.
The extension part in setup.py looks like:

ndcombine_sources = [os.path.join('src', 'ext_lib', 'combine', p) for  
p in \
                      ('ndcombine_module.c', 'combine.c')]
ndcombine_ext = Extension('ndcombine',
                           sources=ndcombine_sources,
                           depends=[os.path.join('src', 'ext_lib',  
'combine',
                                                'combine.h')],
                           include_dirs = [numpyincludepath])

where I have tried to use 'depends', which seems to fail. Below that,  
there is of course

    setup(..., ext_modules=[ndcombine_ext], ...)

I feel I'm missing something, but I cannot think of what.
Suggestions most welcome.

Thanks,

   Evert

(The numpyincludepath points to the NumPy header files; that would be  
another question, how to that propely, other than going through the  
numpy configuration options, but I'll leave that.).


From chukgoodin at gmail.com  Wed Nov 28 19:36:26 2007
From: chukgoodin at gmail.com (Chuk Goodin)
Date: Wed, 28 Nov 2007 10:36:26 -0800
Subject: [Tutor] Getting a binary value from a file
Message-ID: <5bfe5dce0711281036r712a6336v22ceac27573f5c97@mail.gmail.com>

Okay, I actually can load the value fine, but then I'm not sure how to do
anything with it.

I have a file full of "integers". If I get a file handle (e.g. file1) and
then read something in, I get back some hex value. How can I go on to use
that in my program?

For example, in interactive mode, file1.read(4) gets me an output of
'/x00/x00/x00/x1c' (might not be exact, I'm at a different computer right
now). Can I just store that in a variable and then somehow convert it to
decimal?

Sorry if this is too newbish.

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

From jason.massey at gmail.com  Wed Nov 28 19:47:19 2007
From: jason.massey at gmail.com (Jason Massey)
Date: Wed, 28 Nov 2007 12:47:19 -0600
Subject: [Tutor] update a ws.ListBox
In-Reply-To: <1196274242.5261.13.camel@forellle92>
References: <1196274242.5261.13.camel@forellle92>
Message-ID: <7e3eab2c0711281047s265fcc3ex5794d0f8d55f55e1@mail.gmail.com>

Inserting this line:

self.listbox2.InsertItems([choice],0)

in your OnListBox1 method after your if/then/else statement puts the item
you select in ListBox1 appear in ListBox2.

You have to force choice into a list, otherwise it will insert each
individual letter in the string into the box one at a time.

Docs: http://wxwidgets.org/manuals/stable/wx_wxlistbox.html#wxlistbox

Now, admittedly, this is on a Windows XP machine, but I don't think that
such basic functionality would be different between platforms.


On Nov 28, 2007 12:24 PM, John Gerdeman <johnpatrick at gerdeman.de> wrote:

> Hello,
>
> I'm trying to create a gui using wxpython on ubuntu 6.10 (read, that
> some functions of wx differ on different OS).
>
> I have two Listbox items, Listbox1 and Listbox2. I want to update
> Listbox2 according to the choice made in Listbox1.
> I already looked at the wx API doc, but only found methods to insert
> items or (de)select.
>
> I know I can update a textctrl, but I need a way to make a choice based
> on the first.
>
> Here a Minimal example:
>
> #!/usr/bin/python
>
> import wx
>
> class MyFrame(wx.Frame):
>    def __init__(self, parent, id, title):
>        wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition,
> (550, 350))
>
>        self.listbox1_items = [ 'item1', 'item2']
>        self.listbox2_items = ['select a item from the right']
>
>        hbox1 = wx.BoxSizer(wx.HORIZONTAL)
>        vbox = wx.BoxSizer(wx.VERTICAL)
>
>        panel = wx.Panel(self, -1)
>
>        self.listbox1 = wx.ListBox(panel, 1, wx.DefaultPosition, (170,
> 130), self.listbox1_items, wx.LB_SINGLE)
>        self.listbox1.SetSelection(0)
>        self.listbox2 = wx.ListBox(panel, 2, wx.DefaultPosition, (170,
> 130), self.listbox2_items, wx.LB_SINGLE)
>        self.listbox2.SetSelection(0)
>        hbox1.Add(self.listbox1, 0, wx.TOP, 40)
>        hbox1.Add(self.listbox2, 0, wx.TOP, 40)
>        vbox.Add(hbox1, 0, wx.ALIGN_CENTRE)
>        panel.SetSizer(vbox)
>
>        self.Bind(wx.EVT_LISTBOX, self.OnListBox1, id=1)
>        self.Bind(wx.EVT_LISTBOX, self.OnListBox2, id=2)
>
>    def OnListBox1(self, event):
>                index = event.GetSelection()
>                choice = self.listbox1_items[index]
>                print "You chose " + str(choice)
>                if choice == 'item1':
>                        ret = ['choice1', 'choice2']
>                elif choice == 'item2':
>                        ret = ['choice3', 'choice4']
>                else:
>                        ret = ['Ooops']
>                print "Now I somehow need a way to pass to self.listbox2 I
> can set
> self.listbox2_items to ret, but self.listbox2 doesn't get updated"
>                print ret
>    def OnListBox2(self, event):
>            return True
>
>
> class MyApp(wx.App):
>    def OnInit(self):
>        frame = MyFrame(None, -1, 'minexample.py')
>        frame.Centre()
>        frame.Show(True)
>        return True
>
> app = MyApp(0)
> app.MainLoop()
>
>
> _______________________________________________
> 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/20071128/e34a59e3/attachment.htm 

From ingoogni at gmail.com  Wed Nov 28 19:53:03 2007
From: ingoogni at gmail.com (ingo janssen)
Date: Wed, 28 Nov 2007 19:53:03 +0100
Subject: [Tutor] two way dictionary
Message-ID: <ffe191d10711281053w2d51324r407cd4f131cf8ff1@mail.gmail.com>

for a little cherrypy app I'm working on I wrote the piece of code
below. Goal is to obscure the first part of a directory path(s) the
user is browsing. Replacing the first part of the path with an alias
works fine, but for the application it has to work both ways. I know
how to swap the keys and values of the dict but that's not elegant as
it can be changed over time.
Is there a dict that works "both ways"?
Could a dict be constructed from the dict class that works both ways?
Is writing code around a list of tuples more elegant? home = [('one' ,
"c:\\gnuwin32"), ('two' , "c:\\dell")]
Did I miss the completely obvious way to deal with the problem?


%<-----%<-----%<-----%<-----%<-----%<-----

import os

home={
   'one':"c:\\gnuwin32",
   'two':"c:\\dell",
}

def fetch_alias(path, home_dict):
   path = os.path.normpath(path)
   pathlist = path.split(os.sep)
   if pathlist[0] in home_dict:
       pathlist[0] = home_dict[pathlist[0]]
       newpath = os.sep.join(pathlist)
       return os.path.normpath(newpath)
   else:
       print "fail"

path='two\\truus\\tovert\\konijn'
print fetch_alias(path, home)

%<-----%<-----%<-----%<-----%<-----%<-----

Ingo

From kent37 at tds.net  Wed Nov 28 19:58:37 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 28 Nov 2007 13:58:37 -0500
Subject: [Tutor] Getting a binary value from a file
In-Reply-To: <5bfe5dce0711281036r712a6336v22ceac27573f5c97@mail.gmail.com>
References: <5bfe5dce0711281036r712a6336v22ceac27573f5c97@mail.gmail.com>
Message-ID: <474DBA5D.4040906@tds.net>

Chuk Goodin wrote:

> I have a file full of "integers". If I get a file handle (e.g. file1) 
> and then read something in, I get back some hex value. How can I go on 
> to use that in my program?
> 
> For example, in interactive mode, file1.read(4) gets me an output of 
> '/x00/x00/x00/x1c' (might not be exact, I'm at a different computer 
> right now). Can I just store that in a variable and then somehow convert 
> it to decimal?

Use the struct module:
In [26]: import struct
In [29]: struct.unpack('>i', '\x00\x00\x00\x1c')[0]
Out[29]: 28

Note the value returned from unpack is a tuple, hence the [0] subscript.
http://docs.python.org/lib/module-struct.html

> Sorry if this is too newbish.

Not for this list!

Kent

From evert.rol at gmail.com  Wed Nov 28 20:09:46 2007
From: evert.rol at gmail.com (Evert Rol)
Date: Wed, 28 Nov 2007 19:09:46 +0000
Subject: [Tutor] distutils: how to include a header file belonging to an
	extension module
In-Reply-To: <CAF9E68A-9F3D-4851-BE82-8BF9FE24C43A@gmail.com>
References: <CAF9E68A-9F3D-4851-BE82-8BF9FE24C43A@gmail.com>
Message-ID: <37146D54-2CAD-4331-9578-C7FFE7090D3A@gmail.com>

> I have a small C-extension module, consisting of 3 files  
> (ndcombine_module.c, combine.c & combine.h). I can build the  
> extension find 'in place' using distutils, but when creating a  
> distribution (with setup.py sdist), the combine.h header file  
> seemingly gets lost and I cannot build it anywhere else.
> The extension part in setup.py looks like:
>
> ndcombine_sources = [os.path.join('src', 'ext_lib', 'combine', p)  
> for p in \
>                      ('ndcombine_module.c', 'combine.c')]
> ndcombine_ext = Extension('ndcombine',
>                           sources=ndcombine_sources,
>                           depends=[os.path.join('src', 'ext_lib',  
> 'combine',
>                                                'combine.h')],
>                           include_dirs = [numpyincludepath])
>
> where I have tried to use 'depends', which seems to fail. Below  
> that, there is of course
>
>    setup(..., ext_modules=[ndcombine_ext], ...)
>
> I feel I'm missing something, but I cannot think of what.


Got it (and I had done it correctly for another extension, ages ago):  
use MANIFEST.in.

<MANIFEST.in>:
recursive-include src *.py
include src/ext_lib/combine/combine.c
include src/ext_lib/combine/combine.h
include src/ext_lib/combine/ndcombine_module.c
<EOF>

(aka read chapter 4 of the distutils documentation; sigh)

'depends' only tells to rebuild things when anything in those files  
changes; it functions more like a Makefile.



From kent37 at tds.net  Wed Nov 28 20:16:28 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 28 Nov 2007 14:16:28 -0500
Subject: [Tutor] two way dictionary
In-Reply-To: <ffe191d10711281053w2d51324r407cd4f131cf8ff1@mail.gmail.com>
References: <ffe191d10711281053w2d51324r407cd4f131cf8ff1@mail.gmail.com>
Message-ID: <474DBE8C.1040700@tds.net>

ingo janssen wrote:
> Is there a dict that works "both ways"?

Some discussion here:
http://groups.google.com/group/comp.lang.python/tree/browse_frm/thread/c5ab5cf524a158be/2a4a941d55e011be?hl=en&rnum=1&_done=%2Fgroup%2Fcomp.lang.python%2Fbrowse_frm%2Fthread%2Fc5ab5cf524a158be%2F4c02e7b9c3b44c37%3Fhl%3Den%26lnk%3Dgst%26#doc_2a4a941d55e011be

another implementation here:
http://www.radlogic.com/releases/two_way_dict.py

Kent

From alan.gauld at btinternet.com  Wed Nov 28 21:04:20 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 28 Nov 2007 20:04:20 -0000
Subject: [Tutor] update a ws.ListBox
References: <1196274242.5261.13.camel@forellle92>
Message-ID: <fikhk9$d2d$1@ger.gmane.org>

I'm not sure this is exactly what you want but it does 
something like it:

 def OnListBox1(self, event):
    index = event.GetSelection()
    choice = self.listbox1_items[index]
    if choice == 'item1':
       ret = ['choice1', 'choice2']
    elif choice == 'item2':
       ret = ['choice3', 'choice4']
    else:
       ret = ['Ooops']
    self.listbox2.SetItems(ret)
    self.listbox2.SetSelection(index)

The help() command at the >>> prompt is your 
friend...es[ecially coupled with the IDLE/Pythonwin 
method completion feature

>>> import wx
>>> help(wx.ListBox.

Should display a list of long methods which you can browse and view

-- 
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/20071128/3c16bd01/attachment.htm 

From macintyredev at gmail.com  Wed Nov 28 22:00:24 2007
From: macintyredev at gmail.com (Devon MacIntyre)
Date: Wed, 28 Nov 2007 13:00:24 -0800
Subject: [Tutor] Variables and Functions
Message-ID: <4c12d31a0711281300v67a6e8a2he4d200d8a111703d@mail.gmail.com>

Hi,
Just wondering, how would I get a variable out of one function and into
another? I'm trying to make a Sudoku puzzle for Python 2.5.1, and in one
function I have the finished puzzle (as a matrix) called 'puzzle'. Using the
'copy' module I made a deep copy called 'new_puzzle'. That function is
called to create the puzzle and its duplicate, because new_puzzle gets
changed so that 85% of the numbers in the matrix get replaced by an empty
string. Now, I have another function that allows you to choose the where on
the grid to put in the number, but I also need to get new_puzzle in that
function to add numbers not only on the Turtle grid, but add them in
new_puzzle so I can compare it with the original 'puzzle' variable.

PS: Both functions 'new_sudoku()' and 'play_game()' are called by a function
called 'new_game()'. Also, I'm using a Mac, but I'm not sure if that affects
the code or not.

Thanks in advance.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071128/aaa93151/attachment.htm 

From keridee at jayco.net  Wed Nov 28 22:47:26 2007
From: keridee at jayco.net (Tiger12506)
Date: Wed, 28 Nov 2007 16:47:26 -0500
Subject: [Tutor] Variables and Functions
References: <4c12d31a0711281300v67a6e8a2he4d200d8a111703d@mail.gmail.com>
Message-ID: <006a01c83208$6f221190$62fce004@jslaptop>

Sounds like an excuse for a global (aggh!) variable.
Or more properly, wrap all of the relevant functions in a class and use a
class variable for your puzzle



----- Original Message ----- 
From: "Devon MacIntyre" <macintyredev at gmail.com>
To: <tutor at python.org>
Sent: Wednesday, November 28, 2007 4:00 PM
Subject: [Tutor] Variables and Functions


> Hi,
> Just wondering, how would I get a variable out of one function and into
> another? I'm trying to make a Sudoku puzzle for Python 2.5.1, and in one
> function I have the finished puzzle (as a matrix) called 'puzzle'. Using
> the
> 'copy' module I made a deep copy called 'new_puzzle'. That function is
> called to create the puzzle and its duplicate, because new_puzzle gets
> changed so that 85% of the numbers in the matrix get replaced by an empty
> string. Now, I have another function that allows you to choose the where
> on
> the grid to put in the number, but I also need to get new_puzzle in that
> function to add numbers not only on the Turtle grid, but add them in
> new_puzzle so I can compare it with the original 'puzzle' variable.
>
> PS: Both functions 'new_sudoku()' and 'play_game()' are called by a
> function
> called 'new_game()'. Also, I'm using a Mac, but I'm not sure if that
> affects
> the code or not.
>
> Thanks in advance.
>


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


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


From ingoogni at gmail.com  Wed Nov 28 22:50:00 2007
From: ingoogni at gmail.com (ingo janssen)
Date: Wed, 28 Nov 2007 22:50:00 +0100
Subject: [Tutor] two way dictionary
In-Reply-To: <474DBE8C.1040700@tds.net>
References: <ffe191d10711281053w2d51324r407cd4f131cf8ff1@mail.gmail.com>
	<474DBE8C.1040700@tds.net>
Message-ID: <ffe191d10711281350l165ad897jf60f8a43ac2e5c89@mail.gmail.com>

On Nov 28, 2007 8:16 PM, Kent Johnson <kent37 at tds.net> wrote:
> ingo janssen wrote:
> > Is there a dict that works "both ways"?
>
> another implementation here:
> http://www.radlogic.com/releases/two_way_dict.py
>

Perfect, never thought to actually search for 'two way dict'.
Thanks Kent.

Ingo

From kent37 at tds.net  Thu Nov 29 01:18:48 2007
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 28 Nov 2007 19:18:48 -0500
Subject: [Tutor] Variables and Functions
In-Reply-To: <4c12d31a0711281300v67a6e8a2he4d200d8a111703d@mail.gmail.com>
References: <4c12d31a0711281300v67a6e8a2he4d200d8a111703d@mail.gmail.com>
Message-ID: <474E0568.60202@tds.net>

Devon MacIntyre wrote:
> Hi,
> Just wondering, how would I get a variable out of one function and into 
> another? 

I don't understand your description of your situation, maybe you could 
show a little code as a simple example?

The usual way to get a variable out of a function is to return a value 
from the function. The usual way to get a variable into a function is to 
pass a parameter. If you want tighter coupling than that maybe you 
should make the functions into methods of a class and make the variables 
into instance attributes.

HTH,
Kent

From alan.gauld at btinternet.com  Thu Nov 29 01:43:34 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 29 Nov 2007 00:43:34 -0000
Subject: [Tutor] Python CMS advice wanted
References: <a9dde83f82e727c3c50e915118fc7d8c@well.com><r02010500-1049-9D090E509D2711DC8B31001124DEBE0E@192.168.69.99>
	<7d81675b0711271849t61c450bel2bc9f950960f4fbc@mail.gmail.com>
Message-ID: <fil1vr$2ut$1@ger.gmane.org>

"Richard Querin" <rfquerin at gmail.com> wrote

> After reading it all I'm wondering if maybe a templating system like
> Cheetah might be the way to go for us.

For a simple CMS a templating system like Kid or Cheetah are
probably all you need. If you want to include dynamic content
add CherryPy or similar to translate HTTP requests into Python
method calls. Finally if you use a database then look at an
Object Relational Mapper (ORM) such as Alchemy. And if
you need all three opt for TurboGears(which is simply a packaging
of Kid, CherryPy and Alchemy) or Django (which is a more homogenous
whole)

But having looked at several web frameworks, including non-Python
ones they are all pretty much tackling those three areas:
1) Mapping HTTP requests to functions/methods
2) Template systems to decouple application and presentation
3) An OOP link to a database

In short, it won't make much difference which you use if your
needs are basic and conventional.

> reading and exploring. I'd love to learn something like Django but
> like it has been said, that's really a framework you'd use to build 
> a
> CMS.

I disagree, Django is a system to make building web sites easy.
A CMS manages content on a web site and includes all sorts of
features that Django doesn't and most folks don't need unless they
have thousands of pages and need to allow non technical users to
dynamically add new pages without coding. Products like Zope
and BroadVision (a commercial alternative) are CMS capable
of managing sites like Amazon or Expedia, but most small web
sites with only a few dozen pages get by with simple templates.

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 Nov 29 01:56:30 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 29 Nov 2007 00:56:30 -0000
Subject: [Tutor] update a ws.ListBox
References: <1196274242.5261.13.camel@forellle92> <fikhk9$d2d$1@ger.gmane.org>
Message-ID: <fil2o3$4qb$1@ger.gmane.org>


"Alan Gauld" <alan.gauld at btinternet.com> wrote 

> >>> import wx
> >>> help(wx.ListBox.
>
> Should display a list of long methods which you can browse and view

Doh!
Should be "... a long list of methods..." of course.

:-(

Alan G.


From alan.gauld at btinternet.com  Thu Nov 29 02:01:59 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 29 Nov 2007 01:01:59 -0000
Subject: [Tutor] Variables and Functions
References: <4c12d31a0711281300v67a6e8a2he4d200d8a111703d@mail.gmail.com>
Message-ID: <fil32c$5ot$1@ger.gmane.org>

"Devon MacIntyre" <macintyredev at gmail.com> wrote

> Just wondering, how would I get a variable out of one function and 
> into
> another?

return the value from one function and pass it as an argument to the 
other.
Example:

def oneFunction()
     x = [1,2,3]
     return x

def another(aValue):
     print aValue


def main():
    myList = oneFunction()
    another(myList)

Does that make any kind of sense to you?
For more on functions and arguments and parameter passing
see my tutorial topic on Modules and functions.

> called 'new_game()'. Also, I'm using a Mac, but I'm not sure if that 
> affects
> the code or not.

Nope, the Mac makes no difference whatsoever in this situation. :-)


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



From macintyredev at gmail.com  Thu Nov 29 02:51:39 2007
From: macintyredev at gmail.com (Devon MacIntyre)
Date: Wed, 28 Nov 2007 17:51:39 -0800
Subject: [Tutor] Variables and Functions
In-Reply-To: <474E0568.60202@tds.net>
References: <4c12d31a0711281300v67a6e8a2he4d200d8a111703d@mail.gmail.com>
	<474E0568.60202@tds.net>
Message-ID: <4c12d31a0711281751i75d6439bnfb37e089ce0afc87@mail.gmail.com>

Hi,

I have two functions, 'new_sudoku' and 'play_game'. In new_sudoku, I have a
pre-determined puzzle (I wasn't able to get a randomly generated puzzle
working), as a matrix in the variable 'puzzle'. I imported the 'copy' module
and made a deep-copy of 'puzzle' to make 'new_puzzle', which randomly has
85% of the digits replaced by an empty string. Now that 'new_puzzle' is only
15% filled with numbers, I use turtle to place the numbers on a grid that I
made (also with turtle). After the grid and 'new_puzzle' are generated, I
ask the player if he/she wants to begin playing. If yes, then the function
'play_game' is started. Here, I'm going to let the player choose spots to
input their own numbers to fill in the board. My problem is that I can't get
the variables 'puzzle' and 'new_puzzle' into that function (to be compared)
because they are not globally defined; only in 'new_sudoku' function. Here's
some selected code from my program:

def swap_row(puzzle,row1,row2):
    temp = puzzle[row1]
    puzzle[row1] = puzzle[row2]
    puzzle[row2] = temp

def new_sudoku():
    puzzle = [[1,2,3,4,5,6,7,8,9], \
              [4,5,6,7,8,9,1,2,3], \
              [7,8,9,1,2,3,4,5,6], \
              [2,3,4,5,6,7,8,9,1], \
              [5,6,7,8,9,1,2,3,4], \
              [8,9,1,2,3,4,5,6,7], \
              [3,4,5,6,7,8,9,1,2], \
              [6,7,8,9,1,2,3,4,5], \
              [9,1,2,3,4,5,6,7,8]]
    num_of_swap = random.randint(10,20)
    for i in range(num_of_swap):
        row1 = random.randint(0,8)
        row2 = random.randint(0,8)
        if row1/3 == row2/3:
            swap_row(puzzle,row1,row2)
    new_puzzle = copy.deepcopy(puzzle)
    sparseness = 0.85
    for i in range(9):
        for j in range(9):
            if random.uniform(0,1) < sparseness:
                new_puzzle[i][j] = ''

def play_game():
    '''
    Here is where I need the variables 'puzzle' and 'new_puzzle' to be
brought.
    '''

I read about the 'class' module, but am not sure on it's execution. I really
appreciate any time spent on my (simple) problem.
Thanks in advance.

On Nov 28, 2007 4:18 PM, Kent Johnson <kent37 at tds.net> wrote:

> Devon MacIntyre wrote:
> > Hi,
> > Just wondering, how would I get a variable out of one function and into
> > another?
>
> I don't understand your description of your situation, maybe you could
> show a little code as a simple example?
>
> The usual way to get a variable out of a function is to return a value
> from the function. The usual way to get a variable into a function is to
> pass a parameter. If you want tighter coupling than that maybe you
> should make the functions into methods of a class and make the variables
> into instance attributes.
>
> HTH,
> Kent
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071128/f9061173/attachment.htm 

From keridee at jayco.net  Thu Nov 29 04:13:12 2007
From: keridee at jayco.net (Tiger12506)
Date: Wed, 28 Nov 2007 22:13:12 -0500
Subject: [Tutor] Variables and Functions
References: <4c12d31a0711281300v67a6e8a2he4d200d8a111703d@mail.gmail.com><474E0568.60202@tds.net>
	<4c12d31a0711281751i75d6439bnfb37e089ce0afc87@mail.gmail.com>
Message-ID: <002301c83235$ee3511d0$45fce004@jslaptop>

Okay. "Class" is not a module. It is a keyword that defines a new type. 
Similar to an integer, or a string. But in the case of a class, you define 
what happens when you add, subtract, open, close, etc. by defining "methods" 
of a class. A classic example is a car.

class Car:
  running = 0
  headlightson = 0
  driving = 0
  def start(self):
    self.running = 1
  def drive(self):
    self.driving = 1
  def opendoor(self):
    self.door = 1
  def closedoor(self):
    self.door = 0
  def turnonheadlights(self):
    self.headlightson = 1

In the case of your puzzle, it would roughly look like this->

class Sudoku:
    def creatpuzzle(self, which):
      self.puzzle = #whatever code it takes to make that list
    def emptypuzzle(self):
      #code that uses self.puzzle because it is accessible in all methods of 
the class

Just a rough guideline of what we mean when we say you can put all of your 
functions in a class and use a class variable (in this case... self.puzzle)



----- Original Message ----- 
From: "Devon MacIntyre" <macintyredev at gmail.com>
To: "Kent Johnson" <kent37 at tds.net>
Cc: <tutor at python.org>
Sent: Wednesday, November 28, 2007 8:51 PM
Subject: Re: [Tutor] Variables and Functions


> Hi,
>
> I have two functions, 'new_sudoku' and 'play_game'. In new_sudoku, I have 
> a
> pre-determined puzzle (I wasn't able to get a randomly generated puzzle
> working), as a matrix in the variable 'puzzle'. I imported the 'copy' 
> module
> and made a deep-copy of 'puzzle' to make 'new_puzzle', which randomly has
> 85% of the digits replaced by an empty string. Now that 'new_puzzle' is 
> only
> 15% filled with numbers, I use turtle to place the numbers on a grid that 
> I
> made (also with turtle). After the grid and 'new_puzzle' are generated, I
> ask the player if he/she wants to begin playing. If yes, then the function
> 'play_game' is started. Here, I'm going to let the player choose spots to
> input their own numbers to fill in the board. My problem is that I can't 
> get
> the variables 'puzzle' and 'new_puzzle' into that function (to be 
> compared)
> because they are not globally defined; only in 'new_sudoku' function. 
> Here's
> some selected code from my program:
>
> def swap_row(puzzle,row1,row2):
>    temp = puzzle[row1]
>    puzzle[row1] = puzzle[row2]
>    puzzle[row2] = temp
>
> def new_sudoku():
>    puzzle = [[1,2,3,4,5,6,7,8,9], \
>              [4,5,6,7,8,9,1,2,3], \
>              [7,8,9,1,2,3,4,5,6], \
>              [2,3,4,5,6,7,8,9,1], \
>              [5,6,7,8,9,1,2,3,4], \
>              [8,9,1,2,3,4,5,6,7], \
>              [3,4,5,6,7,8,9,1,2], \
>              [6,7,8,9,1,2,3,4,5], \
>              [9,1,2,3,4,5,6,7,8]]
>    num_of_swap = random.randint(10,20)
>    for i in range(num_of_swap):
>        row1 = random.randint(0,8)
>        row2 = random.randint(0,8)
>        if row1/3 == row2/3:
>            swap_row(puzzle,row1,row2)
>    new_puzzle = copy.deepcopy(puzzle)
>    sparseness = 0.85
>    for i in range(9):
>        for j in range(9):
>            if random.uniform(0,1) < sparseness:
>                new_puzzle[i][j] = ''
>
> def play_game():
>    '''
>    Here is where I need the variables 'puzzle' and 'new_puzzle' to be
> brought.
>    '''
>
> I read about the 'class' module, but am not sure on it's execution. I 
> really
> appreciate any time spent on my (simple) problem.
> Thanks in advance.
>
> On Nov 28, 2007 4:18 PM, Kent Johnson <kent37 at tds.net> wrote:
>
>> Devon MacIntyre wrote:
>> > Hi,
>> > Just wondering, how would I get a variable out of one function and into
>> > another?
>>
>> I don't understand your description of your situation, maybe you could
>> show a little code as a simple example?
>>
>> The usual way to get a variable out of a function is to return a value
>> from the function. The usual way to get a variable into a function is to
>> pass a parameter. If you want tighter coupling than that maybe you
>> should make the functions into methods of a class and make the variables
>> into instance attributes.
>>
>> HTH,
>> Kent
>>
>


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


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


From goldwamh at slu.edu  Thu Nov 29 04:18:11 2007
From: goldwamh at slu.edu (Michael H. Goldwasser)
Date: Wed, 28 Nov 2007 21:18:11 -0600
Subject: [Tutor] Variables and Functions
In-Reply-To: <4c12d31a0711281751i75d6439bnfb37e089ce0afc87@mail.gmail.com>
References: <4c12d31a0711281300v67a6e8a2he4d200d8a111703d@mail.gmail.com>
	<474E0568.60202@tds.net>
	<4c12d31a0711281751i75d6439bnfb37e089ce0afc87@mail.gmail.com>
Message-ID: <18254.12147.646480.202724@euclid.slu.edu>


Hello Devon,

   Here's a quick [untested] push in the direction of taking the code
   you gave below and modeling it as a class using an object-oriented
   design. With this code, you could then create an instance of a puzzle as:

       toughOne = Sudoku()
       toughOne.play_game()

   Within the class definition, variables that you need to have shared
   between the differnt functions are qualified as instance variables
   using the syntax self.blah  (as in self.puzzle and self.new_puzzle).  
   Unqualified variables are local to an individual function and
   cannot be shared.

With regard,
Michael


class Sudoku:
    def __init__(self):
        self.puzzle = [[1,2,3,4,5,6,7,8,9],
                       [4,5,6,7,8,9,1,2,3],
                       [7,8,9,1,2,3,4,5,6],
                       [2,3,4,5,6,7,8,9,1],
                       [5,6,7,8,9,1,2,3,4],
                       [8,9,1,2,3,4,5,6,7],
                       [3,4,5,6,7,8,9,1,2],
                       [6,7,8,9,1,2,3,4,5],
                       [9,1,2,3,4,5,6,7,8]]
        num_of_swap = random.randint(10,20)
        for i in range(num_of_swap):
            row1 = random.randint(0,8)
            row2 = random.randint(0,8)
            if row1/3 == row2/3:
                self.swap_row(row1,row2)
        self.new_puzzle = copy.deepcopy(puzzle)
        sparseness = 0.85
        for i in range(9):
            for j in range(9):
                if random.uniform(0,1) < sparseness:
                    self.new_puzzle[i][j] = ''
    
    def swap_row(self,row1,row2):
        temp = self.puzzle[row1]
        self.puzzle[row1] = self.puzzle[row2]
        self.puzzle[row2] = temp
    
    def play_game(self):
        '''Here is where I need the variables 'puzzle' and 'new_puzzle' to be brought.'''
        pass


       +-----------------------------------------------
       | Michael Goldwasser
       | Associate Professor
       | Dept. Mathematics and Computer Science
       | Saint Louis University
       | 220 North Grand Blvd.
       | St. Louis, MO 63103-2007
       |
       | Office: Ritter Hall 6
       | Email:  goldwamh at slu dot edu
       | URL:    euler.slu.edu/~goldwasser


On Wednesday November 28, 2007, Devon MacIntyre wrote: 

>    Hi,
>    
>    I have two functions, 'new_sudoku' and 'play_game'. In new_sudoku, I have a
>    pre-determined puzzle (I wasn't able to get a randomly generated puzzle
>    working), as a matrix in the variable 'puzzle'. I imported the 'copy' module
>    and made a deep-copy of 'puzzle' to make 'new_puzzle', which randomly has
>    85% of the digits replaced by an empty string. Now that 'new_puzzle' is only
>    15% filled with numbers, I use turtle to place the numbers on a grid that I
>    made (also with turtle). After the grid and 'new_puzzle' are generated, I
>    ask the player if he/she wants to begin playing. If yes, then the function
>    'play_game' is started. Here, I'm going to let the player choose spots to
>    input their own numbers to fill in the board. My problem is that I can't get
>    the variables 'puzzle' and 'new_puzzle' into that function (to be compared)
>    because they are not globally defined; only in 'new_sudoku' function. Here's
>    some selected code from my program:
>    
>    def swap_row(puzzle,row1,row2):
>        temp = puzzle[row1]
>        puzzle[row1] = puzzle[row2]
>        puzzle[row2] = temp
>    
>    def new_sudoku():
>        puzzle = [[1,2,3,4,5,6,7,8,9], \
>                  [4,5,6,7,8,9,1,2,3], \
>                  [7,8,9,1,2,3,4,5,6], \
>                  [2,3,4,5,6,7,8,9,1], \
>                  [5,6,7,8,9,1,2,3,4], \
>                  [8,9,1,2,3,4,5,6,7], \
>                  [3,4,5,6,7,8,9,1,2], \
>                  [6,7,8,9,1,2,3,4,5], \
>                  [9,1,2,3,4,5,6,7,8]]
>        num_of_swap = random.randint(10,20)
>        for i in range(num_of_swap):
>            row1 = random.randint(0,8)
>            row2 = random.randint(0,8)
>            if row1/3 == row2/3:
>                swap_row(puzzle,row1,row2)
>        new_puzzle = copy.deepcopy(puzzle)
>        sparseness = 0.85
>        for i in range(9):
>            for j in range(9):
>                if random.uniform(0,1) < sparseness:
>                    new_puzzle[i][j] = ''
>    
>    def play_game():
>        '''
>        Here is where I need the variables 'puzzle' and 'new_puzzle' to be
>    brought.
>        '''


From varsha.purohit at gmail.com  Thu Nov 29 04:34:41 2007
From: varsha.purohit at gmail.com (Varsha Purohit)
Date: Wed, 28 Nov 2007 19:34:41 -0800
Subject: [Tutor] [wxPython-users]How to avoid the traces of frame or panel
	window
Message-ID: <c2157c790711281934w65199edbs573461c2720a0a27@mail.gmail.com>

Hello Everyone,
         I created a simple frame, but when i move the frame or any panel
window i get traces of the windows all over which makes the screen look
shabby. How can i avoid getting them ? sample code for a panel is


# simple.py

import wx

app = wx.App()

frame = wx.Frame(None, -1, 'simple.py')
frame.Show()

app.MainLoop()


what should i add in the above code to not get the traces of the window.
Also, i have another problem, whenever i execute any wxpython program
inorder to execute it again i have to close all the programs including the
shell and then restart python otherwise i get like 25lines of some stupid
error messages having no link to the program. I have to close all python
programs again !!! Does anybody now why i am getting this....

thanks,
-- 
Varsha Purohit
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071128/9cd98fc1/attachment-0001.htm 

From nospamformeSVP at gmail.com  Thu Nov 29 04:42:31 2007
From: nospamformeSVP at gmail.com (Don Taylor)
Date: Wed, 28 Nov 2007 22:42:31 -0500
Subject: [Tutor] Starting a browser instance and passing a parameter to it.
Message-ID: <filcfa$rh5$1@ger.gmane.org>

I am trying to start a browser from within a Python program and I want 
it to show a local file on my system and I want to pass a parameter to 
that browser page that will be picked up by some Javascript embedded in 
the page.

I have this code:

import webbrowser
webbrowser.open("file:///D:/EclipseWS/XML-RPCTesting/webbrowser.htm?open=8001")

when executed it does bring up the web-page ok, but the parameter 
(?open=8001) is lost.  If I try the same thing with an http url then it 
works as expected.  However, I do not want to run a web-server on my 
machine.

Is there any way I can get a browser to display a web-page from a 
file-based url and pass a parameter to the code running in that page?

FWIW.  I am trying to use a web page as the GUI for a Python program. 
The Python program is started in the usual way and it initiates its web 
page GUI.  The Javascript in the web page then communicates with the 
Python program using XML-RPC.  The parameter I need to pass is the port 
number to be used for this communication.

I am currently using WinXP/Firefox but I want this to work on all 
platforms and browser combos.

TIA.


Don.


From oclbdk at gmail.com  Thu Nov 29 05:18:06 2007
From: oclbdk at gmail.com (Johnston Jiaa)
Date: Wed, 28 Nov 2007 23:18:06 -0500
Subject: [Tutor] Grid Manager Positioning
Message-ID: <556DB29B-397D-4386-AEAE-A64E1C365CE6@gmail.com>

How do I get widgets to be on the extreme left and right sides of a  
frame using the grid manager?  My code is similar to this..

	big_frame = Frame(root)
	big_frame.grid(sticky=W+E)

	left_frame = Frame(big_frame)
	left_frame.grid(row=0, column=0, sticky=W)

	right_frame = Frame(big_frame)
	right_frame.grid(row=0, column=1, sticky=E)

Supposing the root window is wider than the left and right frames put  
together, why doesn't left_frame go all the way to the left and  
right_frame all the way to the right with a space between them?  How  
do I make it do that?


Johnston Jiaa

From alan.gauld at btinternet.com  Thu Nov 29 09:43:16 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 29 Nov 2007 08:43:16 -0000
Subject: [Tutor] Variables and Functions
References: <4c12d31a0711281300v67a6e8a2he4d200d8a111703d@mail.gmail.com><474E0568.60202@tds.net>
	<4c12d31a0711281751i75d6439bnfb37e089ce0afc87@mail.gmail.com>
Message-ID: <filu39$4ae$1@ger.gmane.org>

"Devon MacIntyre" <macintyredev at gmail.com> wrote

> input their own numbers to fill in the board. My problem is that I 
> can't get
> the variables 'puzzle' and 'new_puzzle' into that function (to be 
> compared)
> because they are not globally defined; only in 'new_sudoku' 
> function. Here's
> some selected code from my program:

As per my prevuiouis email and example, simply return the puzzles

>
> def swap_row(puzzle,row1,row2):
>    temp = puzzle[row1]
>    puzzle[row1] = puzzle[row2]
>    puzzle[row2] = temp
      return puzzle   # just to be safe and consistent

> def new_sudoku():
>    puzzle = [[1,2,3,4,5,6,7,8,9], \
>              [4,5,6,7,8,9,1,2,3], \
>              [7,8,9,1,2,3,4,5,6], \
>              [2,3,4,5,6,7,8,9,1], \
>              [5,6,7,8,9,1,2,3,4], \
>              [8,9,1,2,3,4,5,6,7], \
>              [3,4,5,6,7,8,9,1,2], \
>              [6,7,8,9,1,2,3,4,5], \
>              [9,1,2,3,4,5,6,7,8]]
>    num_of_swap = random.randint(10,20)
>    for i in range(num_of_swap):
>        row1 = random.randint(0,8)
>        row2 = random.randint(0,8)
>        if row1/3 == row2/3:
>            swap_row(puzzle,row1,row2)
>    new_puzzle = copy.deepcopy(puzzle)
>    sparseness = 0.85
>    for i in range(9):
>        for j in range(9):
>            if random.uniform(0,1) < sparseness:
>                new_puzzle[i][j] = ''
      return puzzle,new_puzzle

> def play_game():
>    '''
>    Here is where I need the variables 'puzzle' and 'new_puzzle' to 
> be
> brought.
>    '''

original,new = new_sudoku()
compare(original,new)


> I read about the 'class' module, but am not sure on it's execution.

I'm not sure what the class module is? Its not one of the standard
Python modules. If you mean the class construct that is not a module
but a part of the language - like def is for functions.

See the OOP topic of my tutor for more info on how to use it.

But for this problem you don;t need classes, just pass the data
out of one function and into the other as shown above.
Have a read of the Modules & Functions topic in my tutor for
more explanation.

-- 
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 Nov 29 10:04:02 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 29 Nov 2007 09:04:02 -0000
Subject: [Tutor] [wxPython-users]How to avoid the traces of frame or
	panelwindow
References: <c2157c790711281934w65199edbs573461c2720a0a27@mail.gmail.com>
Message-ID: <filva7$876$1@ger.gmane.org>


"Varsha Purohit" <varsha.purohit at gmail.com> wrote

>         I created a simple frame, but when i move the frame or any 
> panel
> window i get traces of the windows all over which makes the screen 
> look
> shabby. How can i avoid getting them ? sample code for a panel is

> # simple.py
>
> import wx
>
> app = wx.App()
>
> frame = wx.Frame(None, -1, 'simple.py')
> frame.Show()
>
> app.MainLoop()

You need to create a subclass of App or use PySimpleApp.
The best way is to subclass App:

import wx
class MyApp(wx.App):
    def OnInit(self):
        frame = wx.Frame(None, -1, 'simple')
        frame.Show()
        return True

app = MyApp()
app.MainLoop()

Does that work?

> Also, i have another problem, whenever i execute any wxpython 
> program
> inorder to execute it again i have to close all the programs 
> including the
> shell and then restart python otherwise i get like 25lines of some 
> stupid
> error messages having no link to the program. I have to close all 
> python
> programs again !!! Does anybody now why i am getting this....

No, but it could be related to the fact that your code wasn't 
subclassing App.
See if the same happens with the sample above.

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 Nov 29 10:10:34 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 29 Nov 2007 09:10:34 -0000
Subject: [Tutor] Starting a browser instance and passing a parameter to
	it.
References: <filcfa$rh5$1@ger.gmane.org>
Message-ID: <filvmf$9e6$1@ger.gmane.org>

"Don Taylor" <nospamformeSVP at gmail.com> wrote

> I have this code:
>
> import webbrowser
> webbrowser.open("file:///D:/EclipseWS/XML-RPCTesting/webbrowser.htm?open=8001")
>
> when executed it does bring up the web-page ok, but the parameter
> (?open=8001) is lost.  If I try the same thing with an http url then 
> it
> works as expected.  However, I do not want to run a web-server on my
> machine.
>
> Is there any way I can get a browser to display a web-page from a
> file-based url and pass a parameter to the code running in that 
> page?

I don't think so because the file protocol does not support the
GET/POST methods of http. You could maybe change the
JavaScript to prompt for the value but it would be much easier
to just run a web srver on an unusual port - maybe the simple
web server that comes with Python.

> FWIW.  I am trying to use a web page as the GUI for a Python 
> program.
> The Python program is started in the usual way and it initiates its 
> web
> page GUI.  The Javascript in the web page then communicates with the
> Python program using XML-RPC.  The parameter I need to pass is the 
> port
> number to be used for this communication.

What are you using for the XML-RPC server? Doesn't that need to be a
web server of some sort anyhow? XML-RPC communicates using http...

You seem to be making a fairly easy task very complicated.

Alan G.

> I am currently using WinXP/Firefox but I want this to work on all
> platforms and browser combos.

Remember that portable JavaScript is quite hard to write due to 
browser
differences.

HTH,

Alan G 



From alan.gauld at btinternet.com  Thu Nov 29 10:18:47 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 29 Nov 2007 09:18:47 -0000
Subject: [Tutor] Grid Manager Positioning
References: <556DB29B-397D-4386-AEAE-A64E1C365CE6@gmail.com>
Message-ID: <fim05s$b03$1@ger.gmane.org>

"Johnston Jiaa" <oclbdk at gmail.com> wrote

> big_frame = Frame(root)
> big_frame.grid(sticky=W+E)
>
> left_frame = Frame(big_frame)
> left_frame.grid(row=0, column=0, sticky=W)
>
> right_frame = Frame(big_frame)
> right_frame.grid(row=0, column=1, sticky=E)
>
> Supposing the root window is wider than the left and right frames 
> put
> together, why doesn't left_frame go all the way to the left and
> right_frame all the way to the right with a space between them?

Presumably because big_frame is narrower than root. The inner
frames will only go as far as the border of big_frame. Also there
may be some default padding around the grid edges (I rarely use
the grid its too rigid, so I'm not sure)

> do I make it do that?

Use pack(side= expand="true" )     ;-)

Alan G 



From oclbdk at gmail.com  Thu Nov 29 13:33:02 2007
From: oclbdk at gmail.com (Johnston Jiaa)
Date: Thu, 29 Nov 2007 07:33:02 -0500
Subject: [Tutor] Grid Manager Positioning
In-Reply-To: <mailman.13.1196334006.25132.tutor@python.org>
References: <mailman.13.1196334006.25132.tutor@python.org>
Message-ID: <EBE5C2FC-7C46-40B2-9A9F-A06C18B876B2@gmail.com>

>
> Presumably because big_frame is narrower than root.
> The inner frames will only go as far as the border of big_frame.

Well, with my code, I made bg="blue" so I see that it's big enough,  
and the big_frame stretches to fit inside root if i use sticky=W+E.


> Use pack(side= expand="true" )     ;-)

I heard that it's not good to mix grid and pack positioning?  And I  
already wrote it in grid.


Johnston Jiaa

From nospamformeSVP at gmail.com  Thu Nov 29 15:40:41 2007
From: nospamformeSVP at gmail.com (Don Taylor)
Date: Thu, 29 Nov 2007 09:40:41 -0500
Subject: [Tutor] Starting a browser instance and passing a parameter to
	it.
In-Reply-To: <filvmf$9e6$1@ger.gmane.org>
References: <filcfa$rh5$1@ger.gmane.org> <filvmf$9e6$1@ger.gmane.org>
Message-ID: <fimj1d$bqc$1@ger.gmane.org>

Alan Gauld wrote:

> What are you using for the XML-RPC server? Doesn't that need to be a
> web server of some sort anyhow? XML-RPC communicates using http...
> 

I am using simpleXMLRPCServer.  Yes, XML-RPC does use http as its 
transport protocol, but it does not have to run in the context of a 
web-server.  You can run XML-RPC 'under' CGI but that costs a lot in 
performance (continual re-loads) and, more importantly, forces a REST 
model on to the XML-RPC server.  I am treating XML-RPC as a socket 
server that happens to use http for its transport.

> You seem to be making a fairly easy task very complicated.
> 

Yes, quite possibly.  Just for fun, I am experimenting with ways to 
build portable desktop GUI applications - where portability includes 
independence from window managers.  I am trying to use a browser as the 
window manager for a (Python) application.

 > Remember that portable JavaScript is quite hard to write due to
 > browser
 > differences.

I plan to use something like Google Web Toolkit for the browser-side 
code.  GWT (and many others tools and libraries) abstracts away browser 
differences.  I don't plan to manipulate the browser DOM directly.

Sadly, the Pyjamas project has died - Pyjamas promised to be like GWT, 
but used Python instead of Java for writing the ui code.

Thx.  Don.


From alan.gauld at btinternet.com  Thu Nov 29 18:51:52 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 29 Nov 2007 17:51:52 -0000
Subject: [Tutor] Starting a browser instance and passing a parameter
	toit.
References: <filcfa$rh5$1@ger.gmane.org> <filvmf$9e6$1@ger.gmane.org>
	<fimj1d$bqc$1@ger.gmane.org>
Message-ID: <fimu7t$obb$1@ger.gmane.org>


"Don Taylor" <nospamformeSVP at gmail.com> wrote

> Yes, quite possibly.  Just for fun, I am experimenting with ways to
> build portable desktop GUI applications - where portability includes
> independence from window managers.  I am trying to use a browser as 
> the
> window manager for a (Python) application.

Have you considered writing a small Java applet (maybe using Jython to 
do so?)
that could communicate with the Javascript and send the XML-RPC stuff 
to
your server?

That doesn't help you get the parameters but it might be possible to 
utilise
the OnLoad event to trigger an XML message to the server to get the 
parameters
and feed it to JavaScript from within the applet. I know that this is 
theoretically
possibly but I admit I've never attempted anything like it. But a 
simple applet
on every page might just work. In fact, if JavaScript can send the 
XML-RPC
you wouldn't need the applet, just get the JavaScript code send the 
message
to fetch the parameter from the server once the page is loaded. Hmm, 
but you
want to pass the port number... So until you get that you  are 
stuck...Hmmm
that probably isn't going to work! :-)

Just a thought,

-- 
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 Nov 29 18:55:22 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 29 Nov 2007 17:55:22 -0000
Subject: [Tutor] Grid Manager Positioning
References: <mailman.13.1196334006.25132.tutor@python.org>
	<EBE5C2FC-7C46-40B2-9A9F-A06C18B876B2@gmail.com>
Message-ID: <fimueg$p4e$1@ger.gmane.org>

"Johnston Jiaa" <oclbdk at gmail.com> wrote

> I heard that it's not good to mix grid and pack positioning?  And I
> already wrote it in grid.

You can't mix them within a Frame but provided you are operating
in different frames you can (and should!) choose whichever is most
appropriate for that Frame's structure.

Othewise you get into the trap of forcing everything to look like a 
grid
or everything like a stack. (The "When all you have is a hammer,
everything looks like a nail" syndrome).

Alan G. 



From rfquerin at gmail.com  Thu Nov 29 19:19:56 2007
From: rfquerin at gmail.com (Richard Querin)
Date: Thu, 29 Nov 2007 13:19:56 -0500
Subject: [Tutor] List processing question - consolidating duplicate
	entries
In-Reply-To: <474C9CE9.9080807@tds.net>
References: <7d81675b0711271337o3c92fafga8f7d3392b71abfc@mail.gmail.com>
	<474C964E.5020404@alum.rpi.edu> <474C9CE9.9080807@tds.net>
Message-ID: <7d81675b0711291019g2ea70955j93955c0967fb12ad@mail.gmail.com>

On Nov 27, 2007 5:40 PM, Kent Johnson <kent37 at tds.net> wrote:

>
> This is a two-liner using itertools.groupby() and operator.itemgetter:
>
> data = [['Bob', '07129', 'projectA', '4001',5],
> ['Bob', '07129', 'projectA', '5001',2],
> ['Bob', '07101', 'projectB', '4001',1],
> ['Bob', '07140', 'projectC', '3001',3],
> ['Bob', '07099', 'projectD', '3001',2],
> ['Bob', '07129', 'projectA', '4001',4],
> ['Bob', '07099', 'projectD', '4001',3],
> ['Bob', '07129', 'projectA', '4001',2]
> ]
>
> import itertools, operator
> for k, g in itertools.groupby(sorted(data), key=operator.itemgetter(0,
> 1, 2, 3)):
>   print k, sum(item[4] for item in g)
>


I'm trying to understand what's going on in the for statement but I'm having
troubles. The interpreter is telling me that itemgetter expects 1 argument
and is getting 4.

I understand that groupby takes 2 parameters the first being the sorted
list. The second is a key and this is where I'm confused. The itemgetter
function is going to return a tuple of functions (f[0],f[1],f[2],f[3]).

Should I only be calling itemgetter with whatever element (0 to 3) that I
want to group the items by?

I'm almost getting this but not quite. ;)

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

From kent37 at tds.net  Thu Nov 29 19:57:53 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 29 Nov 2007 13:57:53 -0500
Subject: [Tutor] List processing question - consolidating duplicate
	entries
In-Reply-To: <7d81675b0711291019g2ea70955j93955c0967fb12ad@mail.gmail.com>
References: <7d81675b0711271337o3c92fafga8f7d3392b71abfc@mail.gmail.com>	
	<474C964E.5020404@alum.rpi.edu> <474C9CE9.9080807@tds.net>
	<7d81675b0711291019g2ea70955j93955c0967fb12ad@mail.gmail.com>
Message-ID: <474F0BB1.5090702@tds.net>

Richard Querin wrote:
>     import itertools, operator
>     for k, g in itertools.groupby(sorted(data), key=operator.itemgetter(0,
>     1, 2, 3)):
>       print k, sum(item[4] for item in g)
> 
> 
> 
> I'm trying to understand what's going on in the for statement but I'm 
> having troubles. The interpreter is telling me that itemgetter expects 1 
> argument and is getting 4.

You must be using an older version of Python, the ability to pass 
multiple arguments to itemgetter was added in 2.5. Meanwhile it's easy 
enough to define your own:
def make_key(item):
   return (item[:4])

and then specify key=make_key.

BTW when you want help with an error, please copy and paste the entire 
error message and traceback into your email.

> I understand that groupby takes 2 parameters the first being the sorted 
> list. The second is a key and this is where I'm confused. The itemgetter 
> function is going to return a tuple of functions (f[0],f[1],f[2],f[3]).

No, it returns one function that will return a tuple of values.

> Should I only be calling itemgetter with whatever element (0 to 3) that 
> I want to group the items by?

If you do that it will only group by the single item you specify. 
groupby() doesn't sort so you should also sort by the same key. But I 
don't think that is what you want.

Kent

From nospamformeSVP at gmail.com  Thu Nov 29 20:16:37 2007
From: nospamformeSVP at gmail.com (Don Taylor)
Date: Thu, 29 Nov 2007 14:16:37 -0500
Subject: [Tutor] Starting a browser instance and passing a parameter
	toit.
In-Reply-To: <fimu7t$obb$1@ger.gmane.org>
References: <filcfa$rh5$1@ger.gmane.org>
	<filvmf$9e6$1@ger.gmane.org>	<fimj1d$bqc$1@ger.gmane.org>
	<fimu7t$obb$1@ger.gmane.org>
Message-ID: <fin36o$b3f$1@ger.gmane.org>

Alan Gauld wrote:

> Have you considered writing a small Java applet (maybe using Jython to 
> do so?)
> that could communicate with the Javascript and send the XML-RPC stuff 
> to
> your server?
>

Well, I am on a Procrustean bed here - Java is not available on one of 
my target platforms.


> In fact, if JavaScript can send the 
> XML-RPC
> you wouldn't need the applet, just get the JavaScript code send the 
> message
> to fetch the parameter from the server once the page is loaded. Hmm,

I can do that in JavaScript as soon as I know the port used for the 
XML-RPC server...

> but you
> want to pass the port number... So until you get that you  are 
> stuck...Hmmm
> that probably isn't going to work! :-)
> 

No, I don't think so but I have a couple of ideas to try.

First is to construct the apps opening web-page on the fly in the 
XML-RPC server before the server instantiates the page.  I can generate 
some custom Javascript in this page that has the port number embedded 
within it.  Then the Javascript can store it in a cookie or pass it on 
to the next page as a parameter.


From kent37 at tds.net  Thu Nov 29 20:50:39 2007
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 29 Nov 2007 14:50:39 -0500
Subject: [Tutor] Starting a browser instance and passing a parameter to
 it.
In-Reply-To: <fimj1d$bqc$1@ger.gmane.org>
References: <filcfa$rh5$1@ger.gmane.org> <filvmf$9e6$1@ger.gmane.org>
	<fimj1d$bqc$1@ger.gmane.org>
Message-ID: <474F180F.6020109@tds.net>

Don Taylor wrote:
> Alan Gauld wrote:
> 
>> What are you using for the XML-RPC server? Doesn't that need to be a
>> web server of some sort anyhow? XML-RPC communicates using http...
>>
> 
> I am using simpleXMLRPCServer.  Yes, XML-RPC does use http as its 
> transport protocol, but it does not have to run in the context of a 
> web-server.  You can run XML-RPC 'under' CGI but that costs a lot in 
> performance (continual re-loads) and, more importantly, forces a REST 
> model on to the XML-RPC server.  I am treating XML-RPC as a socket 
> server that happens to use http for its transport.
> 
>> You seem to be making a fairly easy task very complicated.
>>
> 
> Yes, quite possibly.  Just for fun, I am experimenting with ways to 
> build portable desktop GUI applications - where portability includes 
> independence from window managers.  I am trying to use a browser as the 
> window manager for a (Python) application.

I can't decide if this is brilliant or crazy or both :-)

I guess what you get from XMLRPC is an almost-free way to expose 
functions to the browser. But it forces you to build the UI entirely in 
javascript.

I wonder if you wouldn't be better off starting with a simple web server 
such as CherryPy and building a standard web application on that...you 
would be swimming with the stream then, instead of across it.

 > I plan to use something like Google Web Toolkit for the browser-side
 > code.  GWT (and many others tools and libraries) abstracts away browser
 > differences.  I don't plan to manipulate the browser DOM directly.

GWT is targeted to Java developers, probably something like Dojo or YUI 
would be more appropriate.

Kent

From brunson at brunson.com  Thu Nov 29 21:00:25 2007
From: brunson at brunson.com (Eric Brunson)
Date: Thu, 29 Nov 2007 13:00:25 -0700
Subject: [Tutor] Starting a browser instance and passing a parameter to
 it.
In-Reply-To: <474F180F.6020109@tds.net>
References: <filcfa$rh5$1@ger.gmane.org>
	<filvmf$9e6$1@ger.gmane.org>	<fimj1d$bqc$1@ger.gmane.org>
	<474F180F.6020109@tds.net>
Message-ID: <474F1A59.3030007@brunson.com>

Kent Johnson wrote:
> Don Taylor wrote:
>   
>> Alan Gauld wrote:
>>
>>     
>>> What are you using for the XML-RPC server? Doesn't that need to be a
>>> web server of some sort anyhow? XML-RPC communicates using http...
>>>
>>>       
>> I am using simpleXMLRPCServer.  Yes, XML-RPC does use http as its 
>> transport protocol, but it does not have to run in the context of a 
>> web-server.  You can run XML-RPC 'under' CGI but that costs a lot in 
>> performance (continual re-loads) and, more importantly, forces a REST 
>> model on to the XML-RPC server.  I am treating XML-RPC as a socket 
>> server that happens to use http for its transport.
>>
>>     
>>> You seem to be making a fairly easy task very complicated.
>>>
>>>       
>> Yes, quite possibly.  Just for fun, I am experimenting with ways to 
>> build portable desktop GUI applications - where portability includes 
>> independence from window managers.  I am trying to use a browser as the 
>> window manager for a (Python) application.
>>     
>
> I can't decide if this is brilliant or crazy or both :-)
>
> I guess what you get from XMLRPC is an almost-free way to expose 
> functions to the browser. But it forces you to build the UI entirely in 
> javascript.
>
> I wonder if you wouldn't be better off starting with a simple web server 
> such as CherryPy and building a standard web application on that...you 
> would be swimming with the stream then, instead of across it.
>   

Definitely,  or even just CGIHTTPServer.

>  > I plan to use something like Google Web Toolkit for the browser-side
>  > code.  GWT (and many others tools and libraries) abstracts away browser
>  > differences.  I don't plan to manipulate the browser DOM directly.
>
> GWT is targeted to Java developers, probably something like Dojo or YUI 
> would be more appropriate.
>
> Kent
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From nospamformeSVP at gmail.com  Thu Nov 29 21:30:57 2007
From: nospamformeSVP at gmail.com (Don Taylor)
Date: Thu, 29 Nov 2007 15:30:57 -0500
Subject: [Tutor] Starting a browser instance and passing a parameter
	toit.
In-Reply-To: <fin36o$b3f$1@ger.gmane.org>
References: <filcfa$rh5$1@ger.gmane.org>	<filvmf$9e6$1@ger.gmane.org>	<fimj1d$bqc$1@ger.gmane.org>	<fimu7t$obb$1@ger.gmane.org>
	<fin36o$b3f$1@ger.gmane.org>
Message-ID: <fin7i5$s46$1@ger.gmane.org>

Don Taylor wrote:

> 
> First is to construct the apps opening web-page on the fly in the 
> XML-RPC server before the server instantiates the page.  I can generate 
> some custom Javascript in this page that has the port number embedded 
> within it.  Then the Javascript can store it in a cookie or pass it on 
> to the next page as a parameter.
> 

Ok, this worked for me.  From a Python application, I constructed a file 
containing:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
   <head>
     <script type="text/javascript" language="JavaScript1.1">
       <!--
 
location.replace("file:///D:/EclipseWS/XML-RPCTesting/webbrowser.htm?port=8001");
       //-->
     </script>

     <title>Redirector</title>
   </head>
   <body>
   Re-directing ...
   </body>
</html>

used webbrowser.open to fire it up in a browser.  This file immediately 
redirects as above and includes the ?port=8001 in the url on the target 
page.  I am able to extract the port number using a bit of Javascript in 
the final page.

So, I think that bit will work for me.

Don.


From bizag007 at yahoo.com  Thu Nov 29 21:28:37 2007
From: bizag007 at yahoo.com (ray sa)
Date: Thu, 29 Nov 2007 12:28:37 -0800 (PST)
Subject: [Tutor] parsing a continuous log file
Message-ID: <762818.57123.qm@web51704.mail.re2.yahoo.com>

Hello

I need some help. I am working with a program that dumps a continuous file while the program is running. This file contains loads of information and I am only looking for a small amount of the data. 

I have written the program below:

import re,os

fopen = open("c:\\data.txt",'r')
lines = fopen.readlines()
fopen.close()

def parser():        
    ul = r"dataRate=(\w+)"
    count = 0
    for line in lines:
        count = count + 1
        match1 = re.search(ul,line)
        if match1:
            print match1.group(1)

parser()

data.txt file content

dataRate=104
dataRate=107
dataRate=103
dataRate=102

this was an example the file contains much more.

This works but it doesn't show me the results real time. I would like this program to keep on running while the program is running once the program is closed and the file stops growing it should exit. I was checking with google and came accross a command used in UNIX called the tail command.

May be someone can help me to achieve the same result with modifying the above code? Also the file could be up to 200 MB long.

Many thanks for your kind help. /Ray

       
---------------------------------
Be a better sports nut! Let your teams follow you with Yahoo Mobile. Try it now.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071129/b0be7ea4/attachment.htm 

From nospamformeSVP at gmail.com  Thu Nov 29 22:04:48 2007
From: nospamformeSVP at gmail.com (Don Taylor)
Date: Thu, 29 Nov 2007 16:04:48 -0500
Subject: [Tutor] Starting a browser instance and passing a parameter to
	it.
In-Reply-To: <474F180F.6020109@tds.net>
References: <filcfa$rh5$1@ger.gmane.org>
	<filvmf$9e6$1@ger.gmane.org>	<fimj1d$bqc$1@ger.gmane.org>
	<474F180F.6020109@tds.net>
Message-ID: <fin9hj$3in$1@ger.gmane.org>

Kent Johnson wrote:

> I can't decide if this is brilliant or crazy or both :-)

Definitely crazy, but I hope both.

In addition, I want to be able to run these apps on a Nokia Internet 
Tablet...
> 
> I guess what you get from XMLRPC is an almost-free way to expose 
> functions to the browser. 

Yes, you got it.  Well, free as in a ~30 ms round-trip overhead.

But it forces you to build the UI entirely in
> javascript.

Yes, that is rather sad.

> 
> I wonder if you wouldn't be better off starting with a simple web server 
> such as CherryPy and building a standard web application on that...you 

Too big, too heavy, too RESTy and you have to maintain your own state.

I also want this to look and install like a genuine desktop application. 
  To start it you just double-click the server which then initiates the 
browser.  To shut it down, you just close the browser window and the 
server (eventually) goes away on its own.

> would be swimming with the stream then, instead of across it.

No fun in that.

> 
>  > I plan to use something like Google Web Toolkit for the browser-side
>  > code.  GWT (and many others tools and libraries) abstracts away browser
>  > differences.  I don't plan to manipulate the browser DOM directly.
> 
> GWT is targeted to Java developers, probably something like Dojo or YUI 
> would be more appropriate.
>

Well, my choice is between Java and Javascript.  GWT is nice because it 
has really good Eclipse-based tool-chain including a debugger.  It also 
generates pretty tight Javascript code.    Dojo or YUI mean wrestling 
directly with Javascript and its not so good tool-chain.  However, I am 
probably going to try more than one approach to see what I like best.

Pyjamas would have been nice as it was a port of GWT that had a Python 
to Javascript compiler instead of a Java to Javascript compiler.  Sadly, 
the project seems to have disappeared from the web.


From cngamba at yahoo.co.in  Thu Nov 29 22:17:44 2007
From: cngamba at yahoo.co.in (enter_weirdman)
Date: Thu, 29 Nov 2007 21:17:44 +0000 (GMT)
Subject: [Tutor] (no subject)
Message-ID: <335223.76214.qm@web8912.mail.in.yahoo.com>



       
---------------------------------
 Get the freedom to save as many mails as you wish. Click here to know how.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071129/252f95b5/attachment.htm 

From nospamformeSVP at gmail.com  Thu Nov 29 22:11:39 2007
From: nospamformeSVP at gmail.com (Don Taylor)
Date: Thu, 29 Nov 2007 16:11:39 -0500
Subject: [Tutor] Starting a browser instance and passing a parameter to
	it.
In-Reply-To: <474F1A59.3030007@brunson.com>
References: <filcfa$rh5$1@ger.gmane.org>	<filvmf$9e6$1@ger.gmane.org>	<fimj1d$bqc$1@ger.gmane.org>	<474F180F.6020109@tds.net>
	<474F1A59.3030007@brunson.com>
Message-ID: <fin9uf$51j$1@ger.gmane.org>

Eric Brunson wrote:

> Definitely,  or even just CGIHTTPServer.
> 

No, I don't think so.  I am not a RESTafarian.  :-)

Don.


From brunson at brunson.com  Thu Nov 29 22:45:29 2007
From: brunson at brunson.com (Eric Brunson)
Date: Thu, 29 Nov 2007 14:45:29 -0700
Subject: [Tutor] Starting a browser instance and passing a parameter to
 it.
In-Reply-To: <fin9uf$51j$1@ger.gmane.org>
References: <filcfa$rh5$1@ger.gmane.org>	<filvmf$9e6$1@ger.gmane.org>	<fimj1d$bqc$1@ger.gmane.org>	<474F180F.6020109@tds.net>	<474F1A59.3030007@brunson.com>
	<fin9uf$51j$1@ger.gmane.org>
Message-ID: <474F32F9.7040605@brunson.com>

Don Taylor wrote:
> Eric Brunson wrote:
>
>   
>> Definitely,  or even just CGIHTTPServer.
>>
>>     
>
> No, I don't think so.  I am not a RESTafarian.  :-)
>   

Forgive my inexperience with the SimpleXMLRPCServer, but I didn't think 
it provided state any more than any other connection oriented server?  
Am I wrong about that?

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


From alan.gauld at btinternet.com  Fri Nov 30 01:06:09 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 30 Nov 2007 00:06:09 -0000
Subject: [Tutor] parsing a continuous log file
References: <762818.57123.qm@web51704.mail.re2.yahoo.com>
Message-ID: <fink5m$7f5$1@ger.gmane.org>


"ray sa" <bizag007 at yahoo.com> wrote

> used in UNIX called the tail command.
>
> May be someone can help me to achieve the same result with modifying 
> the above code?

Sorry i didnm't look too closely but i think you should only need to 
keep the file open andd then  loop around with a delay.
Sometjing like:

try:
  f = open('foo.txt')
  for line in f:
     print line
     time.sleep(1)
finally:
   f.close()

That will keep reading the lines until it hits the end of the file.
Of course if the file is eventually empty then it exits so you
may want a while True loop instead and only print if the line is non 
empty
In that case you need to figure out how to stop the loop - maybe 
Ctrl-C
is good enough.

HTH,


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



From goldwamh at slu.edu  Fri Nov 30 02:08:46 2007
From: goldwamh at slu.edu (Michael H. Goldwasser)
Date: Thu, 29 Nov 2007 19:08:46 -0600
Subject: [Tutor] parsing a continuous log file
In-Reply-To: <fink5m$7f5$1@ger.gmane.org>
References: <762818.57123.qm@web51704.mail.re2.yahoo.com>
	<fink5m$7f5$1@ger.gmane.org>
Message-ID: <18255.25246.218160.896274@euclid.slu.edu>


The for loop below will exit once it hits EOF (and will not continue
if more data is later appended.  But as Alan says, a while loop will
suffice.  I've tested the following variant.

import time
f = file('foo.txt')

while True:
    line = f.readline()
    if line:
        print "do what you want with", line
    else:                 # currently at end of file
        time.sleep(1)     # don't want to poll too quickly

Good luck,
Michael

On Friday November 30, 2007, Alan Gauld wrote: 

>    
>    "ray sa" <bizag007 at yahoo.com> wrote
>    
>    > used in UNIX called the tail command.
>    >
>    > May be someone can help me to achieve the same result with modifying 
>    > the above code?
>    
>    Sorry i didnm't look too closely but i think you should only need to 
>    keep the file open andd then  loop around with a delay.
>    Sometjing like:
>    
>    try:
>      f = open('foo.txt')
>      for line in f:
>         print line
>         time.sleep(1)
>    finally:
>       f.close()
>    
>    That will keep reading the lines until it hits the end of the file.
>    Of course if the file is eventually empty then it exits so you
>    may want a while True loop instead and only print if the line is non 
>    empty



From lavendula6654 at yahoo.com  Fri Nov 30 08:28:44 2007
From: lavendula6654 at yahoo.com (Elaine)
Date: Thu, 29 Nov 2007 23:28:44 -0800 (PST)
Subject: [Tutor] Ruby on Rails course at Foothill College
Message-ID: <378660.91850.qm@web31707.mail.mud.yahoo.com>


If you would like to get an introduction to web
application development with Ruby on Rails, Foothill
College in Los Altos Hills, CA  is offering a course
starting Tues. evening, January 8th, 2008, at 6pm. The
course is designed for students who are already
familiar with web application development using tools
such as Perl or PHP. Here is the course description:

COIN 67	RUBY ON RAILS - WEB APPLICATION DEVELOPMENT	5
Units

Introduction to web application development with Ruby
on Rails. Students learn how to create database-driven
web applications using the Ruby language and the Rails
framework.

Fours hours lecture, four hours laboratory.
Advisories: Prior programming experience and CIS 52A
or database experience.

Please preregister for Winter quarter by going to:
http://www.foothill.fhda.edu/reg/index.php





      ____________________________________________________________________________________
Get easy, one-click access to your favorites. 
Make Yahoo! your homepage.
http://www.yahoo.com/r/hs 

From tiagosaboga at terra.com.br  Fri Nov 30 13:07:54 2007
From: tiagosaboga at terra.com.br (Tiago Saboga)
Date: Fri, 30 Nov 2007 10:07:54 -0200
Subject: [Tutor] PyQt segfault
Message-ID: <20071130120754.GD8055@localdomain>

Hi!

I am making a front-end to ffmpeg with pyqt and I am stuck in a
segmentation fault I can't understand. I have written a little
dialogbox just to show the problem. I have already found a workaround,
commented out in the code, but I would like to know where is the
problem.

I am sending the pyuic-generated file in attachment, as well as ui file.

I am working in a debian/lenny system, with py 2.4 and 2.5.

cbox.py
=======

#!/usr/bin/python2.5
# -*- coding: utf-8 -*-

from PyQt4 import QtCore, QtGui
from comboboxsegfault import Ui_Dialog
import sys

class Aux:
    pass
    
class Combobox(QtGui.QDialog):
    def __init__(self):
        QtGui.QDialog.__init__(self)
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
			
        self.connect(self.ui.comboBox, QtCore.SIGNAL("activated(QString)"),
                     self.save)
        def save(self, qstring):
	    # Here it works:
            #Aux.mystring = unicode(qstring)
	    Aux.mystring = qstring
					 
def main(args):
    app = QtGui.QApplication(args)
    win = Combobox()
    win.show()
    app.exec_()

    print type(Aux.mystring)
    # If uncommented segfaults
    # mystring = unicode(Aux.mystring)
    print ("The same" if Aux.mystring==Aux.mystring2 else "Different")
    print Aux.compare
    # segfault
    print Aux.mystring
def compare(args):
    st = QtCore.QString("Second")
    Aux.compare = st
			
if __name__=='__main__':
    compare(sys.argv)
    main(sys.argv)

-------------- next part --------------
A non-text attachment was scrubbed...
Name: comboboxsegfault.py
Type: text/x-python
Size: 1651 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20071130/1d27ea41/attachment.py 
-------------- next part --------------
<ui version="4.0" >
 <class>Dialog</class>
 <widget class="QDialog" name="Dialog" >
  <property name="geometry" >
   <rect>
    <x>0</x>
    <y>0</y>
    <width>400</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle" >
   <string>Dialog</string>
  </property>
  <widget class="QDialogButtonBox" name="buttonBox" >
   <property name="geometry" >
    <rect>
     <x>30</x>
     <y>240</y>
     <width>341</width>
     <height>32</height>
    </rect>
   </property>
   <property name="orientation" >
    <enum>Qt::Horizontal</enum>
   </property>
   <property name="standardButtons" >
    <set>QDialogButtonBox::Cancel|QDialogButtonBox::NoButton|QDialogButtonBox::Ok</set>
   </property>
  </widget>
  <widget class="QComboBox" name="comboBox" >
   <property name="geometry" >
    <rect>
     <x>60</x>
     <y>30</y>
     <width>231</width>
     <height>31</height>
    </rect>
   </property>
   <item>
    <property name="text" >
     <string>First</string>
    </property>
   </item>
   <item>
    <property name="text" >
     <string>Second</string>
    </property>
   </item>
  </widget>
 </widget>
 <resources/>
 <connections>
  <connection>
   <sender>buttonBox</sender>
   <signal>accepted()</signal>
   <receiver>Dialog</receiver>
   <slot>accept()</slot>
   <hints>
    <hint type="sourcelabel" >
     <x>248</x>
     <y>254</y>
    </hint>
    <hint type="destinationlabel" >
     <x>157</x>
     <y>274</y>
    </hint>
   </hints>
  </connection>
  <connection>
   <sender>buttonBox</sender>
   <signal>rejected()</signal>
   <receiver>Dialog</receiver>
   <slot>reject()</slot>
   <hints>
    <hint type="sourcelabel" >
     <x>316</x>
     <y>260</y>
    </hint>
    <hint type="destinationlabel" >
     <x>286</x>
     <y>274</y>
    </hint>
   </hints>
  </connection>
 </connections>
</ui>

From bhaaluu at gmail.com  Fri Nov 30 14:11:04 2007
From: bhaaluu at gmail.com (bhaaluu)
Date: Fri, 30 Nov 2007 08:11:04 -0500
Subject: [Tutor] parsing a continuous log file
In-Reply-To: <762818.57123.qm@web51704.mail.re2.yahoo.com>
References: <762818.57123.qm@web51704.mail.re2.yahoo.com>
Message-ID: <ea979d70711300511i27b5a3bcx42d5ff41f15f8caa@mail.gmail.com>

On Nov 29, 2007 3:28 PM, ray sa <bizag007 at yahoo.com> wrote:
> Hello
>
> I need some help. I am working with a program that dumps a continuous file
> while the program is running. This file contains loads of information and I
> am only looking for a small amount of the data.
>
> I have written the program below:
>
[snip]
>
> closed and the file stops growing it should exit. I was checking with google
> and came accross a command used in UNIX called the tail command.

The UNIX 'tail' command with the -f option does this.
$ tail filename   <-- by default, the last 10 lines will be shown,
then tail exits.
$ tail -n20 filename  <-- the last 20 lines are shown, then tail exits
$ tail -f filename  <-- follow the end of the file

--from the manual:
-f, --follow[={name|descriptor}]
     output  appended data as the file grows;
     -f, --follow, and --follow=descriptor are equivalent

One of the benefits of Open Source (Free) Software is that the source code
can be studied, modified, and freely shared with the community.

>
> May be someone can help me to achieve the same result with modifying the
> above code? Also the file could be up to 200 MB long.
>
> Many thanks for your kind help. /Ray
>

May the Source be with you! 8^D
-- 
b h a a l u u at g m a i l dot c o m

From alan.gauld at btinternet.com  Fri Nov 30 14:13:39 2007
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 30 Nov 2007 13:13:39 -0000
Subject: [Tutor] PyQt segfault
References: <20071130120754.GD8055@localdomain>
Message-ID: <fip2a9$ul9$1@ger.gmane.org>

"Tiago Saboga" <tiagosaboga at terra.com.br> wrote

> I am making a front-end to ffmpeg with pyqt and I am stuck in a
> segmentation fault I can't understand. I have written a little

> def main(args):
>    app = QtGui.QApplication(args)
>    win = Combobox()
>    win.show()
>    app.exec_()
>
>    print type(Aux.mystring)
>    # If uncommented segfaults
>    # mystring = unicode(Aux.mystring)
>    print ("The same" if Aux.mystring==Aux.mystring2 else 
> "Different")

It looks from this that it has nothing to do with Qt per se.
Does unicode() work OK outside of Qt?
Or is Aux.mystring an insance of a QtString class that you need to
deference to get the real string that unicode will understand?

All I can think of, not knowing anything much of Qt.

Alan G.



From tiagosaboga at terra.com.br  Fri Nov 30 15:14:05 2007
From: tiagosaboga at terra.com.br (Tiago Saboga)
Date: Fri, 30 Nov 2007 12:14:05 -0200
Subject: [Tutor] PyQt segfault
In-Reply-To: <fip2a9$ul9$1@ger.gmane.org>
References: <20071130120754.GD8055@localdomain> <fip2a9$ul9$1@ger.gmane.org>
Message-ID: <20071130141405.GF8055@localdomain>

First, I just noticed I sent a non-working version of the code. The line

print ("The same" if Aux.mystring==Aux.mystring2 else "Different")

should be 

print ("The same" if Aux.mystring==Aux.compare else "Different")

Sorry for that.

On Fri, Nov 30, 2007 at 01:13:39PM -0000, Alan Gauld wrote:
> "Tiago Saboga" <tiagosaboga at terra.com.br> wrote
> > I am making a front-end to ffmpeg with pyqt and I am stuck in a
> > segmentation fault I can't understand. I have written a little
> 
> > def main(args):
> >    app = QtGui.QApplication(args)
> >    win = Combobox()
> >    win.show()
> >    app.exec_()
> >
> >    print type(Aux.mystring)
> >    # If uncommented segfaults
> >    # mystring = unicode(Aux.mystring)
> >    print ("The same" if Aux.mystring==Aux.mystring2 else 
> > "Different")
> 
> It looks from this that it has nothing to do with Qt per se.
> Does unicode() work OK outside of Qt?

Not only outside of Qt, but even with a constructed QString. That's
why I have put in the example the compare() function. It wasn't clear
enough, but I have a segfault a few lines later:

    print type(Aux.mystring)
    # If uncommented segfaults
    # mystring = unicode(Aux.mystring)
    print ("The same" if Aux.mystring==Aux.mystring2 else "Different")
    print Aux.compare                                                 
    # segfault
    print Aux.mystring

Aux.compare is a QString constructed directly (QString("Second")) and
Aux.mystring constructed read from ComboBox, but originally with the
same string:

self.comboBox.addItem(QtGui.QApplication.translate("Dialog", "Second",
None, QtGui.QApplication.UnicodeUTF8))

I have also tried constructing Aux.compare with
QtGui.QApplication.translate, with the same args, and still no
problems! 

> Or is Aux.mystring an insance of a QtString class that you need to
> deference to get the real string that unicode will understand?

Both Aux.mystring and Aux.compare have the same type,
PyQt4.QtCore.QString.

> All I can think of, not knowing anything much of Qt.

Thank you anyway. I am sending a new version of my test case attached,
and I will try to run it in another machine to see if it's a local
problem.

Tiago.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: cbox.py
Type: text/x-python
Size: 1510 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20071130/2f907f59/attachment.py 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: comboboxsegfault.py
Type: text/x-python
Size: 1651 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20071130/2f907f59/attachment-0001.py 
-------------- next part --------------
<ui version="4.0" >
 <class>Dialog</class>
 <widget class="QDialog" name="Dialog" >
  <property name="geometry" >
   <rect>
    <x>0</x>
    <y>0</y>
    <width>400</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle" >
   <string>Dialog</string>
  </property>
  <widget class="QDialogButtonBox" name="buttonBox" >
   <property name="geometry" >
    <rect>
     <x>30</x>
     <y>240</y>
     <width>341</width>
     <height>32</height>
    </rect>
   </property>
   <property name="orientation" >
    <enum>Qt::Horizontal</enum>
   </property>
   <property name="standardButtons" >
    <set>QDialogButtonBox::Cancel|QDialogButtonBox::NoButton|QDialogButtonBox::Ok</set>
   </property>
  </widget>
  <widget class="QComboBox" name="comboBox" >
   <property name="geometry" >
    <rect>
     <x>60</x>
     <y>30</y>
     <width>231</width>
     <height>31</height>
    </rect>
   </property>
   <item>
    <property name="text" >
     <string>First</string>
    </property>
   </item>
   <item>
    <property name="text" >
     <string>Second</string>
    </property>
   </item>
  </widget>
 </widget>
 <resources/>
 <connections>
  <connection>
   <sender>buttonBox</sender>
   <signal>accepted()</signal>
   <receiver>Dialog</receiver>
   <slot>accept()</slot>
   <hints>
    <hint type="sourcelabel" >
     <x>248</x>
     <y>254</y>
    </hint>
    <hint type="destinationlabel" >
     <x>157</x>
     <y>274</y>
    </hint>
   </hints>
  </connection>
  <connection>
   <sender>buttonBox</sender>
   <signal>rejected()</signal>
   <receiver>Dialog</receiver>
   <slot>reject()</slot>
   <hints>
    <hint type="sourcelabel" >
     <x>316</x>
     <y>260</y>
    </hint>
    <hint type="destinationlabel" >
     <x>286</x>
     <y>274</y>
    </hint>
   </hints>
  </connection>
 </connections>
</ui>

From tim at johnsons-web.com  Fri Nov 30 18:17:38 2007
From: tim at johnsons-web.com (Tim Johnson)
Date: Fri, 30 Nov 2007 08:17:38 -0900
Subject: [Tutor] lstrip removes '/' unexpectedly
Message-ID: <200711300817.38828.tim@johnsons-web.com>

Hello:
I'm seeing some strange behavior with lstrip operating
on string representations of *nix-style file paths
Example:
>>> s = '/home/test/'
>>> s1 = s.lstrip('/home')
>>> s1
'test/'   ## '/test/' was expected! '/' was unexpectedly removed
Any comments or corrective measures are welcome
thanks
Tim

From tiagosaboga at terra.com.br  Fri Nov 30 18:36:39 2007
From: tiagosaboga at terra.com.br (Tiago Saboga)
Date: Fri, 30 Nov 2007 15:36:39 -0200
Subject: [Tutor] lstrip removes '/' unexpectedly
In-Reply-To: <200711300817.38828.tim@johnsons-web.com>
References: <200711300817.38828.tim@johnsons-web.com>
Message-ID: <20071130173639.GA31299@localdomain>

Read this:

----
In [50]: print str.lstrip.__doc__
S.lstrip([chars]) -> string or unicode

Return a copy of the string S with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping
---

The point is "characters in chars", not strings.

---
In [52]: 'abababbbaacaaba'.lstrip('ab')
Out[52]: 'caaba'
---

Cheers,

Tiago.

From brunson at brunson.com  Fri Nov 30 18:38:39 2007
From: brunson at brunson.com (Eric Brunson)
Date: Fri, 30 Nov 2007 10:38:39 -0700
Subject: [Tutor] lstrip removes '/' unexpectedly
In-Reply-To: <200711300817.38828.tim@johnsons-web.com>
References: <200711300817.38828.tim@johnsons-web.com>
Message-ID: <47504A9F.7030704@brunson.com>

Tim Johnson wrote:
> Hello:
> I'm seeing some strange behavior with lstrip operating
> on string representations of *nix-style file paths
> Example:
>   
>>>> s = '/home/test/'
>>>> s1 = s.lstrip('/home')
>>>> s1
>>>>         
> 'test/'   ## '/test/' was expected! '/' was unexpectedly removed
>   

Hi Tim,

I believe you've misunderstood how lstrip works.  The sequence passed to 
the lstrip() method is a list of characters to remove from the string, 
not a string to match as a unit:

 >>> s1 = 'aaaaabbbbbcccccc'
 >>> s1.lstrip( 'ab' )
'cccccc'

In your example, since the '/' character is in the list to strip, the 
second slash goes with it.

Hope that helps,
e.


> Any comments or corrective measures are welcome
> thanks
> Tim
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From brunson at brunson.com  Fri Nov 30 18:56:04 2007
From: brunson at brunson.com (Eric Brunson)
Date: Fri, 30 Nov 2007 10:56:04 -0700
Subject: [Tutor] PyQt segfault
In-Reply-To: <20071130141405.GF8055@localdomain>
References: <20071130120754.GD8055@localdomain> <fip2a9$ul9$1@ger.gmane.org>
	<20071130141405.GF8055@localdomain>
Message-ID: <47504EB4.2070004@brunson.com>

Tiago Saboga wrote:
> First, I just noticed I sent a non-working version of the code. The line
>
> print ("The same" if Aux.mystring==Aux.mystring2 else "Different")
>
> should be 
>
> print ("The same" if Aux.mystring==Aux.compare else "Different")
>
> Sorry for that.
>   

This comboboxsegfault.py doesn't seem to do anything on my box, but I 
did get an "MemoryError" and a stack trace when I ran cbox.py and 
changed the dropdown menu selection.

I changed the line:
        Globals.changedtext = qstring

to:
        Globals.changedtext = qstring[:]

to get a copy of qstring instead of a reference to it, and cbox.py seems 
to execute without problems now.  My guess is that the qstring is being 
disposed of when the dialog is torn down.

Just a guess, but you can research more to confirm or deny.

Hope that helps,
e.


> On Fri, Nov 30, 2007 at 01:13:39PM -0000, Alan Gauld wrote:
>   
>> "Tiago Saboga" <tiagosaboga at terra.com.br> wrote
>>     
>>> I am making a front-end to ffmpeg with pyqt and I am stuck in a
>>> segmentation fault I can't understand. I have written a little
>>>       
>>> def main(args):
>>>    app = QtGui.QApplication(args)
>>>    win = Combobox()
>>>    win.show()
>>>    app.exec_()
>>>
>>>    print type(Aux.mystring)
>>>    # If uncommented segfaults
>>>    # mystring = unicode(Aux.mystring)
>>>    print ("The same" if Aux.mystring==Aux.mystring2 else 
>>> "Different")
>>>       
>> It looks from this that it has nothing to do with Qt per se.
>> Does unicode() work OK outside of Qt?
>>     
>
> Not only outside of Qt, but even with a constructed QString. That's
> why I have put in the example the compare() function. It wasn't clear
> enough, but I have a segfault a few lines later:
>
>     print type(Aux.mystring)
>     # If uncommented segfaults
>     # mystring = unicode(Aux.mystring)
>     print ("The same" if Aux.mystring==Aux.mystring2 else "Different")
>     print Aux.compare                                                 
>     # segfault
>     print Aux.mystring
>
> Aux.compare is a QString constructed directly (QString("Second")) and
> Aux.mystring constructed read from ComboBox, but originally with the
> same string:
>
> self.comboBox.addItem(QtGui.QApplication.translate("Dialog", "Second",
> None, QtGui.QApplication.UnicodeUTF8))
>
> I have also tried constructing Aux.compare with
> QtGui.QApplication.translate, with the same args, and still no
> problems! 
>
>   
>> Or is Aux.mystring an insance of a QtString class that you need to
>> deference to get the real string that unicode will understand?
>>     
>
> Both Aux.mystring and Aux.compare have the same type,
> PyQt4.QtCore.QString.
>
>   
>> All I can think of, not knowing anything much of Qt.
>>     
>
> Thank you anyway. I am sending a new version of my test case attached,
> and I will try to run it in another machine to see if it's a local
> problem.
>
> Tiago.
>   
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


From nospamformeSVP at gmail.com  Fri Nov 30 19:24:50 2007
From: nospamformeSVP at gmail.com (Don Taylor)
Date: Fri, 30 Nov 2007 13:24:50 -0500
Subject: [Tutor] Starting a browser instance and passing a parameter to
	it.
In-Reply-To: <474F32F9.7040605@brunson.com>
References: <filcfa$rh5$1@ger.gmane.org>	<filvmf$9e6$1@ger.gmane.org>	<fimj1d$bqc$1@ger.gmane.org>	<474F180F.6020109@tds.net>	<474F1A59.3030007@brunson.com>	<fin9uf$51j$1@ger.gmane.org>
	<474F32F9.7040605@brunson.com>
Message-ID: <fipkhq$1sj$1@ger.gmane.org>

Eric Brunson wrote:
> Don Taylor wrote:
>> Eric Brunson wrote:
>>
>>   
>>> Definitely,  or even just CGIHTTPServer.
>>>
>>>     
>> No, I don't think so.  I am not a RESTafarian.  :-)
>>   
> 
> Forgive my inexperience with the SimpleXMLRPCServer, but I didn't think 
> it provided state any more than any other connection oriented server?  
> Am I wrong about that?
> 

Eric:

I am sorry about being flippant in my earlier reply to you - I am not 
really that religious about this stuff.  I am just interested in using 
xml-rpc or json-rpc as a way to glue a browser UI onto a stand-alone 
Python application.

As I understand it, a web-server like Apache is a connection-oriented 
server and so is a stand-alone XML-RPC server.  Both open a port and 
listen for, and respond to, requests on that port until they are 
terminated.

A CGI server application behind Apache, however, is effectively a 
connectionless server.  It accepts one request at a time from any 
client, processes that request, and sends a response to the requester.

A server application embedded within an XML-RPC server (as a set of 
function or method calls) is still connection-oriented.  There is only 
one process running.

If you create a stand-alone SimpleXMLRPCServer (that is not behind a 
web-server, but having its own socket service) then you can write 
service routines that work almost as if those routines were part of the 
client's process.  If the service routine saves something, opens a file 
or whatever, then the next time the client calls that server the state 
is still there.  You could write service routines to open a file, write 
to it and close it.  If you called these routines in order from the 
client then they would do just what you expected.  (This is assuming the 
server only has one client - which is what I am doing).  The server runs 
as a long-running process - it runs until it is terminated.

If you contrast that with a CGI web server application then the server 
application is short-lived - it exists only for the duration of a single 
transaction with its client. Because it can have no memory of what 
happened on previous instantiations it must somehow pass state back at 
the end of a transaction so that the web client can re-send it to the 
server the next time that the client wants some work done.  Cookies and 
url rewriting are a couple of techniques for passing state back and 
forth between client and server.

All of the above is a gross simplification, is probably bs and I am sure 
is stuff that you know better than I do.

Don.


From james.homme at highmark.com  Fri Nov 30 19:58:21 2007
From: james.homme at highmark.com (james.homme at highmark.com)
Date: Fri, 30 Nov 2007 13:58:21 -0500
Subject: [Tutor] Indentation Issue and Blind People
Message-ID: <OF6F547C55.EC5E5707-ON852573A3.0067A087-852573A3.00683D63@highmark.com>


Hi,
I am just getting started with Python, as in learning the syntax for basic
statements and how to write functions and all. Here is my question.
Usually, if you are a person who is blind, you run the risk of having
trouble keeping your code indented properly. There are ways to do it, but
they are often time-consuming. Can I get a program that I can use that will
take my Python code as input and make sure it is indented properly? Or,
does Python let you write code, compile it, and indent it later? For anyone
who may be interested, I have created a scheme for my screen reader that
plays piano notes at indentations of two space increments. I made the code
indent that way because four spaces is a lot to have on a braille display.
If four spaces is more acceptable, I could globally replace two spaces with
four.

Thanks.

Jim

James D Homme, , Usability Engineering, Highmark Inc.,
james.homme at highmark.com, 412-544-1810

"Never doubt that a thoughtful group of committed citizens can change the
world.  Indeed, it is the only thing that ever has." -- Margaret Mead


From jim at well.com  Fri Nov 30 20:17:28 2007
From: jim at well.com (jim stockford)
Date: Fri, 30 Nov 2007 11:17:28 -0800
Subject: [Tutor] lstrip removes '/' unexpectedly
In-Reply-To: <200711300817.38828.tim@johnsons-web.com>
References: <200711300817.38828.tim@johnsons-web.com>
Message-ID: <9991fbc18c56185ecf596263ab8c5927@well.com>


it might work just to strip 'home' and leave

print s1
//test/

the '/' character is a separator, so
/this//that/andmore/
is, at least at the shell level, the same as
/this/that/andmore/
i.e. any number of '/' characters adjacent has
the effect of a single '/' character (again, at the
shell level).

On Nov 30, 2007, at 9:17 AM, Tim Johnson wrote:

> Hello:
> I'm seeing some strange behavior with lstrip operating
> on string representations of *nix-style file paths
> Example:
>>>> s = '/home/test/'
>>>> s1 = s.lstrip('/home')
>>>> s1
> 'test/'   ## '/test/' was expected! '/' was unexpectedly removed
> Any comments or corrective measures are welcome
> thanks
> Tim
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


From jim at well.com  Fri Nov 30 20:34:05 2007
From: jim at well.com (jim stockford)
Date: Fri, 30 Nov 2007 11:34:05 -0800
Subject: [Tutor] Indentation Issue and Blind People
In-Reply-To: <OF6F547C55.EC5E5707-ON852573A3.0067A087-852573A3.00683D63@highmark.com>
References: <OF6F547C55.EC5E5707-ON852573A3.0067A087-852573A3.00683D63@highmark.com>
Message-ID: <7c8c39801d5b1fd60aab09ef137ac4f9@well.com>


    you might consider keeping your code at two
spaces and when/if the need arises to share
your code, write a little filter program that
translates the two-space indents to four.
    very interesting idea to play piano notes.
how'd you do that?


On Nov 30, 2007, at 10:58 AM, james.homme at highmark.com wrote:

>
> Hi,
> I am just getting started with Python, as in learning the syntax for 
> basic
> statements and how to write functions and all. Here is my question.
> Usually, if you are a person who is blind, you run the risk of having
> trouble keeping your code indented properly. There are ways to do it, 
> but
> they are often time-consuming. Can I get a program that I can use that 
> will
> take my Python code as input and make sure it is indented properly? Or,
> does Python let you write code, compile it, and indent it later? For 
> anyone
> who may be interested, I have created a scheme for my screen reader 
> that
> plays piano notes at indentations of two space increments. I made the 
> code
> indent that way because four spaces is a lot to have on a braille 
> display.
> If four spaces is more acceptable, I could globally replace two spaces 
> with
> four.
>
> Thanks.
>
> Jim
>
> James D Homme, , Usability Engineering, Highmark Inc.,
> james.homme at highmark.com, 412-544-1810
>
> "Never doubt that a thoughtful group of committed citizens can change 
> the
> world.  Indeed, it is the only thing that ever has." -- Margaret Mead
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


From kent37 at tds.net  Fri Nov 30 20:31:40 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 30 Nov 2007 14:31:40 -0500
Subject: [Tutor] lstrip removes '/' unexpectedly
In-Reply-To: <200711300817.38828.tim@johnsons-web.com>
References: <200711300817.38828.tim@johnsons-web.com>
Message-ID: <4750651C.4080104@tds.net>

Tim Johnson wrote:
> Hello:
> I'm seeing some strange behavior with lstrip operating
> on string representations of *nix-style file paths
> Example:
>>>> s = '/home/test/'
>>>> s1 = s.lstrip('/home')
>>>> s1
> 'test/'   ## '/test/' was expected! '/' was unexpectedly removed
> Any comments or corrective measures are welcome

I usually do something like
if s.startswith('/home'):
   s = s[5:]

or
   s = s[len('/home'):]

Kent

From kent37 at tds.net  Fri Nov 30 20:37:36 2007
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 30 Nov 2007 14:37:36 -0500
Subject: [Tutor] Indentation Issue and Blind People
In-Reply-To: <OF6F547C55.EC5E5707-ON852573A3.0067A087-852573A3.00683D63@highmark.com>
References: <OF6F547C55.EC5E5707-ON852573A3.0067A087-852573A3.00683D63@highmark.com>
Message-ID: <47506680.5040103@tds.net>

james.homme at highmark.com wrote:
> Hi,
> I am just getting started with Python, as in learning the syntax for basic
> statements and how to write functions and all. Here is my question.
> Usually, if you are a person who is blind, you run the risk of having
> trouble keeping your code indented properly. There are ways to do it, but
> they are often time-consuming. Can I get a program that I can use that will
> take my Python code as input and make sure it is indented properly?

Not really. The 'proper' indent depends on what you want to do. For 
example both of these snippets are correct:

if a==1:
   x=2
   y=3

if a==1:
   x=2
y=3

The best you can do is check that the code is syntactically correct, 
which the compiler does.

> Or,
> does Python let you write code, compile it, and indent it later?

No, if it is not syntactically correct it will not compile.

You might be interested in PyFlakes. It will syntax check your code 
without executing it.
http://divmod.org/trac/wiki/DivmodPyflakes

> For anyone
> who may be interested, I have created a scheme for my screen reader that
> plays piano notes at indentations of two space increments. I made the code
> indent that way because four spaces is a lot to have on a braille display.
> If four spaces is more acceptable, I could globally replace two spaces with
> four.

Four spaces is more common but two spaces should be fine.

Kent

From dyoo at cs.wpi.edu  Fri Nov 30 20:36:14 2007
From: dyoo at cs.wpi.edu (Danny Yoo)
Date: Fri, 30 Nov 2007 14:36:14 -0500 (EST)
Subject: [Tutor] lstrip removes '/' unexpectedly
In-Reply-To: <200711300817.38828.tim@johnsons-web.com>
References: <200711300817.38828.tim@johnsons-web.com>
Message-ID: <Pine.LNX.4.63.0711301433050.3190@cs.wpi.edu>

> Hello:
> I'm seeing some strange behavior with lstrip operating
> on string representations of *nix-style file paths
> Example:
>>>> s = '/home/test/'
>>>> s1 = s.lstrip('/home')
>>>> s1
> 'test/'   ## '/test/' was expected! '/' was unexpectedly removed
> Any comments or corrective measures are welcome



Hi Tim,

Here's another example to help you see what's going on:

##########################
>>> s = '/home/test/'
>>> s1 = s.lstrip('/ehmo')
>>> s1
'test/'
##########################

Take a closer look at the documentation of lstrip, and you should see that 
what it takes in isn't treated as a prefix: rather, it'll be treated as a 
set of characters.

From ricaraoz at gmail.com  Fri Nov 30 13:45:52 2007
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Fri, 30 Nov 2007 09:45:52 -0300
Subject: [Tutor] Selecting a browser
Message-ID: <47500600.3050204@bigfoot.com>

Hi, I've checked webbrowser module and so far I find no way of selecting
a browser other than the default one. Say I want certain places opened
with IE and others with Mozilla, and I don't want to mess with the
user's setting of the default browser. Any tips?
TIA


From ricaraoz at gmail.com  Fri Nov 30 14:04:36 2007
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Fri, 30 Nov 2007 10:04:36 -0300
Subject: [Tutor] Variables and Functions
In-Reply-To: <filu39$4ae$1@ger.gmane.org>
References: <4c12d31a0711281300v67a6e8a2he4d200d8a111703d@mail.gmail.com><474E0568.60202@tds.net>	<4c12d31a0711281751i75d6439bnfb37e089ce0afc87@mail.gmail.com>
	<filu39$4ae$1@ger.gmane.org>
Message-ID: <47500A64.30902@bigfoot.com>

Alan Gauld wrote:
> "Devon MacIntyre" <macintyredev at gmail.com> wrote
> 
>> input their own numbers to fill in the board. My problem is that I 
>> can't get
>> the variables 'puzzle' and 'new_puzzle' into that function (to be 
>> compared)
>> because they are not globally defined; only in 'new_sudoku' 
>> function. Here's
>> some selected code from my program:
> 
> As per my prevuiouis email and example, simply return the puzzles
> 
>> def swap_row(puzzle,row1,row2):
>>    temp = puzzle[row1]
>>    puzzle[row1] = puzzle[row2]
>>    puzzle[row2] = temp
>       return puzzle   # just to be safe and consistent
> 
>> def new_sudoku():
>>    puzzle = [[1,2,3,4,5,6,7,8,9], \
>>              [4,5,6,7,8,9,1,2,3], \
>>              [7,8,9,1,2,3,4,5,6], \
>>              [2,3,4,5,6,7,8,9,1], \
>>              [5,6,7,8,9,1,2,3,4], \
>>              [8,9,1,2,3,4,5,6,7], \
>>              [3,4,5,6,7,8,9,1,2], \
>>              [6,7,8,9,1,2,3,4,5], \
>>              [9,1,2,3,4,5,6,7,8]]
>>    num_of_swap = random.randint(10,20)
>>    for i in range(num_of_swap):
>>        row1 = random.randint(0,8)
>>        row2 = random.randint(0,8)
>>        if row1/3 == row2/3:
>>            swap_row(puzzle,row1,row2)
>>    new_puzzle = copy.deepcopy(puzzle)
>>    sparseness = 0.85
>>    for i in range(9):
>>        for j in range(9):
>>            if random.uniform(0,1) < sparseness:
>>                new_puzzle[i][j] = ''
>       return puzzle,new_puzzle
> 
>> def play_game():
>>    '''
>>    Here is where I need the variables 'puzzle' and 'new_puzzle' to 
>> be
>> brought.
>>    '''
> 
> original,new = new_sudoku()
> compare(original,new)
> 
> 
>> I read about the 'class' module, but am not sure on it's execution.
> 
> I'm not sure what the class module is? Its not one of the standard
> Python modules. If you mean the class construct that is not a module
> but a part of the language - like def is for functions.
> 
> See the OOP topic of my tutor for more info on how to use it.
> 
> But for this problem you don;t need classes, just pass the data
> out of one function and into the other as shown above.
> Have a read of the Modules & Functions topic in my tutor for
> more explanation.
> 

Right! This is not something that needs OOP!
Besides, I find this belief that inside a class everything goes
completely wrong. In that case you could write your code with globals
and do whatever, then wrap it in a class, make your globals to be
properties and voil?,  every thing's all right. I don't think that is
the way to go.




From tim at johnsons-web.com  Fri Nov 30 19:27:42 2007
From: tim at johnsons-web.com (Tim Johnson)
Date: Fri, 30 Nov 2007 09:27:42 -0900
Subject: [Tutor] lstrip removes '/' unexpectedly
In-Reply-To: <47504A9F.7030704@brunson.com>
References: <200711300817.38828.tim@johnsons-web.com>
	<47504A9F.7030704@brunson.com>
Message-ID: <200711300927.42815.tim@johnsons-web.com>

On Friday 30 November 2007, Eric Brunson wrote:
> Tim Johnson wrote:
> > Hello:
> > I'm seeing some strange behavior with lstrip operating
> > on string representations of *nix-style file paths
> >
> > Example:
> >>>> s = '/home/test/'
> >>>> s1 = s.lstrip('/home')
> >>>> s1
> >
> > 'test/'   ## '/test/' was expected! '/' was unexpectedly removed
>
 Hi Folks:
 I actually resent this as a test because I've had problems contacting
 this list. The understanding of it percolated up to my wee little brain
 shortly after the first send (which didn't arrive).
I wrote the following as a solution:
def lstrip(S,chars):
	if S.startswith(chars):
		return S[len(chars):]
	else: return S
and a global rstrip would be an easy corrolary.
Thanks
(and thanks also to Danny and Kent for clearing up the email problem)
Tim

From tim at johnsons-web.com  Fri Nov 30 21:26:05 2007
From: tim at johnsons-web.com (Tim Johnson)
Date: Fri, 30 Nov 2007 11:26:05 -0900
Subject: [Tutor] lstrip removes '/' unexpectedly
In-Reply-To: <47504A9F.7030704@brunson.com>
References: <200711300817.38828.tim@johnsons-web.com>
	<47504A9F.7030704@brunson.com>
Message-ID: <200711301126.05485.tim@johnsons-web.com>

Gentlemen:
There appears to still be a problem.
The email below was also sent, but I do not see
that it has been received. Send time was about
2 hours previous to this. 
(09:27:42 Alaska Standard Time)
tim
----------------------------------------------------------------------------------------------
On Friday 30 November 2007, Eric Brunson wrote:
> Tim Johnson wrote:
> > Hello:
> > I'm seeing some strange behavior with lstrip operating
> > on string representations of *nix-style file paths
> >
> > Example:
> >>>> s = '/home/test/'
> >>>> s1 = s.lstrip('/home')
> >>>> s1
> >
> > 'test/'   ## '/test/' was expected! '/' was unexpectedly removed
>
 Hi Folks:
 I actually resent this as a test because I've had problems contacting
 this list. The understanding of it percolated up to my wee little brain
 shortly after the first send (which didn't arrive).
I wrote the following as a solution:
def lstrip(S,chars):
	if S.startswith(chars):
		return S[len(chars):]
	else: return S
and a global rstrip would be an easy corrolary.
Thanks
(and thanks also to Danny and Kent for clearing up the email problem)
Tim