From john at fouhy.net  Tue Jul  1 00:14:44 2008
From: john at fouhy.net (John Fouhy)
Date: Tue, 1 Jul 2008 10:14:44 +1200
Subject: [Tutor] Is "var = None" in Python equivalent to "Set var
In-Reply-To: <8249c4ac0806301143q353276c0m1e5b8a9153ee8bed@mail.gmail.com>
References: <8249c4ac0806301143q353276c0m1e5b8a9153ee8bed@mail.gmail.com>
Message-ID: <5e58f2e40806301514qfe19c35oc01990659213ab04@mail.gmail.com>

On 01/07/2008, Tony Cappellini <cappy2112 at gmail.com> wrote:
> In VB6 ( I have not worked with VB.NET), objects are set to Nothing when
> they go out of scope, yet there is a fair amount lot of code out there where
> objects are explicitly set to Nothing. This is a pretty common practice in
> VB land.
>
> >>but in Python these statements are unnecessary.
> What happened to "Explicit is better than implicit"?

If a name goes out of scope in python, you can't get at it anyway.  I
guess if you're worried about it, you could do 'del [var]' every time
you finish using a local variable -- but the only point of this would
be as a way of telling the programmer: "I have finished with this
variable."  If your functions are small enough to fit on a page, the
programmer should be able to see that anyway.

Sure, explicit is better than implicit, but worrying about what
happens to local variables when they go out of scope is a bridge too
far for most people.

(I don't want to criticise VB programmers because I am not one.
"Follow the local conventions" is generally always a good rule of
programming)

-- 
John.

From cappy2112 at gmail.com  Tue Jul  1 00:48:47 2008
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Mon, 30 Jun 2008 15:48:47 -0700
Subject: [Tutor] Is "var = None" in Python equivalent to "Set var
In-Reply-To: <5e58f2e40806301514qfe19c35oc01990659213ab04@mail.gmail.com>
References: <8249c4ac0806301143q353276c0m1e5b8a9153ee8bed@mail.gmail.com>
	<5e58f2e40806301514qfe19c35oc01990659213ab04@mail.gmail.com>
Message-ID: <8249c4ac0806301548x62cc455aye8df0fa5fc46a26@mail.gmail.com>

This thread got a bit off track....

> >>but in Python these statements are unnecessary.
> > What happened to "Explicit is better than implicit"?
>

Regarding the "original poster" contrasting VB with Python
setting someObject = None is perfectly fine in Python, and a good analogy
between the languages.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080630/5595bcfe/attachment.htm>

From alan.gauld at btinternet.com  Tue Jul  1 01:09:33 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 1 Jul 2008 00:09:33 +0100
Subject: [Tutor] s[len(s):len(s)] = [x] ??
References: <20080628010246.9295E1E4003@bag.python.org><5e58f2e40806291539x4948ca19yaeec7896b2b16f2@mail.gmail.com><20080630021704.414791E4006@bag.python.org><78b3a9580806292301y3399a87as98586729182ccc26@mail.gmail.com><20080630204007.2F3CD1E400C@bag.python.org><20080630204807.82D611E4009@bag.python.org>
	<16651e80806301359n2e7bfae6kd255e274b0228ea8@mail.gmail.com>
Message-ID: <g4bp3i$bp6$1@ger.gmane.org>

"Jerry Hill" <malaclypse2 at gmail.com> wrote

> You can do it with slice assignment too:
>>>> a = [1, 2, 3, 4]
>>>> a[1:3] = [[7, 8]]
>>>> a
> [1, [7, 8], 4]
>
> Now, which way is better?  The answer depends on context.

> If, conceptually, you are removing two elements from a list, then
> adding a new element which is itself a list, then doing it with 
> remove
> and insert is probably best.

Even in that case I'd replace themultiple removes with a slice:

>>> L = [1,2,3,4]
>>> L[1:3] = []
>>> L.insert(1,[7,8])
>>> L
[1, [7, 8], 4]

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 Jul  1 01:20:32 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 1 Jul 2008 00:20:32 +0100
Subject: [Tutor] Is "var = None" in Python equivalent to "Set var
References: <8249c4ac0806301143q353276c0m1e5b8a9153ee8bed@mail.gmail.com>
	<5e58f2e40806301514qfe19c35oc01990659213ab04@mail.gmail.com>
Message-ID: <g4bpo5$d7k$1@ger.gmane.org>

"John Fouhy" <john at fouhy.net> wrote 

> (I don't want to criticise VB programmers because I am not one.
> "Follow the local conventions" is generally always a good rule of
> programming)

I think this is a key point. I'm no VB expert but I do have
to read it from time to time.

VB programmers tend to set to null more often than Python 
programmers because their variables are not typeless.
In VB Set is explicitly used for setting variables to object 
references (as opposed to Let which is (optionally) used 
to set variables to non-object values(int, string etc). 
ie 

Set myvar = New MyObject

is like Python doing

myvar = MyObject()

and is different to 

Let X = myvalue

which in turn is usually written more simply as

X = myvalue

In Python we do not distinguish. Because of the specific 
nature of Set it seems to me that VB programmers treat 
explicitly freeing object references rather like we would 
treat closure of files. Most of the time you can get away 
with not doing it but its safer if you do. So while you do see

Set myobj = Nothing

You almost never see

Let X = Nothing

In fact it's possibly not even valid syntax!

Alan G.


From alan.gauld at btinternet.com  Tue Jul  1 01:26:27 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 1 Jul 2008 00:26:27 +0100
Subject: [Tutor] Deleting specified files using a python program...help
	with code?]
References: <48694809.7000901@abbottdavid.com>
Message-ID: <g4bq37$dv2$1@ger.gmane.org>


"David" <david at abbottdavid.com> wrote

> dir_input = raw_input('Enter dir: ')
> win_trace = ['*.ini', '*.db']
> files_removed = 0
> for root, dirs, files in os.walk(dir_input):
>    for trace in win_trace:
>        win_trace_path = os.path.join(root, trace)
>        for filename in glob.glob(win_trace_path):
>            if os.path.exists(filename):
>                print filename
>            else:
>                print 'No files found'

Note that at this point you have printed both names 
but you have not stored a reference to them.
Thus filename contains only the last name.

You need to create a list of the valid filenames.
You could use a list compreghension like so:

files = [f for f in glob.glob(win_trace_path) if os.path.exists(f)]
print files

> confirmation = raw_input('Confirm removal: ')
> if confirmation == 'y':
>    print "removing '%s'" % filename
>    os.remove(filename)
>    files_removed += 1

And now you are removing only one file, but you need to 
remove all of the files in your list so add a loop like:

> if confirmation == 'y':
     for filename in files:
        print "removing '%s'" % filename
        os.remove(filename)
        files_removed += 1


> elif confirmation == 'n':
>    pass
> else:
>    sys.exit()

The elif doesn't do anything so you can delete it.

HTH,


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


From david at abbottdavid.com  Tue Jul  1 03:05:47 2008
From: david at abbottdavid.com (David)
Date: Mon, 30 Jun 2008 21:05:47 -0400
Subject: [Tutor] Deleting specified files using a python program...help
 with code?]
In-Reply-To: <g4bq37$dv2$1@ger.gmane.org>
References: <48694809.7000901@abbottdavid.com> <g4bq37$dv2$1@ger.gmane.org>
Message-ID: <486982EB.20003@abbottdavid.com>

Alan Gauld wrote:
>
> "David" <david at abbottdavid.com> wrote
>
>> dir_input = raw_input('Enter dir: ')
>> win_trace = ['*.ini', '*.db']
>> files_removed = 0
>> for root, dirs, files in os.walk(dir_input):
>>    for trace in win_trace:
>>        win_trace_path = os.path.join(root, trace)
>>        for filename in glob.glob(win_trace_path):
>>            if os.path.exists(filename):
>>                print filename
>>            else:
>>                print 'No files found'
>
> Note that at this point you have printed both names but you have not 
> stored a reference to them.
> Thus filename contains only the last name.
>
> You need to create a list of the valid filenames.
> You could use a list compreghension like so:
>
> files = [f for f in glob.glob(win_trace_path) if os.path.exists(f)]
> print files
>
>> confirmation = raw_input('Confirm removal: ')
>> if confirmation == 'y':
>>    print "removing '%s'" % filename
>>    os.remove(filename)
>>    files_removed += 1
>
> And now you are removing only one file, but you need to remove all of 
> the files in your list so add a loop like:
>
>> if confirmation == 'y':
>     for filename in files:
>        print "removing '%s'" % filename
>        os.remove(filename)
>        files_removed += 1
>
>
>> elif confirmation == 'n':
>>    pass
>> else:
>>    sys.exit()
>
> The elif doesn't do anything so you can delete it.
>
> HTH,
>
>
Thanks Alan,

I am learning python in a group and one of the members came up with this;

#!/usr/bin/python
# Filename : new_remove-file.py
import os
import sys
import glob

dir_input = raw_input('Enter dir: ')
win_trace = ['*.ini', '*.db', '*.txt']
files_removed = 0
file_list = []
for root, dirs, files in os.walk(dir_input):
    for trace in win_trace:
        win_trace_path = os.path.join(root, trace)
        for filename in glob.glob(win_trace_path):
            if os.path.exists(filename):
                print filename
                file_list.append(filename)
            else:
                print 'No files found'
confirmation = raw_input('Confirm removal: ')
if confirmation == 'y':
    for file in file_list:
        print "removing " + file
        os.remove(file)
        files_removed += 1
if files_removed :
    print '%d files removed' % files_removed
else :
    print 'No files removed'


Can see why it did not work before. That is progress.

-- 
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com


From mwalsh at groktech.org  Tue Jul  1 05:52:10 2008
From: mwalsh at groktech.org (Martin Walsh)
Date: Mon, 30 Jun 2008 22:52:10 -0500
Subject: [Tutor] list objects are unhashable
In-Reply-To: <48692C28.2050804@khine.net>
References: <48692C28.2050804@khine.net>
Message-ID: <4869A9EA.10600@groktech.org>

Hi Norman,

Norman Khine wrote:
> 
>         for brain in brains:
>             x = getattr(brain, horizontal)
>             x = string.join(x, '' )
>             y = getattr(brain, vertical)
>             y = string.join(y, '' )
>             if x and y and (x, y) in table:
>                 table[(x, y)] += 1
>                 table[(x, '')] += 1
>                 table[('', y)] += 1
>                 table[('', '')] += 1

For what it's worth, string.join has been deprecated since the addition
of the join method for str and unicode types. Other deprecated string
module functions are documented here: http://docs.python.org/lib/node42.html

If I'm not mistaken, the conventional form would be:

  x = ''.join(x)

> 
> So now my list becomes a string, which is not really good for me, as
> this fails when there is more then one item.
> 
> Is there a better way to loop through this and sum up all occurrences of
> each entry ie  'airport-car-parking'

Maybe, can you show us a brief excerpt of what 'table' might look like
before the loop, and what you expect it to look like after one
iteration, with data samples for both x and y?

Most likely it's just me, but I'm having trouble reconciling your code
examples with your questions. AFAICT, either you want more than just a
simple count of occurrences from your data set, or you have some
confusion regarding dictionaries (if 'table' is a dictionary, of course).

If you want a count of each unique occurrence in a list -- not sure if
it's better, but something like this might get you started (untested):

from sets import Set
x = ['airlines-scheduled', 'airport-car-parking',
     'more-than-100ml', 'do-not-bring-toothpaste',
     'airport-car-parking', 'airlines-scheduled']

entity_count = dict((item, x.count(item)) for item in Set(x))
print entity_count['airlines-scheduled']
# 2

HTH,
Marty


From technorapture at gmail.com  Tue Jul  1 07:12:21 2008
From: technorapture at gmail.com (Shrutarshi Basu)
Date: Tue, 1 Jul 2008 01:12:21 -0400
Subject: [Tutor] String concatenation too slow
Message-ID: <376fbdcf0806302212t5466be7eoa759d56266c42839@mail.gmail.com>

I'm working on a program to create Lindenmayer systems. These systems
depend on heavy string rewriting to form complex patterns.I've been
using string concatenation to read through the string, and then create
the new one based on a dictionary lookup. However it becomes very slow
once the string gets very long (several thousand characters). Part of
it is undoubtedly due to the fact that the algorithm is quadratic (i'm
trying to find a better way) but I was wondering if there might be a
faster alternative to string concatenation. Would appending to a list
of strings be faster? I'm going to be doing thousands of these
appends, so even a small boost would be helpful.
Thanks,
Basu

-- 
The ByteBaker :
http://www.bytebaker.com

From wescpy at gmail.com  Tue Jul  1 07:37:04 2008
From: wescpy at gmail.com (wesley chun)
Date: Mon, 30 Jun 2008 22:37:04 -0700
Subject: [Tutor] String concatenation too slow
In-Reply-To: <376fbdcf0806302212t5466be7eoa759d56266c42839@mail.gmail.com>
References: <376fbdcf0806302212t5466be7eoa759d56266c42839@mail.gmail.com>
Message-ID: <78b3a9580806302237g2dffb0ebpb78239a0cd6f072c@mail.gmail.com>

> I've been
>  using string concatenation to read through the string, and then create
>  the new one based on a dictionary lookup. However it becomes very slow
>  once the string gets very long (several thousand characters). [...]
> I was wondering if there might be a
>  faster alternative to string concatenation. Would appending to a list
>  of strings be faster?

without knowing more about your application, my 1st inclination would
be to turn your code that "appends" each successive addition to the
string into a generator function.  then when you need to final
massively large string, i'd use a generator expression inside the call
to the delimiter's join() method.

for example:

def nextLsystem(...):
        :
    for n in range(XXX):
        # blah-blah stuff in a loop
        yield nextStr

final = ''.join(x for x in nextLsystem(XXX))

i like this code because it doesn't keep building up a data structure
like continuously concatenating strings nor continually appending to a
list, both of which are memory-intensive.

i'm using a generator to create each successive string, without saving
previous result necessarily.  then the generator expression -- unlike
a list comprehension which must build an entire list -- passes each
string to join(), which then creates the final string.

i'm sure others have better ideas, but like it said, it's just a gut
shot from me here.

good luck!
-- 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 technorapture at gmail.com  Tue Jul  1 07:55:27 2008
From: technorapture at gmail.com (Shrutarshi Basu)
Date: Tue, 1 Jul 2008 01:55:27 -0400
Subject: [Tutor] String concatenation too slow
In-Reply-To: <78b3a9580806302237g2dffb0ebpb78239a0cd6f072c@mail.gmail.com>
References: <376fbdcf0806302212t5466be7eoa759d56266c42839@mail.gmail.com>
	<78b3a9580806302237g2dffb0ebpb78239a0cd6f072c@mail.gmail.com>
Message-ID: <376fbdcf0806302255v5b86dc12kc8af95b75343c921@mail.gmail.com>

My bad, should have included some code. Here's the function which does
the grunt work. self.axiom is a string, where each character gets
replaced by its counterpart from self.rules. output then goes back to
the calling function. That's the end of one generation of the string.
The next generation happens when generate() is called again after
axiom has been replaced (usually by output and some additions)

    def generate(self):
        output = ''
        for element in self.axiom:
            if element in self.rules.keys():
                output = output + self.rules[element]
            else:
                output = output + element
        return output

Looking at Wesley's example. the function should then yield each
character replacement (a dict lookup) and the join() would put
everything together. I think that would be faster. Will try soon.
Thanks,
Basu

On Tue, Jul 1, 2008 at 1:37 AM, wesley chun <wescpy at gmail.com> wrote:
>> I've been
>>  using string concatenation to read through the string, and then create
>>  the new one based on a dictionary lookup. However it becomes very slow
>>  once the string gets very long (several thousand characters). [...]
>> I was wondering if there might be a
>>  faster alternative to string concatenation. Would appending to a list
>>  of strings be faster?
>
> without knowing more about your application, my 1st inclination would
> be to turn your code that "appends" each successive addition to the
> string into a generator function.  then when you need to final
> massively large string, i'd use a generator expression inside the call
> to the delimiter's join() method.
>
> for example:
>
> def nextLsystem(...):
>        :
>    for n in range(XXX):
>        # blah-blah stuff in a loop
>        yield nextStr
>
> final = ''.join(x for x in nextLsystem(XXX))
>
> i like this code because it doesn't keep building up a data structure
> like continuously concatenating strings nor continually appending to a
> list, both of which are memory-intensive.
>
> i'm using a generator to create each successive string, without saving
> previous result necessarily.  then the generator expression -- unlike
> a list comprehension which must build an entire list -- passes each
> string to join(), which then creates the final string.
>
> i'm sure others have better ideas, but like it said, it's just a gut
> shot from me here.
>
> good luck!
> -- 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
>



-- 
The ByteBaker :
http://www.bytebaker.com

From cfuller084 at thinkingplanet.net  Tue Jul  1 08:00:33 2008
From: cfuller084 at thinkingplanet.net (Chris Fuller)
Date: Tue, 1 Jul 2008 01:00:33 -0500
Subject: [Tutor] String concatenation too slow
In-Reply-To: <376fbdcf0806302212t5466be7eoa759d56266c42839@mail.gmail.com>
References: <376fbdcf0806302212t5466be7eoa759d56266c42839@mail.gmail.com>
Message-ID: <200807010100.33570.cfuller084@thinkingplanet.net>

You could try creating a list of strings, and then using a ''.join(list) to 
concatenate, but you are probably going to be best off using the cStringIO 
module (http://docs.python.org/lib/module-cStringIO.html).  Try timing all 
three and see how they compare when joining lots of strings.  The length of 
the strings probably won't matter as much as the number of them.

Cheers

On Tuesday 01 July 2008 00:12, Shrutarshi Basu wrote:
> I'm working on a program to create Lindenmayer systems. These systems
> depend on heavy string rewriting to form complex patterns.I've been
> using string concatenation to read through the string, and then create
> the new one based on a dictionary lookup. However it becomes very slow
> once the string gets very long (several thousand characters). Part of
> it is undoubtedly due to the fact that the algorithm is quadratic (i'm
> trying to find a better way) but I was wondering if there might be a
> faster alternative to string concatenation. Would appending to a list
> of strings be faster? I'm going to be doing thousands of these
> appends, so even a small boost would be helpful.
> Thanks,
> Basu

From andreengels at gmail.com  Tue Jul  1 08:12:43 2008
From: andreengels at gmail.com (Andre Engels)
Date: Tue, 1 Jul 2008 08:12:43 +0200
Subject: [Tutor] Fwd:  Problem Euler 26
In-Reply-To: <6faf39c90806302311x13344adib2ce5a335fd8b2d6@mail.gmail.com>
References: <1214771673.6922.46.camel@www.kinuthia.com>
	<6faf39c90806302311x13344adib2ce5a335fd8b2d6@mail.gmail.com>
Message-ID: <6faf39c90806302312m6e2697e4uca8e929cef9990b4@mail.gmail.com>

On Sun, Jun 29, 2008 at 10:34 PM, kinuthiA muchanE <muchanek at gmail.com> wrote:

> Er... er, that does not exactly work as expected but it narrows the
> search to only 3 candidates because of the inclusion of the zero:
>
>  (28, '035714286')
>  (38, '026315789')
>  (81, '012345679')
>
> For 28, the digit, in the fractional part, after 8 is 5, so 5 is
> repeated and as for, 81 the next digit after 7 is 0, so again 0 occurs
> twice. But for 38, the next digit after 9 is 4, and because it has NOT
> occurred before, I assume 38 is the correct answer... and I am wrong!
>
> I suspect I have completely misunderstood the question.

Yes, it seems you have... I will try to rephrase:

For each fraction x/y (y>x to get it below 1), its representation as a
decimal fraction consists of two parts: first some arbitrary series of
numbers, then a series of numbers that is repeated over and over
again. For example, 1/55 = 0.018181818181818..., or in short 0.0(18) -
the arbitrary series here is 0, the repeating part 18. You are asked
to get the largest repeating part.

Your solution finds the longest time before a digit is repeated
instead, which is incorrect because the same digit can be used more
than once in the repeating part (and also because it might occur once
or more in the non-repeating part) - for example, the 1/38 that you
mentioned equals:
0.0(263157894736842105)

A hint for solving this problem: use methods similar to the once you
use for a long division with pen and paper.

--
Andre Engels, andreengels at gmail.com
ICQ: 6260644 -- Skype: a_engels

From norman at khine.net  Tue Jul  1 09:09:56 2008
From: norman at khine.net (Norman Khine)
Date: Tue, 01 Jul 2008 09:09:56 +0200
Subject: [Tutor] list objects are unhashable
In-Reply-To: <4869A9EA.10600@groktech.org>
References: <48692C28.2050804@khine.net> <4869A9EA.10600@groktech.org>
Message-ID: <4869D844.2010309@khine.net>

Hi,
Here is the 'full' code as such which gets the data from the files.

         ## Classify the users
         table = {}
         table[('', '')] = 0
         for x in horizontal_criterias:
             table[(x['id'], '')] = 0
         for y in vertical_criterias:
             table[('', y['id'])] = 0
         for x in horizontal_criterias:
             x = x['id']
             for y in vertical_criterias:
                 table[(x, y['id'])] = 0

         for brain in brains:
             x = getattr(brain, horizontal)
             if isinstance(x, list):
                 for item in x:
                     x = item
             else:
                 x
             y = getattr(brain, vertical)
             if isinstance(y, list):
                 for item in y:
                     y = item
             else:
                 y
             if x and y and (x, y) in table:
                 table[(x, y)] += 1
                 table[(x, '')] += 1
                 table[('', y)] += 1
                 table[('', '')] += 1


table is a dictionary, which returns, for example:

{   ('', ''): 1,
     ('', 'fr'): 0,
     ('', 'uk'): 1,
     ('', 'us'): 0,
     ('airport-car-parking', ''): 2,
     ('airport-car-parking', 'fr'): 0,
     ('airport-car-parking', 'uk'): 2,
     ('airport-car-parking', 'us'): 0,
     ('air-taxi-operators', ''): 1,
     ('air-taxi-operators', 'fr'): 0,
     ('air-taxi-operators', 'uk'): 1,
     ('air-taxi-operators', 'us'): 0,
      ...
     ('worldwide-attractions-and-ticket-agents', ''): 0,
     ('worldwide-attractions-and-ticket-agents', 'fr'): 0,
     ('worldwide-attractions-and-ticket-agents', 'uk'): 0,
     ('worldwide-attractions-and-ticket-agents', 'us'): 0}


The output is something like:


country |airport-car|air-taxi-operators|airlines-schedule| total
---------------------------------------------------------------
france  |0	    |0		       |0		|0
uk	|2	    |0		       |0		|2
us	|0          |0		       |0		|0
---------------------------------------------------------------
total	|2	    |0                 |0		|2
---------------------------------------------------------------

What I can't seem to figure out is how to do a cumulative sum for each 
record, for example, my files contain:

file1
<topic>airport-car air-taxi-operators</topic>

file2
<topic>airport-car air-taxi-operators airlines-schedule</topic>

etc...


If I put a print, to see what is listed, in this code

             if isinstance(x, list):
                 for item in x:
                     x = item
		    pp.pprint(x)
             else:

I get:

u'airport-car-parking'
u'air-taxi-operators'
u'airport-car-parking'
u'airlines-scheduled'
u'air-taxi-operators'

Which is correct, but the table only counts the first item of the tuple.

Ideally my table should be:

country |airport-car|air-taxi-operators|airlines-schedule| total
---------------------------------------------------------------
france  |0	    |0		       |0		|0
uk	|2	    |2		       |1		|2
us	|0          |0		       |0		|0
---------------------------------------------------------------
total	|2	    |2                 |1		|2
---------------------------------------------------------------


Cheers

Norman

Martin Walsh wrote:
> Hi Norman,
> 
> Norman Khine wrote:
>>         for brain in brains:
>>             x = getattr(brain, horizontal)
>>             x = string.join(x, '' )
>>             y = getattr(brain, vertical)
>>             y = string.join(y, '' )
>>             if x and y and (x, y) in table:
>>                 table[(x, y)] += 1
>>                 table[(x, '')] += 1
>>                 table[('', y)] += 1
>>                 table[('', '')] += 1
> 
> For what it's worth, string.join has been deprecated since the addition
> of the join method for str and unicode types. Other deprecated string
> module functions are documented here: http://docs.python.org/lib/node42.html
> 
> If I'm not mistaken, the conventional form would be:
> 
>   x = ''.join(x)
> 
>> So now my list becomes a string, which is not really good for me, as
>> this fails when there is more then one item.
>>
>> Is there a better way to loop through this and sum up all occurrences of
>> each entry ie  'airport-car-parking'
> 
> Maybe, can you show us a brief excerpt of what 'table' might look like
> before the loop, and what you expect it to look like after one
> iteration, with data samples for both x and y?
> 
> Most likely it's just me, but I'm having trouble reconciling your code
> examples with your questions. AFAICT, either you want more than just a
> simple count of occurrences from your data set, or you have some
> confusion regarding dictionaries (if 'table' is a dictionary, of course).
> 
> If you want a count of each unique occurrence in a list -- not sure if
> it's better, but something like this might get you started (untested):
> 
> from sets import Set
> x = ['airlines-scheduled', 'airport-car-parking',
>      'more-than-100ml', 'do-not-bring-toothpaste',
>      'airport-car-parking', 'airlines-scheduled']
> 
> entity_count = dict((item, x.count(item)) for item in Set(x))
> print entity_count['airlines-scheduled']
> # 2
> 
> HTH,
> Marty
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

From sbjaved at gmail.com  Tue Jul  1 09:41:21 2008
From: sbjaved at gmail.com (Saad Javed)
Date: Tue, 1 Jul 2008 13:41:21 +0600
Subject: [Tutor] Deleting specified files using a python program...help
	with code?
In-Reply-To: <3c10cd400806290813s6cb74717u3e86a0196c86803d@mail.gmail.com>
References: <3c10cd400806290813s6cb74717u3e86a0196c86803d@mail.gmail.com>
Message-ID: <3c10cd400807010041i74ea5c1an3feea2f15c67a869@mail.gmail.com>

Thankyou cedric!

On 6/29/08, Saad Javed <sbjaved at gmail.com> wrote:
> I transfer files a lot between my windows and linux partitions...these
> folders sometimes contain *.db and *.ini files which are not recognized or
> used by linux. So i tried to write a program to crawl through my home dir
> and remove these files...I'm *very* new to programming and python so please
> be gentle. Here is the code:
>
> *import os
>
> list = ['*.ini', '*.db']
>
> for root, dirs, files in os.walk('/home/saad'):
> **for list in files:
> **os.remove(os.path.join('root', 'list'))
> print 'done'*
>
> Unfortunately its a bit too efficient and nearly wiped my home dir before i
> manually killed it. Again...treat me like a super noob.
>
> Saad
>

-- 
Sent from Gmail for mobile | mobile.google.com

From alan.gauld at btinternet.com  Tue Jul  1 10:37:36 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 1 Jul 2008 09:37:36 +0100
Subject: [Tutor] list objects are unhashable
References: <48692C28.2050804@khine.net> <4869A9EA.10600@groktech.org>
	<4869D844.2010309@khine.net>
Message-ID: <g4cqck$ufk$1@ger.gmane.org>


"Norman Khine" <norman at khine.net> wrote

> Here is the 'full' code as such which gets the data from the files.

Unfortunately trying to read this is still difficult since we don't
know what the structure of x, horizontal_criterias, 
vertical_criterias,
or brains is like.

>         ## Classify the users
>         table = {}
>         table[('', '')] = 0
>         for x in horizontal_criterias:
>             table[(x['id'], '')] = 0
>         for y in vertical_criterias:
>             table[('', y['id'])] = 0
>         for x in horizontal_criterias:
>             x = x['id']

You select a collection of some sort and replace it with a value
from the collection. Is that really what you want to do? You don't
do it for y...

>             for y in vertical_criterias:
>                 table[(x, y['id'])] = 0

It would be just as readable IMHO to just use

          table[ x['id'],y['id'] ] = 0

>         for brain in brains:
>             x = getattr(brain, horizontal)
>             if isinstance(x, list):
>                 for item in x:
>                     x = item

And here you replace the list x with it' first item.
You could just do

x = x[0]

>             else:
>                 x

And this does nothing useful whatsoever. It just
siilently evaluates x.

>             y = getattr(brain, vertical)
>             if isinstance(y, list):
>                 for item in y:
>                     y = item
>             else:
>                 y

Same comments apply

>             if x and y and (x, y) in table:
>                 table[(x, y)] += 1
>                 table[(x, '')] += 1
>                 table[('', y)] += 1
>                 table[('', '')] += 1
>
>
> table is a dictionary, which returns, for example:
>
> {   ('', ''): 1,
>     ('', 'fr'): 0,
>     ('airport-car-parking', ''): 2,
>     ('airport-car-parking', 'fr'): 0,
>     ('air-taxi-operators', ''): 1,
>     ('air-taxi-operators', 'fr'): 0,
>      ...
>     ('worldwide-attractions-and-ticket-agents', ''): 0,
>     ('worldwide-attractions-and-ticket-agents', 'fr'): 0,

>From this I suggest you rename your variable from x and y
to something meaningful like facility and country. That
might make your code more meaningful to read.

> The output is something like:
> country |airport-car|air-taxi-operators|airlines-schedule| total
> ---------------------------------------------------------------
> france  |0     |0        |0 |0
> uk |2     |0        |0 |2
> us |0          |0        |0 |0
> ---------------------------------------------------------------
> total |2     |0                 |0 |2
> ---------------------------------------------------------------
>
> What I can't seem to figure out is how to do a cumulative sum for 
> each record, for example, my files contain:

Frankly I'd use a database. Just load the data into it using Python.
Then execute SQL querioes to get the counts etc.

>             if isinstance(x, list):
>                 for item in x:
>                     x = item
>     pp.pprint(x)
>             else:
>
> Which is correct, but the table only counts the first item of the 
> tuple.

Isn't that because you replace x with the first element of x?

Alan G. 



From alan.gauld at btinternet.com  Tue Jul  1 10:47:59 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 1 Jul 2008 09:47:59 +0100
Subject: [Tutor] Deleting specified files using a python program...help
	with code?]
References: <48694809.7000901@abbottdavid.com> <g4bq37$dv2$1@ger.gmane.org>
	<486982EB.20003@abbottdavid.com>
Message-ID: <g4cr03$on$1@ger.gmane.org>

"David" <david at abbottdavid.com> wrote 

Thats better.

Now on a wee usability aspect:

> confirmation = raw_input('Confirm removal: ')

You might want to print the list of files before asking the 
question. Although if its a likely to be a long list maybe just
say how many files - it gives the user a chance to back out 
if it sounds suspicious!

Also, its good to tell the user what are valid values to type
or to provide a default value:

confirmation = raw_input('Confirm removal[y/n]: ')

or

confirmation = raw_input('Confirm removal[yes]: ')

> if confirmation == 'y':

And to cover slight errors of input, like 'Y' or 'yes' try this:

if confirmation[0] in 'yY':

Which will correctly process any input beginning 
with y or Y which is more friendly.

Some prefer a slightly different route to the same end:

if confirmation.lower().startswith('y')

But I find the in technique more flexible.

If you go with the default approach the test becomes:

if confirmation in 'yY' or not confirmation:
      # go ahead and delete them

HTH,

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


From srilyk at gmail.com  Tue Jul  1 11:21:01 2008
From: srilyk at gmail.com (W W)
Date: Tue, 1 Jul 2008 04:21:01 -0500
Subject: [Tutor] Deleting specified files using a python program...help
	with code?]
In-Reply-To: <g4cr03$on$1@ger.gmane.org>
References: <48694809.7000901@abbottdavid.com> <g4bq37$dv2$1@ger.gmane.org>
	<486982EB.20003@abbottdavid.com> <g4cr03$on$1@ger.gmane.org>
Message-ID: <333efb450807010221r2f1f786fpd64c8106ac081d9e@mail.gmail.com>

On Tue, Jul 1, 2008 at 3:47 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> But I find the in technique more flexible.
>
> If you go with the default approach the test becomes:
>
> if confirmation in 'yY' or not confirmation:
>     # go ahead and delete them

That's slightly different, but basically the same (I think) how I
often run input:

if confirmation in ('yes', 'ye', 'y', 'Y', 'YES', 'si', 'ja', 'absolutely'):
    do this

Mostly it's my tongue in cheek brand of humor coming out in my
programming... Perhaps I go a little overboard, but I doubt, even if
you had that many options, that you would find much of an increase in
execution time. I'm sure in most cases, 'input [y/n]:' and 'in ('y',
'Y')' would be fine, though.

Testing your example, Alan, you have it defaulted to "delete",
correct? That's where the "not confirmation" part comes in? I just
tried it in a simple function:

def confirm(iput):  #I wasn't sure if input was "reserved"
    if iput in 'yY' or not iput:
        print "Confirmed"
    else:
        print "Not confirmed"

>>>confirm('y')
Confirmed
>>>confirm('n')
Not confirmed
>>>confirm('')
Confirmed

That's something I didn't expect at first, mainly because I'm not used
to setting up that sort of input (but it makes sense to do it that
way).

HTH,
Wayne

From srilyk at gmail.com  Tue Jul  1 11:25:44 2008
From: srilyk at gmail.com (W W)
Date: Tue, 1 Jul 2008 04:25:44 -0500
Subject: [Tutor] String concatenation too slow
In-Reply-To: <200807010100.33570.cfuller084@thinkingplanet.net>
References: <376fbdcf0806302212t5466be7eoa759d56266c42839@mail.gmail.com>
	<200807010100.33570.cfuller084@thinkingplanet.net>
Message-ID: <333efb450807010225n38743a95ud69c2a59c6b10c35@mail.gmail.com>

> On Tuesday 01 July 2008 00:12, Shrutarshi Basu wrote:
<snip>
>>I've been
>> using string concatenation to read through the string, and then create
>> the new one based on a dictionary lookup. However it becomes very slow
>> once the string gets very long (several thousand characters). Part of
>> it is undoubtedly due to the fact that the algorithm is quadratic (i'm
>> trying to find a better way) but I was wondering if there might be a
>> faster alternative to string concatenation. Would appending to a list
>> of strings be faster? I'm going to be doing thousands of these
>> appends, so even a small boost would be helpful.
>> Thanks,
>> Basu

Basu,

You might find this study/links to be helpful! We just had a
discussion on this very concept, my guess is that you'll find the
results informative, and especially helpful.

At 04:28 AM 6/27/2008, Kent Johnson wrote:

    On Fri, Jun 27, 2008 at 6:48 AM, Dick Moores <rdm at rcblue.com> wrote:

    > Instead I've tried to find out if it's true what Alex Martelli
writes on p.
    > 484 in the section, "Building up a string from pieces" in his _Python in a
    > Nutshell_, 2nd ed., which covers Python 2.4x.

    You might be interested in this, complete with a picture:
    http://personalpages.tds.net/~kent37/blog/arch_m1_2004_08.html#e55

    and this followup:
    http://personalpages.tds.net/~kent37/blog/arch_m1_2004_08.html#e56

HTH,
Wayne

From srilyk at gmail.com  Tue Jul  1 11:48:56 2008
From: srilyk at gmail.com (W W)
Date: Tue, 1 Jul 2008 04:48:56 -0500
Subject: [Tutor] Fwd: Problem Euler 26
In-Reply-To: <6faf39c90806302312m6e2697e4uca8e929cef9990b4@mail.gmail.com>
References: <1214771673.6922.46.camel@www.kinuthia.com>
	<6faf39c90806302311x13344adib2ce5a335fd8b2d6@mail.gmail.com>
	<6faf39c90806302312m6e2697e4uca8e929cef9990b4@mail.gmail.com>
Message-ID: <333efb450807010248s27988906hfde96997cf7116a8@mail.gmail.com>

Just a tidbit:

A neat function my friend came up with last year to figure out the
length of a whole number (now converted to python for your viewing
pleasure):

from math import log10 as log
from math import floor

def findNumberLength(number):
    number = float(number)
    x = log(number)
    x = floor(x)
    x += 1
    x = int(x)
    return x

The only catch is that this only works for a whole (non-decimal) number:
>>>print findNumberLength(123)
3
>>>print findNumberLength(1234.5234)
4

Though you could easily split your number in two:

def splitNum(mynum):
    mynum = str(mynum)
    mynum = mynum.split('.')
    for x in range(2):
        mynum[x] = float(mynum[x])
    return mynum

and then run the operation on both. A simple error check would
eliminate, say, working this on 123.0 (which would give you 4 digits,
and I suppose if you were looking for significant figures that would
work)

if (mynum % 1) == 0:
    print "This number is X.0"
else:
    splitNum(mynum)

Although, now that I think about it, if you were really lazy, you
could just convert the int to a str and run len on it. Heh... Can't do
that (easily) in c++.

*Shrugs* oh well.

HTH,
Wayne
On Tue, Jul 1, 2008 at 1:12 AM, Andre Engels <andreengels at gmail.com> wrote:
> On Sun, Jun 29, 2008 at 10:34 PM, kinuthiA muchanE <muchanek at gmail.com> wrote:
>
>> Er... er, that does not exactly work as expected but it narrows the
>> search to only 3 candidates because of the inclusion of the zero:
>>
>>  (28, '035714286')
>>  (38, '026315789')
>>  (81, '012345679')
>>
>> For 28, the digit, in the fractional part, after 8 is 5, so 5 is
>> repeated and as for, 81 the next digit after 7 is 0, so again 0 occurs
>> twice. But for 38, the next digit after 9 is 4, and because it has NOT
>> occurred before, I assume 38 is the correct answer... and I am wrong!
>>
>> I suspect I have completely misunderstood the question.
>
> Yes, it seems you have... I will try to rephrase:
>
> For each fraction x/y (y>x to get it below 1), its representation as a
> decimal fraction consists of two parts: first some arbitrary series of
> numbers, then a series of numbers that is repeated over and over
> again. For example, 1/55 = 0.018181818181818..., or in short 0.0(18) -
> the arbitrary series here is 0, the repeating part 18. You are asked
> to get the largest repeating part.
>
> Your solution finds the longest time before a digit is repeated
> instead, which is incorrect because the same digit can be used more
> than once in the repeating part (and also because it might occur once
> or more in the non-repeating part) - for example, the 1/38 that you
> mentioned equals:
> 0.0(263157894736842105)
>
> A hint for solving this problem: use methods similar to the once you
> use for a long division with pen and paper.
>
> --
> Andre Engels, andreengels at gmail.com
> ICQ: 6260644 -- Skype: a_engels
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
To be considered stupid and to be told so is more painful than being
called gluttonous, mendacious, violent, lascivious, lazy, cowardly:
every weakness, every vice, has found its defenders, its rhetoric, its
ennoblement and exaltation, but stupidity hasn't. - Primo Levi

From kent37 at tds.net  Tue Jul  1 12:10:41 2008
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 1 Jul 2008 06:10:41 -0400
Subject: [Tutor] list objects are unhashable
In-Reply-To: <4869D844.2010309@khine.net>
References: <48692C28.2050804@khine.net> <4869A9EA.10600@groktech.org>
	<4869D844.2010309@khine.net>
Message-ID: <1c2a2c590807010310k4bec9624p3ccefb84a9982524@mail.gmail.com>

On Tue, Jul 1, 2008 at 3:09 AM, Norman Khine <norman at khine.net> wrote:

>            x = getattr(brain, horizontal)
>            if isinstance(x, list):
>                for item in x:
>                    x = item

This just assigns x to the last element of the list, it doesn't
process the whole list. One possibility would be to ensure that x and
y are always lists, then use nested loops to iterate over all
combinations:
x = getattr(brain, horizontal)
if not isinstance(x, list):
  x = [x]
y = getattr(brain, vertical)
if not isinstance(y, list):
  y = [y]
for first in x:
  for second in y:
    if first and second and (first, second) in table:

etc.

Kent

From kent37 at tds.net  Tue Jul  1 12:26:03 2008
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 1 Jul 2008 06:26:03 -0400
Subject: [Tutor] String concatenation too slow
In-Reply-To: <333efb450807010225n38743a95ud69c2a59c6b10c35@mail.gmail.com>
References: <376fbdcf0806302212t5466be7eoa759d56266c42839@mail.gmail.com>
	<200807010100.33570.cfuller084@thinkingplanet.net>
	<333efb450807010225n38743a95ud69c2a59c6b10c35@mail.gmail.com>
Message-ID: <1c2a2c590807010326w428a8b43u493b540950a65452@mail.gmail.com>

On Tue, Jul 1, 2008 at 5:25 AM, W W <srilyk at gmail.com> wrote:

> You might find this study/links to be helpful! We just had a
> discussion on this very concept, my guess is that you'll find the
> results informative, and especially helpful.

There is also an interesting recent thread on comp.lang.python:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/cdef678dd995c54f/2af9e9eed46bf18c?lnk=gst

One thing I didn't know is that the optimization for string += only
occurs in some specific circumstances.

Kent

From alan.gauld at btinternet.com  Tue Jul  1 12:27:17 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 1 Jul 2008 11:27:17 +0100
Subject: [Tutor] list objects are unhashable
References: <48692C28.2050804@khine.net>
	<4869A9EA.10600@groktech.org><4869D844.2010309@khine.net>
	<1c2a2c590807010310k4bec9624p3ccefb84a9982524@mail.gmail.com>
Message-ID: <g4d0qa$m7u$1@ger.gmane.org>

"Kent Johnson" <kent37 at tds.net> wrote 
>>            if isinstance(x, list):
>>                for item in x:
>>                    x = item
> 
> This just assigns x to the last element of the list

Oops, yes, I said the first but in fact reassigning x does 
not stop the loop, it seems the loop works on a local 
copy of the original reference.

Alan G


From norman at khine.net  Tue Jul  1 12:55:56 2008
From: norman at khine.net (Norman Khine)
Date: Tue, 01 Jul 2008 12:55:56 +0200
Subject: [Tutor] list objects are unhashable
In-Reply-To: <g4cqck$ufk$1@ger.gmane.org>
References: <48692C28.2050804@khine.net>
	<4869A9EA.10600@groktech.org>	<4869D844.2010309@khine.net>
	<g4cqck$ufk$1@ger.gmane.org>
Message-ID: <486A0D3C.3050000@khine.net>

Hi,


Alan Gauld wrote:
> 
> "Norman Khine" <norman at khine.net> wrote
> 
>> Here is the 'full' code as such which gets the data from the files.
> 
> Unfortunately trying to read this is still difficult since we don't
> know what the structure of x, horizontal_criterias, vertical_criterias,
> or brains is like.

Here is the code http://www.pastie.org/225436


> 
>>         ## Classify the users
>>         table = {}
>>         table[('', '')] = 0
>>         for x in horizontal_criterias:
>>             table[(x['id'], '')] = 0
>>         for y in vertical_criterias:
>>             table[('', y['id'])] = 0
>>         for x in horizontal_criterias:
>>             x = x['id']
> 
> You select a collection of some sort and replace it with a value
> from the collection. Is that really what you want to do? You don't
> do it for y...



> 
>>             for y in vertical_criterias:
>>                 table[(x, y['id'])] = 0
> 
> It would be just as readable IMHO to just use
> 
>          table[ x['id'],y['id'] ] = 0
> 
Here I get an error

Traceback (most recent call last):
   File 
"/Users/khinester/Sites/itools/0.16.9/Python-2.5.1/lib/python2.5/site-packages/abakuc/training.py", 
line 531, in statistics
     table[ x['id'],y['id'] ] = 0
TypeError: string indices must be integers


>>         for brain in brains:
>>             x = getattr(brain, horizontal)
>>             if isinstance(x, list):
>>                 for item in x:
>>                     x = item
> 
> And here you replace the list x with it' first item.
> You could just do
> 
> x = x[0]

Here is my issue, as I would like to count each item in the list and 
place it in the table, but don't see how to do it.

> 
>>             else:
>>                 x
> 
> And this does nothing useful whatsoever. It just
> siilently evaluates x.

Removed.
> 
>>             y = getattr(brain, vertical)
>>             if isinstance(y, list):
>>                 for item in y:
>>                     y = item
>>             else:
>>                 y
> 
> Same comments apply
> 
>>             if x and y and (x, y) in table:
>>                 table[(x, y)] += 1
>>                 table[(x, '')] += 1
>>                 table[('', y)] += 1
>>                 table[('', '')] += 1
>>
>>
>> table is a dictionary, which returns, for example:
>>
>> {   ('', ''): 1,
>>     ('', 'fr'): 0,
>>     ('airport-car-parking', ''): 2,
>>     ('airport-car-parking', 'fr'): 0,
>>     ('air-taxi-operators', ''): 1,
>>     ('air-taxi-operators', 'fr'): 0,
>>      ...
>>     ('worldwide-attractions-and-ticket-agents', ''): 0,
>>     ('worldwide-attractions-and-ticket-agents', 'fr'): 0,
> 
>> From this I suggest you rename your variable from x and y
> to something meaningful like facility and country. That
> might make your code more meaningful to read.
> 
>> The output is something like:
>> country |airport-car|air-taxi-operators|airlines-schedule| total
>> ---------------------------------------------------------------
>> france  |0     |0        |0 |0
>> uk |2     |0        |0 |2
>> us |0          |0        |0 |0
>> ---------------------------------------------------------------
>> total |2     |0                 |0 |2
>> ---------------------------------------------------------------
>>
>> What I can't seem to figure out is how to do a cumulative sum for each 
>> record, for example, my files contain:
> 
> Frankly I'd use a database. Just load the data into it using Python.
> Then execute SQL querioes to get the counts etc.

Not really an option to use SQL just for this.

> 
>>             if isinstance(x, list):
>>                 for item in x:
>>                     x = item
>>     pp.pprint(x)
>>             else:
>>
>> Which is correct, but the table only counts the first item of the tuple.
> 
> Isn't that because you replace x with the first element of x?

As mentioned above, I know this, but I would like to find out how to do 
it so that it counts each item in the list.

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

From norman at khine.net  Tue Jul  1 13:03:55 2008
From: norman at khine.net (Norman Khine)
Date: Tue, 01 Jul 2008 13:03:55 +0200
Subject: [Tutor] list objects are unhashable
In-Reply-To: <1c2a2c590807010310k4bec9624p3ccefb84a9982524@mail.gmail.com>
References: <48692C28.2050804@khine.net> <4869A9EA.10600@groktech.org>	
	<4869D844.2010309@khine.net>
	<1c2a2c590807010310k4bec9624p3ccefb84a9982524@mail.gmail.com>
Message-ID: <486A0F1B.8090806@khine.net>



Kent Johnson wrote:
> On Tue, Jul 1, 2008 at 3:09 AM, Norman Khine <norman at khine.net> wrote:
> 
>>            x = getattr(brain, horizontal)
>>            if isinstance(x, list):
>>                for item in x:
>>                    x = item
> 
> This just assigns x to the last element of the list, it doesn't
> process the whole list. One possibility would be to ensure that x and
> y are always lists, then use nested loops to iterate over all
> combinations:
> x = getattr(brain, horizontal)
> if not isinstance(x, list):
>   x = [x]
> y = getattr(brain, vertical)
> if not isinstance(y, list):
>   y = [y]
> for first in x:
>   for second in y:
>     if first and second and (first, second) in table:

I don't really see this clearly as I may have n'th values for 'x' and 
n'th values for 'y' so I will need to loop over all these, but without 
knowing the n'th value where to stop my loop?

Or have I missed the point ;)

> 
> etc.
> 
> Kent
> 


From kent37 at tds.net  Tue Jul  1 13:04:37 2008
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 1 Jul 2008 07:04:37 -0400
Subject: [Tutor] list objects are unhashable
In-Reply-To: <g4d0qa$m7u$1@ger.gmane.org>
References: <48692C28.2050804@khine.net> <4869A9EA.10600@groktech.org>
	<4869D844.2010309@khine.net>
	<1c2a2c590807010310k4bec9624p3ccefb84a9982524@mail.gmail.com>
	<g4d0qa$m7u$1@ger.gmane.org>
Message-ID: <1c2a2c590807010404p359cdd18s22f60bcb6b074740@mail.gmail.com>

On Tue, Jul 1, 2008 at 6:27 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> "Kent Johnson" <kent37 at tds.net> wrote
>>>
>>>           if isinstance(x, list):
>>>               for item in x:
>>>                   x = item
>>
>> This just assigns x to the last element of the list
>
> Oops, yes, I said the first but in fact reassigning x does not stop the
> loop, it seems the loop works on a local copy of the original reference.

Under the hood, 'for item in x' creates an iterator which has a
reference to the original list.

Kent

From f8lcoder at hotmail.com  Tue Jul  1 13:51:24 2008
From: f8lcoder at hotmail.com (S Potter)
Date: Tue, 1 Jul 2008 07:51:24 -0400
Subject: [Tutor] Novice Python Question
Message-ID: <BLU127-W47B577CF435E0F14AC4837829E0@phx.gbl>

To whom it may concern;
 
I am a just experimenting with Python and learning as I go. The majority of my stumbling blocks have been syntax. So with that I must ask a couple of technical albeit probably very simple questions. Hopefully, you may provide me some insight and help me on my way.
 
Question 1.) 
    I have dictionary or list containing multiple  instances 'duplicate entries' of the same information. Lets say it's a list of addresses and list item i[0] contains city values equal to 'Albany' . 
    
    I am using a second list of one element to provide my filter criteria. This list contains only cities with no duplicate entries.
 
    How do I filter my first list based upon the selected position or a variable equal to the value of the selected position from my second list? 
 
Question 2.) If I assign a value to a variable x = "MyVlaue"
                    How do I put the value of  x into a list? 
                            I would think it would be something like:
                                    list[(str(x))]
                            But I'm not getting the results I expect. 
                            This would probably be considered macro-substitution in other languages but I cannot find reference to this in python.
 
Your help is greatly appreciated.
 
Thank you in advanced,
 
S.
_________________________________________________________________
Making the world a better place one message at a time.
http://www.imtalkathon.com/?source=EML_WLH_Talkathon_BetterPlace
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080701/17662590/attachment.htm>

From alan.gauld at btinternet.com  Tue Jul  1 14:16:16 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 1 Jul 2008 13:16:16 +0100
Subject: [Tutor] list objects are unhashable
References: <48692C28.2050804@khine.net><4869A9EA.10600@groktech.org>	<4869D844.2010309@khine.net><g4cqck$ufk$1@ger.gmane.org>
	<486A0D3C.3050000@khine.net>
Message-ID: <g4d76k$ek7$1@ger.gmane.org>

"Norman Khine" <norman at khine.net> wrote

>> Frankly I'd use a database. Just load the data into it using 
>> Python.
>> Then execute SQL querioes to get the counts etc.
>
> Not really an option to use SQL just for this.

I'm curious why?
It seems to suggest that using SQL is somehow a big deal?

But with the SqlLite database access that ships with Python 2.5+
the database is just a normal file and you access it using
SQL commands. There is no database server or DBA involvement
etc. if that is your concern.

SqlLite is specifically designed for these kinds of small scale
ad-hoc query of complex data type of scenarios.

Or is there something else that rules it out?

Alan G. 



From alan.gauld at btinternet.com  Tue Jul  1 14:19:44 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 1 Jul 2008 13:19:44 +0100
Subject: [Tutor] Deleting specified files using a python
	program...helpwith code?]
References: <48694809.7000901@abbottdavid.com>
	<g4bq37$dv2$1@ger.gmane.org><486982EB.20003@abbottdavid.com>
	<g4cr03$on$1@ger.gmane.org>
	<333efb450807010221r2f1f786fpd64c8106ac081d9e@mail.gmail.com>
Message-ID: <g4d7d4$fd3$1@ger.gmane.org>


"W W" <srilyk at gmail.com> wrote

> Testing your example, Alan, you have it defaulted to "delete",
> correct? That's where the "not confirmation" part comes in? I just
> tried it in a simple function:

Correct. Purely an arbitrary choice.

> def confirm(iput):  #I wasn't sure if input was "reserved"

input is a builtin function so you can use the name OK
but it will hide the function so is not a good idea.

> That's something I didn't expect at first, mainly because I'm not 
> used
> to setting up that sort of input (but it makes sense to do it that
> way).

Its just another form of user friendliness.
Actually I wouldn't use a default approach on anything thats 
potentially
destructive - like deleting files - but for other applications its a 
useful
device.

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



From omer at no-log.org  Tue Jul  1 14:35:54 2008
From: omer at no-log.org (=?utf-8?q?C=C3=A9dric_Lucantis?=)
Date: Tue, 1 Jul 2008 14:35:54 +0200
Subject: [Tutor] Novice Python Question
In-Reply-To: <BLU127-W47B577CF435E0F14AC4837829E0@phx.gbl>
References: <BLU127-W47B577CF435E0F14AC4837829E0@phx.gbl>
Message-ID: <200807011435.54062.omer@no-log.org>

Le Tuesday 01 July 2008 13:51:24 S Potter, vous avez ?crit?:
> To whom it may concern;
>
> I am a just experimenting with Python and learning as I go. The majority of
> my stumbling blocks have been syntax. So with that I must ask a couple of
> technical albeit probably very simple questions. Hopefully, you may provide
> me some insight and help me on my way.
>
> Question 1.)
>     I have dictionary or list containing multiple  instances 'duplicate
> entries' of the same information. Lets say it's a list of addresses and
> list item i[0] contains city values equal to 'Albany' .
>
>     I am using a second list of one element to provide my filter criteria.
> This list contains only cities with no duplicate entries.
>
>     How do I filter my first list based upon the selected position or a
> variable equal to the value of the selected position from my second list?
>

Is it a list or a dictionary ? These are very different objects with different 
purposes. And what you want is not clear, maybe a piece of code would help us 
to understand, event if it doesn't work (also post the error message in that 
case).

Filtering a list is generally done with the filter() builtin function or with 
a list comprehension such as:

# checks if 'item' meets your criteria, returning True if yes
# and False otherwise
#
def check_item(item) :
	...

# with filter
filter_result = filter(check_item, input_list)

# with a list comprehension
filter_result = [item for item in input_list if check_item(item)]

Those two forms will give the same result but the second is preferred 
nowadays.

> Question 2.) If I assign a value to a variable x = "MyVlaue"
>                     How do I put the value of  x into a list?
>                             I would think it would be something like:
>                                     list[(str(x))]
>                             But I'm not getting the results I expect.

First thing: avoid using 'list' as a variable name, as it is the name of the 
builtin list class and can be confusing for the reader. But here you are 
using a list as a dictionary, which is even more confusing :) You can add an 
item to a list with mylist.append(x). See the links below for more.

>                             This would probably be considered
> macro-substitution in other languages but I cannot find reference to this
> in python.

There are no macros in python, only functions.

It sounds like you are confusing lists and dictionaries. You should read the 
following sections for more infos (you'll find even more in the library 
reference) :

http://docs.python.org/tut/node5.html#SECTION005140000000000000000
http://docs.python.org/tut/node7.html#SECTION007100000000000000000
http://docs.python.org/tut/node7.html#SECTION007500000000000000000

-- 
C?dric Lucantis

From rdm at rcblue.com  Tue Jul  1 14:38:36 2008
From: rdm at rcblue.com (Dick Moores)
Date: Tue, 01 Jul 2008 05:38:36 -0700
Subject: [Tutor] random.choice()
Message-ID: <20080701123848.0893E1E4002@bag.python.org>

I'm writing a demonstration version of a program which does things 
with integers, and with floats, which are randomly generated. I want 
to also randomly pick whether the integer side, or the float side is 
demonstrated next. I have 2 functions, use_for_integer_demo() 
and  use_for_float_demo(), and one or the other of these will start 
the demo. So I want to randomly choose between them. I thought that I 
might be able to use choice() to do that. So,

      (bunch of functions here)
if __name__ == '__main__':
     choice([use_for_float_demo(), use_for_integer_demo()])	

I find that what's gets run each time is BOTH of these functions, 
first use_for_float_demo(), and then use_for_integer_demo()!  What's going on?

I've used choice in simpler ways before, such as   coin = 
choice(["Heads", "Tails"]) , which is very handy. And even for a 
radically biased coin,

coin = choice(["Heads", "Tails", "Heads", "Tails", "Heads", "Tails", "Tails"])

Thanks,

Dick Moores


From alan.gauld at btinternet.com  Tue Jul  1 14:38:22 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 1 Jul 2008 13:38:22 +0100
Subject: [Tutor] Novice Python Question
References: <BLU127-W47B577CF435E0F14AC4837829E0@phx.gbl>
Message-ID: <g4d8g3$jl8$1@ger.gmane.org>


"S Potter" <f8lcoder at hotmail.com> wrote

> How do I filter my first list based upon the selected position
> or a variable equal to the value of the selected position from
> my second list?

The most common way of filtering a list is to use a list comprehension

filteredList = [item <for expression> if <filter expression> ]

where <filter expression> can be any expression or function that you 
can write.
and <for expression> is like a normal for loop construct.
So if you write a function that compares an item from the original 
list
with the items in your control list you can get what you want

eg
>>> L = [5,6,7,8,9]
>>> [n for i,n in enumerate(L) if i % 2]   # equivalent to getting all 
>>> odd indexed items
[6, 8]

There is also the older filter() function which some people prefer.
You will find examples of both in the Functional Programming topic
of my tutor.


> Question 2.) If I assign a value to a variable x = "MyVlaue"
>                     How do I put the value of  x into a list?

You can use append or insert or use slicing to replace a series of 
values
with a new value.

>>> x = 42
>>> myList = [x]    # new list containing x
>>> myList.append(66)    # add 66 to the list -> [42,66]
>>> myList.insert(1,7)      # insert 7 at index 1 -> [42,7,66]

> I would think it would be something like:
>                                     list[(str(x))]

That would convert x to a string and then try to use it to
index a list called list (which is a bad name because it would
hide the function for converting things to a list!)

Which tutorial are you using to learn? Most tutorials will cover this
sort of stuff. Look in the Raw Materials topic of my tutor for more
info on using lists.

> This would probably be considered macro-substitution in other
> languages but I cannot find reference to this in python.

There is no real concept of macro substitution in Python and frankly
I don't see what you describe as being much like what I understand
macro substitution to be in languages like C, Assembler or Lisp...

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



From kent37 at tds.net  Tue Jul  1 14:40:11 2008
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 1 Jul 2008 08:40:11 -0400
Subject: [Tutor] Novice Python Question
In-Reply-To: <BLU127-W47B577CF435E0F14AC4837829E0@phx.gbl>
References: <BLU127-W47B577CF435E0F14AC4837829E0@phx.gbl>
Message-ID: <1c2a2c590807010540h33c09af9r9a458d779b3a61f7@mail.gmail.com>

On Tue, Jul 1, 2008 at 7:51 AM, S Potter <f8lcoder at hotmail.com> wrote:

> Question 1.)
>     I have dictionary or list containing multiple  instances 'duplicate
> entries' of the same information. Lets say it's a list of addresses and list
> item i[0] contains city values equal to 'Albany' .
>
>     I am using a second list of one element to provide my filter criteria.
> This list contains only cities with no duplicate entries.
>
>     How do I filter my first list based upon the selected position or a
> variable equal to the value of the selected position from my second list?

It would help to see more specific examples of the data you have and
the desired result, but in general a list comprehension is the easiest
way to filter a list.
http://docs.python.org/tut/node7.html#SECTION007140000000000000000

> Question 2.) If I assign a value to a variable x = "MyVlaue"
>                     How do I put the value of  x into a list?

>                             I would think it would be something like:
>                                     list[(str(x))]
>                             But I'm not getting the results I expect.
>                             This would probably be considered
> macro-substitution in other languages but I cannot find reference to this in
> python.

The value of x is the string "MyVlaue", is that what you want? If so
what you are doingis close, you can use simply [x] to create a list
containing the value of x. Or do you want the value of the variable
named MyVlaue? In that case you probably should use a dictionary to
hold the value rather than a named variable.

Kent

From kent37 at tds.net  Tue Jul  1 14:42:58 2008
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 1 Jul 2008 08:42:58 -0400
Subject: [Tutor] list objects are unhashable
In-Reply-To: <486A0F1B.8090806@khine.net>
References: <48692C28.2050804@khine.net> <4869A9EA.10600@groktech.org>
	<4869D844.2010309@khine.net>
	<1c2a2c590807010310k4bec9624p3ccefb84a9982524@mail.gmail.com>
	<486A0F1B.8090806@khine.net>
Message-ID: <1c2a2c590807010542n7494d163xe638f63b9b5dd083@mail.gmail.com>

On Tue, Jul 1, 2008 at 7:03 AM, Norman Khine <norman at khine.net> wrote:
> Kent Johnson wrote:
>> for first in x:
>>  for second in y:
>>    if first and second and (first, second) in table:
>
> I don't really see this clearly as I may have n'th values for 'x' and n'th
> values for 'y' so I will need to loop over all these, but without knowing
> the n'th value where to stop my loop?
>
> Or have I missed the point ;)

I think so, as that is exactly what the for loop will do. For example:
In [1]: x = [1,2, 5]

In [2]: for item in x:
   ...:     print item
   ...:
1
2
5

Kent

From mail at timgolden.me.uk  Tue Jul  1 14:43:22 2008
From: mail at timgolden.me.uk (Tim Golden)
Date: Tue, 01 Jul 2008 13:43:22 +0100
Subject: [Tutor] random.choice()
In-Reply-To: <20080701123848.0893E1E4002@bag.python.org>
References: <20080701123848.0893E1E4002@bag.python.org>
Message-ID: <486A266A.8060608@timgolden.me.uk>

Dick Moores wrote:
> So I want to randomly choose between them. I thought that I might be 
> able to use choice() to do that. So,
> 
>      (bunch of functions here)
> if __name__ == '__main__':
>     choice([use_for_float_demo(), use_for_integer_demo()])   
> 
> I find that what's gets run each time is BOTH of these functions, first 
> use_for_float_demo(), and then use_for_integer_demo()!  What's going on?

What you *want* to do is choose one of two functions, and call
whichever is chosen:

fn = choice ([a, b])
result = fn ()

What you're *actually* doing is calling two functions, and returning
one result or the other:

result = choice ([a (), b ()])
TJG

From omer at no-log.org  Tue Jul  1 14:52:11 2008
From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=)
Date: Tue, 1 Jul 2008 14:52:11 +0200
Subject: [Tutor] random.choice()
In-Reply-To: <20080701123848.0893E1E4002@bag.python.org>
References: <20080701123848.0893E1E4002@bag.python.org>
Message-ID: <200807011452.11889.omer@no-log.org>

Le Tuesday 01 July 2008 14:38:36 Dick Moores, vous avez ?crit?:
> I'm writing a demonstration version of a program which does things
> with integers, and with floats, which are randomly generated. I want
> to also randomly pick whether the integer side, or the float side is
> demonstrated next. I have 2 functions, use_for_integer_demo()
> and  use_for_float_demo(), and one or the other of these will start
> the demo. So I want to randomly choose between them. I thought that I
> might be able to use choice() to do that. So,
>
>       (bunch of functions here)
> if __name__ == '__main__':
>      choice([use_for_float_demo(), use_for_integer_demo()])
>

Writing this [use_for_float_demo(), use_for_integer_demo()] calls the two 
functions and build a list with their returned values. So the choice is 
between 'the result of use_for_float_demo()' and 'the result of 
use_for_integer_demo()'. This explains why the two functions are called. You 
should rather use function objects like this:

# choose a function (note there are no () after the names)
func = choice([use_for_float_demo, use_for_integer_demo])

# then call it
func()

-- 
C?dric Lucantis

From rdm at rcblue.com  Tue Jul  1 15:04:11 2008
From: rdm at rcblue.com (Dick Moores)
Date: Tue, 01 Jul 2008 06:04:11 -0700
Subject: [Tutor] random.choice()
In-Reply-To: <486A266A.8060608@timgolden.me.uk>
References: <20080701123848.0893E1E4002@bag.python.org>
	<486A266A.8060608@timgolden.me.uk>
Message-ID: <20080701130423.9E22D1E4002@bag.python.org>

At 05:43 AM 7/1/2008, Tim Golden wrote:
>Dick Moores wrote:
>>So I want to randomly choose between them. I thought that I might 
>>be able to use choice() to do that. So,
>>      (bunch of functions here)
>>if __name__ == '__main__':
>>     choice([use_for_float_demo(), use_for_integer_demo()])
>>I find that what's gets run each time is BOTH of these functions, 
>>first use_for_float_demo(), and then use_for_integer_demo()!  What's going on?
>
>What you *want* to do is choose one of two functions, and call
>whichever is chosen:
>
>fn = choice ([a, b])
>result = fn ()
>
>What you're *actually* doing is calling two functions, and returning
>one result or the other:
>
>result = choice ([a (), b ()])

I'm not sure I understand the distinction. It seems you're saying in 
either case I get one result or the other. In fact, each time I run 
the program, I get BOTH results.

Dick



From rdm at rcblue.com  Tue Jul  1 15:08:57 2008
From: rdm at rcblue.com (Dick Moores)
Date: Tue, 01 Jul 2008 06:08:57 -0700
Subject: [Tutor] random.choice()
In-Reply-To: <200807011452.11889.omer@no-log.org>
References: <20080701123848.0893E1E4002@bag.python.org>
	<200807011452.11889.omer@no-log.org>
Message-ID: <20080701130909.6F8CF1E4002@bag.python.org>

At 05:52 AM 7/1/2008, C?dric Lucantis wrote:
>Le Tuesday 01 July 2008 14:38:36 Dick Moores, vous avez ?crit :
> > I'm writing a demonstration version of a program which does things
> > with integers, and with floats, which are randomly generated. I want
> > to also randomly pick whether the integer side, or the float side is
> > demonstrated next. I have 2 functions, use_for_integer_demo()
> > and  use_for_float_demo(), and one or the other of these will start
> > the demo. So I want to randomly choose between them. I thought that I
> > might be able to use choice() to do that. So,
> >
> >       (bunch of functions here)
> > if __name__ == '__main__':
> >      choice([use_for_float_demo(), use_for_integer_demo()])
> >
>
>Writing this [use_for_float_demo(), use_for_integer_demo()] calls the two
>functions and build a list with their returned values. So the choice is
>between 'the result of use_for_float_demo()' and 'the result of
>use_for_integer_demo()'.

But why do I see BOTH results each time I run the 
program? There's no random choice made. (I already asked Tim Golden this.)

>This explains why the two functions are called. You
>should rather use function objects like this:
>
># choose a function (note there are no () after the names)
>func = choice([use_for_float_demo, use_for_integer_demo])
>
># then call it
>func()

I didn't realize that I should leave off the (). 
Thanks. (And to Tim Golden also.)

DIck 


From norman at khine.net  Tue Jul  1 15:12:27 2008
From: norman at khine.net (Norman Khine)
Date: Tue, 01 Jul 2008 15:12:27 +0200
Subject: [Tutor] list objects are unhashable
In-Reply-To: <g4d76k$ek7$1@ger.gmane.org>
References: <48692C28.2050804@khine.net><4869A9EA.10600@groktech.org>	<4869D844.2010309@khine.net><g4cqck$ufk$1@ger.gmane.org>	<486A0D3C.3050000@khine.net>
	<g4d76k$ek7$1@ger.gmane.org>
Message-ID: <486A2D3B.2010801@khine.net>



Alan Gauld wrote:
> "Norman Khine" <norman at khine.net> wrote
> 
>>> Frankly I'd use a database. Just load the data into it using Python.
>>> Then execute SQL querioes to get the counts etc.
>>
>> Not really an option to use SQL just for this.
> 
> I'm curious why?
> It seems to suggest that using SQL is somehow a big deal?

I am not sure how to implement this for now, as I have not used SqlLite.

> 
> But with the SqlLite database access that ships with Python 2.5+
> the database is just a normal file and you access it using
> SQL commands. There is no database server or DBA involvement
> etc. if that is your concern.
> 
> SqlLite is specifically designed for these kinds of small scale
> ad-hoc query of complex data type of scenarios.

I will look into this, but for now, can you advise on how to loop 
through the list and add each item found to the counter as this is the 
logic I don't understand.

> 
> Or is there something else that rules it out?
> 
> Alan G.
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


From mail at timgolden.me.uk  Tue Jul  1 15:13:40 2008
From: mail at timgolden.me.uk (Tim Golden)
Date: Tue, 01 Jul 2008 14:13:40 +0100
Subject: [Tutor] random.choice()
In-Reply-To: <20080701130423.9E22D1E4002@bag.python.org>
References: <20080701123848.0893E1E4002@bag.python.org>	<486A266A.8060608@timgolden.me.uk>
	<20080701130423.9E22D1E4002@bag.python.org>
Message-ID: <486A2D84.9000304@timgolden.me.uk>

Dick Moores wrote:
> At 05:43 AM 7/1/2008, Tim Golden wrote:
>> Dick Moores wrote:
>>> So I want to randomly choose between them. I thought that I might be 
>>> able to use choice() to do that. So,
>>>      (bunch of functions here)
>>> if __name__ == '__main__':
>>>     choice([use_for_float_demo(), use_for_integer_demo()])
>>> I find that what's gets run each time is BOTH of these functions, 
>>> first use_for_float_demo(), and then use_for_integer_demo()!  What's 
>>> going on?
>>
>> What you *want* to do is choose one of two functions, and call
>> whichever is chosen:
>>
>> fn = choice ([a, b])
>> result = fn ()
>>
>> What you're *actually* doing is calling two functions, and returning
>> one result or the other:
>>
>> result = choice ([a (), b ()])
> 
> I'm not sure I understand the distinction. It seems you're saying in 
> either case I get one result or the other. In fact, each time I run the 
> program, I get BOTH results.


Let's talk through what the Python interpreter's doing in each case:

a) fn = choice ([a, b]); print fn ()

Here, the interpreter is saying: ok, let's build a list which contains
two functions. Now, let's pick one of those functions. Whichever one
we picked, let's call it and print out the result.

b) print choice ([a (), b ()]

In this case, the interpreter is saying: build a list containing *the result*
of calling each of these functions, so both functions are called when the
list is built, and the list contains [<result of calling a>, <result of calling b>].
Now pick one of those results and display it.

Is that any clearer? If not, I'm obviously not too good at explaining this
kind of thing; maybe someone else can have a go.

TJG

From omer at no-log.org  Tue Jul  1 15:23:24 2008
From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=)
Date: Tue, 1 Jul 2008 15:23:24 +0200
Subject: [Tutor] random.choice()
In-Reply-To: <20080701130423.9E22D1E4002@bag.python.org>
References: <20080701123848.0893E1E4002@bag.python.org>
	<486A266A.8060608@timgolden.me.uk>
	<20080701130423.9E22D1E4002@bag.python.org>
Message-ID: <200807011523.24984.omer@no-log.org>

Le Tuesday 01 July 2008 15:04:11 Dick Moores, vous avez ?crit?:
> At 05:43 AM 7/1/2008, Tim Golden wrote:
> >Dick Moores wrote:
> >>So I want to randomly choose between them. I thought that I might
> >>be able to use choice() to do that. So,
> >>      (bunch of functions here)
> >>if __name__ == '__main__':
> >>     choice([use_for_float_demo(), use_for_integer_demo()])
> >>I find that what's gets run each time is BOTH of these functions,
> >>first use_for_float_demo(), and then use_for_integer_demo()!  What's
> >> going on?
> >
> >What you *want* to do is choose one of two functions, and call
> >whichever is chosen:
> >
> >fn = choice ([a, b])
> >result = fn ()
> >
> >What you're *actually* doing is calling two functions, and returning
> >one result or the other:
> >
> >result = choice ([a (), b ()])
>
> I'm not sure I understand the distinction. It seems you're saying in
> either case I get one result or the other. In fact, each time I run
> the program, I get BOTH results.
>

You _see_ both results because _you_ call both functions. choice() has nothing 
to do with that. Here's an example:

>>> def foo1() : print 'running foo1'; return 'bar1'
>>> def foo2() : print 'running foo2'; return 'bar2'

>>> [foo1(), foo2()]
running foo1
running foo2
['bar1', 'bar2']

>>> [foo1, foo2]
[<function foo1 at 0x2b88257fc140>, <function foo2 at 0x2b88257fc230>]

Do you see the difference now ? In the first case you call the two functions 
and store their returned value in the list, while in the second you only 
store the function objects themselves without calling them. You want the 
second one.

-- 
C?dric Lucantis

From nicole4real4eva at yahoo.com  Tue Jul  1 15:19:01 2008
From: nicole4real4eva at yahoo.com (Nkem Onyemachi)
Date: Tue, 1 Jul 2008 06:19:01 -0700 (PDT)
Subject: [Tutor] Newbie question
Message-ID: <480864.9886.qm@web51006.mail.re2.yahoo.com>

Hi,
I am studying "thinking like a computer scientist using Python". chapter 4 importing turtleworld is kind of a hitch 4 me .I downloaded the swampy module and when importing, the interpreter gives am error saying this module does not exist what do i do? i saved the swampy folder in the Python folder in drive C . Thanks
_____________________________
Sent from my phone using flurry - Get free mobile email and news at: http://www.flurry.com



      

From nicole4real4eva at yahoo.com  Tue Jul  1 15:19:01 2008
From: nicole4real4eva at yahoo.com (Nkem Onyemachi)
Date: Tue, 1 Jul 2008 06:19:01 -0700 (PDT)
Subject: [Tutor] Newbie question
Message-ID: <480864.9886.qm@web51006.mail.re2.yahoo.com>

Hi,
I am studying "thinking like a computer scientist using Python". chapter 4 importing turtleworld is kind of a hitch 4 me .I downloaded the swampy module and when importing, the interpreter gives am error saying this module does not exist what do i do? i saved the swampy folder in the Python folder in drive C . Thanks
_____________________________
Sent from my phone using flurry - Get free mobile email and news at: http://www.flurry.com



      

From rdm at rcblue.com  Tue Jul  1 15:33:04 2008
From: rdm at rcblue.com (Dick Moores)
Date: Tue, 01 Jul 2008 06:33:04 -0700
Subject: [Tutor] random.choice()
In-Reply-To: <200807011523.24984.omer@no-log.org>
References: <20080701123848.0893E1E4002@bag.python.org>
	<486A266A.8060608@timgolden.me.uk>
	<20080701130423.9E22D1E4002@bag.python.org>
	<200807011523.24984.omer@no-log.org>
Message-ID: <20080701133317.4635E1E4002@bag.python.org>

At 06:23 AM 7/1/2008, C?dric Lucantis wrote:
>Le Tuesday 01 July 2008 15:04:11 Dick Moores, vous avez ?crit :
> > At 05:43 AM 7/1/2008, Tim Golden wrote:
> > >Dick Moores wrote:
> > >>So I want to randomly choose between them. I thought that I might
> > >>be able to use choice() to do that. So,
> > >>      (bunch of functions here)
> > >>if __name__ == '__main__':
> > >>     choice([use_for_float_demo(), use_for_integer_demo()])
> > >>I find that what's gets run each time is BOTH of these functions,
> > >>first use_for_float_demo(), and then use_for_integer_demo()!  What's
> > >> going on?
> > >
> > >What you *want* to do is choose one of two functions, and call
> > >whichever is chosen:
> > >
> > >fn = choice ([a, b])
> > >result = fn ()
> > >
> > >What you're *actually* doing is calling two functions, and returning
> > >one result or the other:
> > >
> > >result = choice ([a (), b ()])
> >
> > I'm not sure I understand the distinction. It seems you're saying in
> > either case I get one result or the other. In fact, each time I run
> > the program, I get BOTH results.
> >
>
>You _see_ both results because _you_ call both 
>functions. choice() has nothing
>to do with that. Here's an example:
>
> >>> def foo1() : print 'running foo1'; return 'bar1'
> >>> def foo2() : print 'running foo2'; return 'bar2'
>
> >>> [foo1(), foo2()]
>running foo1
>running foo2
>['bar1', 'bar2']
>
> >>> [foo1, foo2]
>[<function foo1 at 0x2b88257fc140>, <function foo2 at 0x2b88257fc230>]
>
>Do you see the difference now ?

Finally, I do. Thanks very much.

>In the first case you call the two functions
>and store their returned value in the list, while in the second you only
>store the function objects themselves without calling them. You want the
>second one.

Dick



From mishu_yim at yahoo.com  Tue Jul  1 17:40:07 2008
From: mishu_yim at yahoo.com (asdg asdg)
Date: Tue, 1 Jul 2008 08:40:07 -0700 (PDT)
Subject: [Tutor] Newbie question
In-Reply-To: <480864.9886.qm@web51006.mail.re2.yahoo.com>
Message-ID: <850914.2553.qm@web46111.mail.sp1.yahoo.com>

You need to add the folder containing this module to your PYTHONPATH.

To do this, go to you interpreter and type:
>>> import sys
>>> sys.path.append("C:\Python25\ExampleFolder") 
That path was just an example, insert your own path leading to the desired folder there.

Python imports it's modules from specific folders on your hard-drive.
These folders where Python looks in are contained in a list. sys.path is actually a the list containing those path names. Appending new path names to sys.path makes python look in those locations too when importing modules.

Hope this helped you understand.

-Mishu

--- On Tue, 7/1/08, Nkem Onyemachi <nicole4real4eva at yahoo.com> wrote:
From: Nkem Onyemachi <nicole4real4eva at yahoo.com>
Subject: [Tutor] Newbie question
To: tutor at python.org
Date: Tuesday, July 1, 2008, 1:19 PM

Hi,
I am studying "thinking like a computer scientist using Python".
chapter 4 importing turtleworld is kind of a hitch 4 me .I downloaded the
swampy module and when importing, the interpreter gives am error saying this
module does not exist what do i do? i saved the swampy folder in the Python
folder in drive C . Thanks
_____________________________
Sent from my phone using flurry - Get free mobile email and news at:
http://www.flurry.com



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


      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080701/945deba9/attachment.htm>

From f8lcoder at hotmail.com  Tue Jul  1 18:12:17 2008
From: f8lcoder at hotmail.com (S Potter)
Date: Tue, 1 Jul 2008 12:12:17 -0400
Subject: [Tutor] : Novice Python Question
Message-ID: <BLU127-W105DAC383DC90B4EE6149F829E0@phx.gbl>

To all;
 
Since this was my first time using this resource I just wanted to extend my thanks for the many responses/explanations.
I'm actually not using much of a tutorial but I will look over the links provided herein. I did make a mistake in my question post
I wasn't using a dictionary but a source list. Anyway, the explanations helped a lot I think I may actually get it now.
 
As for the macro-substitution comment I guess I should be careful not all languages handle this as I know of it.
 
ex: &VarName[.cExpression] in FoxPro
 
I assumed the concept to be the same, but that's what 'assume' gets me. Sorry;-)
 
S.
_________________________________________________________________
Use video conversation to talk face-to-face with Windows Live Messenger.
http://www.windowslive.com/messenger/connect_your_way.html?ocid=TXT_TAGLM_WL_Refresh_messenger_video_072008
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080701/055fe995/attachment-0001.htm>

From kent37 at tds.net  Tue Jul  1 18:26:38 2008
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 1 Jul 2008 12:26:38 -0400
Subject: [Tutor] Novice Python Question
In-Reply-To: <BLU127-W9E84E838F6BFF59B86C4B829E0@phx.gbl>
References: <BLU127-W47B577CF435E0F14AC4837829E0@phx.gbl>
	<1c2a2c590807010540h33c09af9r9a458d779b3a61f7@mail.gmail.com>
	<BLU127-W9E84E838F6BFF59B86C4B829E0@phx.gbl>
Message-ID: <1c2a2c590807010926y172a2c29se2f91de4891d686e@mail.gmail.com>

Forwarding to the list with my reply. (Please use reply all to reply
to the list)

On Tue, Jul 1, 2008 at 11:36 AM, S Potter <f8lcoder at hotmail.com> wrote:
> Kent,
>
> Thanks for the response the answer to question 2 helped. It seem python is
> much less verbose than I anticipate at times.
>
> As for my first question, my apologies I'm using a static list not a
> dictionary.
>
> ex:
>
> senders = [('albany','somestreet address','state','zipcode'),
> ('albany','somestreet address','state','zipcode'),
> ('albany','somestreet address','state','zipcode'),
> ('albany','somestreet address','state','zipcode'),
> ('buffalo','somestreet address','state','zipcode'),
> ('buffalo','somestreet address','state','zipcode'),
> ('cairo','somestreet address','state','zipcode'),]
>
> states = [('albany'),
> ('buffalo'),
> ('cairo'),]
>
> or states = sort(senders[0])
>
> Lets say I select from list states the value of states[0] = 'albany'
>
> I'd like to filter senders for states[0] ## where the selected value is =
> 'albany'
>  so here I think I'd use a variable to grab the the value
>        x = states.getselectedvalue() ## for my example x should be 'albany'

I don't know how you are selecting from the list? There is no GUI
here, just a simple list.

Anyway, to get all the values of senders which start with 'albany' you
can use a list comprehension:
x = 'albany' # doesn't have to be in a variable, just showing that it
*can* be a variable
filteredlist = [ item for item in senders if item[0] == x ]

Are you reading a tutorial? If not I recommend you pick one from this list:
http://wiki.python.org/moin/BeginnersGuide/NonProgrammers

Kent

> providing me with a filtered list from senders only containing the
> following:
>
> [('albany','somestreet address','state','zipcode'),
> ('albany','somestreet address','state','zipcode'),
> ('albany','somestreet address','state','zipcode'),
> ('albany','somestreet address','state','zipcode'),]
>
> Please excuse this is quasi-pseudo code but I think it clears things up a
> bit.
>
> Basically I need an example of the syntax for this as I'm not certain I have
> it correct.
> I'm thinking it should be something like this maybe - result(senders,x)
>
> But I'm clear on it.
>
> Thanks Again,
>
> S
>
>
>
> ________________________________
>> Date: Tue, 1 Jul 2008 08:40:11 -0400
>> From: kent37 at tds.net
>> To: f8lcoder at hotmail.com
>> Subject: Re: [Tutor] Novice Python Question
>> CC: tutor at python.org
>>
>> On Tue, Jul 1, 2008 at 7:51 AM, S Potter <f8lcoder at hotmail.com> wrote:
>>
>> > Question 1.)
>> > I have dictionary or list containing multiple instances 'duplicate
>> > entries' of the same information. Lets say it's a list of addresses and
>> > list
>> > item i[0] contains city values equal to 'Albany' .
>> >
>> > I am using a second list of one element to provide my filter criteria.
>> > This list contains only cities with no duplicate entries.
>> >
>> > How do I filter my first list based upon the selected position or a
>> > variable equal to the value of the selected position from my second
>> > list?
>>
>> It would help to see more specific examples of the data you have and
>> the desired result, but in general a list comprehension is the easiest
>> way to filter a list.
>> http://docs.python.org/tut/node7.html#SECTION007140000000000000000
>>
>> > Question 2.) If I assign a value to a variable x = "MyVlaue"
>> > How do I put the value of x into a list?
>>
>> > I would think it would be something like:
>> > list[(str(x))]
>> > But I'm not getting the results I expect.
>> > This would probably be considered
>> > macro-substitution in other languages but I cannot find reference to
>> > this in
>> > python.
>>
>> The value of x is the string "MyVlaue", is that what you want? If so
>> what you are doingis close, you can use simply [x] to create a list
>> containing the value of x. Or do you want the value of the variable
>> named MyVlaue? In that case you probably should use a dictionary to
>> hold the value rather than a named variable.
>>
>> Kent
>
>
> ________________________________
> Making the world a better place one message at a time. Check out the i'm
> Talkathon.

From alan.gauld at btinternet.com  Tue Jul  1 18:41:08 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 1 Jul 2008 17:41:08 +0100
Subject: [Tutor] Newbie question
References: <480864.9886.qm@web51006.mail.re2.yahoo.com>
	<850914.2553.qm@web46111.mail.sp1.yahoo.com>
Message-ID: <g4dmn8$fmt$1@ger.gmane.org>


"asdg asdg" <mishu_yim at yahoo.com> wrote

> You need to add the folder containing this module to your 
> PYTHONPATH.

Being picky you want to add it to your sys.path value

Python loads sys.path from the values in PYTHONPATH which is
an OS environment variable. Modifying PYTHONPATH after you
start Python will have no effect on the current session. PYTHONPATH
changes will only affect the next session you start.

> To do this, go to you interpreter and type:
>>>> import sys
>>>> sys.path.append("C:\Python25\ExampleFolder")

The snag with this is you need to do it every time you want to use
swampy. To make it apply in every session then you need to add it to
PYTHONPATH.

> Python imports it's modules from specific folders on your 
> hard-drive.
> These folders where Python looks in are contained in a list.
> sys.path is actually the list containing those path names.
> Appending new path names to sys.path makes python look
> in those locations too when importing modules.

And Python automatically appends any folders it finds in
PYTHONPATH when it starts up.

HTH,

Alan G 



From cspears2002 at yahoo.com  Wed Jul  2 06:36:57 2008
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Tue, 1 Jul 2008 21:36:57 -0700 (PDT)
Subject: [Tutor] TypeError: not enough arguments for format string
Message-ID: <592338.3700.qm@web51609.mail.re2.yahoo.com>

I'm working on problem 13-5 in Core Python Programming (2nd Edition).  I am supposed to create point class.  Here is what I have so far:

#!/usr/bin/python

class Point(object):
    def __init__(self, x=0.0,y=0.0):
        self.x = float(x)
	self.y = float(y)
	
    def __repr__(self):
        coord = (self.x,self.y)
	return coord
	
    def __str__(self):
	point_str = "(%f,%f)" % self.x, self.y
	return point_str
	
    def get_x(self):
        return self.x
	
    def get_y(self):
        return self.y
	
if __name__ == '__main__':
    print "Creating a point"
    x = raw_input("Enter a x value: ")
    y = raw_input("Enter a y value: ")
    p = Point(x,y)
    print p

I ran the script and got the following error message:

Creating a point
Enter a x value: 1
Enter a y value: 2
Traceback (most recent call last):
  File "point.py", line 27, in ?
    print p
  File "point.py", line 13, in __str__
    point_str = "(%f,%f)" % self.x, self.y
TypeError: not enough arguments for format string

Does anyone know what is wrong?  I'm sure it is something obvious, but I can't see it.


      

From eric at ericabrahamsen.net  Wed Jul  2 06:48:01 2008
From: eric at ericabrahamsen.net (Eric Abrahamsen)
Date: Wed, 2 Jul 2008 12:48:01 +0800
Subject: [Tutor] TypeError: not enough arguments for format string
In-Reply-To: <592338.3700.qm@web51609.mail.re2.yahoo.com>
References: <592338.3700.qm@web51609.mail.re2.yahoo.com>
Message-ID: <50DEF19E-2C3F-420C-B766-CA294A95DED6@ericabrahamsen.net>


On Jul 2, 2008, at 12:36 PM, Christopher Spears wrote:

> I'm working on problem 13-5 in Core Python Programming (2nd  
> Edition).  I am supposed to create point class.  Here is what I have  
> so far:
>
> #!/usr/bin/python
>
> class Point(object):
>    def __init__(self, x=0.0,y=0.0):
>        self.x = float(x)
> 	self.y = float(y)
> 	
>    def __repr__(self):
>        coord = (self.x,self.y)
> 	return coord
> 	
>    def __str__(self):
> 	point_str = "(%f,%f)" % self.x, self.y
> 	return point_str

Hi Christopher,
The problem's right above here ? string formatting takes only one  
value. If you're trying format more than one string, you have to pass  
them in as a tuple. Try this:

point_str = "(%f,%f)" % (self.x, self.y)

>
> 	
>    def get_x(self):
>        return self.x
> 	
>    def get_y(self):
>        return self.y
> 	
> if __name__ == '__main__':
>    print "Creating a point"
>    x = raw_input("Enter a x value: ")
>    y = raw_input("Enter a y value: ")
>    p = Point(x,y)
>    print p
>
> I ran the script and got the following error message:
>
> Creating a point
> Enter a x value: 1
> Enter a y value: 2
> Traceback (most recent call last):
>  File "point.py", line 27, in ?
>    print p
>  File "point.py", line 13, in __str__
>    point_str = "(%f,%f)" % self.x, self.y
> TypeError: not enough arguments for format string
>
> Does anyone know what is wrong?  I'm sure it is something obvious,  
> but I can't see it.
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


From john at fouhy.net  Wed Jul  2 06:49:19 2008
From: john at fouhy.net (John Fouhy)
Date: Wed, 2 Jul 2008 16:49:19 +1200
Subject: [Tutor] TypeError: not enough arguments for format string
In-Reply-To: <592338.3700.qm@web51609.mail.re2.yahoo.com>
References: <592338.3700.qm@web51609.mail.re2.yahoo.com>
Message-ID: <5e58f2e40807012149x12de3aa7y988e537cc68ddce1@mail.gmail.com>

On 02/07/2008, Christopher Spears <cspears2002 at yahoo.com> wrote:
>   File "point.py", line 13, in __str__
>     point_str = "(%f,%f)" % self.x, self.y
>  TypeError: not enough arguments for format string
>
>  Does anyone know what is wrong?  I'm sure it is something obvious, but I can't see it.

Hi Christopher,

Here's the short answer: You need to put brackets around "self.x, self.y"
i.e.     point_str = "(%f,%f)" % (self.x, self.y)

The long answer: Python interprets the statement "point_str =
"(%f,%f)" % self.x, self.y" as "point_str = ("(%f,%f)" % self.x),
self.y".  There are two "%f" expressions in the string, but you only
supplied one argument, self.x.  Thus python tells you that there
aren't enough arguments.  To deal with this, you need to supply the
arguments as a tuple.

-- 
John.

From wescpy at gmail.com  Wed Jul  2 09:54:50 2008
From: wescpy at gmail.com (wesley chun)
Date: Wed, 2 Jul 2008 00:54:50 -0700
Subject: [Tutor] random.choice()
In-Reply-To: <20080701133317.4635E1E4002@bag.python.org>
References: <20080701123848.0893E1E4002@bag.python.org>
	<486A266A.8060608@timgolden.me.uk>
	<20080701130423.9E22D1E4002@bag.python.org>
	<200807011523.24984.omer@no-log.org>
	<20080701133317.4635E1E4002@bag.python.org>
Message-ID: <78b3a9580807020054s442c4ac8je51e8ba78963fde5@mail.gmail.com>

ok, someone has to be the bad guy and show an example of equivalent
code that's more difficult to read:

choice([use_for_float_demo, use_for_integer_demo])()

seriously tho, the bottom line of what people have been telling you is
that for the function (or method) foo():

def foo():
     :

there is a distinction between:

foo and foo()

in the former, you have a function object.  it's just like any other
Python object, but with one heaping distinction:  it's callable --
this means that u can slap on a pair of parentheses after the object
and execute it, which is what i did after calling choice() above to
pick one of the 2 functions, then *calling it* with the trailing "()".

in the latter, you've not only picked out a function object, but have
also executed it as well.  that's why when you had choice([a(), b()]),
you see the results/output from a() and b() -- you called both, got
both return values, and asked choice() to pick one of the 2 return
values!! and since you throw away the return value, it didn't matter
which one came back because both had executed.

cheers,
-wesley

From rdm at rcblue.com  Wed Jul  2 10:12:31 2008
From: rdm at rcblue.com (Dick Moores)
Date: Wed, 02 Jul 2008 01:12:31 -0700
Subject: [Tutor] random.choice()
In-Reply-To: <78b3a9580807020054s442c4ac8je51e8ba78963fde5@mail.gmail.co
 m>
References: <20080701123848.0893E1E4002@bag.python.org>
	<486A266A.8060608@timgolden.me.uk>
	<20080701130423.9E22D1E4002@bag.python.org>
	<200807011523.24984.omer@no-log.org>
	<20080701133317.4635E1E4002@bag.python.org>
	<78b3a9580807020054s442c4ac8je51e8ba78963fde5@mail.gmail.com>
Message-ID: <20080702081244.9283A1E400A@bag.python.org>

At 12:54 AM 7/2/2008, wesley chun wrote:
>ok, someone has to be the bad guy and show an example of equivalent
>code that's more difficult to read:
>
>choice([use_for_float_demo, use_for_integer_demo])()
>
>seriously tho, the bottom line of what people have been telling you is
>that for the function (or method) foo():
>
>def foo():
>      :
>
>there is a distinction between:
>
>foo and foo()
>
>in the former, you have a function object.  it's just like any other
>Python object, but with one heaping distinction:  it's callable --
>this means that u can slap on a pair of parentheses after the object
>and execute it, which is what i did after calling choice() above to
>pick one of the 2 functions, then *calling it* with the trailing "()".
>
>in the latter, you've not only picked out a function object, but have
>also executed it as well.  that's why when you had choice([a(), b()]),
>you see the results/output from a() and b() -- you called both, got
>both return values, and asked choice() to pick one of the 2 return
>values!! and since you throw away the return value, it didn't matter
>which one came back because both had executed.

Thanks, Wes, for the further clarity.

Dick



From paul at assured-networks.co.uk  Wed Jul  2 10:27:52 2008
From: paul at assured-networks.co.uk (Paul Melvin)
Date: Wed, 2 Jul 2008 09:27:52 +0100
Subject: [Tutor] General design question
Message-ID: <004c01c8dc1d$854b8360$8fe28a20$@co.uk>

Hi,

 

I am new to python and although have done basic many, many years ago it has
all gone, replaced by rubbish!

 

My question is this:

 

If I have a set of numbers, or strings etc. which have been generated and I
then want to do something with them, for example a sum function call.  Is
the best way to put those items in a list, or similar container, before
applying the function.

 

For example, if I generate some numbers using range the only way I could
easily sum them was to append them to a list and then call the sum function,
if I tried without the list I couldn't sum them at all.

 

I have read a lot of the recommended reading and am now trying to figure out
general code design, if anyone had any pointers/links it would be
appreciated.

 

Regards

 

paul

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080702/4b959906/attachment-0001.htm>

From mail at timgolden.me.uk  Wed Jul  2 11:54:58 2008
From: mail at timgolden.me.uk (Tim Golden)
Date: Wed, 02 Jul 2008 10:54:58 +0100
Subject: [Tutor] General design question
In-Reply-To: <004c01c8dc1d$854b8360$8fe28a20$@co.uk>
References: <004c01c8dc1d$854b8360$8fe28a20$@co.uk>
Message-ID: <486B5072.2060101@timgolden.me.uk>

Paul Melvin wrote:
> If I have a set of numbers, or strings etc. which have been generated 
> and I then want to do something with them, for example a sum function 
> call.  Is the best way to put those items in a list, or similar 
> container, before applying the function.

Not only "best" but "necessary". the sum () builtin takes an
iterator -- often a list, but needn't be -- of numbers. Generally
you'll have the numbers in some container already. If you've used
range, then range already generates a list:

<code>

nums = range (5, 10) # the numbers 5, 6, 7, 8, 9 in a list
print sum (nums)

</code>

If you're getting a user to enter them (say) by raw_input, you'll
need to create your own list:

<code>

nums = []
while True:
  snum = raw_input ("Enter number (0 to finish): ")
  num = int (snum)
  if num == 0:
    break
  else:
    nums.append (num)

print nums, "->", sum (nums)

</code>

(Obviously tons of assumptions in that code, which is just
a Noddy example)

TJG

From d.conca at gmail.com  Wed Jul  2 12:31:32 2008
From: d.conca at gmail.com (Daniele)
Date: Wed, 2 Jul 2008 12:31:32 +0200
Subject: [Tutor] General design question
Message-ID: <537341c70807020331y715edfd3safdac49eedd630f9@mail.gmail.com>

>> If I have a set of numbers, or strings etc. which have been generated and I then want to do something with them, for example a sum function call.  Is the best way to put those items in a list, or similar container, before applying the function.
>
> Not only "best" but "necessary". the sum () builtin takes an
> iterator -- often a list, but needn't be -- of numbers.

I'm a total newbie, but wouldn't it be possible to use a set (from
which I think you can get an iterator)?
By the way, if you only need to sum a range(n, m) you can use the
formula [ m*(m-1) - n*(n-1) ] / 2 or the equivalent (m+n-1)*(m-n)/2.
Sorry for pointing out this last thing, of course it is not general at
all, but maybe you'll find it useful anyway.

Daniele

From kent37 at tds.net  Wed Jul  2 12:46:45 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 2 Jul 2008 06:46:45 -0400
Subject: [Tutor] random.choice()
In-Reply-To: <78b3a9580807020054s442c4ac8je51e8ba78963fde5@mail.gmail.com>
References: <20080701123848.0893E1E4002@bag.python.org>
	<486A266A.8060608@timgolden.me.uk>
	<20080701130423.9E22D1E4002@bag.python.org>
	<200807011523.24984.omer@no-log.org>
	<20080701133317.4635E1E4002@bag.python.org>
	<78b3a9580807020054s442c4ac8je51e8ba78963fde5@mail.gmail.com>
Message-ID: <1c2a2c590807020346s471764a3nbbc8ab12f9173a29@mail.gmail.com>

On Wed, Jul 2, 2008 at 3:54 AM, wesley chun <wescpy at gmail.com> wrote:

> in the former, you have a function object.  it's just like any other
> Python object, but with one heaping distinction:  it's callable --
> this means that u can slap on a pair of parentheses after the object
> and execute it, which is what i did after calling choice() above to
> pick one of the 2 functions, then *calling it* with the trailing "()".

A slight nit-pick - being callable is not such a huge distinction. Any
object whose class has a __call__() method is callable, including
functions, bound and unbound methods, and instances of user-defined
classes containing __call__(). For example:
In [6]: class Callable(object):
   ...:     def __call__(self):
   ...:         print "I'm not a function"

In [7]: c=Callable()

In [8]: c()
I'm not a function

Like so many things in Python, the mechanism underlying function call
is exposed through a special method and available to hook into.

Kent

From kent37 at tds.net  Wed Jul  2 12:50:19 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 2 Jul 2008 06:50:19 -0400
Subject: [Tutor] General design question
In-Reply-To: <486B5072.2060101@timgolden.me.uk>
References: <004c01c8dc1d$854b8360$8fe28a20$@co.uk>
	<486B5072.2060101@timgolden.me.uk>
Message-ID: <1c2a2c590807020350w28381649j1a965e6d8cf25b1e@mail.gmail.com>

On Wed, Jul 2, 2008 at 5:54 AM, Tim Golden <mail at timgolden.me.uk> wrote:
> Paul Melvin wrote:
>>
>> If I have a set of numbers, or strings etc. which have been generated and
>> I then want to do something with them, for example a sum function call.  Is
>> the best way to put those items in a list, or similar container, before
>> applying the function.

Putting them in a list is one way, sometimes you can just handle them
as they are generated.

> If you're getting a user to enter them (say) by raw_input, you'll
> need to create your own list:
>
> <code>
>
> nums = []
> while True:
>  snum = raw_input ("Enter number (0 to finish): ")
>  num = int (snum)
>  if num == 0:
>   break
>  else:
>   nums.append (num)
>
> print nums, "->", sum (nums)
>
> </code>

Or add each number to a running total within the loop:

total = 0
while True:
 snum = raw_input ("Enter number (0 to finish): ")
 num = int (snum)
 if num == 0:
  break
 else:
  total += num

print nums, "->", total

Kent

From kent37 at tds.net  Wed Jul  2 12:55:28 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 2 Jul 2008 06:55:28 -0400
Subject: [Tutor] General design question
In-Reply-To: <537341c70807020331y715edfd3safdac49eedd630f9@mail.gmail.com>
References: <537341c70807020331y715edfd3safdac49eedd630f9@mail.gmail.com>
Message-ID: <1c2a2c590807020355y52ba1008k3f75c703adfe5fd1@mail.gmail.com>

On Wed, Jul 2, 2008 at 6:31 AM, Daniele <d.conca at gmail.com> wrote:
>>> If I have a set of numbers, or strings etc. which have been generated and I then want to do something with them, for example a sum function call.  Is the best way to put those items in a list, or similar container, before applying the function.
>>
>> Not only "best" but "necessary". the sum () builtin takes an
>> iterator -- often a list, but needn't be -- of numbers.
>
> I'm a total newbie, but wouldn't it be possible to use a set (from
> which I think you can get an iterator)?

Sets and lists are not interchangeable. A set removes duplicates, is
not ordered and has a fast membership test; a list preserves
duplicates, is ordered and is relatively slow for membership testing.
Members of a set must be hashable, so you can't put lists and dicts
into a set; members of a list can be any object.

Yes, you can get an iterator from a set (and a list).

Kent

From lie.1296 at gmail.com  Wed Jul  2 17:31:22 2008
From: lie.1296 at gmail.com (Lie Ryan)
Date: Wed, 02 Jul 2008 22:31:22 +0700
Subject: [Tutor] General design question (Tim Golden)
Message-ID: <1215012682.6836.4.camel@lieryan-laptop>

?> If I have a set of numbers, or strings etc. which have been
generated 
> and I then want to do something with them, for example a sum function 
> call.  Is the best way to put those items in a list, or similar 
> container, before applying the function.

The best design tips I could give is not to optimize early. Choose the
way which is the easiest to implement first, if for example, that simple
solution doesn't solve the problem satisfyingly enough (e.g. it's not
fast enough) then you find alternatives. Whether you should use a number
and add them over and over or make a list then use sum is not a problem,
choose one which feels most natural to you and the program you're
writing.


From rdm at rcblue.com  Wed Jul  2 17:50:48 2008
From: rdm at rcblue.com (Dick Moores)
Date: Wed, 02 Jul 2008 08:50:48 -0700
Subject: [Tutor] random.choice()
In-Reply-To: <1c2a2c590807020346s471764a3nbbc8ab12f9173a29@mail.gmail.co
 m>
References: <20080701123848.0893E1E4002@bag.python.org>
	<486A266A.8060608@timgolden.me.uk>
	<20080701130423.9E22D1E4002@bag.python.org>
	<200807011523.24984.omer@no-log.org>
	<20080701133317.4635E1E4002@bag.python.org>
	<78b3a9580807020054s442c4ac8je51e8ba78963fde5@mail.gmail.com>
	<1c2a2c590807020346s471764a3nbbc8ab12f9173a29@mail.gmail.com>
Message-ID: <20080702155100.9A3C71E4014@bag.python.org>

At 03:46 AM 7/2/2008, Kent Johnson wrote:
>On Wed, Jul 2, 2008 at 3:54 AM, wesley chun <wescpy at gmail.com> wrote:
>
> > in the former, you have a function object.  it's just like any other
> > Python object, but with one heaping distinction:  it's callable --
> > this means that u can slap on a pair of parentheses after the object
> > and execute it, which is what i did after calling choice() above to
> > pick one of the 2 functions, then *calling it* with the trailing "()".
>
>A slight nit-pick - being callable is not such a huge distinction. Any
>object whose class has a __call__() method is callable, including
>functions, bound and unbound methods, and instances of user-defined
>classes containing __call__(). For example:
>In [6]: class Callable(object):
>    ...:     def __call__(self):
>    ...:         print "I'm not a function"
>
>In [7]: c=Callable()
>
>In [8]: c()
>I'm not a function
>
>Like so many things in Python, the mechanism underlying function call
>is exposed through a special method and available to hook into.

Kent,

It seems to me that Wes is saying only that all function objects are 
callable, not that all callable objects are functions. Are there 
function objects that aren't callable? Your example is a callable 
object that isn't a function, right?

Dick


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


From sean.m.mcdaniel at gmail.com  Wed Jul  2 17:40:03 2008
From: sean.m.mcdaniel at gmail.com (sean_mcdaniel)
Date: Wed, 2 Jul 2008 08:40:03 -0700 (PDT)
Subject: [Tutor]  Inheritance help
Message-ID: <18240495.post@talk.nabble.com>


Hi folks,

I am having problems with classes and subclasses. Do the different __init__
statements have to have different argument lists? I expected my code to
print out "location 1" and "location 2" indicating that both __init__
statements had been successfully called, but it seems like only the
superclass __init__ is.

Any suggestions would be appreciated.

Thanks,

Sean

<code>
"""Contains various classes for parsing input files. Used for various
fitting routines.

Created: 1 July 2008
Last updated: 1 July 2008

"""
from __future__ import with_statement

class FileParse(object):
    """Base class for all parsing classes."""

    def __init__(self,filename):
        """Initialize variables common to all parsers. Read the file to a
list."""
        self.filecontent = []
        self.dictionary = {}
        self.parsefile(filename)
        print "Location 1"

    def __getitem__(self,key): 
        return self.dictionary[key]

    def __setitem__(self,key,value):
        self.dictionary[key]=value
    
    def parsefile(self,filename):
        """Parse a file. Ignore blank lines and comments. Save the results
to a list."""
        with open(filename,'r') as f:
            for l in f:
                if not l.startswith('#') and len(l)!=1: 
                    self.filecontent.append(l)

    def populate_dictionary(self, validkeys):
        """Convert the list of lines in the file to appropriate key,value
pairs and 
        populate the dictionary."""
        for inputline in self.parselist:
            print inputline
            key = inputline.split()[0]
            print values
            if key in self.validkeys:
                valuetype = validkeys[key]
                if valuetype=="string":
                    self.dictionary[key]="".join(values)
                if valuetype=="int":
                    self.dictionary[key]=int(values[0])
                if valuetype=="float":
                    self.dictionary[key]=float(values[0])
                if valuetype=="listfloat":
                    self.dictionary[key]=map(float,values)
                if valuetype=="listint":
                    self.dictionary[key]=map(int,values)
            else:
                badkeys.append(key)
        if len(badkeys)!=0:
            print "Could not parse keys: ", " ".join(badkeys)

class SinglePeakFit(FileParse):
    """Parses an input file used for fitting a single peak."""

    def __init___(self, filename):
        super(FileParser,self).__init__(filename)
        self.validkeys = \
                {"title":"string",
                "xtitle":"string",
                "ytitle":"string",
                "ztitle":"string",
                "npars":"int",
                "peaktype":"string",
                "peakpars":"listfloat",
                "backgroundtype":"string",
                "backgroundpars":"listfloat",
                "fitrange":"listfloat"}
        self.populate_dictionary(self.validkeys)
        print "Location 2."
</code>
-- 
View this message in context: http://www.nabble.com/Inheritance-help-tp18240495p18240495.html
Sent from the Python - tutor mailing list archive at Nabble.com.


From sean.m.mcdaniel at gmail.com  Wed Jul  2 18:03:50 2008
From: sean.m.mcdaniel at gmail.com (sean_mcdaniel)
Date: Wed, 2 Jul 2008 09:03:50 -0700 (PDT)
Subject: [Tutor] Inheritance help
In-Reply-To: <18240495.post@talk.nabble.com>
References: <18240495.post@talk.nabble.com>
Message-ID: <18241051.post@talk.nabble.com>


Hi Folks,

I can redefine the class and I get a "TypeError: __init__() takes exactly 1
argument (2 given)" error.  I'm creating a SinglePeakFit object and not a
FileParse one. Still puzzled...

Thanks,

Sean

New definition: 
"""Contains various classes for parsing input files. Used for various
fitting routines.

Created: 1 July 2008
Last updated: 1 July 2008

"""
from __future__ import with_statement

class FileParse(object):
    """Base class for all parsing classes."""

    def __init__(self):
        """Initialize variables common to all parsers. Read the file to a
list."""
        self.filecontent = []
        self.dictionary = {}
        print "Location 1"

    def __getitem__(self,key): 
        return self.dictionary[key]

    def __setitem__(self,key,value):
        self.dictionary[key]=value
    
    def parsefile(self,filename):
        """Parse a file. Ignore blank lines and comments. Save the results
to a list."""
        with open(filename,'r') as f:
            for l in f:
                if not l.startswith('#') and len(l)!=1: 
                    self.filecontent.append(l)

    def populate_dictionary(self, validkeys):
        """Convert the list of lines in the file to appropriate key,value
pairs and 
        populate the dictionary."""
        for inputline in self.parselist:
            print inputline
            key = inputline.split()[0]
            print values
            if key in self.validkeys:
                valuetype = validkeys[key]
                if valuetype=="string":
                    self.dictionary[key]="".join(values)
                if valuetype=="int":
                    self.dictionary[key]=int(values[0])
                if valuetype=="float":
                    self.dictionary[key]=float(values[0])
                if valuetype=="listfloat":
                    self.dictionary[key]=map(float,values)
                if valuetype=="listint":
                    self.dictionary[key]=map(int,values)
            else:
                badkeys.append(key)
        if len(badkeys)!=0:
            print "Could not parse keys: ", " ".join(badkeys)

class SinglePeakFit(FileParse):
    """Parses an input file used for fitting a single peak."""

    def __init___(self, filename):
        print "I am here!"
        super(FileParse,self).__init__()
        self.validkeys = \
                {"title":"string",
                "xtitle":"string",
                "ytitle":"string",
                "ztitle":"string",
                "npars":"int",
                "peaktype":"string",
                "peakpars":"listfloat",
                "backgroundtype":"string",
                "backgroundpars":"listfloat",
                "fitrange":"listfloat"}
        self.parsefile(filename)
        self.populate_dictionary(self.validkeys)
        print "Location 2."


-- 
View this message in context: http://www.nabble.com/Inheritance-help-tp18240495p18241051.html
Sent from the Python - tutor mailing list archive at Nabble.com.


From kent37 at tds.net  Wed Jul  2 18:14:36 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 2 Jul 2008 12:14:36 -0400
Subject: [Tutor] random.choice()
In-Reply-To: <20080702155100.9A3C71E4014@bag.python.org>
References: <20080701123848.0893E1E4002@bag.python.org>
	<486A266A.8060608@timgolden.me.uk>
	<20080701130423.9E22D1E4002@bag.python.org>
	<200807011523.24984.omer@no-log.org>
	<20080701133317.4635E1E4002@bag.python.org>
	<78b3a9580807020054s442c4ac8je51e8ba78963fde5@mail.gmail.com>
	<1c2a2c590807020346s471764a3nbbc8ab12f9173a29@mail.gmail.com>
	<20080702155100.9A3C71E4014@bag.python.org>
Message-ID: <1c2a2c590807020914j233a60ch7898c79877204650@mail.gmail.com>

On Wed, Jul 2, 2008 at 11:50 AM, Dick Moores <rdm at rcblue.com> wrote:

> It seems to me that Wes is saying only that all function objects are
> callable, not that all callable objects are functions.

Wesley said that function objects have a "heaping distinction" of
being callable. Only he can say for sure what that means; I took it to
mean that being callable is a very special property, perhaps one that
only function objects have. I just wanted to point out that there is
nothing really very special about that property, any more than being
iterable or having a length or a string representation or any of the
other properties that are implemented with special methods.

> Are there function
> objects that aren't callable?

Not that I can think of off-hand though maybe there is some pathological case...

> Your example is a callable object that isn't a
> function, right?

Yes, my point is that it is very easy to create such an object.

Kent

From lie.1296 at gmail.com  Wed Jul  2 18:55:34 2008
From: lie.1296 at gmail.com (Lie Ryan)
Date: Wed, 02 Jul 2008 23:55:34 +0700
Subject: [Tutor] Inheritance help
In-Reply-To: <mailman.16335.1215014682.1043.tutor@python.org>
References: <mailman.16335.1215014682.1043.tutor@python.org>
Message-ID: <1215017735.6836.20.camel@lieryan-laptop>

> Hi Folks,
> 
> I can redefine the class and I get a "TypeError: __init__() takes
> exactly 1
> argument (2 given)" error.  I'm creating a SinglePeakFit object and
> not a
> FileParse one. Still puzzled...

In this:

?class SinglePeakFit(FileParse):
    ...
    def __init___(self, filename):
        print "I am here!"
        super(FileParse,self).__init__()
    ...
...

You called the __init__ of FileParse's superclass(es), i.e.
object.__init__

What you wanted is this:

?class SinglePeakFit(FileParse):
    ...
    def __init___(self, filename):
        print "I am here!"
        super(SinglePeakFit,self).__init__()
    ...
...

which calls the superclass(es) of SinglePeakFit, i.e. FileParse.__init__

Anyway, you don't actually need to use super() unless your class use
multiple inheritance. And even the en it is only really required if
there is 'diamond'-shaped inheritance, like: A(object), B(A), C(A), D(A,
B). But it is good practice to use super for any multiple inheritance,
even though it's not diamond shaped (actually all cases of multiple
inheritance is diamond shaped since all (new-style) classes inherits
from object).


From paul at assured-networks.co.uk  Wed Jul  2 19:02:28 2008
From: paul at assured-networks.co.uk (Paul Melvin)
Date: Wed, 2 Jul 2008 18:02:28 +0100
Subject: [Tutor] General design question
In-Reply-To: <1215012682.6836.4.camel@lieryan-laptop>
References: <1215012682.6836.4.camel@lieryan-laptop>
Message-ID: <00c701c8dc65$69043470$3b0c9d50$@co.uk>

> -----Original Message-----
> From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On
> Behalf Of Lie Ryan
> Sent: 02 July 2008 16:31
> To: tutor at python.org
> Subject: Re: [Tutor] General design question (Tim Golden)
> 
> > If I have a set of numbers, or strings etc. which have been
> generated
> > and I then want to do something with them, for example a sum function
> > call.  Is the best way to put those items in a list, or similar
> > container, before applying the function.
> 
> The best design tips I could give is not to optimize early. Choose the
> way which is the easiest to implement first, if for example, that
> simple
> solution doesn't solve the problem satisfyingly enough (e.g. it's not
> fast enough) then you find alternatives. Whether you should use a
> number
> and add them over and over or make a list then use sum is not a
> problem,
> choose one which feels most natural to you and the program you're
> writing.

Thanks to everyone for their suggestions, it is somewhat daunting to learn to 'program'.

I have a relatively good understanding of all the key components now, its just putting them together to make something meaningful :)

If anyone has any tips/link/experiences to help me on my way I would appreciate it

Cheers

paul
 

__________ Information from ESET Smart Security, version of virus signature database 3236 (20080702) __________

The message was checked by ESET Smart Security.

http://www.eset.com
 


From broek at cc.umanitoba.ca  Wed Jul  2 19:15:58 2008
From: broek at cc.umanitoba.ca (broek at cc.umanitoba.ca)
Date: Wed, 02 Jul 2008 12:15:58 -0500
Subject: [Tutor] TypeError: not enough arguments for format string
In-Reply-To: <5e58f2e40807012149x12de3aa7y988e537cc68ddce1@mail.gmail.com>
References: <592338.3700.qm@web51609.mail.re2.yahoo.com>
	<5e58f2e40807012149x12de3aa7y988e537cc68ddce1@mail.gmail.com>
Message-ID: <20080702121558.mafuunzlkwgww88w@webware.cc.umanitoba.ca>


----- Message from john at fouhy.net ---------
     Date: Wed, 2 Jul 2008 16:49:19 +1200
     From: John Fouhy <john at fouhy.net>


> On 02/07/2008, Christopher Spears <cspears2002 at yahoo.com> wrote:
>>   File "point.py", line 13, in __str__
>>     point_str = "(%f,%f)" % self.x, self.y
>>  TypeError: not enough arguments for format string
>>
>>  Does anyone know what is wrong?  I'm sure it is something obvious,  
>>  but I can't see it.
>
> Hi Christopher,
>
> Here's the short answer: You need to put brackets around "self.x, self.y"
> i.e.     point_str = "(%f,%f)" % (self.x, self.y)
>
> The long answer: Python interprets the statement "point_str =
> "(%f,%f)" % self.x, self.y" as "point_str = ("(%f,%f)" % self.x),
> self.y".  There are two "%f" expressions in the string, but you only
> supplied one argument, self.x.  Thus python tells you that there
> aren't enough arguments.  To deal with this, you need to supply the
> arguments as a tuple.


Hi all,

While it is true that you need to put parenthesis around the  
arguments, it isn`t quite the case that they are needed so as to  
provide the arguments as a tuple:

>>> a = 42, 42
>>> type(a)
<type 'tuple'>
>>>

It is the comma, not the parens that make for a tuple. My guess is  
that the parens are needed to disambiguate the end of the arguments as  
the comma can also indicate that another element is to be printed on  
the same line:

>>> print '%s' %42 , 333
42 333
>>>

In a case like

>>> print '%s%s' %42 , 333
...
TypeError: not enough arguments for format string

it would be ambiguous whether 333 was intended as a second formatting  
argument or as a second thing to be printed.

Best,

Brian vdB

From sean.m.mcdaniel at gmail.com  Wed Jul  2 19:30:45 2008
From: sean.m.mcdaniel at gmail.com (sean_mcdaniel)
Date: Wed, 2 Jul 2008 10:30:45 -0700 (PDT)
Subject: [Tutor] Inheritance help
In-Reply-To: <1215017735.6836.20.camel@lieryan-laptop>
References: <18240495.post@talk.nabble.com>
	<1215017735.6836.20.camel@lieryan-laptop>
Message-ID: <18242833.post@talk.nabble.com>


Thank you for the reply.

I have made the substitution, but I still receive the same error. I
previously defined the __init__ statements in the old way, i.e.

FileParse.__init__(self)

but with the same problematic outcome. 

Thank you,

Sean


Lie Ryan wrote:
> 
>> Hi Folks,
>> 
>> I can redefine the class and I get a "TypeError: __init__() takes
>> exactly 1
>> argument (2 given)" error.  I'm creating a SinglePeakFit object and
>> not a
>> FileParse one. Still puzzled...
> 
> In this:
> 
> ?class SinglePeakFit(FileParse):
>     ...
>     def __init___(self, filename):
>         print "I am here!"
>         super(FileParse,self).__init__()
>     ...
> ...
> 
> You called the __init__ of FileParse's superclass(es), i.e.
> object.__init__
> 
> What you wanted is this:
> 
> ?class SinglePeakFit(FileParse):
>     ...
>     def __init___(self, filename):
>         print "I am here!"
>         super(SinglePeakFit,self).__init__()
>     ...
> ...
> 
> which calls the superclass(es) of SinglePeakFit, i.e. FileParse.__init__
> 
> Anyway, you don't actually need to use super() unless your class use
> multiple inheritance. And even the en it is only really required if
> there is 'diamond'-shaped inheritance, like: A(object), B(A), C(A), D(A,
> B). But it is good practice to use super for any multiple inheritance,
> even though it's not diamond shaped (actually all cases of multiple
> inheritance is diamond shaped since all (new-style) classes inherits
> from object).
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
View this message in context: http://www.nabble.com/Inheritance-help-tp18240495p18242833.html
Sent from the Python - tutor mailing list archive at Nabble.com.


From wescpy at gmail.com  Wed Jul  2 20:24:04 2008
From: wescpy at gmail.com (wesley chun)
Date: Wed, 2 Jul 2008 11:24:04 -0700
Subject: [Tutor] random.choice()
In-Reply-To: <1c2a2c590807020914j233a60ch7898c79877204650@mail.gmail.com>
References: <20080701123848.0893E1E4002@bag.python.org>
	<486A266A.8060608@timgolden.me.uk>
	<20080701130423.9E22D1E4002@bag.python.org>
	<200807011523.24984.omer@no-log.org>
	<20080701133317.4635E1E4002@bag.python.org>
	<78b3a9580807020054s442c4ac8je51e8ba78963fde5@mail.gmail.com>
	<1c2a2c590807020346s471764a3nbbc8ab12f9173a29@mail.gmail.com>
	<20080702155100.9A3C71E4014@bag.python.org>
	<1c2a2c590807020914j233a60ch7898c79877204650@mail.gmail.com>
Message-ID: <78b3a9580807021124i38337e8bt28b1b3451dd72cbc@mail.gmail.com>

>  > It seems to me that Wes is saying only that all function objects are
>  > callable, not that all callable objects are functions.
>
> Wesley said that function objects have a "heaping distinction" of
>  being callable. Only he can say for sure what that means; I took it to
>  mean that being callable is a very special property, perhaps one that
>  only function objects have. I just wanted to point out that there is
>  nothing really very special about that property, any more than being
>  iterable or having a length or a string representation or any of the
>  other properties that are implemented with special methods.


yeah, apologies for not going further to clarify... i was just
focusing on functions in my reply and could've mentioned the others
like classes, methods (regular, static, class), as well as any
instances of classes that have implemented __call__.  the point i was
trying to make is that most standard Python objects *aren't* callable,
so it does seem to be magic for newbies that functions are 1st class
objects and that a mere pair of parentheses can make them execute.

on a related note, currently in Python, there is a callable() Boolean
function that returns True if the object's callable and False
otherwise. this will be removed for Python 3.x because you can just
use hasattr(obj, '__call__').

cheers,
-wesley

From bgailer at gmail.com  Wed Jul  2 20:32:27 2008
From: bgailer at gmail.com (bob gailer)
Date: Wed, 02 Jul 2008 14:32:27 -0400
Subject: [Tutor] TypeError: not enough arguments for format string
In-Reply-To: <20080702121558.mafuunzlkwgww88w@webware.cc.umanitoba.ca>
References: <592338.3700.qm@web51609.mail.re2.yahoo.com>	<5e58f2e40807012149x12de3aa7y988e537cc68ddce1@mail.gmail.com>
	<20080702121558.mafuunzlkwgww88w@webware.cc.umanitoba.ca>
Message-ID: <486BC9BB.7010701@gmail.com>

broek at cc.umanitoba.ca wrote:
> [snip]

>
> In a case like
>
>>>> print '%s%s' %42 , 333
> ...
> TypeError: not enough arguments for format string
>
> it would be ambiguous whether 333 was intended as a second formatting 
> argument or as a second thing to be printed.

Here's where the Language Reference comes in handy:
 
print_stmt ::= "print" ( [expression ("," expression)* [","]]
expression_list ::= expression ( "," expression )* [","] # An expression 
list containing at least one comma yields a tuple

Given that, there is no ambiguity in print '%s%s' %42 , 333

-- 
Bob Gailer
919-636-4239 Chapel Hill, NC


From sean.m.mcdaniel at gmail.com  Wed Jul  2 20:50:57 2008
From: sean.m.mcdaniel at gmail.com (sean_mcdaniel)
Date: Wed, 2 Jul 2008 11:50:57 -0700 (PDT)
Subject: [Tutor] Inheritance help
In-Reply-To: <18242833.post@talk.nabble.com>
References: <18240495.post@talk.nabble.com>
	<1215017735.6836.20.camel@lieryan-laptop>
	<18242833.post@talk.nabble.com>
Message-ID: <18244255.post@talk.nabble.com>


Hi y'all,

I found the problem. My __init__ statement in the subclass had an extra
underscore, which is why the baseclass __init__ was the only one called.

Duh!

Sean


sean_mcdaniel wrote:
> 
> Thank you for the reply.
> 
> I have made the substitution, but I still receive the same error. I
> previously defined the __init__ statements in the old way, i.e.
> 
> FileParse.__init__(self)
> 
> but with the same problematic outcome. 
> 
> Thank you,
> 
> Sean
> 
> 
> Lie Ryan wrote:
>> 
>>> Hi Folks,
>>> 
>>> I can redefine the class and I get a "TypeError: __init__() takes
>>> exactly 1
>>> argument (2 given)" error.  I'm creating a SinglePeakFit object and
>>> not a
>>> FileParse one. Still puzzled...
>> 
>> In this:
>> 
>> ?class SinglePeakFit(FileParse):
>>     ...
>>     def __init___(self, filename):
>>         print "I am here!"
>>         super(FileParse,self).__init__()
>>     ...
>> ...
>> 
>> You called the __init__ of FileParse's superclass(es), i.e.
>> object.__init__
>> 
>> What you wanted is this:
>> 
>> ?class SinglePeakFit(FileParse):
>>     ...
>>     def __init___(self, filename):
>>         print "I am here!"
>>         super(SinglePeakFit,self).__init__()
>>     ...
>> ...
>> 
>> which calls the superclass(es) of SinglePeakFit, i.e. FileParse.__init__
>> 
>> Anyway, you don't actually need to use super() unless your class use
>> multiple inheritance. And even the en it is only really required if
>> there is 'diamond'-shaped inheritance, like: A(object), B(A), C(A), D(A,
>> B). But it is good practice to use super for any multiple inheritance,
>> even though it's not diamond shaped (actually all cases of multiple
>> inheritance is diamond shaped since all (new-style) classes inherits
>> from object).
>> 
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>> 
>> 
> 
> 

-- 
View this message in context: http://www.nabble.com/Inheritance-help-tp18240495p18244255.html
Sent from the Python - tutor mailing list archive at Nabble.com.


From broek at cc.umanitoba.ca  Wed Jul  2 21:11:58 2008
From: broek at cc.umanitoba.ca (broek at cc.umanitoba.ca)
Date: Wed, 02 Jul 2008 14:11:58 -0500
Subject: [Tutor] TypeError: not enough arguments for format string
In-Reply-To: <486BC9BB.7010701@gmail.com>
References: <592338.3700.qm@web51609.mail.re2.yahoo.com>
	<5e58f2e40807012149x12de3aa7y988e537cc68ddce1@mail.gmail.com>
	<20080702121558.mafuunzlkwgww88w@webware.cc.umanitoba.ca>
	<486BC9BB.7010701@gmail.com>
Message-ID: <20080702141158.aks01wcrcwcw4c40@webware.cc.umanitoba.ca>



----- Message from bgailer at gmail.com ---------
     Date: Wed, 02 Jul 2008 14:32:27 -0400
     From: bob gailer <bgailer at gmail.com>

> broek at cc.umanitoba.ca wrote:
>> [snip]
>
>>
>> In a case like
>>
>>>>> print '%s%s' %42 , 333
>> ...
>> TypeError: not enough arguments for format string
>>
>> it would be ambiguous whether 333 was intended as a second   
>> formatting argument or as a second thing to be printed.
>
> Here's where the Language Reference comes in handy:
>
> print_stmt ::= "print" ( [expression ("," expression)* [","]]
> expression_list ::= expression ( "," expression )* [","] # An
> expression list containing at least one comma yields a tuple
>
> Given that, there is no ambiguity in print '%s%s' %42 , 333
>


I think I poorly expressed my intent. It was my starting point that
42, 333
provides a tuple, even absent the parens.

What I meant to express was the hypothesis that
>>> print '%s%s' %42 , 333
even while following the '%' with a tuple might be ruled out due to a  
possible 'ambiguity in the intent', not in the syntax. I meant to  
suggest that the perhaps the parens were required to make it explicit  
where the end of the '%'-following tuple was, and where the 'more  
stuff to print, distinct from the format-string stuff' began.

Were the following legal:
>>> c = "I am distinct from the format string, but that is hard to see."
>>> print "%s%s" % 42, 333, c
>> ...
>> TypeError: not enough arguments for format string

it would be harder to parse than:
>>> c = "I am obviously distinct from the format string."
>>> print "%s%s" % (42, 333), c
42333 I am obviously distinct from the format string.


If not that, then why are the parens required?

Best,

Brian vdB

From john at fouhy.net  Thu Jul  3 01:22:19 2008
From: john at fouhy.net (John Fouhy)
Date: Thu, 3 Jul 2008 11:22:19 +1200
Subject: [Tutor] random.choice()
In-Reply-To: <78b3a9580807021124i38337e8bt28b1b3451dd72cbc@mail.gmail.com>
References: <20080701123848.0893E1E4002@bag.python.org>
	<486A266A.8060608@timgolden.me.uk>
	<20080701130423.9E22D1E4002@bag.python.org>
	<200807011523.24984.omer@no-log.org>
	<20080701133317.4635E1E4002@bag.python.org>
	<78b3a9580807020054s442c4ac8je51e8ba78963fde5@mail.gmail.com>
	<1c2a2c590807020346s471764a3nbbc8ab12f9173a29@mail.gmail.com>
	<20080702155100.9A3C71E4014@bag.python.org>
	<1c2a2c590807020914j233a60ch7898c79877204650@mail.gmail.com>
	<78b3a9580807021124i38337e8bt28b1b3451dd72cbc@mail.gmail.com>
Message-ID: <5e58f2e40807021622g66193db2sa10e03bda20f3998@mail.gmail.com>

On 03/07/2008, wesley chun <wescpy at gmail.com> wrote:
>  on a related note, currently in Python, there is a callable() Boolean
>  function that returns True if the object's callable and False
>  otherwise. this will be removed for Python 3.x because you can just
>  use hasattr(obj, '__call__').

I believe this also comes down to a preference for EAFP over LBYL
(http://mail.python.org/pipermail/python-list/2003-May/205182.html).

i.e. instead of saying:

if callable(foo):
    foo()
else:
    # do something else

you can instead say:

try:
    foo()
except TypeError:
    # do something else

-- 
John.

From kuffert_med_hat at hotmail.com  Thu Jul  3 02:46:51 2008
From: kuffert_med_hat at hotmail.com (Emil)
Date: Thu, 3 Jul 2008 02:46:51 +0200
Subject: [Tutor] Fibonacci series(perhaps slightly off topic)
Message-ID: <BAY112-W36561F2306FBBC3F8558A0A3980@phx.gbl>


Hello all

I have created a class called Fibs which allow you to access a specific number in the Fibonacci series(http://en.wikipedia.org/wiki/Fibonacci_number) But it seems to me that it is a bit inefficient, any suggestions on how to make it more efficient?

Here is the code:

class Fibs(object):

        def __init__(self):
                self.fibsseq = [0, 1]

        def __getitem__(self, key):
                for i in xrange(key):
                        self.fibsseq.append(self.fibsseq[-1] + self.fibsseq[-2]) 
                print self.fibsseq[key]


in advance, thank you 

- Emil Agerschou

_________________________________________________________________
Connect to the next generation of MSN Messenger?
http://imagine-msn.com/messenger/launch80/default.aspx?locale=en-us&source=wlmailtagline

From alan.gauld at btinternet.com  Thu Jul  3 02:52:58 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 3 Jul 2008 01:52:58 +0100
Subject: [Tutor] General design question
References: <004c01c8dc1d$854b8360$8fe28a20$@co.uk>
Message-ID: <g4h7tg$muq$1@ger.gmane.org>


"Paul Melvin" <paul at assured-networks.co.uk> wrote

> For example, if I generate some numbers using range the only way I 
> could
> easily sum them was to append them to a list and then call the sum 
> function,
> if I tried without the list I couldn't sum them at all.

Lots of good general answers but specifically for a range try:

>>> print sum( range(3,7) )
18

ie range() returns the numbers already in a list you don't
need to append them to another list.


BTW If you haven't already, take a look at my tutorial.
It compares Python to VBScript which is a modern version of Basic
It may bring back some of your old menories and help translate
those to Python.

HTH

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



From john at fouhy.net  Thu Jul  3 02:59:39 2008
From: john at fouhy.net (John Fouhy)
Date: Thu, 3 Jul 2008 12:59:39 +1200
Subject: [Tutor] Fibonacci series(perhaps slightly off topic)
In-Reply-To: <BAY112-W36561F2306FBBC3F8558A0A3980@phx.gbl>
References: <BAY112-W36561F2306FBBC3F8558A0A3980@phx.gbl>
Message-ID: <5e58f2e40807021759na5a13afiee926bb74ecb6423@mail.gmail.com>

On 03/07/2008, Emil <kuffert_med_hat at hotmail.com> wrote:
>  I have created a class called Fibs which allow you to access a specific number in the
> Fibonacci series(http://en.wikipedia.org/wiki/Fibonacci_number) But it seems to me that it
> is a bit inefficient, any suggestions on how to make it more efficient?

Does this behaviour seem correct to you? --

>>> class Fibs(object):
...        def __init__(self):
...                self.fibsseq = [0, 1]
...        def __getitem__(self, key):
...                for i in xrange(key):
...                        self.fibsseq.append(self.fibsseq[-1] +
self.fibsseq[-2])
...                return self.fibsseq[key]
...
>>> f = Fibs()
>>> f[1]
1
>>> f[1]
1
>>> f[1]
1
>>> f.fibsseq
[0, 1, 1, 2, 3]

Maybe if I examine the first Fibonacci number a few hundred times:

>>> ones = [f[1] for i in xrange(500)]
>>> len(f.fibsseq)
505

Hmm, that's a lot of numbers to calculate when we're only looking at
the first element in the sequence..

(by the way: you might want to replace 'print' with 'return' in your
definition of __getitem__)

(by the way 2: if you follow the above code, and then display
f.fibsseq, you may see some nice curves caused by the " " between each
number.  Aren't fibonacci numbers wonderful :-) )

-- 
John.

From alan.gauld at btinternet.com  Thu Jul  3 03:05:15 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 3 Jul 2008 02:05:15 +0100
Subject: [Tutor] Inheritance help
References: <18240495.post@talk.nabble.com>
Message-ID: <g4h8kh$oje$1@ger.gmane.org>

"sean_mcdaniel" <sean.m.mcdaniel at gmail.com> wrote

> I am having problems with classes and subclasses. Do the different 
> __init__
> statements have to have different argument lists?

You got the solution to your specific question but to answer
your more pholosophical one:

sub classes should ideally have the same signature as their
superclass (the Liskov Substitution Principle or LSP). In other
words you should be able to plug a sub class in anywhere that the
superclass can be used.

This implies that depending on language provisions) your
sub class should have

a) one constructor with the same signature as the superclass
(if multiple constructors are supported).
b) a constructor with the same parameters as the superclass plus
some more - provided the new parameters can have default values
(the Python option)
c) a constructor with the same parameters as the superclass,
plus an initialisation method with any extra parameters which clients
must call immediately after construction if variant behaviour is 
required.
(where only single constructor is supported and no default params)

So not only is it possible but its a good idea from a pure OOP 
viewpoint.
Of course there are plenty examples of subclasses which do not follow
the LSP but they are limited in reuse capability as a result.

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 Jul  3 03:12:28 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 3 Jul 2008 02:12:28 +0100
Subject: [Tutor] random.choice()
References: <20080701123848.0893E1E4002@bag.python.org><486A266A.8060608@timgolden.me.uk><20080701130423.9E22D1E4002@bag.python.org><200807011523.24984.omer@no-log.org><20080701133317.4635E1E4002@bag.python.org><78b3a9580807020054s442c4ac8je51e8ba78963fde5@mail.gmail.com><1c2a2c590807020346s471764a3nbbc8ab12f9173a29@mail.gmail.com><20080702155100.9A3C71E4014@bag.python.org><1c2a2c590807020914j233a60ch7898c79877204650@mail.gmail.com><78b3a9580807021124i38337e8bt28b1b3451dd72cbc@mail.gmail.com>
	<5e58f2e40807021622g66193db2sa10e03bda20f3998@mail.gmail.com>
Message-ID: <g4h922$pgk$1@ger.gmane.org>


"John Fouhy" <john at fouhy.net> wrote

>>  otherwise. this will be removed for Python 3.x because you can 
>> just
>>  use hasattr(obj, '__call__').

I was about to go BOO HISS because callable() is much more
readable than hasattr() but...

> you can instead say:
>
> try:
>    foo()
> except TypeError:
>    # do something else

This makes slightly more sense, although a TypeError seems a bit
too vague, if it had bveen a CallableError then I'd say fine. With
TypeError we have a much wider chance of a problem, particularly
if the callable takes parameters:

>>> sum('foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>

I can see the reason easily interactively but in a try except
its much harder to tell if the Typeerror was due to sum being
non callable or to me giving an invalid argument!

So still a bit of a boo hiss. But at least I can use hasattr within
the handler I suppose.

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



From john at fouhy.net  Thu Jul  3 03:26:03 2008
From: john at fouhy.net (John Fouhy)
Date: Thu, 3 Jul 2008 13:26:03 +1200
Subject: [Tutor] random.choice()
In-Reply-To: <g4h922$pgk$1@ger.gmane.org>
References: <20080701123848.0893E1E4002@bag.python.org>
	<200807011523.24984.omer@no-log.org>
	<20080701133317.4635E1E4002@bag.python.org>
	<78b3a9580807020054s442c4ac8je51e8ba78963fde5@mail.gmail.com>
	<1c2a2c590807020346s471764a3nbbc8ab12f9173a29@mail.gmail.com>
	<20080702155100.9A3C71E4014@bag.python.org>
	<1c2a2c590807020914j233a60ch7898c79877204650@mail.gmail.com>
	<78b3a9580807021124i38337e8bt28b1b3451dd72cbc@mail.gmail.com>
	<5e58f2e40807021622g66193db2sa10e03bda20f3998@mail.gmail.com>
	<g4h922$pgk$1@ger.gmane.org>
Message-ID: <5e58f2e40807021826m3db2e903meaa2ef3739e4ac4@mail.gmail.com>

On 03/07/2008, Alan Gauld <alan.gauld at btinternet.com> wrote:
>  "John Fouhy" <john at fouhy.net> wrote
> > you can instead say:
> >
> > try:
> >   foo()
> > except TypeError:
> >   # do something else
>  This makes slightly more sense, although a TypeError seems a bit
>  too vague, if it had bveen a CallableError then I'd say fine. With
>  TypeError we have a much wider chance of a problem, particularly
>  if the callable takes parameters:

Well, I'm going by something I recall reading a while ago.  TypeError
is just what you get now if you try to call something that is not
callable.  Maybe things will change?

There's some discussion here which you could read:
http://mail.python.org/pipermail/python-3000/2006-July/002619.html

(and, of course, you could always put 'callable = lambda x: hasattr(x,
"__call__")' in some utility module)

-- 
John.

From kent37 at tds.net  Thu Jul  3 04:20:05 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 2 Jul 2008 22:20:05 -0400
Subject: [Tutor] Inheritance help
In-Reply-To: <g4h8kh$oje$1@ger.gmane.org>
References: <18240495.post@talk.nabble.com> <g4h8kh$oje$1@ger.gmane.org>
Message-ID: <1c2a2c590807021920oda701d3xaed31fb339d5988@mail.gmail.com>

On Wed, Jul 2, 2008 at 9:05 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> "sean_mcdaniel" <sean.m.mcdaniel at gmail.com> wrote
>
>> I am having problems with classes and subclasses. Do the different
>> __init__
>> statements have to have different argument lists?
>
> You got the solution to your specific question but to answer
> your more pholosophical one:
>
> sub classes should ideally have the same signature as their
> superclass (the Liskov Substitution Principle or LSP). In other
> words you should be able to plug a sub class in anywhere that the
> superclass can be used.
>
> This implies that depending on language provisions) your
> sub class should have
>
> a) one constructor with the same signature as the superclass

Hmm. I don't understand the LSP to make any requirements on the
constructors. It says that instances of a subclass should be
substitutable for instances of the base class, it doesn't say anthing
how the instances are created.

BTW  those wondering what we are talking about might be interested in
this paper:
http://objectmentor.com/resources/articles/lsp.pdf

Kent

From dongli2020 at gmail.com  Thu Jul  3 08:05:53 2008
From: dongli2020 at gmail.com (Dong Li)
Date: Thu, 03 Jul 2008 14:05:53 +0800
Subject: [Tutor] Question about string
Message-ID: <1215065153.10274.6.camel@localhost.localdomain>

Hi, everyone

I am new to python, so what I ask may be so basic. I don't know the
difference between

s = 'a' 'b'

and

s = 'a'+'b'

They have the same results. Thanks for relying!


From alan.gauld at btinternet.com  Thu Jul  3 11:14:02 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 3 Jul 2008 10:14:02 +0100
Subject: [Tutor] Inheritance help
References: <18240495.post@talk.nabble.com> <g4h8kh$oje$1@ger.gmane.org>
	<1c2a2c590807021920oda701d3xaed31fb339d5988@mail.gmail.com>
Message-ID: <g4i591$fm$1@ger.gmane.org>


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

> Hmm. I don't understand the LSP to make any requirements on the
> constructors. It says that instances of a subclass should be
> substitutable for instances of the base class, it doesn't say 
> anthing
> how the instances are created.

LSP doesn't distinguish between method types but the substitution
principle can extend beyond instances to include class methods etc.

The issue is that you could have a collection of class references
and have a loop that creates instances from those. To do that the
constructor calls need to be compatible in signature for the LSP
to apply.

Its much less common for the LSP to be strictly applied to 
constructors
because in many languages class references are either non existent
or a bit of a kluge. But in languages that support classes as objects
then applying LSP at the conastructor and class method level
makes a lot of sense.

Alan G. 



From alan.gauld at btinternet.com  Thu Jul  3 11:18:23 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 3 Jul 2008 10:18:23 +0100
Subject: [Tutor] Question about string
References: <1215065153.10274.6.camel@localhost.localdomain>
Message-ID: <g4i5h5$1cc$1@ger.gmane.org>


"Dong Li" <dongli2020 at gmail.com> wrote

> I am new to python, so what I ask may be so basic. I don't know the
> difference between
>
> s = 'a' 'b'
> and
> s = 'a'+'b'
>
> They have the same results. Thanks for relying!

I think the differencec is that the first is purely a syntax thing so
the interpreter does the work of joining the strings together before
processing the result as a single string whereas the second the
two strings are treated separately and actual string addition
(concatenation) is done which is a much more expensive
operation in terms of computer power.

The first is only possible if you have literal strings but the second
can be used for variables:

s1 = 'a'
s2 = 'b'
s = s1 s2     # doesn't work
s = s1 + s2   # works

HTH,

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



From monjissvel at googlemail.com  Thu Jul  3 11:53:07 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Thu, 3 Jul 2008 09:53:07 +0000
Subject: [Tutor] Question about string
In-Reply-To: <g4i5h5$1cc$1@ger.gmane.org>
References: <1215065153.10274.6.camel@localhost.localdomain>
	<g4i5h5$1cc$1@ger.gmane.org>
Message-ID: <e2f191310807030253p681550d0t76e69a4080055584@mail.gmail.com>

Python is one of the smartest languages, it does many things for the
programmer  (I don't know but this might be what they mean with
Batteries-Included) , & you have just scratched the surface of it,  here
python concatenated your strings together for you, later you will meet list
comprehention & other stuff that actually does most of the programing logic
for you for free.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080703/9c54d12a/attachment.htm>

From python at mrfab.info  Thu Jul  3 14:47:00 2008
From: python at mrfab.info (Michael)
Date: Thu, 03 Jul 2008 20:47:00 +0800
Subject: [Tutor] directory traversal help
Message-ID: <486CCA44.6030708@mrfab.info>

Hi

I have modified an algorithm from the think like a python programmer 
book for traversing folders and printing the files in those folders. It 
works for my original purposes but I have a students that wants to use 
it to run from a root folder, problem is that it crashes on the 
recycling bin as well as hidden and other types of folders. Is there a 
way to modify it to skip folders that would make it crash? I have tried 
using exception handling (try) and other functions in the os module but 
I cannot work it out. Any ideas? thanks

Michael

import os
import string

def walk(dir):
    for name in os.listdir(dir):
        path = os.path.join(dir,name)
        if os.path.isfile(path):
            beg = string.rfind(path,'\Student')
            end = len(path)
            filename = path[beg:end]
            #print "___________ ",filename
            print "___________ ",name

        else:
            print path
            walk (path)

cwd = os.getcwd()
walk(cwd)


From brnstrmrs at gmail.com  Thu Jul  3 15:53:37 2008
From: brnstrmrs at gmail.com (Brain Stormer)
Date: Thu, 3 Jul 2008 09:53:37 -0400
Subject: [Tutor] Array filling
Message-ID: <24bc7f6c0807030653o37077a87l48f43410f4d6b467@mail.gmail.com>

I am using numpy to create an array then filling some of the values using a
for loop, I was wondering if there is way to easily fill the values without
iterating through sort of like "array.fill[start:stop,start:stop]"?  The
reason for my question is, in some cases, I might have to fill hundreds
(within a 10,000x10,000 matrix) of values and I am not sure if iteration is
the right way to go.

Code:
from numpy import *
x, y = 5, 5
matrix = zeros((y,x), int)
print matrix
fillxstart, fillystart = 1,1
fillxstop,fillystop = 4, 4
for i in range(fillystart,fillystop,1):
    for j in range(fillxstart,fillxstop,1):
        matrix[i,j] = 1
print matrix

Output before filling:
[[0 0 0 0 0]
 [0 0 0 0 0]
 [0 0 0 0 0]
 [0 0 0 0 0]
 [0 0 0 0 0]]
Output after filling:
[[0 0 0 0 0]
 [0 1 1 1 0]
 [0 1 1 1 0]
 [0 1 1 1 0]
 [0 0 0 0 0]]
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080703/cf4cb5c8/attachment.htm>

From kuffert_med_hat at hotmail.com  Thu Jul  3 17:27:10 2008
From: kuffert_med_hat at hotmail.com (Emil)
Date: Thu, 3 Jul 2008 17:27:10 +0200
Subject: [Tutor] Fibonacci series(perhaps slightly off topic)
In-Reply-To: <5e58f2e40807021759na5a13afiee926bb74ecb6423@mail.gmail.com>
References: <BAY112-W36561F2306FBBC3F8558A0A3980@phx.gbl>
	<5e58f2e40807021759na5a13afiee926bb74ecb6423@mail.gmail.com>
Message-ID: <BAY112-W3337F0310991A977DF9E15A3980@phx.gbl>


Hey John thank you for your reply. I came up with this code, it is not elegant( yet) but i would say that it is more efficient :)    




class Fibs(object):
	
	def __init__(self):
		self.fibsseq = [0,1]
	
	def __getitem__(self, key):
		try:
			return self.fibsseq[key]
		except IndexError:
			for i in xrange(key-len(self.fibsseq)+1):
				self.fibsseq.append(self.fibsseq[-1] + self.fibsseq[-2])
			return self.fibsseq[key]





----------------------------------------
> Date: Thu, 3 Jul 2008 12:59:39 +1200
> From: john at fouhy.net
> To: kuffert_med_hat at hotmail.com
> Subject: Re: [Tutor] Fibonacci series(perhaps slightly off topic)
> CC: tutor at python.org
> 
> On 03/07/2008, Emil  wrote:
>>  I have created a class called Fibs which allow you to access a specific number in the
>> Fibonacci series(http://en.wikipedia.org/wiki/Fibonacci_number) But it seems to me that it
>> is a bit inefficient, any suggestions on how to make it more efficient?
> 
> Does this behaviour seem correct to you? --
> 
>>>> class Fibs(object):
> ...        def __init__(self):
> ...                self.fibsseq = [0, 1]
> ...        def __getitem__(self, key):
> ...                for i in xrange(key):
> ...                        self.fibsseq.append(self.fibsseq[-1] +
> self.fibsseq[-2])
> ...                return self.fibsseq[key]
> ...
>>>> f = Fibs()
>>>> f[1]
> 1
>>>> f[1]
> 1
>>>> f[1]
> 1
>>>> f.fibsseq
> [0, 1, 1, 2, 3]
> 
> Maybe if I examine the first Fibonacci number a few hundred times:
> 
>>>> ones = [f[1] for i in xrange(500)]
>>>> len(f.fibsseq)
> 505
> 
> Hmm, that's a lot of numbers to calculate when we're only looking at
> the first element in the sequence..
> 
> (by the way: you might want to replace 'print' with 'return' in your
> definition of __getitem__)
> 
> (by the way 2: if you follow the above code, and then display
> f.fibsseq, you may see some nice curves caused by the " " between each
> number.  Aren't fibonacci numbers wonderful :-) )
> 
> -- 
> John.





_________________________________________________________________
Connect to the next generation of MSN Messenger?
http://imagine-msn.com/messenger/launch80/default.aspx?locale=en-us&source=wlmailtagline

From kent37 at tds.net  Thu Jul  3 17:41:43 2008
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 3 Jul 2008 11:41:43 -0400
Subject: [Tutor] directory traversal help
In-Reply-To: <486CCA44.6030708@mrfab.info>
References: <486CCA44.6030708@mrfab.info>
Message-ID: <1c2a2c590807030841i54c905e2r285bca7139686838@mail.gmail.com>

On Thu, Jul 3, 2008 at 8:47 AM, Michael <python at mrfab.info> wrote:
> Hi
>
> I have modified an algorithm from the think like a python programmer book
> for traversing folders and printing the files in those folders. It works for
> my original purposes but I have a students that wants to use it to run from
> a root folder, problem is that it crashes on the recycling bin as well as
> hidden and other types of folders.

How does it fail? It would help to see the complete error message
including the traceback.

Kent

From dongli2020 at gmail.com  Thu Jul  3 18:29:03 2008
From: dongli2020 at gmail.com (Dong Li)
Date: Fri, 04 Jul 2008 00:29:03 +0800
Subject: [Tutor] Question about string
In-Reply-To: <mailman.69.1215079213.18076.tutor@python.org>
References: <mailman.69.1215079213.18076.tutor@python.org>
Message-ID: <1215102543.13683.4.camel@localhost.localdomain>


> Date: Thu, 3 Jul 2008 10:18:23 +0100
> From: "Alan Gauld" <alan.gauld at btinternet.com>
> Subject: Re: [Tutor] Question about string
> To: tutor at python.org
> Message-ID: <g4i5h5$1cc$1 at ger.gmane.org>
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
> 	reply-type=original
> 
> 
> "Dong Li" <dongli2020 at gmail.com> wrote
> 
> > I am new to python, so what I ask may be so basic. I don't know the
> > difference between
> >
> > s = 'a' 'b'
> > and
> > s = 'a'+'b'
> >
> > They have the same results. Thanks for relying!
> 
> I think the differencec is that the first is purely a syntax thing so
> the interpreter does the work of joining the strings together before
> processing the result as a single string whereas the second the
> two strings are treated separately and actual string addition
> (concatenation) is done which is a much more expensive
> operation in terms of computer power.
> 
> The first is only possible if you have literal strings but the second
> can be used for variables:
> 
> s1 = 'a'
> s2 = 'b'
> s = s1 s2     # doesn't work
> s = s1 + s2   # works
> 
> HTH,
> 
> -- 
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld 
> 

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

> Date: Thu, 3 Jul 2008 09:53:07 +0000
> From: "Monika Jisswel" <monjissvel at googlemail.com>
> Subject: Re: [Tutor] Question about string
> To: tutor at python.org
> Message-ID:
> 	<e2f191310807030253p681550d0t76e69a4080055584 at mail.gmail.com>
> Content-Type: text/plain; charset="iso-8859-1"
> 
> Python is one of the smartest languages, it does many things for the
> programmer  (I don't know but this might be what they mean with
> Batteries-Included) , & you have just scratched the surface of it,  here
> python concatenated your strings together for you, later you will meet list
> comprehention & other stuff that actually does most of the programing logic
> for you for free.
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL: <http://mail.python.org/pipermail/tutor/attachments/20080703/9c54d12a/attachment-0001.htm>
> 
> ------------------------------

Thank you for excellent explanations! I have been attracted by python
more and more!


From michael at yavarsity.com  Thu Jul  3 19:20:36 2008
From: michael at yavarsity.com (Michael yaV)
Date: Thu, 3 Jul 2008 13:20:36 -0400
Subject: [Tutor] Question about string
In-Reply-To: <1215102543.13683.4.camel@localhost.localdomain>
References: <mailman.69.1215079213.18076.tutor@python.org>
	<1215102543.13683.4.camel@localhost.localdomain>
Message-ID: <EEF5747F-FEF9-490F-A78A-95E8DBF52D12@yavarsity.com>

This is in the " Snake Wrangling For Kids" Learning to Program with  
Python by Jason R Briggs
Thought this would help.
Michael

What?s the difference between 10 and ?10??
Not much apart from the quotes, you might be thinking. Well, from  
reading
the earlier chapters, you know that the first is a number and the  
second is a string.
This makes them differ more than you might expect. Earlier we compared  
the value
of a variable (age) to a number in an if-statement:
 >>> if age == 10:
... print ?you are 10?
If you set variable age to 10, the print statement will be called:
 >>> age = 10
 >>> if age == 10:
... print ?you are 10?
...
you are 10
However, if age is set to ?10? (note the quotes), then it won?t:
 >>> age = ?10?
 >>> if age == 10:
... print ?you are 10?
...
Why is the code in the block not run? Because a string is different  
from a
number, even if they look the same:
 >>> age1 = 10
 >>> age2 = ?10?
 >>> print age1
10
 >>> print age2
10
See! They look exactly the same. Yet, because one is a string, and the  
other is
a number, they are different values. Therefore age == 10 (age equals  
10) will never
be true, if the value of the variable is a string.
Probably the best way to think about it, is to consider 10 books and  
10 bricks.
The number of items might be the same, but you couldn?t say that 10  
books are
exactly the same as 10 bricks, could you? Luckily in Python we have  
magic functions
which can turn strings into numbers and numbers into strings (even if  
they won?t
quite turn bricks into books). For example, to convert the string ?10?  
into a number
you would use the function int:
4.5. WHAT?S THE DIFFERENCE. . .? 43
 >>> age = ?10?
 >>> converted_age = int(age)
The variable converted age now holds the number 10, and not a string.  
To convert
a number into a string, you would use the function str:
 >>> age = 10
 >>> converted_age = str(age)
converted age now holds the string 10, and not a number. Back to that  
if-statement
which prints nothing:
 >>> age = ?10?
 >>> if age == 10:
... print ?you are 10?
...
If we convert the variable before we check, then we?ll get a different  
result:
 >>> age = ?10?
 >>> converted_age = int(age)
 >>> if converted_age == 10:
... print ?you are 10?
...
you are 10






On Jul 3, 2008, at 12:29 PM, Dong Li wrote:

>
>> Date: Thu, 3 Jul 2008 10:18:23 +0100
>> From: "Alan Gauld" <alan.gauld at btinternet.com>
>> Subject: Re: [Tutor] Question about string
>> To: tutor at python.org
>> Message-ID: <g4i5h5$1cc$1 at ger.gmane.org>
>> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
>> 	reply-type=original
>>
>>
>> "Dong Li" <dongli2020 at gmail.com> wrote
>>
>>> I am new to python, so what I ask may be so basic. I don't know the
>>> difference between
>>>
>>> s = 'a' 'b'
>>> and
>>> s = 'a'+'b'
>>>
>>> They have the same results. Thanks for relying!
>>
>> I think the differencec is that the first is purely a syntax thing so
>> the interpreter does the work of joining the strings together before
>> processing the result as a single string whereas the second the
>> two strings are treated separately and actual string addition
>> (concatenation) is done which is a much more expensive
>> operation in terms of computer power.
>>
>> The first is only possible if you have literal strings but the second
>> can be used for variables:
>>
>> s1 = 'a'
>> s2 = 'b'
>> s = s1 s2     # doesn't work
>> s = s1 + s2   # works
>>
>> HTH,
>>
>> -- 
>> Alan Gauld
>> Author of the Learn to Program web site
>> http://www.freenetpages.co.uk/hp/alan.gauld
>>
>
>> ------------------------------
>
>> Date: Thu, 3 Jul 2008 09:53:07 +0000
>> From: "Monika Jisswel" <monjissvel at googlemail.com>
>> Subject: Re: [Tutor] Question about string
>> To: tutor at python.org
>> Message-ID:
>> 	<e2f191310807030253p681550d0t76e69a4080055584 at mail.gmail.com>
>> Content-Type: text/plain; charset="iso-8859-1"
>>
>> Python is one of the smartest languages, it does many things for the
>> programmer  (I don't know but this might be what they mean with
>> Batteries-Included) , & you have just scratched the surface of it,   
>> here
>> python concatenated your strings together for you, later you will  
>> meet list
>> comprehention & other stuff that actually does most of the  
>> programing logic
>> for you for free.
>> -------------- next part --------------
>> An HTML attachment was scrubbed...
>> URL: <http://mail.python.org/pipermail/tutor/attachments/20080703/9c54d12a/attachment-0001.htm 
>> >
>>
>> ------------------------------
>
> Thank you for excellent explanations! I have been attracted by python
> more and more!
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


From bgailer at gmail.com  Thu Jul  3 23:38:41 2008
From: bgailer at gmail.com (bob gailer)
Date: Thu, 03 Jul 2008 17:38:41 -0400
Subject: [Tutor] Array filling
In-Reply-To: <24bc7f6c0807030653o37077a87l48f43410f4d6b467@mail.gmail.com>
References: <24bc7f6c0807030653o37077a87l48f43410f4d6b467@mail.gmail.com>
Message-ID: <486D46E1.7020601@gmail.com>

Brain Stormer wrote:
> I am using numpy to create an array then filling some of the values 
> using a for loop, I was wondering if there is way to easily fill the 
> values without iterating through sort of like 
> "array.fill[start:stop,start:stop]"?  The reason for my question is, 
> in some cases, I might have to fill hundreds (within a 10,000x10,000 
> matrix) of values and I am not sure if iteration is the right way to go.
>
> Code:
> from numpy import *
> x, y = 5, 5
> matrix = zeros((y,x), int)
> print matrix
for row in matrix[1:4]:
    row[1:4] = [1,1,1]
> print matrix
>
> Output before filling:
> [[0 0 0 0 0]
>  [0 0 0 0 0]
>  [0 0 0 0 0]
>  [0 0 0 0 0]
>  [0 0 0 0 0]]
> Output after filling:
> [[0 0 0 0 0]
>  [0 1 1 1 0]
>  [0 1 1 1 0]
>  [0 1 1 1 0]
>  [0 0 0 0 0]]
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


-- 
Bob Gailer
919-636-4239 Chapel Hill, NC


From chester_lab at fltg.net  Fri Jul  4 00:06:10 2008
From: chester_lab at fltg.net (FT)
Date: Thu, 3 Jul 2008 18:06:10 -0400
Subject: [Tutor] Mixer and Busy Flag Never Working?
References: <79642.8421.qm@web59816.mail.ac4.yahoo.com><005e01c8d948$7a6289d0$0501a8c0@brucetower>
	<g46ae4$dts$1@ger.gmane.org>
Message-ID: <00a901c8dd59$06897a40$0501a8c0@brucetower>



A Question:

    Has anyone ever played with Pygame and the sound mixer? If so, has
anyone ever had the busy flag, and the problem below ever work?

Subject: Re: [pygame] Mixer Quit / Restart

This appears to get the total number of channels, not the number of active
channels.  However, I tried using get_busy(), but it still does not seem to
work.

See the following modifications to my original code:

import pygame, time

for x in range(10):
    print("Starting iteration " + str(x))
    print("Initializing mixer")
    pygame.mixer.init()

    print("Loading sound")
    sound = pygame.mixer.Sound("foo.wav")
    print("Finding free channel")
    channel = pygame.mixer.find_channel()

    print("Channel object: " + str(channel))

    print("Setting volume")
    channel.set_volume(0.7)

    print("Playing sound")
    channel.play(sound)

    print("Sleeping until sound is finished playing...")
    while pygame.mixer.get_busy():
        time.sleep(1)

    print("Quitting mixer\n\n")
    pygame.mixer.quit()



This displays the same behaviour.

In response to a previous comment about using channel.stop() before quitting
the mixer: this does not work either, as can be seen by adding
channel.stop() after the get_busy loop above.


Has anyone tried running this code themselves?  I am wondering if I am
experiencing some obscure bug, possibly platform specific.  I am running on
OS X, but don't have access to other systems for troubleshooting.  If
someone else has access to a Windows or Linux box, and is able to prove if
this fails on those systems as well, that may be useful.

Cheers

Ian Mallett wrote:
  On 7/2/08, Wyatt Olson <wyatt.olson at gmail.com> wrote:
    Is there anything which can return a list of all currently active
channels?
  pygame.mixer.get_num_channels()
  This returns 0 if none are playing and > 0 if there are.




From eike.welk at post.rwth-aachen.de  Fri Jul  4 00:48:41 2008
From: eike.welk at post.rwth-aachen.de (Eike Welk)
Date: Fri, 04 Jul 2008 00:48:41 +0200
Subject: [Tutor] Array filling
In-Reply-To: <24bc7f6c0807030653o37077a87l48f43410f4d6b467@mail.gmail.com>
References: <24bc7f6c0807030653o37077a87l48f43410f4d6b467@mail.gmail.com>
Message-ID: <200807040048.41759.eike.welk@post.rwth-aachen.de>

On Thursday 03 July 2008 15:53, Brain Stormer wrote:
> I am using numpy to create an array then filling some of the values
> using a for loop, I was wondering if there is way to easily fill
> the values without iterating through sort of like
> "array.fill[start:stop,start:stop]"?  The reason for my question
> is, in some cases, I might have to fill hundreds (within a
> 10,000x10,000 matrix) of values and I am not sure if iteration is
> the right way to go.

You can do it this way:

>>> from numpy import *
>>> m = zeros((5,5), int)
>>> m[1:4, 1:4] = 1
>>> m
array([[0, 0, 0, 0, 0],
       [0, 1, 1, 1, 0],
       [0, 1, 1, 1, 0],
       [0, 1, 1, 1, 0],
       [0, 0, 0, 0, 0]])

HTH, Eike.

From metolone+gmane at gmail.com  Fri Jul  4 03:55:55 2008
From: metolone+gmane at gmail.com (Mark Tolonen)
Date: Thu, 3 Jul 2008 18:55:55 -0700
Subject: [Tutor] Fibonacci series(perhaps slightly off topic)
References: <BAY112-W36561F2306FBBC3F8558A0A3980@phx.gbl><5e58f2e40807021759na5a13afiee926bb74ecb6423@mail.gmail.com>
	<BAY112-W3337F0310991A977DF9E15A3980@phx.gbl>
Message-ID: <g4jvv3$774$1@ger.gmane.org>

You can actually remove the try/except, because if the calculation 
key-len(self.fibsseq)+1 <= 0 the for loop won't execute.  The for loop will 
make sure self.fibsseq is long enough to satisify the return 
self.febsseq[key] access:

class Fibs(object):
    def __init__(self):
        self.fibsseq = [0, 1]
    def __getitem__(self, key):
        for i in xrange(key - len(self.fibsseq) + 1):
            self.fibsseq.append(self.fibsseq[-1] + self.fibsseq[-2])
        return self.fibsseq[key]

-Mark


"Emil" <kuffert_med_hat at hotmail.com> wrote in message 
news:BAY112-W3337F0310991A977DF9E15A3980 at phx.gbl...

Hey John thank you for your reply. I came up with this code, it is not 
elegant( yet) but i would say that it is more efficient :)




class Fibs(object):

def __init__(self):
self.fibsseq = [0,1]

def __getitem__(self, key):
try:
return self.fibsseq[key]
except IndexError:
for i in xrange(key-len(self.fibsseq)+1):
self.fibsseq.append(self.fibsseq[-1] + self.fibsseq[-2])
return self.fibsseq[key]





----------------------------------------
> Date: Thu, 3 Jul 2008 12:59:39 +1200
> From: john at fouhy.net
> To: kuffert_med_hat at hotmail.com
> Subject: Re: [Tutor] Fibonacci series(perhaps slightly off topic)
> CC: tutor at python.org
>
> On 03/07/2008, Emil  wrote:
>>  I have created a class called Fibs which allow you to access a specific 
>> number in the
>> Fibonacci series(http://en.wikipedia.org/wiki/Fibonacci_number) But it 
>> seems to me that it
>> is a bit inefficient, any suggestions on how to make it more efficient?
>
> Does this behaviour seem correct to you? --
>
>>>> class Fibs(object):
> ...        def __init__(self):
> ...                self.fibsseq = [0, 1]
> ...        def __getitem__(self, key):
> ...                for i in xrange(key):
> ...                        self.fibsseq.append(self.fibsseq[-1] +
> self.fibsseq[-2])
> ...                return self.fibsseq[key]
> ...
>>>> f = Fibs()
>>>> f[1]
> 1
>>>> f[1]
> 1
>>>> f[1]
> 1
>>>> f.fibsseq
> [0, 1, 1, 2, 3]
>
> Maybe if I examine the first Fibonacci number a few hundred times:
>
>>>> ones = [f[1] for i in xrange(500)]
>>>> len(f.fibsseq)
> 505
>
> Hmm, that's a lot of numbers to calculate when we're only looking at
> the first element in the sequence..
>
> (by the way: you might want to replace 'print' with 'return' in your
> definition of __getitem__)
>
> (by the way 2: if you follow the above code, and then display
> f.fibsseq, you may see some nice curves caused by the " " between each
> number.  Aren't fibonacci numbers wonderful :-) )
>
> -- 
> John.



From dongli2020 at gmail.com  Fri Jul  4 08:33:52 2008
From: dongli2020 at gmail.com (Dong Li)
Date: Fri, 04 Jul 2008 14:33:52 +0800
Subject: [Tutor] help for building tui?
Message-ID: <1215153232.3564.4.camel@localhost.localdomain>

Hi, everyone

If I want to create a text user interface for my application, is there
any existed module to facilitate such building?


From wolfram.kraus at fen-net.de  Fri Jul  4 08:50:23 2008
From: wolfram.kraus at fen-net.de (Wolfram Kraus)
Date: Fri, 04 Jul 2008 08:50:23 +0200
Subject: [Tutor] help for building tui?
In-Reply-To: <1215153232.3564.4.camel@localhost.localdomain>
References: <1215153232.3564.4.camel@localhost.localdomain>
Message-ID: <g4kh4k$dai$1@ger.gmane.org>

Am 04.07.2008 08:33, Dong Li schrieb:
> Hi, everyone
> 
> If I want to create a text user interface for my application, is there
> any existed module to facilitate such building?
> 

Yes, there is curses:

http://docs.python.org/lib/module-curses.html
http://www.amk.ca/python/howto/curses/

HTH,
Wolfram


From alan.gauld at btinternet.com  Fri Jul  4 10:28:12 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 4 Jul 2008 09:28:12 +0100
Subject: [Tutor] help for building tui?
References: <1215153232.3564.4.camel@localhost.localdomain>
Message-ID: <g4kmv3$ad$1@ger.gmane.org>


"Dong Li" <dongli2020 at gmail.com> wrote

> If I want to create a text user interface for my application, is 
> there
> any existed module to facilitate such building?

Yes, Python includes the cmd module which is a framework
for a menu driven command line. It is very like the help system
that Python uses (also the Python debugger pdb).

try

import cmd
help(cmd)

or look at the module documentation.

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



From sanelson at gmail.com  Fri Jul  4 10:57:43 2008
From: sanelson at gmail.com (Stephen Nelson-Smith)
Date: Fri, 4 Jul 2008 09:57:43 +0100
Subject: [Tutor] Init Scripts
Message-ID: <b6131fdc0807040157x6d59ff3dr4d1c13c022c78dd6@mail.gmail.com>

Hello,

I've been wrestling with some badly written init scripts, and picking
my way through the redhat init script system.  I'm getting to the
point of thinking I could do this sort of thing in Python just as
effectively.

Are there any pointers available?  Eg libraries that give process
information, so I can obtain status information?

S.

From kf9150 at gmail.com  Fri Jul  4 12:25:03 2008
From: kf9150 at gmail.com (Kelie)
Date: Fri, 4 Jul 2008 10:25:03 +0000 (UTC)
Subject: [Tutor] Where is this tr function?
Message-ID: <loom.20080704T101911-935@post.gmane.org>

Hello,

I see a lots tr('some string') in codes, especially the ones related to
wxPython. Where is this tr function defined and what does it do? To make the
argument a raw string?

When I type print tr('some string') in PyShell that comes with wxPython, no
error. But if I type that line in a .py file and run it, I get an error:
NameError: name 'tr' is not defined

Thanks!




From kent37 at tds.net  Fri Jul  4 14:19:31 2008
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 4 Jul 2008 08:19:31 -0400
Subject: [Tutor] Where is this tr function?
In-Reply-To: <loom.20080704T101911-935@post.gmane.org>
References: <loom.20080704T101911-935@post.gmane.org>
Message-ID: <1c2a2c590807040519i6a7ce563kb1e3c46fd6d351c2@mail.gmail.com>

On Fri, Jul 4, 2008 at 6:25 AM, Kelie <kf9150 at gmail.com> wrote:
> Hello,
>
> I see a lots tr('some string') in codes, especially the ones related to
> wxPython. Where is this tr function defined and what does it do? To make the
> argument a raw string?

tr() is not a standard part of Python. My guess is that it is a
wrapper function that helps with localization.

Raw strings are a syntactic construct, i.e. they exist only in source
code as an instruction to the parser. There is no such thing as a raw
string at runtime, so there is no function to create one.

> When I type print tr('some string') in PyShell that comes with wxPython, no
> error. But if I type that line in a .py file and run it, I get an error:
> NameError: name 'tr' is not defined

You have to find where tr() is being imported. From PyShell type
tr.__module__
that should print the name of the module containing tr().

Kent

From ebrosh at nana10.co.il  Fri Jul  4 16:14:08 2008
From: ebrosh at nana10.co.il (Eli Brosh)
Date: Fri, 4 Jul 2008 17:14:08 +0300
Subject: [Tutor] open-file GUI
Message-ID: <957526FB6E347743AAB42B212AB54FDA95BB47@NANAMAILBACK1.nanamail.co.il>

Hello,
I am starting to use Python+NumPy+SciPy+Matplotlib as a substitute to MATLAB.
 
I need a simple GUI that can help me to open files and save file i.e. something similar to uigetfile in MATLAB.
Is there a simple script that opens a window with a possibility to browse through the file system and pick an ASCII file ?
After the file is spcified using the GUI, I want to read it using fromfile and similar commands.
After I process the data I want a similar GUI that enables choosing the path and name for saving the results file.
 
Are scripts of this type available ?
 
Thanks
Eli Brosh
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080704/23fa70f5/attachment.htm>

From akanksha.kumar14 at yahoo.com  Fri Jul  4 18:14:35 2008
From: akanksha.kumar14 at yahoo.com (Akanskha Kumar)
Date: Fri, 4 Jul 2008 09:14:35 -0700 (PDT)
Subject: [Tutor] tic tac toe
Message-ID: <689419.65550.qm@web45615.mail.sp1.yahoo.com>

how can i make tic tac toe game using python programing.?


      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080704/cc9b7c99/attachment.htm>

From monjissvel at googlemail.com  Fri Jul  4 18:16:12 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Fri, 4 Jul 2008 16:16:12 +0000
Subject: [Tutor] file object in memory
Message-ID: <e2f191310807040916q447b6145xf797f03171f91490@mail.gmail.com>

Hi everyone,

In my program I have this code :

self.run_cmd_0 = subprocess.Popen(self.cmd_0, stdout = subprocess.PIPE,
> shell = True)     #(1)
> self.run_cmd_1 = subprocess.Popen(self.TOCOL, stdin =
> self.run_cmd_0.stdout, stdout = subprocess.PIPE, shell = True)    #(2)
> self.result_0 = StringIO.StringIO(self.run_cmd_1.communicate()[0])
> #(3)


(1) :  executes cmd_0 as a subprocess with stdout to PIPE
(2) : executes cmd_1 a second process with stdin from the previouse cmd_0
(3) : Here I tried to use StringIO module to create a file object from
stdout of cmd_1 : I need a file object because I have a mysql query later in
my program to load it into the database :

self.cmd_sql_2 = "load data local infile '%s' into table statistics fields
> terminated by '\t' lines terminated by '\n'" % self.FILE


so self.cur.execute(self.cmd_sql_2) fails.
the problem is that  mysql  is expecting a REAL file for this query !! is
there any pythonic way of avoiding to write to disk before loading into
Mysql database ? some sort of in-memory file oject.

Thanks In Advance.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080704/0501eb05/attachment.htm>

From alan.gauld at btinternet.com  Fri Jul  4 18:35:10 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 4 Jul 2008 17:35:10 +0100
Subject: [Tutor] Where is this tr function?
References: <loom.20080704T101911-935@post.gmane.org>
	<1c2a2c590807040519i6a7ce563kb1e3c46fd6d351c2@mail.gmail.com>
Message-ID: <g4ljg5$32j$1@ger.gmane.org>

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

> tr() is not a standard part of Python. My guess is that it is a
> wrapper function that helps with localization.

So far as I can see it's not a native part of wxPython either - at
least its not mentioned in the book anywhere and I've
never seen/used it personally.

>> When I type print tr('some string') in PyShell that comes with 
>> wxPython, no
>> error. But if I type that line in a .py file and run it, I get an 
>> error:
>> NameError: name 'tr' is not defined

To the OP:
Are you importing any other modules? Is this a specific application's
code you are looking at?

Alan G. 



From alan.gauld at btinternet.com  Fri Jul  4 18:36:59 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 4 Jul 2008 17:36:59 +0100
Subject: [Tutor] open-file GUI
References: <957526FB6E347743AAB42B212AB54FDA95BB47@NANAMAILBACK1.nanamail.co.il>
Message-ID: <g4ljji$3cn$1@ger.gmane.org>


"Eli Brosh" <ebrosh at nana10.co.il> wrote 

> I need a simple GUI that can help me to open files 
> and save file i.e. something similar to uigetfile in MATLAB.

Google for easygui I think it will do what you want.

Otherwise any GUI toolkit will have similar dialiogs but 
will require that you write a full GUI app. EasyGUI 
can be mixed with command line output.

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  Fri Jul  4 18:43:07 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 4 Jul 2008 17:43:07 +0100
Subject: [Tutor] tic tac toe
References: <689419.65550.qm@web45615.mail.sp1.yahoo.com>
Message-ID: <g4ljv2$4i0$1@ger.gmane.org>

"Akanskha Kumar" <akanksha.kumar14 at yahoo.com> wrote

> how can i make tic tac toe game using python programing.

Do you know how to program at all?
How much Python do you know?

Is this a homework assignment?

We need to know of these before we can give you the best answer.

If you are experienced uin programming then the anser is probably
to define a 2D table for the grid, capture the rules in a function and
then apply the rules to the table - parameterised by the users inputs.

Alan G. 



From chester_lab at fltg.net  Fri Jul  4 18:48:46 2008
From: chester_lab at fltg.net (FT)
Date: Fri, 4 Jul 2008 12:48:46 -0400
Subject: [Tutor] open-file GUI
References: <957526FB6E347743AAB42B212AB54FDA95BB47@NANAMAILBACK1.nanamail.co.il>
Message-ID: <004201c8ddf5$d97f3e20$0501a8c0@brucetower>


Hi!
    My demo is from wspython.



Hello,
I am starting to use Python+NumPy+SciPy+Matplotlib as a substitute to MATLAB.

I need a simple GUI that can help me to open files and save file i.e. something similar to uigetfile in MATLAB.
Is there a simple script that opens a window with a possibility to browse through the file system and pick an ASCII file ?
After the file is spcified using the GUI, I want to read it using fromfile and similar commands.
After I process the data I want a similar GUI that enables choosing the path and name for saving the results file.

Are scripts of this type available ?

Thanks
Eli Brosh


This method allows you to either display the last file name or change the fn to "" for an open command so it does not display the file name. Then fn assignment commented out...



    def setFilePath(self, type4file=""):
        " Search directory for path and file name!"
        fn=self.filename
        t4f = wx.OPEN
        if type4file[0] in "sS":
            t4f = wx.SAVE|wx.FD_OVERWRITE_PROMPT
#            fn = self.filename
        dlg = wx.FileDialog(self, self.filename +" or Choose a file",
self.dirname, fn, "*.*", t4f)
        if dlg.ShowModal() == wx.ID_OK:
            self.filename = dlg.GetFilename()
            self.dirname = dlg.GetDirectory()
        dlg.Destroy()

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080704/489a347f/attachment-0001.htm>

From monjissvel at googlemail.com  Fri Jul  4 19:33:13 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Fri, 4 Jul 2008 17:33:13 +0000
Subject: [Tutor] open-file GUI
In-Reply-To: <e2f191310807041032m20c6d063w2672fb7077c91ac1@mail.gmail.com>
References: <957526FB6E347743AAB42B212AB54FDA95BB47@NANAMAILBACK1.nanamail.co.il>
	<e2f191310807041032m20c6d063w2672fb7077c91ac1@mail.gmail.com>
Message-ID: <e2f191310807041033h14c36d5dn7c8531d9b1e1b1a3@mail.gmail.com>

Go for wxPython, they have a pretty good tutorial on thier website (
wxpython.org)
If you can use Python_Numpy_Scipy_Matplotlib  then I can assure you that
you  will learn wxpython in a matter of minutes.


>
> 2008/7/4 Eli Brosh <ebrosh at nana10.co.il>:
>
>>  Hello,
>> I am starting to use Python+NumPy+SciPy+Matplotlib as a substitute to
>> MATLAB.
>>
>> I need a simple GUI that can help me to open files and save file *i.e.** something
>> similar to uigetfile in MATLAB*.
>> Is there a simple script that opens a window with a possibility to browse
>> through the file system and pick an ASCII file ?
>> After the file is spcified using the GUI, I want to read it using fromfile
>> and similar commands.
>> After I process the data I want a similar GUI that enables choosing the
>> path and name for saving the results file.
>>
>> Are scripts of this type available ?
>>
>> Thanks
>> Eli Brosh
>>
>> _______________________________________________
>> 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/20080704/b57cd33d/attachment.htm>

From bhaaluu at gmail.com  Fri Jul  4 19:43:57 2008
From: bhaaluu at gmail.com (bhaaluu)
Date: Fri, 4 Jul 2008 13:43:57 -0400
Subject: [Tutor] tic tac toe
In-Reply-To: <689419.65550.qm@web45615.mail.sp1.yahoo.com>
References: <689419.65550.qm@web45615.mail.sp1.yahoo.com>
Message-ID: <ea979d70807041043h2938394emaed8fc4e3333bba2@mail.gmail.com>

On Fri, Jul 4, 2008 at 12:14 PM, Akanskha Kumar
<akanksha.kumar14 at yahoo.com> wrote:
> how can i make tic tac toe game using python programing.
>

There is an excellent tic-tac-toe tutorial in Michael Dawson's book,
Python Programming for the Absolute Beginner Second Edition
(ISBN-13: 978-1-59863-112-8).Chapter 6, pages 159-191.

Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m
In a world without fences, who needs Gates?
Kid on Bus: What are you gonna do today, Napoleon?
Napoleon Dynamite: Whatever I feel like I wanna do. Gosh!

From monjissvel at googlemail.com  Fri Jul  4 19:49:11 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Fri, 4 Jul 2008 17:49:11 +0000
Subject: [Tutor] Init Scripts
In-Reply-To: <b6131fdc0807040157x6d59ff3dr4d1c13c022c78dd6@mail.gmail.com>
References: <b6131fdc0807040157x6d59ff3dr4d1c13c022c78dd6@mail.gmail.com>
Message-ID: <e2f191310807041049y3b577a1an7a731449290d9e82@mail.gmail.com>

IMHO the Linux OS itself relays heavily on python in some way or the other,
but as far as the boot process is concerned I think you should consider the
fact that it was engeneered by very smart poeple, very security aware
poeple, so you will have to give a really good ALTERNATIVE to thier
engeneering to compete with them, I would suggest you move to Debian instead
of Redhat, I think it's better but its a personal choice.

But the Modules that deal with this would be : os, sys, subprocess & many
other I don't know of :)





2008/7/4 Stephen Nelson-Smith <sanelson at gmail.com>:

> Hello,
>
> I've been wrestling with some badly written init scripts, and picking
> my way through the redhat init script system.  I'm getting to the
> point of thinking I could do this sort of thing in Python just as
> effectively.
>
> Are there any pointers available?  Eg libraries that give process
> information, so I can obtain status information?
>
> S.
> _______________________________________________
> 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/20080704/ae5ad850/attachment.htm>

From chester_lab at fltg.net  Fri Jul  4 19:59:10 2008
From: chester_lab at fltg.net (FT)
Date: Fri, 4 Jul 2008 13:59:10 -0400
Subject: [Tutor] open-file GUI
Message-ID: <001701c8ddff$eda93ef0$0501a8c0@brucetower>




Hi!
    My demo is from wspython.



Hello,
I am starting to use Python+NumPy+SciPy+Matplotlib as a substitute to MATLAB.

I need a simple GUI that can help me to open files and save file i.e. something similar to uigetfile in MATLAB.
Is there a simple script that opens a window with a possibility to browse through the file system and pick an ASCII file ?
After the file is spcified using the GUI, I want to read it using fromfile and similar commands.
After I process the data I want a similar GUI that enables choosing the path and name for saving the results file.

Are scripts of this type available ?

Thanks
Eli Brosh
 

This method allows you to either display the last file name or change the fn to "" for an open command so it does not display the file name. Then fn assignment commented out... 

        self.dirname=os.getcwd()  #SEARCH FROM PRESENT DIRECTORY!
        self.filename="" 

    def setFilePath(self, type4file=""):
        " Search directory for path and file name!"
        fn=self.filename
        t4f = wx.OPEN
        if type4file[0] in "sS":
            t4f = wx.SAVE|wx.FD_OVERWRITE_PROMPT
#            fn = self.filename
        dlg = wx.FileDialog(self, self.filename +" or Choose a file",
self.dirname, fn, "*.*", t4f)
        if dlg.ShowModal() == wx.ID_OK:
            self.filename = dlg.GetFilename()
            self.dirname = dlg.GetDirectory()
        dlg.Destroy()

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080704/0712c339/attachment.htm>

From chester_lab at fltg.net  Fri Jul  4 20:11:27 2008
From: chester_lab at fltg.net (FT)
Date: Fri, 4 Jul 2008 14:11:27 -0400
Subject: [Tutor] open-file GUI
Message-ID: <003d01c8de01$656e4c40$0501a8c0@brucetower>


Hi!
    My demo is from wspython. The Hebrew window messed up my reading and now
I have included the imports and the initial assignment. You can place them
in caps for global vars, but place them inside a class so they are
self...calls.



Hello,
I am starting to use Python+NumPy+SciPy+Matplotlib as a substitute to
MATLAB.

I need a simple GUI that can help me to open files and save file i.e.
something similar to uigetfile in MATLAB.
Is there a simple script that opens a window with a possibility to browse
through the file system and pick an ASCII file ?
After the file is spcified using the GUI, I want to read it using fromfile
and similar commands.
After I process the data I want a similar GUI that enables choosing the path
and name for saving the results file.

Are scripts of this type available ?

Thanks
Eli Brosh



This method allows you to either display the last file name or change the fn
to "" for an open command so it does not display the file name. Then fn
assignment commented out...

import wx
import os


dirname=os.getcwd()  #SEARCH FROM PRESENT DIRECTORY!
filename=""

    def setFilePath(self, type4file=""):
        " Search directory for path and file name!"
        fn=self.filename
        t4f = wx.OPEN
        if type4file[0] in "sS":
            t4f = wx.SAVE|wx.FD_OVERWRITE_PROMPT
#            fn = self.filename
        dlg = wx.FileDialog(self, self.filename +" or Choose a file",
self.dirname, fn, "*.*", t4f)
        if dlg.ShowModal() == wx.ID_OK:
            self.filename = dlg.GetFilename()
            self.dirname = dlg.GetDirectory()
        dlg.Destroy()



From ebrosh at nana10.co.il  Fri Jul  4 21:01:37 2008
From: ebrosh at nana10.co.il (Eli Brosh)
Date: Fri, 4 Jul 2008 22:01:37 +0300
Subject: [Tutor] open-file GUI
References: <003d01c8de01$656e4c40$0501a8c0@brucetower>
Message-ID: <957526FB6E347743AAB42B212AB54FDA95BB48@NANAMAILBACK1.nanamail.co.il>

 
Many thanks for the tutor mailing-list members for their replies,
The EasyGui is just what I was looking for.
 
Regards
Eli Brosh
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080704/c58921d5/attachment-0001.htm>

From monjissvel at googlemail.com  Fri Jul  4 21:54:23 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Fri, 4 Jul 2008 19:54:23 +0000
Subject: [Tutor] graphs & diagrams in python
Message-ID: <e2f191310807041254i518e93bfsa35c6a30e86e036d@mail.gmail.com>

Hi Again,

What is the best library for drawing graphs & diagrams to ilustrate some
statistics ?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080704/a524869f/attachment.htm>

From optomatic at rogers.com  Fri Jul  4 22:02:19 2008
From: optomatic at rogers.com (Patrick)
Date: Fri, 04 Jul 2008 16:02:19 -0400
Subject: [Tutor] graphs & diagrams in python
In-Reply-To: <e2f191310807041254i518e93bfsa35c6a30e86e036d@mail.gmail.com>
References: <e2f191310807041254i518e93bfsa35c6a30e86e036d@mail.gmail.com>
Message-ID: <486E81CB.6060103@rogers.com>

Hey Monika

How about Matplotlib AKA Pylab?
http://matplotlib.sourceforge.net/
-Patrick

Monika Jisswel wrote:
> Hi Again,
>
> What is the best library for drawing graphs & diagrams to ilustrate 
> some statistics ?
>
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From nickle84_24 at hotmail.com  Fri Jul  4 23:15:40 2008
From: nickle84_24 at hotmail.com (Nick Marmion)
Date: Fri, 4 Jul 2008 15:15:40 -0600
Subject: [Tutor] pygame event.type == QUIT
In-Reply-To: <mailman.752.1215198211.20627.tutor@python.org>
References: <mailman.752.1215198211.20627.tutor@python.org>
Message-ID: <BAY121-W3807AAA5D0994AD0E2EBE79C9B0@phx.gbl>


I am learning pygame using begining game development w/ python and pygame. 
I am doing 'Hello World Redux"  
#!/usr/bin/env python
background_image_filename = 'sushiplate.jpg'mouse_image_filename = 'fugu.png'
import pygamefrom pygame.locals import *from sys import exit
pygame.init()
screen = pygame.display.set_mode((640,480),0,32)pygame.display.set_caption("Hello, World")
background = pygame.image.load(background_image_filename).convert()mouse_cursor = pygame.image.load(mouse_image_filename).convert_alpha()
while True:
    for event in pygame.event.get():        if event.type == QUIT:            exit()
    screen.blit(background,(0,0))
    x,y = pygame.mouse.get_pos()    x -= mouse_cursor.get_width() / 2    y -= mouse_cursor.get_height() / 2    screen.blit(mouse_cursor, (x,y))
    pygame.display.update()This is the code and I am pretty sure it is same as in the book. 
but when I try to close the pygame window I get an error
Traceback (most recent call last):  File "C:\Python25\pythonGameProg\hellowworld redux.py", line 22, in <module>    exit()SystemExit
 
I am trying to figure out how to get the window to close without the error and to make it so I don't have to close the window by using the taskmanager.  Any susgestions would be very helpful. 
_________________________________________________________________
It?s a talkathon ? but it?s not just talk.
http://www.imtalkathon.com/?source=EML_WLH_Talkathon_JustTalk
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080704/c51b7ac3/attachment.htm>

From monjissvel at googlemail.com  Fri Jul  4 23:27:17 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Fri, 4 Jul 2008 21:27:17 +0000
Subject: [Tutor] directory traversal help
In-Reply-To: <1c2a2c590807030841i54c905e2r285bca7139686838@mail.gmail.com>
References: <486CCA44.6030708@mrfab.info>
	<1c2a2c590807030841i54c905e2r285bca7139686838@mail.gmail.com>
Message-ID: <e2f191310807041427i55a76547g286b38ce9de3c17c@mail.gmail.com>

the fact that it fails shoul be due to some windows restriction about trash
& some hidden files,
to bypass that you can add  a filter in here

def walk(dir):
  for name in os.listdir(dir):
      #the following line is the filter
      if name != 'Trash can' or name !=  'some hidden directory name':
          path = os.path.join(dir,name)
          if os.path.isfile(path):
               .....
      else:
          pass
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080704/fdf33b42/attachment.htm>

From kf9150 at gmail.com  Fri Jul  4 23:31:09 2008
From: kf9150 at gmail.com (Kelie)
Date: Fri, 4 Jul 2008 21:31:09 +0000 (UTC)
Subject: [Tutor] Where is this tr function?
References: <loom.20080704T101911-935@post.gmane.org>
	<1c2a2c590807040519i6a7ce563kb1e3c46fd6d351c2@mail.gmail.com>
Message-ID: <loom.20080704T212052-51@post.gmane.org>

Kent Johnson <kent37 <at> tds.net> writes:
> You have to find where tr() is being imported. From PyShell type
> tr.__module__
> that should print the name of the module containing tr().
> 

Thanks Kent. Actually it isn't PyShell. It is in Ulipad's (Ulipad is a freeware
code editor) Python shell. I followed your instruction and found out tr seems to
be an alias of the ugettext function in the gettext module. On my computer, it
is this file: C:\Python25\Lib\gettext.py. Apparently it is for
internationalization and localization support. 

Thanks again.





From kf9150 at gmail.com  Fri Jul  4 23:33:01 2008
From: kf9150 at gmail.com (Kelie)
Date: Fri, 4 Jul 2008 21:33:01 +0000 (UTC)
Subject: [Tutor] Where is this tr function?
References: <loom.20080704T101911-935@post.gmane.org>
	<1c2a2c590807040519i6a7ce563kb1e3c46fd6d351c2@mail.gmail.com>
	<g4ljg5$32j$1@ger.gmane.org>
Message-ID: <loom.20080704T213212-151@post.gmane.org>

Alan Gauld <alan.gauld <at> btinternet.com> writes:
> To the OP:
> Are you importing any other modules? Is this a specific application's
> code you are looking at?
> 

Thanks Alan. You're right. I was reading Ulipad's source code.



From bgailer at gmail.com  Fri Jul  4 23:50:56 2008
From: bgailer at gmail.com (bob gailer)
Date: Fri, 04 Jul 2008 17:50:56 -0400
Subject: [Tutor] file object in memory
In-Reply-To: <e2f191310807040916q447b6145xf797f03171f91490@mail.gmail.com>
References: <e2f191310807040916q447b6145xf797f03171f91490@mail.gmail.com>
Message-ID: <486E9B40.5080708@gmail.com>

Monika Jisswel wrote:
> Hi everyone,
>
> In my program I have this code :
>
>     self.run_cmd_0 = subprocess.Popen(self.cmd_0, stdout =
>     subprocess.PIPE, shell = True)     #(1)
>     self.run_cmd_1 = subprocess.Popen(self.TOCOL, stdin =
>     self.run_cmd_0.stdout, stdout = subprocess.PIPE, shell = True)    #(2)
>     self.result_0 =
>     StringIO.StringIO(self.run_cmd_1.communicate()[0])      #(3)
>
>
> (1) :  executes cmd_0 as a subprocess with stdout to PIPE
> (2) : executes cmd_1 a second process with stdin from the previouse cmd_0
> (3) : Here I tried to use StringIO module to create a file object from 
> stdout of cmd_1 : I need a file object because I have a mysql query 
> later in my program to load it into the database :
>
>     self.cmd_sql_2 = "load data local infile '%s' into table
>     statistics fields terminated by '\t' lines terminated by '\n'" %
>     self.FILE 
>
>
> so self.cur.execute(self.cmd_sql_2) fails.
> the problem is that  mysql  is expecting a REAL file for this query !! 
> is there any pythonic way of avoiding to write to disk before loading 
> into Mysql database ? some sort of in-memory file oject.

I don't think there is a pure Pythonic way. Have you considered using a 
RamDisk? http://en.wikipedia.org/wiki/RAM_disk for general details.

http://www.codeguru.com/cpp/w-p/system/devicedriverdevelopment/article.php/c5789/ 
for a Windows Ram Disk driver installer. I just tried it - it works like 
a charm.

HTH.

-- 
Bob Gailer
919-636-4239 Chapel Hill, NC


From monjissvel at googlemail.com  Sat Jul  5 00:18:59 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Fri, 4 Jul 2008 22:18:59 +0000
Subject: [Tutor] file object in memory
In-Reply-To: <486E9B40.5080708@gmail.com>
References: <e2f191310807040916q447b6145xf797f03171f91490@mail.gmail.com>
	<486E9B40.5080708@gmail.com>
Message-ID: <e2f191310807041518x4da72763q9636d44d8debea32@mail.gmail.com>

You know bob, you are very clever, I have used RAM disk for realtime
recording of audio before but it never occured to me to use it for light
jobs like this one, I just compeletely ignored it as an option & by the way
this openes a lot of doors for many of my other programs.

but wouldn't it be very nice if there  was a way of creating a file object
inside python ? something like :
myfile = mkfile('some_string')
& we're done ?


I don't think there is a pure Pythonic way. Have you considered using a
> RamDisk? http://en.wikipedia.org/wiki/RAM_disk for general details.
>
>
> http://www.codeguru.com/cpp/w-p/system/devicedriverdevelopment/article.php/c5789/for a Windows Ram Disk driver installer. I just tried it - it works like a
> charm.
>
> HTH.
>
> --
> Bob Gailer
> 919-636-4239 Chapel Hill, NC
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080704/ec870243/attachment.htm>

From bgailer at gmail.com  Sat Jul  5 02:12:31 2008
From: bgailer at gmail.com (bob gailer)
Date: Fri, 04 Jul 2008 20:12:31 -0400
Subject: [Tutor] file object in memory
In-Reply-To: <e2f191310807041518x4da72763q9636d44d8debea32@mail.gmail.com>
References: <e2f191310807040916q447b6145xf797f03171f91490@mail.gmail.com>	
	<486E9B40.5080708@gmail.com>
	<e2f191310807041518x4da72763q9636d44d8debea32@mail.gmail.com>
Message-ID: <486EBC6F.6000106@gmail.com>

Monika Jisswel wrote:
> You know bob, you are very clever

Yes. I've observed that before.
> , I have used RAM disk for realtime recording of audio before but it 
> never occured to me to use it for light jobs like this one, I just 
> compeletely ignored it as an option & by the way this openes a lot of 
> doors for many of my other programs.

Oh good.
>
> but wouldn't it be very nice if there  was a way of creating a file 
> object inside python ? something like :
> myfile = mkfile('some_string')

The trick is getting the os to see this object as a disk drive. My 
limited research reveals only ram disk as a way to do that.



-- 
Bob Gailer
919-636-4239 Chapel Hill, NC


From kent37 at tds.net  Sat Jul  5 15:16:38 2008
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 5 Jul 2008 09:16:38 -0400
Subject: [Tutor] graphs & diagrams in python
In-Reply-To: <e2f191310807041254i518e93bfsa35c6a30e86e036d@mail.gmail.com>
References: <e2f191310807041254i518e93bfsa35c6a30e86e036d@mail.gmail.com>
Message-ID: <1c2a2c590807050616i402dc7bfy63f8809f2fc8eb09@mail.gmail.com>

On Fri, Jul 4, 2008 at 3:54 PM, Monika Jisswel
<monjissvel at googlemail.com> wrote:
> Hi Again,
>
> What is the best library for drawing graphs & diagrams to ilustrate some
> statistics ?

A few possibilities here:
http://wiki.python.org/moin/GraphicsAndImages

Kent

From jtp at nc.rr.com  Sat Jul  5 16:57:40 2008
From: jtp at nc.rr.com (James)
Date: Sat, 5 Jul 2008 10:57:40 -0400
Subject: [Tutor] loops, variables and strings
Message-ID: <e107b4ff0807050757v265a6b26y6155e053042e0245@mail.gmail.com>

All,

I'm trying to do something pretty simple, but I can't seem to get
Python to behave nicely. :)

I'd like to automate a script that sends out three or four lists in an
e-mail. I have a function dedicated to sending e-mail that will take a
string variable, slap it in a message, and send it on its merry way.

The issue, however, is that I can't format the string I want
correctly. I'd like to do something similar to the following:

myString = """Hello. Below is an automated e-mail with important statistics.

The following user accounts expired today:
<user1> - <Full Name>
<user2> - <Full Name 2>
...

The following user accounts will expire within the next 7 days:
<user3> - <Full Name 3>
<user4> - <Full Name 4>
...

The following user accounts will expire in the next month:
<user 5> - <Full Name 5>
<user 6> - <Full Name 6>"""

I've written some code that actually does include a list of users, like this:

myString = """Hello. Below is an automated e-mail with important statistics.

The following user accounts expired today:
%s

The following user accounts will expire within the next 7 days:
%s

The following user accounts will expire in the next month:
%s""" % (expiredAccounts,toExpire7,toExpire30,),

Of course in this scenario, the variables in the parenthesis are
strings with newlines in them. But when I do a 'print myString', it
shows everything in one line, including the '\n' characters at the end
of every user account listed.

Thoughts on what I may be doing wrong?

Thanks!
- j

From nathan.farrar at gmail.com  Sat Jul  5 19:07:18 2008
From: nathan.farrar at gmail.com (Nathan Farrar)
Date: Sat, 05 Jul 2008 11:07:18 -0600
Subject: [Tutor] Script Name/Path Information
Message-ID: <1215277638.6950.12.camel@poisontongue>

I'm new to python and wondering if there is a way to reference
information about the script that is running.  For example, if I was
running a script named "FileInfo.py" from the directory
"/home/username", I'm looking for attributes such that something similar
to:

print self.name
print self.path

would output:

FileInfo.py
/home/username

... Thanks!  
Nathan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080705/997d9715/attachment.htm>

From monjissvel at googlemail.com  Sat Jul  5 20:00:39 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Sat, 5 Jul 2008 18:00:39 +0000
Subject: [Tutor] Script Name/Path Information
In-Reply-To: <1215277638.6950.12.camel@poisontongue>
References: <1215277638.6950.12.camel@poisontongue>
Message-ID: <e2f191310807051100s3a2b018dn8b8a1e5b8e18a29b@mail.gmail.com>

import sys      #a module that gives access to the system
import os        #a module that gives access to the os

print sys.argv[0]   #prints file name of the script
print os.getcwd()   #print current working directory
print os.getcwd()+sys.argv[0]   #




2008/7/5 Nathan Farrar <nathan.farrar at gmail.com>:

>  I'm new to python and wondering if there is a way to reference information
> about the script that is running.  For example, if I was running a script
> named "FileInfo.py" from the directory "/home/username", I'm looking for
> attributes such that something similar to:
>
> print self.name
> print self.path
>
> would output:
>
> FileInfo.py
> /home/username
>
> ... Thanks!
> Nathan
>
> _______________________________________________
> 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/20080705/14613b12/attachment.htm>

From monjissvel at googlemail.com  Sat Jul  5 20:11:04 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Sat, 5 Jul 2008 18:11:04 +0000
Subject: [Tutor] loops, variables and strings
In-Reply-To: <e107b4ff0807050757v265a6b26y6155e053042e0245@mail.gmail.com>
References: <e107b4ff0807050757v265a6b26y6155e053042e0245@mail.gmail.com>
Message-ID: <e2f191310807051111y69367435h877346c80a96ce95@mail.gmail.com>

maybe StringIO ?

MsgBody = StringIO.StringIO()
print >> MsgBody, "Hello. Below is an automated e-mail with important
statistics."
print >> MsgBody, ""        #empty line
print >> MsgBody, ""        #empty line
print >> MsgBody, "The following user accounts expired today:"
print >> MsgBody, "<user1> - <Full Name>" % (var1, Name1)
print >> MsgBody, "<user2> - <Full Name 2>" % (var2, Name2)
...
< More code here >
...

MSGBODY = MsgBody.getvalue()  # use MSGBODY in you Email.




2008/7/5 James <jtp at nc.rr.com>:

> All,
>
> I'm trying to do something pretty simple, but I can't seem to get
> Python to behave nicely. :)
>
> I'd like to automate a script that sends out three or four lists in an
> e-mail. I have a function dedicated to sending e-mail that will take a
> string variable, slap it in a message, and send it on its merry way.
>
> The issue, however, is that I can't format the string I want
> correctly. I'd like to do something similar to the following:
>
> myString = """Hello. Below is an automated e-mail with important
> statistics.
>
> The following user accounts expired today:
> <user1> - <Full Name>
> <user2> - <Full Name 2>
> ...
>
> The following user accounts will expire within the next 7 days:
> <user3> - <Full Name 3>
> <user4> - <Full Name 4>
> ...
>
> The following user accounts will expire in the next month:
> <user 5> - <Full Name 5>
> <user 6> - <Full Name 6>"""
>
> I've written some code that actually does include a list of users, like
> this:
>
> myString = """Hello. Below is an automated e-mail with important
> statistics.
>
> The following user accounts expired today:
> %s
>
> The following user accounts will expire within the next 7 days:
> %s
>
> The following user accounts will expire in the next month:
> %s""" % (expiredAccounts,toExpire7,toExpire30,),
>
> Of course in this scenario, the variables in the parenthesis are
> strings with newlines in them. But when I do a 'print myString', it
> shows everything in one line, including the '\n' characters at the end
> of every user account listed.
>
> Thoughts on what I may be doing wrong?
>
> Thanks!
> - j
> _______________________________________________
> 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/20080705/3a81ec6d/attachment.htm>

From bgailer at gmail.com  Sat Jul  5 20:21:20 2008
From: bgailer at gmail.com (bob gailer)
Date: Sat, 05 Jul 2008 14:21:20 -0400
Subject: [Tutor] loops, variables and strings
In-Reply-To: <e107b4ff0807050757v265a6b26y6155e053042e0245@mail.gmail.com>
References: <e107b4ff0807050757v265a6b26y6155e053042e0245@mail.gmail.com>
Message-ID: <486FBBA0.4000200@gmail.com>

James wrote:
> All,
>
> I'm trying to do something pretty simple, but I can't seem to get
> Python to behave nicely. :)
>
> I'd like to automate a script that sends out three or four lists in an
> e-mail. I have a function dedicated to sending e-mail that will take a
> string variable, slap it in a message, and send it on its merry way.
>
> The issue, however, is that I can't format the string I want
> correctly. I'd like to do something similar to the following:
>
> myString = """Hello. Below is an automated e-mail with important statistics.
>
> The following user accounts expired today:
> <user1> - <Full Name>
> <user2> - <Full Name 2>
> ...
>
> The following user accounts will expire within the next 7 days:
> <user3> - <Full Name 3>
> <user4> - <Full Name 4>
> ...
>
> The following user accounts will expire in the next month:
> <user 5> - <Full Name 5>
> <user 6> - <Full Name 6>"""
>
> I've written some code that actually does include a list of users, like this:
>
> myString = """Hello. Below is an automated e-mail with important statistics.
>
> The following user accounts expired today:
> %s
>
> The following user accounts will expire within the next 7 days:
> %s
>
> The following user accounts will expire in the next month:
> %s""" % (expiredAccounts,toExpire7,toExpire30,),
>
>   
Remove the trailing , in the last line. It is causing myString to be a 
tuple.

> Of course in this scenario, the variables in the parenthesis are
> strings with newlines in them. But when I do a 'print myString', it
> shows everything in one line, including the '\n' characters at the end
> of every user account listed.
>
> Thoughts on what I may be doing wrong?


-- 
Bob Gailer
919-636-4239 Chapel Hill, NC


From nathan.farrar at gmail.com  Sat Jul  5 20:23:36 2008
From: nathan.farrar at gmail.com (Nathan Farrar)
Date: Sat, 05 Jul 2008 12:23:36 -0600
Subject: [Tutor] Exploring the Standard Library
Message-ID: <1215282216.6950.27.camel@poisontongue>

I'd like to spend some time exploring the standard library.  I'm running
python on Ubuntu.  How would I find the location of the modules (find /
-name "os.py" does not yield results)?

Thanks!
Nathan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080705/38dd00a5/attachment-0001.htm>

From amingv at gmail.com  Sat Jul  5 20:43:21 2008
From: amingv at gmail.com (amingv at gmail.com)
Date: Sat, 5 Jul 2008 18:43:21 +0000 (GMT)
Subject: [Tutor] Exploring the Standard Library
In-Reply-To: <1215282216.6950.27.camel@poisontongue>
Message-ID: <74445771215283401463@fastmobile.com>

The python interpreter can give you this information; just type:

import sys
for i in sys.path:
    print i

And search in the lib directories it shows.

You might also be interested in the std library reference at docs.python.org.

--
Amin Rainmaker
-------------- next part --------------
An embedded message was scrubbed...
From: Nathan Farrar <nathan.farrar at gmail.com>
Subject: [Tutor] Exploring the Standard Library
Date: Sat, 05 Jul 2008 12:23:36 -0600
Size: 5104
URL: <http://mail.python.org/pipermail/tutor/attachments/20080705/aba7be57/attachment.eml>

From monjissvel at googlemail.com  Sat Jul  5 20:43:33 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Sat, 5 Jul 2008 18:43:33 +0000
Subject: [Tutor] Exploring the Standard Library
In-Reply-To: <1215282216.6950.27.camel@poisontongue>
References: <1215282216.6950.27.camel@poisontongue>
Message-ID: <e2f191310807051143m1ac5939fib0411267dfaa050e@mail.gmail.com>

import sys
print sys.path

but no one recommends starting with python from there. you're better of
reading the python.org/doc files.



2008/7/5 Nathan Farrar <nathan.farrar at gmail.com>:

>  I'd like to spend some time exploring the standard library.  I'm running
> python on Ubuntu.  How would I find the location of the modules (find /
> -name "os.py" does not yield results)?
>
> Thanks!
> Nathan
>
> _______________________________________________
> 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/20080705/0256967e/attachment.htm>

From steve at alchemy.com  Sat Jul  5 20:59:57 2008
From: steve at alchemy.com (Steve Willoughby)
Date: Sat, 05 Jul 2008 11:59:57 -0700
Subject: [Tutor] Script Name/Path Information
In-Reply-To: <e2f191310807051100s3a2b018dn8b8a1e5b8e18a29b@mail.gmail.com>
References: <1215277638.6950.12.camel@poisontongue>
	<e2f191310807051100s3a2b018dn8b8a1e5b8e18a29b@mail.gmail.com>
Message-ID: <486FC4AD.7060300@alchemy.com>

Monika Jisswel wrote:
> import sys      #a module that gives access to the system
> import os        #a module that gives access to the os
> 
> print sys.argv[0]   #prints file name of the script
> print os.getcwd()   #print current working directory
> print os.getcwd()+sys.argv[0]   #

but os.getcwd() returns the current working directory, not necessarily 
the directory containing the script.  os.getcwd()+sys.argv[0] will quite 
often not yield a useful result.  Even if it did, os.path.join is better 
than + when joining pathnames.

> 
> 
> 
> 
> 2008/7/5 Nathan Farrar <nathan.farrar at gmail.com>:
> 
>>  I'm new to python and wondering if there is a way to reference information
>> about the script that is running.  For example, if I was running a script
>> named "FileInfo.py" from the directory "/home/username", I'm looking for
>> attributes such that something similar to:
>>
>> print self.name
>> print self.path
>>
>> would output:
>>
>> FileInfo.py
>> /home/username
>>
>> ... Thanks!
>> Nathan
>>
>> _______________________________________________
>> 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 muchanek at gmail.com  Sat Jul  5 23:02:06 2008
From: muchanek at gmail.com (kinuthiA muchanE)
Date: Sun, 06 Jul 2008 00:02:06 +0300
Subject: [Tutor] Tutor Digest, Vol 53, Issue 18
In-Reply-To: <mailman.995.1215282229.20627.tutor@python.org>
References: <mailman.995.1215282229.20627.tutor@python.org>
Message-ID: <1215291726.5850.10.camel@www.kinuthia.com>


On Sat, 2008-07-05 at 20:23 +0200, tutor-request at python.org wrote:
> Message: 7
> Date: Sat, 05 Jul 2008 12:23:36 -0600
> From: Nathan Farrar <nathan.farrar at gmail.com>
> Subject: [Tutor] Exploring the Standard Library
> To: Python Tutor <tutor at python.org>
> Message-ID: <1215282216.6950.27.camel at poisontongue>
> Content-Type: text/plain; charset="us-ascii"
> 
> I'd like to spend some time exploring the standard library.  I'm
> running
> python on Ubuntu.  How would I find the location of the modules
> (find /
> -name "os.py" does not yield results)?
In Ubuntu, you can find all the documentation in the /usr/share/doc
directory. Therefore, for python you will find it
in /usr/share/doc/python. Furthermore, to find the location of some
documentation, in the terminal enter dpkg -L <package-name>, in your
case, just type dpkg -L python and you will be rewarded with paths for
all python related documentation.

Does this help?
Kinuthia...
> 
> Thanks!
> Nathan


From rosenville at gmail.com  Sat Jul  5 23:05:10 2008
From: rosenville at gmail.com (Josh Rosen)
Date: Sat, 5 Jul 2008 14:05:10 -0700
Subject: [Tutor] Script Name/Path Information
In-Reply-To: <e2f191310807051100s3a2b018dn8b8a1e5b8e18a29b@mail.gmail.com>
References: <1215277638.6950.12.camel@poisontongue>
	<e2f191310807051100s3a2b018dn8b8a1e5b8e18a29b@mail.gmail.com>
Message-ID: <48B0313F-7B16-4FD5-B5A0-A56D60B8AED1@gmail.com>

How about the following:

import os
print os.path.abspath(__file__)		# the full absolute path to the  
current module's file
print os.path.split(os.path.abspath(__file__))		# if you need the  
individual components of the path.


On Jul 5, 2008, at 11:00 AM, Monika Jisswel wrote:

> import sys      #a module that gives access to the system
> import os        #a module that gives access to the os
>
> print sys.argv[0]   #prints file name of the script
> print os.getcwd()   #print current working directory
> print os.getcwd()+sys.argv[0]   #
>
>
>
>
> 2008/7/5 Nathan Farrar <nathan.farrar at gmail.com>:
> I'm new to python and wondering if there is a way to reference  
> information about the script that is running.  For example, if I was  
> running a script named "FileInfo.py" from the directory "/home/ 
> username", I'm looking for attributes such that something similar to:
>
> print self.name
> print self.path
>
> would output:
>
> FileInfo.py
> /home/username
>
> ... Thanks!
> Nathan
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080705/ca2bb18a/attachment.htm>

From gonzillaaa at gmail.com  Sun Jul  6 00:37:04 2008
From: gonzillaaa at gmail.com (Gonzalo Garcia-Perate)
Date: Sat, 5 Jul 2008 23:37:04 +0100
Subject: [Tutor] module paths
Message-ID: <6b6a049d0807051537p1dfdc8b9r995a06d10365f783@mail.gmail.com>

I'm looking at python after a long time. I wanted to build a quick
parser for some rss feeds and have started using feedparser.

When I test my code on the python interactive shell things work fine
but when I try to write it into a file I get the following error:
AttributeError: 'module' object has no attribute 'parse'

this is what I run on the shell:
import feedparser
>>> d = feedparser.parse("http://tedblog.typepad.com/tedblog/atom.xml")
>>> d
{'feed': {'updated': u'2008-07-04T14:11:15Z', 'updated_parsed': (2008,
7, 4, 14, 11, 15, 4, 186, 0), 'links': [{'href':
u'http://blog.ted.com/', 'type': u'text/html', 'rel': u'alternate'},
{'href': u'http://feeds.feedburner.com/TEDBlog', 'type':
u'application/atom+xml', 'rel': u'self'}], 'title': u'TED | TEDBlog',
etc.....

This is what my script (which fails looks like...):
#!/usr/local/bin/python
import feedparser

d = feedparser.parse("http://tedblog.typepad.com/tedblog/atom.xml")
d['feed']['title']

I'm trying to ring this form within textmate or form the terminal at
different locations as (./parse.py)

thanks

From agent.krycek at gmail.com  Sun Jul  6 00:50:35 2008
From: agent.krycek at gmail.com (Alex Krycek)
Date: Sat, 5 Jul 2008 16:50:35 -0600
Subject: [Tutor] Wave module
Message-ID: <a4f6ec110807051550n356f46deo93271bf28cb31217@mail.gmail.com>

Hello,

I'm trying to join two .wav files with the wave module. But when I try to
use wave.open(filename, "rb") I receive the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "F:\PortablePython1.0\lib\wave.py", line 483, in open
    return Wave_read(f)
  File "F:\PortablePython1.0\lib\wave.py", line 162, in __init__
    self.initfp(f)
  File "F:\PortablePython1.0\lib\wave.py", line 143, in initfp
    self._read_fmt_chunk(chunk)
  File "F:\PortablePython1.0\lib\wave.py", line 264, in _read_fmt_chunk
    raise Error, 'unknown format: %r' % (wFormatTag,)
wave.Error: unknown format: 85

I read somewhere that there are various wave formats, only some supported by
Python. Is this true? If so, is there any way I can convert my wave files
into a supported kind?


Thanks!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080705/21bcc562/attachment.htm>

From alan.gauld at btinternet.com  Sun Jul  6 01:52:14 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 6 Jul 2008 00:52:14 +0100
Subject: [Tutor] Tutor Digest, Vol 53, Issue 18
References: <mailman.995.1215282229.20627.tutor@python.org>
	<1215291726.5850.10.camel@www.kinuthia.com>
Message-ID: <g4p1fn$s2l$1@ger.gmane.org>


"kinuthiA muchanE" <muchanek at gmail.com> wrote

>> python on Ubuntu.  How would I find the location of the modules
>> (find /  -name "os.py" does not yield results)?

Not all modules are implemented as .py files.
Some are compiled C libraries. Thus searching 
for .py will not find all Python modules. Also you may only 
have the compiled python installed although thats less likely.

You can find any module by importing it and asking 
for its file:

>>> import os
>>> os.__file__
'/usr/lib/python2.5/os.pyc'
>>>

HTH,

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


From chester_lab at fltg.net  Sun Jul  6 05:37:16 2008
From: chester_lab at fltg.net (FT)
Date: Sat, 5 Jul 2008 23:37:16 -0400
Subject: [Tutor] Voice Text To Speech and Wav File Make and Save
Message-ID: <002001c8df19$9bb6bd00$0501a8c0@brucetower>


Hi!

    I got my text to speech to work better, will in the future remove the
buttons and only have the file menu.
    It seems to work fine and now use sub menu's for voice settings.

    What will be needed as an event to capture the cursor movement inside
the text box. How do I get the key and cursor events so I can speak when
doing ctrl cursor or up/down cursor events to say lines, words, and letters?
    I have tried getting the key event but gets ignored, so I need the
proper kind and location to catch the text box key events. I erased my test,
but below and attached are the complete setup.

        Bruce



desc="""Using two nested sizers, the main one with vertical layout
and the embedded one with horizontal layout
For setting voice parms:"""
#Editor.py
import wx
import os
import Sapi5
tts = Sapi5.Create( {"name":"Mary"})
purge = tts._purge
async = tts._async
punc = tts._punc
MN=0
ID=1
HK=2
KD=3
MF=4
MF2=5
DW_ID=1000
class MainWindow(wx.Frame):
    def __init__(self, parent, id, title):
        self.dirname=os.getcwd()  #SEARCH FROM PRESENT DIRECTORY!
        self.filename=""
        self.items4menu = {"File": [
            {MN:"Open", ID:102, HK:"&Open", KD:" Open a file to edit",
MF:self.OnOpen},
            {MN:"Save", ID:103, HK:"&Save", KD:" save file to disk",
MF:self.OnSave},
            {MN:"Edit", ID:104, HK:"&Edit", KD:" Do editing",
MF:self.OnEdit},
            {MN:"About", ID:101, HK:"&About", KD:" Information about this
program", MF:self.OnAbout},
            {MN:"Exit", ID:109, HK:"E&xit", KD:" Terminate the program",
MF:self.OnExit}
        ],  #END OF FILE MENU!
        "Voice": [
            {MN:"Read", ID:202, HK:"&Read", KD:" Open a file to read",
MF:self.OnWav2Read},
            {MN:"Save", ID:203, HK:"&Save", KD:" save text to audio file",
MF:self.OnSave2Wav},
            {MN:"Text", ID:204, HK:"Te&xt", KD:" read text field",
MF:self.OnRead},
            {MN:"Quit", ID:205, HK:"&Quit", KD:" Stop Reading",
MF:self.OnQuitRead}
        ],  #END OF VOICE MENU!
        "Settings": [
            {MN:"Voice", ID:302, HK:"&Speaker", KD:" Name for voice.",
MF:self.OnVoice, MF2:self.OnClick},
            {MN:"Rate", ID:303, HK:"&Rate", KD:" Rate for voice.",
MF:self.OnVoice, MF2:self.OnClick},
            {MN:"Pitch", ID:304, HK:"&Pitch", KD:" Pitch for voice.",
MF:self.OnVoice, MF2:self.OnClick},
            {MN:"Volume", ID:305, HK:"&Volume", KD:" Volume for voice.",
MF:self.OnVoice, MF2:self.OnClick}
        ],  #END OF SETTINGS MENU!
        "Down": [
            {MN:"Down", ID:DW_ID, HK:"&Down", KD:" Lower Setting.",
MF:self.OnVoice, MF2:self.OnClick}
        ]  #END OF DOWN MENU!
        }  #END OF ITEMS FOR MENU!
        self.buttons4voice = [
            {MN:"Voice", ID:111, HK:"&Voice", KD:" Voice Change",
MF:self.OnEnter, MF2:self.OnClick},
            {MN:"Rate", ID:112, HK:"&Rate", KD:" Rate For Voice Adjust",
MF:self.OnEnter, MF2:self.OnClick},
            {MN:"Pitch", ID:113, HK:"&Pitch", KD:" Pitch Of Voice Adjust",
MF:self.OnEnter, MF2:self.OnClick},
            {MN:"Volume", ID:114, HK:"&Loudness", KD:" Volume Loudness
Adjust", MF:self.OnEnter, MF2:self.OnClick}
        ]  #END OF ITEM FOR BUTTONS!
        wx.Frame.__init__(self, parent, wx.ID_ANY, title)
        self.control = wx.TextCtrl(self, 1, style=wx.TE_MULTILINE)
        self.CreateStatusBar()  #A Statusbar in the bottom of the window
        #Setting up the menu.
        filemenu = wx.Menu()
        for o in self.items4menu["File"]:
            filemenu.Append( o[ID], o[HK], o[KD])
            filemenu.AppendSeparator()
        voicemenu = wx.Menu()
        for o in self.items4menu["Voice"]:
            voicemenu.Append( o[ID], o[HK], o[KD])
            voicemenu.AppendSeparator()
        setting_menu = wx.Menu()
        for o in self.items4menu["Settings"]:
            down_menu = wx.Menu()
            down_menu.Append( o[ID], o[HK], o[KD])
            d = self.items4menu["Down"][0]
            down_menu.Append( d[ID]+o[ID], d[HK], d[KD])
            setting_menu.AppendMenu( o[ID], o[HK]+" Setting", down_menu)
            setting_menu.AppendSeparator()
        voicemenu.AppendMenu(-1, "&VoiceSettings", setting_menu)
        # Creating the menubar.
        menuBar = wx.MenuBar()
        menuBar.Append( filemenu,"&File") # Adding the "filemenu" to the
MenuBar
        menuBar.Append( voicemenu,"&Voice") # Adding the "voicemenu" to the
MenuBar
        self.SetMenuBar(menuBar)  # Adding the MenuBar to the Frame content.
        self.data4menu = {}
        for o in self.items4menu["File"]:
            wx.EVT_MENU(self, o[ID], o[MF])
            self.data4menu[ o[ID]] = o
        for o in self.items4menu["Voice"]:
            wx.EVT_MENU(self, o[ID], o[MF])
            self.data4menu[ o[ID]] = o
        for o in self.items4menu["Settings"]:
            wx.EVT_MENU(self, o[ID], o[MF])
            self.data4menu[ o[ID]] = o
            wx.EVT_MENU(self, o[ID]+DW_ID, o[MF])
            self.data4menu[ o[ID]+DW_ID] = o
        self.sizer2 = wx.BoxSizer(wx.HORIZONTAL)
        self.buttons=[]
        self.data4buttons={}
        i=0
        for o in self.buttons4voice:
            self.buttons.append( wx.Button(self, o[ID], o[HK]+o[KD]))
            self.sizer2.Add( self.buttons[i], 1, wx.EXPAND)
            self.data4buttons[ self.buttons[i].GetId()] = o
            self.buttons[i].Bind(wx.EVT_ENTER_WINDOW, o[MF]) #,
id=self.buttons[i].GetId())
            self.buttons[i].Bind( wx.EVT_RIGHT_DOWN, o[MF2]) #,
id=self.buttons[i].GetId())
            self.buttons[i].Bind( wx.EVT_BUTTON, o[MF2]) #,
id=self.buttons[i].GetId())
            i+=1
        # Use some sizers to see layout options
        self.sizer=wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.sizer2,0,wx.EXPAND)
        self.sizer.Add(self.control,1,wx.EXPAND)
        #Layout sizers
        self.SetSizer(self.sizer)
        self.SetAutoLayout(1)
        self.sizer.Fit(self)
        self.Show(1)
    def OnEnter(self, event):
        "WHEN ENTERING SAY LABEL OF BUTTON!"
#        self.button2bind = self.Bind(wx.EVT_BUTTON, self.OnClick,
id=event.GetId())
        eventType = event.GetEventType()
#        tts.Speak( event.GetPosition())
        label4btn = self.data4buttons[ event.GetId()][0]
#        tts.Speak( label4btn)
        if label4btn == "Voice":
            set_value = tts.getVoiceName()
        elif label4btn == "Rate":
            set_value = str( tts.getRate())
        elif label4btn == "Pitch":
            set_value = str( tts.getPitch())
        elif label4btn == "Volume":
            set_value = str( tts.getVolume())
        text = label4btn +" Button " +set_value
        tts.Speak( text, async, purge)
    def OnVoice(self, event):
        "CHECK IF DOWN KEY FOR VOICE SETTING!"
        wx.EVT_KEY_DOWN(self, self.OnClick)
        self.OnClick( event)
    def OnClick(self, event):
        "BUTTON CLICKED ON AND IN FUTURE GET BUTTON POS!"
#comment        tts.Speak( 'Event Name: %s Time Stamp: %s ' %
(event.GetClassName(), event.GetTimestamp()))
#comment        print 'Event Name: %s Time Stamp: %s ' %
(event.GetClassName(), event.GetTimestamp())
#comment IF KEY EVENT:
#comment        key = event.GetKeyCode()
#comment        pos = event.GetPositionTuple()
        eventType = event.GetEventType()
#comment        if eventType == wx.EVT_BUTTON: print "Mouse! "
        eventName = event.GetClassName()
        eventId = event.GetId()
#comment        self.control.SetValue( eventName)
#comment: CHECKING ID AND SETTING DIRECTION!
        if eventId in self.data4menu:
            label4btn = self.data4menu[ event.GetId()][0]
        else:
            label4btn = self.data4buttons[ event.GetId()][0]
        dir = 1
        if eventName == "wxMouseEvent" or eventId > DW_ID: dir = -1
        set_value = "Error! Wrong Button!"
        if label4btn == "Voice":
            value = tts.getVoiceNum() + dir
            if value < 1:               value += 0
            if value >= tts.getVoiceCount():
                value = tts.getVoiceCount()-1
            tts.setVoice( value)
            set_value = tts.getVoiceName()
        elif label4btn == "Rate":
            value = tts.getRate()
            value += dir
            if value > 10: value = 10
            if value < -10: value = -10
            tts.setRate( value)
            set_value = str( value)
        elif label4btn == "Pitch":
            value = tts.getPitch()
            value += dir
            if value > 10: value = 10
            if value < -10: value = -10
            tts.setPitch( value)
            set_value = str( value)
        elif label4btn == "Volume":
            value = tts.getVolume()
            value += 10*dir
            if value > 100: value = 100
            if value < 0:
                tts.setVolume( 50)
                tts.Speak( "Volume Minimum!")
                value = 0
            tts.setVolume( value)
            set_value = str( value)
        tts.Speak( set_value, async)
    def OnAbout(self,e):
        "A dialog box saying what the editor is about!"
        text = " A sample editor with voice \n in wxPython."
        tts.Speak( "About A Sample Editor!"+text)
        d= wx.MessageDialog( self, text, "About Sample Editor", wx.OK)
                            # Create a message dialog box
        d.ShowModal() # Shows it
        d.Destroy() # finally destroy it when finished.
    def OnExit(self,e):
        self.Close(True)  # Close the frame.
    def OnOpen(self,e):
        """ Open a file"""
        self.setFilePath( "o")
        f=open(os.path.join(self.dirname, self.filename),'r')
        self.control.SetValue(f.read())
        f.close()
    def OnSave(self,e):
        """ Save a file"""
        self.setFilePath( "s")
        f=open(os.path.join(self.dirname, self.filename),'w')
#       self.control.SetValue(f.read())
        f.write( self.control.GetValue())
        f.close()
    def setFilePath(self, type4file=""):
        " Search directory for path and file name!"
        fn=self.filename
        t4f = wx.OPEN
        if type4file[0] in "sS":
            t4f = wx.SAVE|wx.FD_OVERWRITE_PROMPT
#            fn = self.filename
        dlg = wx.FileDialog(self, self.filename +" or Choose a file",
self.dirname, fn, "*.*", t4f)
        if dlg.ShowModal() == wx.ID_OK:
            self.filename = dlg.GetFilename()
            self.dirname = dlg.GetDirectory()
        dlg.Destroy()
    def OnWav2Read(self,e):
        """ Open a file to read"""
        self.setFilePath( "o")
        tts.SpeakFromWav( os.path.join(self.dirname, self.filename), async,
purge)
    def OnSave2Wav(self,e):
        """ Save text to a wav file"""
        self.setFilePath( "s")
        tts.SpeakToWav( os.path.join(self.dirname, self.filename),
self.control.GetValue())
    def OnRead(self,e):
        """ Read the text"""
        tts.Speak( self.control.GetValue(), async, purge)
    def OnQuitRead(self,e):
        """ Quit the reading of the text"""
        tts.Speak( " Talking Stopped!", purge)
    def OnEdit(self,e):
        """ Edit the file"""
        self.control.SetFocus()
app = wx.PySimpleApp()
frame = MainWindow(None, -1, "Sample editor")
app.MainLoop()
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: Editor.py
URL: <http://mail.python.org/pipermail/tutor/attachments/20080705/0c067293/attachment-0002.txt>
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: Sapi5.py
URL: <http://mail.python.org/pipermail/tutor/attachments/20080705/0c067293/attachment-0003.txt>

From tpc247 at gmail.com  Sun Jul  6 06:03:58 2008
From: tpc247 at gmail.com (tpc247 at gmail.com)
Date: Sat, 5 Jul 2008 21:03:58 -0700
Subject: [Tutor] my first object model, using an interface
Message-ID: <bae1efdf0807052103t33422fc1tca2cd2e596a812dd@mail.gmail.com>

Dear fellow Python enthusiasts:

I want to run an idea by you to see if I understand modeling objects
adequately, after reading Alan Gauld's excellent tutorial and two brief
articles about interfaces in Python, here:

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

http://dirtsimple.org/2004/12/python-interfaces-are-not-java.html
                 http://nedbatchelder.com/text/pythonic-interfaces.html

I am attempting to model the following:
a correspondence school has asked me to help them solve a problem.  When the
school sends a student by mail a package containing several courses, each
course having several pieces of gradable homework, when a specific threshold
of homework completed and submitted by the student is met or exceeded,
another package is sent to the student by mail.  Now, this aforementioned
threshold, i.e., an integer indicating percentage, can vary, and is not just
for the totality of homework in the package, but also for certain courses
with many pieces of homework.  For example, say the school sends student Joe
a package (package_1) containing courses A, B and C_sub1.  A, B & C_sub1
have 10 pieces of gradable homework, and the school wants that we can set a
threshold for the totality of homework for package1, as well as a threshold
for C_sub1 alone.  When the thresholds are met or exceeded, independently,
then we send package_2 and C_sub2, respectively.  I envisioned a nascent
object model and noted the following observations:

- a Watchable interface that, when implemented, signifies that the
implementing object has a threshold and associated package.
- a Package class, that can be seen as a container for courses and/or one
part of a course
- a Course class, that can be seen as a container for gradable homework
- a Homework class, that has a flag to indicated whether it has been
received by the school
- most Packages are Watchable (except the last Package object), and only one
or two Courses in a Package need to be Watchable

Two questions:
1) Should I create a first-class Watchable interface object, and then have
my Package and Course objects implement it if they need to ?  If I start
with a Watchable interface, do I handle the name-space conflict, i.e.,
Package(object) vs Package(Watchable), by defining a Package class, and a
W_Package class that implements Watchable, and likewise for Course ?
2) am I even thinking the right way about attacking this problem ?  I am
curious what your experience in writing easy to maintain software might tell
you about my nascent object model.

class Watchable(object):
    def set_threshold(self, an_int):
        raise NotImplemented
    def get_threshold(self):
        raise NotImplemented
    def set_associated_load(self, a_load):
        raise NotImplemented
    def get_associated_load(self):
        raise NotImplemented

class Package(object):
    def __init__(self, courses):
        self.set_courses(courses)
    def set_courses(self, courses):
        self.courses = courses
    def get_courses(self):
        return self.courses

class Course(Watchable):
    def __init__(self, name, homework):
        self.name = name
        self.homework = homework
    def get_name(self):
        return self.name
    def get_homework(self):
        return self.homework

class Homework(object):
    def __init__(self, name):
        self.name = name
        self.academically_received = False
    def set_academically_received(self):
        self.academically_received = True
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080705/9f585546/attachment.htm>

From agent.krycek at gmail.com  Sun Jul  6 06:49:53 2008
From: agent.krycek at gmail.com (Alex Krycek)
Date: Sat, 5 Jul 2008 22:49:53 -0600
Subject: [Tutor] Wave error (solved)
Message-ID: <a4f6ec110807052149lecbd28ap2ad7372ba9067cfa@mail.gmail.com>

Per someone's suggestion I changed my wave files from 32 bit to 16 bit. I
can now open (and manipulate) them without any error. I'm not sure why it
worked but it worked.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080705/39bce2ad/attachment.htm>

From arsyed at gmail.com  Sun Jul  6 07:29:09 2008
From: arsyed at gmail.com (arsyed)
Date: Sun, 6 Jul 2008 01:29:09 -0400
Subject: [Tutor] Exploring the Standard Library
In-Reply-To: <1215282216.6950.27.camel@poisontongue>
References: <1215282216.6950.27.camel@poisontongue>
Message-ID: <9a2cc7a70807052229j70734e9ey733956ea7413664b@mail.gmail.com>

This might work:

>>> import os
>>> print os.__file__
c:\devtools\Python25\lib\os.pyc

Also, you might find Doug Hellman's "Python Module Of The Week" helpful:

http://www.doughellmann.com/projects/PyMOTW/




On 7/5/08, Nathan Farrar <nathan.farrar at gmail.com> wrote:
>
>  I'd like to spend some time exploring the standard library.  I'm running
> python on Ubuntu.  How would I find the location of the modules (find /
> -name "os.py" does not yield results)?
>
> Thanks!
> Nathan
>
> _______________________________________________
> 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/20080706/d9a28990/attachment.htm>

From arsyed at gmail.com  Sun Jul  6 08:03:59 2008
From: arsyed at gmail.com (arsyed)
Date: Sun, 6 Jul 2008 02:03:59 -0400
Subject: [Tutor] module paths
In-Reply-To: <6b6a049d0807051537p1dfdc8b9r995a06d10365f783@mail.gmail.com>
References: <6b6a049d0807051537p1dfdc8b9r995a06d10365f783@mail.gmail.com>
Message-ID: <9a2cc7a70807052303v115ca8d0u34f67bf933e9640@mail.gmail.com>

I copy/pasted your script and it ran fine on my end. Is it possible that
you've got more than one installation of python and the feedparser module is
installed somewhere other than for the python interpreter at
/usr/local/bin/python (since that's what your script references)? Perhaps
trying "python parse.py" will help since your code when you invoke the
python shell.



On 7/5/08, Gonzalo Garcia-Perate <gonzillaaa at gmail.com> wrote:
>
> I'm looking at python after a long time. I wanted to build a quick
> parser for some rss feeds and have started using feedparser.
>
> When I test my code on the python interactive shell things work fine
> but when I try to write it into a file I get the following error:
> AttributeError: 'module' object has no attribute 'parse'
>
> this is what I run on the shell:
> import feedparser
> >>> d = feedparser.parse("http://tedblog.typepad.com/tedblog/atom.xml")
> >>> d
> {'feed': {'updated': u'2008-07-04T14:11:15Z', 'updated_parsed': (2008,
> 7, 4, 14, 11, 15, 4, 186, 0), 'links': [{'href':
> u'http://blog.ted.com/', 'type': u'text/html', 'rel': u'alternate'},
> {'href': u'http://feeds.feedburner.com/TEDBlog', 'type':
> u'application/atom+xml', 'rel': u'self'}], 'title': u'TED | TEDBlog',
> etc.....
>
> This is what my script (which fails looks like...):
> #!/usr/local/bin/python
> import feedparser
>
> d = feedparser.parse("http://tedblog.typepad.com/tedblog/atom.xml")
> d['feed']['title']
>
> I'm trying to ring this form within textmate or form the terminal at
> different locations as (./parse.py)
>
> thanks
> _______________________________________________
> 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/20080706/41dae043/attachment.htm>

From gonzillaaa at gmail.com  Sun Jul  6 08:32:29 2008
From: gonzillaaa at gmail.com (Gonzalo Garcia-Perate)
Date: Sun, 6 Jul 2008 07:32:29 +0100
Subject: [Tutor] module paths
In-Reply-To: <9a2cc7a70807052303v115ca8d0u34f67bf933e9640@mail.gmail.com>
References: <6b6a049d0807051537p1dfdc8b9r995a06d10365f783@mail.gmail.com>
	<9a2cc7a70807052303v115ca8d0u34f67bf933e9640@mail.gmail.com>
Message-ID: <6b6a049d0807052332m41890640le673c7c906cc8bb6@mail.gmail.com>

That's what I thought but no. There is an install of 2.4 but not in
use. /usr/local/bin/Python points to ->
/Library/Frameworks/Python.framework/Versions/2.5/bin/python

feedparser is installed in
/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages

both the interactive interpreter and the one used by textmate/terminal
report to be using Python 2.5

the output of sys.path from textmate looks like this:
['/Users/gonzillaaa/Sites/python_rss',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/setuptools-0.6c5-py2.5.egg',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/MySQL_python-1.2.2-py2.5-macosx-10.3-i386.egg',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/simplejson-1.9.1-py2.5-macosx-10.3-i386.egg',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/python_twitter-0.5-py2.5.egg',
'/Users/gonzillaaa/Sites/python_rss',
'/Users/gonzillaaa/development/Python', '/Users/gonzillaaa/bin',
'/Library/Frameworks/Python.framework/Versions/Current/bin',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages',
'/Users/gonzillaaa/Sites',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python25.zip',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-darwin',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac/lib-scriptpackages',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-dynload']


there are some duplicates but nothing missing that I can see. The
output of sys.path form the interactive interpreter looks like this:

['', '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/setuptools-0.6c5-py2.5.egg',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/MySQL_python-1.2.2-py2.5-macosx-10.3-i386.egg',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/simplejson-1.9.1-py2.5-macosx-10.3-i386.egg',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/python_twitter-0.5-py2.5.egg',
'/Users/gonzillaaa/Sites/python_rss',
'/Users/gonzillaaa/development/Python', '/Users/gonzillaaa/bin',
'/Library/Frameworks/Python.framework/Versions/Current/bin',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages',
'/Users/gonzillaaa/Sites',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python25.zip',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-darwin',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac/lib-scriptpackages',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-dynload']



2008/7/6 arsyed <arsyed at gmail.com>:
> I copy/pasted your script and it ran fine on my end. Is it possible that
> you've got more than one installation of python and the feedparser module is
> installed somewhere other than for the python interpreter at
> /usr/local/bin/python (since that's what your script references)? Perhaps
> trying "python parse.py" will help since your code when you invoke the
> python shell.
>
> On 7/5/08, Gonzalo Garcia-Perate <gonzillaaa at gmail.com> wrote:
>>
>> I'm looking at python after a long time. I wanted to build a quick
>> parser for some rss feeds and have started using feedparser.
>>
>> When I test my code on the python interactive shell things work fine
>> but when I try to write it into a file I get the following error:
>> AttributeError: 'module' object has no attribute 'parse'
>>
>> this is what I run on the shell:
>> import feedparser
>> >>> d = feedparser.parse("http://tedblog.typepad.com/tedblog/atom.xml")
>> >>> d
>> {'feed': {'updated': u'2008-07-04T14:11:15Z', 'updated_parsed': (2008,
>> 7, 4, 14, 11, 15, 4, 186, 0), 'links': [{'href':
>> u'http://blog.ted.com/', 'type': u'text/html', 'rel': u'alternate'},
>> {'href': u'http://feeds.feedburner.com/TEDBlog', 'type':
>> u'application/atom+xml', 'rel': u'self'}], 'title': u'TED | TEDBlog',
>> etc.....
>>
>> This is what my script (which fails looks like...):
>> #!/usr/local/bin/python
>> import feedparser
>>
>> d = feedparser.parse("http://tedblog.typepad.com/tedblog/atom.xml")
>> d['feed']['title']
>>
>> I'm trying to ring this form within textmate or form the terminal at
>> different locations as (./parse.py)
>>
>> thanks
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>
>

From rdm at rcblue.com  Sun Jul  6 08:49:20 2008
From: rdm at rcblue.com (Dick Moores)
Date: Sat, 05 Jul 2008 23:49:20 -0700
Subject: [Tutor] assert() question
Message-ID: <20080706064932.0A2B31E4004@bag.python.org>

An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080705/a5c95108/attachment.htm>

From gonzillaaa at gmail.com  Sun Jul  6 09:12:01 2008
From: gonzillaaa at gmail.com (Gonzalo Garcia-Perate)
Date: Sun, 6 Jul 2008 08:12:01 +0100
Subject: [Tutor] module paths
In-Reply-To: <6b6a049d0807052332m41890640le673c7c906cc8bb6@mail.gmail.com>
References: <6b6a049d0807051537p1dfdc8b9r995a06d10365f783@mail.gmail.com>
	<9a2cc7a70807052303v115ca8d0u34f67bf933e9640@mail.gmail.com>
	<6b6a049d0807052332m41890640le673c7c906cc8bb6@mail.gmail.com>
Message-ID: <6b6a049d0807060012i31d287fdy2fd5cb5522099ecf@mail.gmail.com>

ok I fixed it. I removed 2.4 and re-linked /usr/local/bin/python to
/Library/Frameworks/Python.framework/Versions/Current/bin/python

thanks!

2008/7/6 Gonzalo Garcia-Perate <gonzillaaa at gmail.com>:
> That's what I thought but no. There is an install of 2.4 but not in
> use. /usr/local/bin/Python points to ->
> /Library/Frameworks/Python.framework/Versions/2.5/bin/python
>
> feedparser is installed in
> /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages
>
> both the interactive interpreter and the one used by textmate/terminal
> report to be using Python 2.5
>
> the output of sys.path from textmate looks like this:
> ['/Users/gonzillaaa/Sites/python_rss',
> '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/setuptools-0.6c5-py2.5.egg',
> '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/MySQL_python-1.2.2-py2.5-macosx-10.3-i386.egg',
> '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/simplejson-1.9.1-py2.5-macosx-10.3-i386.egg',
> '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/python_twitter-0.5-py2.5.egg',
> '/Users/gonzillaaa/Sites/python_rss',
> '/Users/gonzillaaa/development/Python', '/Users/gonzillaaa/bin',
> '/Library/Frameworks/Python.framework/Versions/Current/bin',
> '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages',
> '/Users/gonzillaaa/Sites',
> '/Library/Frameworks/Python.framework/Versions/2.5/lib/python25.zip',
> '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5',
> '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-darwin',
> '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac',
> '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac/lib-scriptpackages',
> '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk',
> '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-dynload']
>
>
> there are some duplicates but nothing missing that I can see. The
> output of sys.path form the interactive interpreter looks like this:
>
> ['', '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/setuptools-0.6c5-py2.5.egg',
> '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/MySQL_python-1.2.2-py2.5-macosx-10.3-i386.egg',
> '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/simplejson-1.9.1-py2.5-macosx-10.3-i386.egg',
> '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/python_twitter-0.5-py2.5.egg',
> '/Users/gonzillaaa/Sites/python_rss',
> '/Users/gonzillaaa/development/Python', '/Users/gonzillaaa/bin',
> '/Library/Frameworks/Python.framework/Versions/Current/bin',
> '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages',
> '/Users/gonzillaaa/Sites',
> '/Library/Frameworks/Python.framework/Versions/2.5/lib/python25.zip',
> '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5',
> '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-darwin',
> '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac',
> '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac/lib-scriptpackages',
> '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk',
> '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-dynload']
>
>
>
> 2008/7/6 arsyed <arsyed at gmail.com>:
>> I copy/pasted your script and it ran fine on my end. Is it possible that
>> you've got more than one installation of python and the feedparser module is
>> installed somewhere other than for the python interpreter at
>> /usr/local/bin/python (since that's what your script references)? Perhaps
>> trying "python parse.py" will help since your code when you invoke the
>> python shell.
>>
>> On 7/5/08, Gonzalo Garcia-Perate <gonzillaaa at gmail.com> wrote:
>>>
>>> I'm looking at python after a long time. I wanted to build a quick
>>> parser for some rss feeds and have started using feedparser.
>>>
>>> When I test my code on the python interactive shell things work fine
>>> but when I try to write it into a file I get the following error:
>>> AttributeError: 'module' object has no attribute 'parse'
>>>
>>> this is what I run on the shell:
>>> import feedparser
>>> >>> d = feedparser.parse("http://tedblog.typepad.com/tedblog/atom.xml")
>>> >>> d
>>> {'feed': {'updated': u'2008-07-04T14:11:15Z', 'updated_parsed': (2008,
>>> 7, 4, 14, 11, 15, 4, 186, 0), 'links': [{'href':
>>> u'http://blog.ted.com/', 'type': u'text/html', 'rel': u'alternate'},
>>> {'href': u'http://feeds.feedburner.com/TEDBlog', 'type':
>>> u'application/atom+xml', 'rel': u'self'}], 'title': u'TED | TEDBlog',
>>> etc.....
>>>
>>> This is what my script (which fails looks like...):
>>> #!/usr/local/bin/python
>>> import feedparser
>>>
>>> d = feedparser.parse("http://tedblog.typepad.com/tedblog/atom.xml")
>>> d['feed']['title']
>>>
>>> I'm trying to ring this form within textmate or form the terminal at
>>> different locations as (./parse.py)
>>>
>>> thanks
>>> _______________________________________________
>>> Tutor maillist  -  Tutor at python.org
>>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>

From alan.gauld at btinternet.com  Sun Jul  6 10:19:02 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 6 Jul 2008 09:19:02 +0100
Subject: [Tutor] my first object model, using an interface
References: <bae1efdf0807052103t33422fc1tca2cd2e596a812dd@mail.gmail.com>
Message-ID: <g4pv5v$pj5$1@ger.gmane.org>

<tpc247 at gmail.com> wrote

> adequately, after reading Alan Gauld's excellent tutorial

Thanks for the mention, glad you found it useful.

> - a Watchable interface that, when implemented, signifies that the
> implementing object has a threshold and associated package.
> - a Package class, that can be seen as a container for courses 
> and/or one
> part of a course
> - a Course class, that can be seen as a container for gradable 
> homework
> - a Homework class, that has a flag to indicated whether it has been
> received by the school
> - most Packages are Watchable (except the last Package object), and 
> only one
> or two Courses in a Package need to be Watchable

OK, I'd consider whether you really need all those containers.
Python comes with lots of conrtainer options built in, maybe
simple lists and dictionaries would suffice?

Secondly you are thinking too much about the data. You do
not mention the behaviour of these classes at all.

Go back and describe your classes again but in terms of the
behaviours that they exhibit. What is each class's responsibilities.
What do they do within the program. You might get a smaller
list of classes. I suspect maybe only 2 plus some Python
containers are all thats needed.

I don't have time to do a detailed analysis but my gut feel is
too many data driven classes. And way too many getXXX/setXXX
methods. Python is not Java.

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 Jul  6 10:23:54 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 6 Jul 2008 09:23:54 +0100
Subject: [Tutor] assert() question
References: <20080706064932.0A2B31E4004@bag.python.org>
Message-ID: <g4pvf3$q6m$1@ger.gmane.org>

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

> I've heard about using assert() to check up 


> The top three work silently, but I found that I could not figure 
> out how to use assert() with the functions that print rather than 
> return. E.g., maxDiffBetPrimes() and printTime(). Is there a way?

Thats another good reason for not printing inside functions. 
Just get them to return the pre formatteed string which can 
be printed outside the function.

Unless you have a value to check you can't really use assert()
So if the function uses globals (which it shouldn't!) you might 
check them otherwise you are stuck.

> If it'll help, here's printTime():
> def printTime(timeEnd, timeStart):
>    from mycalc import hmsToText
>    timeElapsed = timeEnd - timeStart
>    if timeElapsed > 60:
>        print "Time was", hmsToText(timeElapsed)
>    else:
>        print "Time was %.4g seconds" % timeElapsed

Replace the prints with returns
change the function name to getTime()
Then call it with

t =  getTime(...)
print t

Now you can use an assert on t...

Of course if getTime is not your functin then 
modification may not be possible!

HTH,

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


From python at mrfab.info  Sun Jul  6 11:42:44 2008
From: python at mrfab.info (Michael)
Date: Sun, 06 Jul 2008 17:42:44 +0800
Subject: [Tutor] directory traversal help
In-Reply-To: <486CCA44.6030708@mrfab.info>
References: <486CCA44.6030708@mrfab.info>
Message-ID: <48709394.9060207@mrfab.info>

Further to this query I actually hit the manuals and found that their 
already was a walk function. My final solution was thus...
Please note it is heavily commented because I am a teacher and created 
this for a student :-)

# Will create a listing in a file called dirlist.txt of all the files in 
all
# the directories of the directory it is started from.

import os   # imports all the functions in the os module (operating 
system functions)

cwd = os.getcwd()   # gets the current working directory and places it 
in the variable cwd

myfile=open("dirlist.txt","w")  # creates the file dirlist.txt ready for 
writing using the variable myfiles

# the walk function returns the current directory in root, the 
directories in dirs
# and the files in root in files. By using the for loop it traverses 
every folder
# from the starting folder.

for root, dirs, files in os.walk(cwd):
   myfile.write(root + "\n")   # writes to dirlist.txt the current 
directory name
   for thefiles in files:      # will iterate all the files in the 
current directory
       myfile.write("___________ " + thefiles + "\n") # writes the 
filename to dirlist.txt. the

myfile.close() # Cleanly saves and closes the file dirlist.txt




# Note: the "\n" in the write lines adds the newline character so that 
the next write starts on a newline
> Hi
>
> I have modified an algorithm from the think like a python programmer 
> book for traversing folders and printing the files in those folders. 
> It works for my original purposes but I have a students that wants to 
> use it to run from a root folder, problem is that it crashes on the 
> recycling bin as well as hidden and other types of folders. Is there a 
> way to modify it to skip folders that would make it crash? I have 
> tried using exception handling (try) and other functions in the os 
> module but I cannot work it out. Any ideas? thanks
>
> Michael
>
> import os
> import string
>
> def walk(dir):
>    for name in os.listdir(dir):
>        path = os.path.join(dir,name)
>        if os.path.isfile(path):
>            beg = string.rfind(path,'\Student')
>            end = len(path)
>            filename = path[beg:end]
>            #print "___________ ",filename
>            print "___________ ",name
>
>        else:
>            print path
>            walk (path)
>
> cwd = os.getcwd()
> walk(cwd)
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


From rdm at rcblue.com  Sun Jul  6 11:56:29 2008
From: rdm at rcblue.com (Dick Moores)
Date: Sun, 06 Jul 2008 02:56:29 -0700
Subject: [Tutor] assert() question
In-Reply-To: <g4pvf3$q6m$1@ger.gmane.org>
References: <20080706064932.0A2B31E4004@bag.python.org>
	<g4pvf3$q6m$1@ger.gmane.org>
Message-ID: <20080706095641.C08FB1E4004@bag.python.org>

An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080706/ac4716ec/attachment-0001.htm>

From monjissvel at googlemail.com  Sun Jul  6 13:39:24 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Sun, 6 Jul 2008 11:39:24 +0000
Subject: [Tutor] my first object model, using an interface
In-Reply-To: <bae1efdf0807052103t33422fc1tca2cd2e596a812dd@mail.gmail.com>
References: <bae1efdf0807052103t33422fc1tca2cd2e596a812dd@mail.gmail.com>
Message-ID: <e2f191310807060439y11c051b5y7526f8d2384d18f0@mail.gmail.com>

This looks like a database driven application.
When you send a package you must save the event on a database.
When a HomeWork is submited it must be entered in the database.
When you need to see what's the situation of any one student or all students
you just query teh database.
so you would be better off designing a database (do you like mysql ?) & a
python front end to it (web ?).
this database would be something like : students_table, courses_table,
teachers_table, homework_table
homework table would be like : idx, student_id, homework_id, statut where
statut is sent, finished, submited ...

the front end python program would be composed of a class  to load data into
database, and another to query it.

import MySQLdb

class NewEvent(object):

    ___init__(self, s = 'dbserv', u = 'username', p = 'password', dbn =
'database_name' ):
         self.s = s
         self.u = u
         self.p = p
         self.dbn = dbn
         self.con = MySQLdb.connect(host = self.s,  user  =  self.u ,
passwd = self.p, db = self.dbn)
         self.cur = self.con.cursor()


  def NewStudent(self, Name, Age, Sex, Address):
         cmd_NewStud = 'insert into student_table (Name, Age, Sex, Address)
values (%s, %d, %s, %s)' % (Name, Age, Sex, Address)
         self.cur.execute(cmd_NewStud)


 def NewHW(self, student_id, HW_id):
         cmd_NewHW = 'insert into homework_table (student_id, homework_id)
values (%s, %s)' % (student_id, HW_id)
         self.cur.execute(cmd_NewHW)


I hope this helps



About the code below :


2008/7/6 <tpc247 at gmail.com>:

> Dear fellow Python enthusiasts:
>
> I want to run an idea by you to see if I understand modeling objects
> adequately, after reading Alan Gauld's excellent tutorial and two brief
> articles about interfaces in Python, here:
>
>                  http://www.freenetpages.co.uk/hp/alan.gauld/tutclass.htm
>
> http://dirtsimple.org/2004/12/python-interfaces-are-not-java.html
>                  http://nedbatchelder.com/text/pythonic-interfaces.html
>
> I am attempting to model the following:
> a correspondence school has asked me to help them solve a problem.  When
> the school sends a student by mail a package containing several courses,
> each course having several pieces of gradable homework, when a specific
> threshold of homework completed and submitted by the student is met or
> exceeded, another package is sent to the student by mail.  Now, this
> aforementioned threshold, i.e., an integer indicating percentage, can vary,
> and is not just for the totality of homework in the package, but also for
> certain courses with many pieces of homework.  For example, say the school
> sends student Joe a package (package_1) containing courses A, B and C_sub1.
> A, B & C_sub1 have 10 pieces of gradable homework, and the school wants that
> we can set a threshold for the totality of homework for package1, as well as
> a threshold for C_sub1 alone.  When the thresholds are met or exceeded,
> independently, then we send package_2 and C_sub2, respectively.  I
> envisioned a nascent object model and noted the following observations:
>
> - a Watchable interface that, when implemented, signifies that the
> implementing object has a threshold and associated package.
> - a Package class, that can be seen as a container for courses and/or one
> part of a course
> - a Course class, that can be seen as a container for gradable homework
> - a Homework class, that has a flag to indicated whether it has been
> received by the school
> - most Packages are Watchable (except the last Package object), and only
> one or two Courses in a Package need to be Watchable
>
> Two questions:
> 1) Should I create a first-class Watchable interface object, and then have
> my Package and Course objects implement it if they need to ?  If I start
> with a Watchable interface, do I handle the name-space conflict, i.e.,
> Package(object) vs Package(Watchable), by defining a Package class, and a
> W_Package class that implements Watchable, and likewise for Course ?
> 2) am I even thinking the right way about attacking this problem ?  I am
> curious what your experience in writing easy to maintain software might tell
> you about my nascent object model.
>
> class Watchable(object):
>     def set_threshold(self, an_int):
>         raise NotImplemented
>     def get_threshold(self):
>         raise NotImplemented
>     def set_associated_load(self, a_load):
>         raise NotImplemented
>     def get_associated_load(self):
>         raise NotImplemented
>
> class Package(object):
>     def __init__(self, courses):
>         self.set_courses(courses)
>     def set_courses(self, courses):
>         self.courses = courses
>     def get_courses(self):
>         return self.courses
>
> class Course(Watchable):
>     def __init__(self, name, homework):
>         self.name = name
>         self.homework = homework
>     def get_name(self):
>         return self.name
>     def get_homework(self):
>         return self.homework
>
> class Homework(object):
>     def __init__(self, name):
>         self.name = name
>         self.academically_received = False
>     def set_academically_received(self):
>         self.academically_received = True
>
> _______________________________________________
> 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/20080706/5fd6f82c/attachment.htm>

From alan.gauld at btinternet.com  Sun Jul  6 14:55:24 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 6 Jul 2008 13:55:24 +0100
Subject: [Tutor] my first object model, using an interface
References: <bae1efdf0807052103t33422fc1tca2cd2e596a812dd@mail.gmail.com>
	<e2f191310807060439y11c051b5y7526f8d2384d18f0@mail.gmail.com>
Message-ID: <g4qfc5$3b0$1@ger.gmane.org>

"Monika Jisswel" <monjissvel at googlemail.com> wrote

> This looks like a database driven application.

I agree the final app will need to use a database for persistence.

However the OP was specifically looking to use OOP principles
so simply encapsulating the database is probably not the best
approach for that purpose.

> When you need to see what's the situation of any one student or all 
> students
> you just query teh database.

Yes and that could be encapsulated in a method of the Student class.

> this database would be something like : students_table, 
> courses_table,
> teachers_table, homework_table

I would drop the _tanble personally.
I don't see much point in naming a table as a table - it just adds
extra typing in every query and reduces the readability IMHO!

> homework table would be like : idx, student_id, homework_id, statut 
> where
> statut is sent, finished, submited ...
>
> the front end python program would be composed of a class  to load 
> data into
> database, and another to query it.

But I really don't like a class to load and another to query. Objects
should do it to themselves so there may be a persistence mixin
or interface that has store/query methods and every stored oobject
can utilise those but creating a class to do that for all objects is
not a good OO approach. Not least because to add new stored
classes means modifying the store/query classes. Much better to
be able to add new objects that inherit the generic store/query 
capability
and keep the new code within those new classes as much as possible.
The ability to add functionality to an OO system without changing
the existing classes is one of the big wins of OOP.

> class NewEvent(object):
>
>  def NewStudent(self, Name, Age, Sex, Address):
>
>  def NewHW(self, student_id, HW_id):

This builds knowledge of every object into the one master class
making that class very susceptible to changes (and thus regression
testing) and reduces its reuse capability.

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 Jul  6 15:01:25 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 6 Jul 2008 14:01:25 +0100
Subject: [Tutor] assert() question
References: <20080706064932.0A2B31E4004@bag.python.org><g4pvf3$q6m$1@ger.gmane.org>
	<20080706095641.C08FB1E4004@bag.python.org>
Message-ID: <g4qfnf$4c8$1@ger.gmane.org>


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

> Traceback (most recent call last):
>  File "E:\PythonWork\Untitled 2.py", line 42, in <module>
>    assert(fact(10,4) == 3.629e+6)
> AssertionError

I'm not sure but I suspect you are running into the dreaded 
floating point precision problem.

You probably need to try:

result = 3.694e+6
e = result/1000000   # add zeros to suit!
assert(result - e < fact(10,4) < result + e)

Or somesuch

Just a guess though.

Alan G.



From kent37 at tds.net  Sun Jul  6 16:15:31 2008
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 6 Jul 2008 10:15:31 -0400
Subject: [Tutor] module paths
In-Reply-To: <6b6a049d0807051537p1dfdc8b9r995a06d10365f783@mail.gmail.com>
References: <6b6a049d0807051537p1dfdc8b9r995a06d10365f783@mail.gmail.com>
Message-ID: <1c2a2c590807060715l53a00dewb5711c0b05beb5cc@mail.gmail.com>

On Sat, Jul 5, 2008 at 6:37 PM, Gonzalo Garcia-Perate
<gonzillaaa at gmail.com> wrote:
> I'm looking at python after a long time. I wanted to build a quick
> parser for some rss feeds and have started using feedparser.
>
> When I test my code on the python interactive shell things work fine
> but when I try to write it into a file I get the following error:
> AttributeError: 'module' object has no attribute 'parse'

It sounds like it is finding the wrong feedparser module. Did you have
a script called feedparser.py? If so rename or delete the .py and .pyc
files. Also you can try
import feedparser
print feedparser.__file__
to see where the module is importing from.

Kent

From rdm at rcblue.com  Sun Jul  6 16:50:31 2008
From: rdm at rcblue.com (Dick Moores)
Date: Sun, 06 Jul 2008 07:50:31 -0700
Subject: [Tutor] assert() question
In-Reply-To: <g4qfnf$4c8$1@ger.gmane.org>
References: <20080706064932.0A2B31E4004@bag.python.org>
	<g4pvf3$q6m$1@ger.gmane.org>
	<20080706095641.C08FB1E4004@bag.python.org>
	<g4qfnf$4c8$1@ger.gmane.org>
Message-ID: <20080706145043.DEA1E1E4005@bag.python.org>

At 06:01 AM 7/6/2008, Alan Gauld wrote:

>"Dick Moores" <rdm at rcblue.com> wrote
>>Traceback (most recent call last):
>>  File "E:\PythonWork\Untitled 2.py", line 42, in <module>
>>    assert(fact(10,4) == 3.629e+6)
>>AssertionError
>
>I'm not sure but I suspect you are running into the dreaded floating 
>point precision problem.
>
>You probably need to try:
>
>result = 3.694e+6
>e = result/1000000   # add zeros to suit!
>assert(result - e < fact(10,4) < result + e)
>
>Or somesuch
>
>Just a guess though.

And a good one!
assert(result - e < fact(10,4) < result + e)

works with  e = result/100000  but not with  e = result/1000000 .

Thanks, Alan.

Dick


From cappy2112 at gmail.com  Sun Jul  6 18:20:46 2008
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Sun, 6 Jul 2008 09:20:46 -0700
Subject: [Tutor] Wave module
Message-ID: <8249c4ac0807060920i1a8955e7r30d73e7219824059@mail.gmail.com>

Message: 1
Date: Sat, 5 Jul 2008 16:50:35 -0600
From: "Alex Krycek" <agent.krycek at gmail.com>
Subject: [Tutor] Wave module
To: tutor at python.org
Message-ID:
       <a4f6ec110807051550n356f46deo93271bf28cb31217 at mail.gmail.com>
Content-Type: text/plain; charset="iso-8859-1"

Hello,

I'm trying to join two .wav files with the wave module. But when I try to
use wave.open(filename, "rb") I receive the following error:

Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "F:\PortablePython1.0\lib\wave.py", line 483, in open
   return Wave_read(f)
 File "F:\PortablePython1.0\lib\wave.py", line 162, in __init__
   self.initfp(f)
 File "F:\PortablePython1.0\lib\wave.py", line 143, in initfp
   self._read_fmt_chunk(chunk)
 File "F:\PortablePython1.0\lib\wave.py", line 264, in _read_fmt_chunk
   raise Error, 'unknown format: %r' % (wFormatTag,)
wave.Error: unknown format: 85

I read somewhere that there are various wave formats, only some supported by
Python. Is this true? If so, is there any way I can convert my wave files
into a supported kind?


Thanks!


Try creating your own wave fiel and open it. It may be that the one you're
opening is corrupted.
http://www.sonicspot.com/guide/wavefiles.html

BTW Agent Krycec: what' that black, oily fluid in your eyes? ;-)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080706/972d69f4/attachment-0001.htm>

From bhaaluu at gmail.com  Sun Jul  6 19:43:27 2008
From: bhaaluu at gmail.com (bhaaluu)
Date: Sun, 6 Jul 2008 13:43:27 -0400
Subject: [Tutor] Exploring the Standard Library
In-Reply-To: <1215282216.6950.27.camel@poisontongue>
References: <1215282216.6950.27.camel@poisontongue>
Message-ID: <ea979d70807061043q529f0782h430f1761a4d907fe@mail.gmail.com>

On Sat, Jul 5, 2008 at 2:23 PM, Nathan Farrar <nathan.farrar at gmail.com> wrote:
> I'd like to spend some time exploring the standard library.  I'm running
> python on Ubuntu.  How would I find the location of the modules (find /
> -name "os.py" does not yield results)?
>
> Thanks!
> Nathan
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

I'm running a standard Debian 4.0r3 Stable with Python 2.4.4.
I've found the to be helpful. Open a Konsole or Terminal.

[~]$ python

Python 2.4.4 (#2, Apr 15 2008, 23:43:20)
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>>> help('modules')

Please wait a moment while I gather a list of all available modules...

[Modules are spooged here.]

Enter any module name to get more help.  Or, type "modules spam" to search
for modules whose descriptions contain the word "spam".

>>> help('os')

The help screen for 'os' comes up. Press the spacebar to scroll through it.

>>> help()

Welcome to Python 2.4!  This is the online help utility.

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://www.python.org/doc/tut/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, or topics, type "modules",
"keywords", or "topics".  Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".

help> quit

>>> Ctrl-D

[~]$

Another thing that comes in very handy is 'dir(name_of_module)'.
Doing your exploration in the interactive interpreter allows you to read up
on a module, then try it. Have a Konsole with the Python interactive interpreter
and a browser open to the docs at the same time, and really go to town with it!

And so forth, and so on....... as you can see, Python itself has an incredible
help engine built-in to the interactive intepreter.

Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m
In a world without fences, who needs Gates?

From collinsjames9 at gmail.com  Sun Jul  6 19:59:22 2008
From: collinsjames9 at gmail.com (james collins)
Date: Sun, 6 Jul 2008 13:59:22 -0400
Subject: [Tutor] unsiscribe
Message-ID: <5E37ACA1-C97E-4F2A-AE5D-282FCDD57E42@gmail.com>

how do i unsiscribe from the mailing list?

From bgailer at gmail.com  Sun Jul  6 20:09:31 2008
From: bgailer at gmail.com (bob gailer)
Date: Sun, 06 Jul 2008 14:09:31 -0400
Subject: [Tutor] unsiscribe
In-Reply-To: <5E37ACA1-C97E-4F2A-AE5D-282FCDD57E42@gmail.com>
References: <5E37ACA1-C97E-4F2A-AE5D-282FCDD57E42@gmail.com>
Message-ID: <48710A5B.9020301@gmail.com>

james collins wrote:
> how do i unsiscribe from the mailing list?
>
>
Follow the link below

-- 
Bob Gailer
919-636-4239 Chapel Hill, NC


From cappy2112 at gmail.com  Sun Jul  6 20:15:47 2008
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Sun, 6 Jul 2008 11:15:47 -0700
Subject: [Tutor] Tutor Digest, Vol 53, Issue 18
In-Reply-To: <mailman.995.1215282229.20627.tutor@python.org>
References: <mailman.995.1215282229.20627.tutor@python.org>
Message-ID: <8249c4ac0807061115i121b83a5yb881c1a0188f1a94@mail.gmail.com>

Message: 7
Date: Sat, 05 Jul 2008 12:23:36 -0600
From: Nathan Farrar <nathan.farrar at gmail.com>
Subject: [Tutor] Exploring the Standard Library
To: Python Tutor <tutor at python.org>
Message-ID: <1215282216.6950.27.camel at poisontongue>
Content-Type: text/plain; charset="us-ascii"

>>I'd like to spend some time exploring the standard library.
This is somewhat tangent to your question, but I think it's an excellent
free resource for the modules in the Standard Library
http://www.doughellmann.com/projects/PyMOTW/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080706/e64e2d9f/attachment.htm>

From robert.johansson at math.umu.se  Sun Jul  6 21:47:03 2008
From: robert.johansson at math.umu.se (Robert Johansson)
Date: Sun, 6 Jul 2008 21:47:03 +0200
Subject: [Tutor] search path
Message-ID: <000c01c8dfa1$13538af0$39faa0d0$@johansson@math.umu.se>

I have some functions written in Matlab which I want to translate into
Python so that my friends (how don't have Matlab) can enjoy them. My program
does some work on a bunch of textfiles which I have put in the same
directory as the Python-scriptfile with the function definitions. Things run
pretty well on my installation (WinXP) but not on my girlfriends Mac (with
leopard).  

 

Running the script file she gets error messages claiming that the textfiles
cannot be found when they are to be opened with
fileid=file('textfilename.txt','r') even though the same thing works fine on
my system. Anyone how knows what the cause of this is? 

 

Regards, Robert

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080706/e6624a7d/attachment.htm>

From bgailer at gmail.com  Sun Jul  6 22:56:15 2008
From: bgailer at gmail.com (bob gailer)
Date: Sun, 06 Jul 2008 16:56:15 -0400
Subject: [Tutor] search path
In-Reply-To: <000c01c8dfa1$13538af0$39faa0d0$@johansson@math.umu.se>
References: <000c01c8dfa1$13538af0$39faa0d0$@johansson@math.umu.se>
Message-ID: <4871316F.6000107@gmail.com>

Robert Johansson wrote:
>
> I have some functions written in Matlab which I want to translate into 
> Python so that my friends (how don?t have Matlab) can enjoy them. My 
> program does some work on a bunch of textfiles which I have put in the 
> same directory as the Python-scriptfile with the function definitions. 
> Things run pretty well on my installation (WinXP) but not on my 
> girlfriends Mac (with leopard).
>
> Running the script file she gets error messages claiming that the 
> textfiles cannot be found when they are to be opened with 
> fileid=file(?textfilename.txt?,?r?) even though the same thing works 
> fine on my system. Anyone how knows what the cause of this is?
>

When you specify a relative path for the file Python looks in the 
"current directory".

To see what that is:

import os
print os.getcwd()

I'll bet that on the Mac the files are not in the "current directory".

If that is the case there are several solutions.

-- 
Bob Gailer
919-636-4239 Chapel Hill, NC


From kent37 at tds.net  Sun Jul  6 23:30:22 2008
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 6 Jul 2008 17:30:22 -0400
Subject: [Tutor] assert() question
In-Reply-To: <20080706064932.0A2B31E4004@bag.python.org>
References: <20080706064932.0A2B31E4004@bag.python.org>
Message-ID: <1c2a2c590807061430hce19364tfeb2ec157c74562e@mail.gmail.com>

On Sun, Jul 6, 2008 at 2:49 AM, Dick Moores <rdm at rcblue.com> wrote:
> I have a module, mycalc.py, which is a collection of functions designed to
> be imported independently.
>
> I've heard about using assert() to check up on whether things are still
> working correctly, or something like that. So I've begun to write some
> assert() expressions(?)  and put them at the bottom of the module.

You might be interested in the doctest module which lets you write
tests similar to these integrated with the doctstrings for your
functions.
http://docs.python.org/lib/module-doctest.html

Kent

From rdm at rcblue.com  Mon Jul  7 00:06:13 2008
From: rdm at rcblue.com (Dick Moores)
Date: Sun, 06 Jul 2008 15:06:13 -0700
Subject: [Tutor] assert() question
In-Reply-To: <1c2a2c590807061430hce19364tfeb2ec157c74562e@mail.gmail.com
 >
References: <20080706064932.0A2B31E4004@bag.python.org>
	<1c2a2c590807061430hce19364tfeb2ec157c74562e@mail.gmail.com>
Message-ID: <20080706220625.95E2E1E4005@bag.python.org>

At 02:30 PM 7/6/2008, Kent Johnson wrote:
>On Sun, Jul 6, 2008 at 2:49 AM, Dick Moores <rdm at rcblue.com> wrote:
> > I have a module, mycalc.py, which is a collection of functions designed to
> > be imported independently.
> >
> > I've heard about using assert() to check up on whether things are still
> > working correctly, or something like that. So I've begun to write some
> > assert() expressions(?)  and put them at the bottom of the module.
>
>You might be interested in the doctest module which lets you write
>tests similar to these integrated with the doctstrings for your
>functions.
>http://docs.python.org/lib/module-doctest.html

Thanks, Kent. Looks interesting. But I'll probably have some 
questions, as usual.

Dick



From mwalsh at groktech.org  Mon Jul  7 02:16:02 2008
From: mwalsh at groktech.org (Martin Walsh)
Date: Sun, 06 Jul 2008 19:16:02 -0500
Subject: [Tutor] file object in memory
In-Reply-To: <e2f191310807041518x4da72763q9636d44d8debea32@mail.gmail.com>
References: <e2f191310807040916q447b6145xf797f03171f91490@mail.gmail.com>	<486E9B40.5080708@gmail.com>
	<e2f191310807041518x4da72763q9636d44d8debea32@mail.gmail.com>
Message-ID: <48716042.9010006@groktech.org>

Monika Jisswel wrote:
> You know bob, you are very clever, I have used RAM disk for realtime
> recording of audio before but it never occured to me to use it for light
> jobs like this one, I just compeletely ignored it as an option & by the
> way this openes a lot of doors for many of my other programs.
> 
> but wouldn't it be very nice if there  was a way of creating a file
> object inside python ? something like :
> myfile = mkfile('some_string')
> & we're done ?

If I understand what you're after, perhaps tempfile.NamedTemporaryFile
is close. Granted it creates a 'real' file, subject to filesystem
performance, but it is automatically deleted when closed.

---

Also, while I wouldn't recommend it, I thought it might be worth
mentioning that you can specify a named pipe (or fifo) with mysql 'load
data' -- although this may be limited to *nix or Mac, I'm not sure.

It is a tricky dance since, IIUC, the mysql process has to open the
named pipe for reading before you can write to it, else the write will
block waiting for a reader and your program will hang. My first thought
would be to spawn a subprocess of the mysql client, or mysqlimport, to
start the read, then write data to the named pipe. Something like the
following (untested):

...

fifoname = '/tmp/mysql.fifo'
if os.path.exists(fifoname):
    os.remove(fifoname)
os.mkfifo(fifoname)

sql = """\
"load data local infile '%s' into table statistics
    fields terminated by '\\t' lines terminated by '\\n';"
""" % fifoname

conninfo[sql] = sql
mysqlcmd = \
  'mysql %(dbname)s -h %(host)s -u %(user)s -e %(sql)s' % conninfo

mysqlp = sp.Popen(mysqlcmd, stdout=sp.PIPE, shell=True)

# should be ready to write
fifofp = file(fifoname, 'w')
p1 = sp.Popen(somecmd1, stdout=fifofp, shell=True)
fifofp.close()

mysqlp.wait()

...

Seems like an awful lot of work, for questionable gain. I would use a
regular file. If you're concerned about performance, Bob's ramdisk
suggestion seems more appropriate.

HTH,
Marty

> 
> 
>     I don't think there is a pure Pythonic way. Have you considered
>     using a RamDisk? http://en.wikipedia.org/wiki/RAM_disk for general
>     details.
> 
>     http://www.codeguru.com/cpp/w-p/system/devicedriverdevelopment/article.php/c5789/
>     for a Windows Ram Disk driver installer. I just tried it - it works
>     like a charm.
> 
>     HTH.
> 
>     -- 
>     Bob Gailer
>     919-636-4239 Chapel Hill, NC

From kent37 at tds.net  Mon Jul  7 04:35:02 2008
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 6 Jul 2008 22:35:02 -0400
Subject: [Tutor] graphs & diagrams in python
In-Reply-To: <1c2a2c590807050616i402dc7bfy63f8809f2fc8eb09@mail.gmail.com>
References: <e2f191310807041254i518e93bfsa35c6a30e86e036d@mail.gmail.com>
	<1c2a2c590807050616i402dc7bfy63f8809f2fc8eb09@mail.gmail.com>
Message-ID: <1c2a2c590807061935p534280u7091b5522c634697@mail.gmail.com>

On Sat, Jul 5, 2008 at 9:16 AM, Kent Johnson <kent37 at tds.net> wrote:
> On Fri, Jul 4, 2008 at 3:54 PM, Monika Jisswel
> <monjissvel at googlemail.com> wrote:
>> Hi Again,
>>
>> What is the best library for drawing graphs & diagrams to ilustrate some
>> statistics ?
>
> A few possibilities here:
> http://wiki.python.org/moin/GraphicsAndImages

Here is a longer list of plotting and visualization tools:
http://code.enthought.com/chaco/
http://gnuplot-py.sourceforge.net/
http://newcenturycomputers.net/projects/gdmodule.html
http://www.slac.stanford.edu/grp/ek/hippodraw/
http://mayavi.sourceforge.net/index.html
http://home.gna.org/pychart/
http://www.pyngl.ucar.edu/
http://www.tarind.com/depgraph.html
https://svn.enthought.com/enthought/wiki/TVTK
http://vpython.org/
http://pyqwt.sourceforge.net/home.html
http://home.gna.org/veusz/
http://www.dislin.de/
http://oss.oetiker.ch/rrdtool/

I have done well with matplotlib.
Kent

From rosenville at gmail.com  Mon Jul  7 07:44:56 2008
From: rosenville at gmail.com (Josh Rosen)
Date: Sun, 6 Jul 2008 22:44:56 -0700
Subject: [Tutor] Regular Expressions: escaping in character
	classes/character sets
Message-ID: <DA1C562E-5CE8-465D-94C2-204B74149513@gmail.com>

I was browsing through the source code of Django when I found the  
following regular expression:

tspecials = re.compile(r'[ \(\)<>@,;:\\"/\[\]\?=]')

As it turns out, this line from the message module in the Python  
standard library's  email module.  It seems to be used to determine if  
an email header parameter's value contains special characters to  
determine whether it should be wrapped in quotes.

What strikes me as odd about this regex is that the parentheses and  
the question-mark are escaped with backslashes.  I know that's  
necessary for including those literals in the rest of the expression,  
but they shouldn't need to be escaped within a character class,  
right?  Shouldn't this be functionally equivalent to the much more  
readable:

tspecials = re.compile(r'[ ()<>@,;:\\"/\[\]?=]')

From kent37 at tds.net  Mon Jul  7 12:28:56 2008
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 7 Jul 2008 06:28:56 -0400
Subject: [Tutor] Regular Expressions: escaping in character
	classes/character sets
In-Reply-To: <DA1C562E-5CE8-465D-94C2-204B74149513@gmail.com>
References: <DA1C562E-5CE8-465D-94C2-204B74149513@gmail.com>
Message-ID: <1c2a2c590807070328r58618d4bp60c958edd4b163f7@mail.gmail.com>

On Mon, Jul 7, 2008 at 1:44 AM, Josh Rosen <rosenville at gmail.com> wrote:
> I was browsing through the source code of Django when I found the following
> regular expression:
>
> tspecials = re.compile(r'[ \(\)<>@,;:\\"/\[\]\?=]')
>
> Shouldn't this be
> functionally equivalent to the much more readable:
>
> tspecials = re.compile(r'[ ()<>@,;:\\"/\[\]?=]')

Yes, I think so. Try it and see!

Kent

From ttlingit at hotmail.com  Mon Jul  7 18:40:01 2008
From: ttlingit at hotmail.com (Jeremiah Stack)
Date: Mon, 7 Jul 2008 09:40:01 -0700
Subject: [Tutor] New to pythong
Message-ID: <BLU105-W38914C642F2EA8B0D18713DE940@phx.gbl>






Hello everybody:

I am new to this mailing list, and it said that i could the simplest of questions. So i was wondering if anyone could be so kind as to e-mail me a project idea or something to go out an learn to do in python. I don't know any languages, but i am definitely not computer illiterate. i have read so many tutorial about getting started but so far that is where the tutorial have left me ( how to print  "Hello World") and such. 

Any ideas great thanks.



_________________________________________________________________
Making the world a better place one message at a time.
http://www.imtalkathon.com/?source=EML_WLH_Talkathon_BetterPlace
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080707/08d71d48/attachment.htm>

From malaclypse2 at gmail.com  Mon Jul  7 18:51:39 2008
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Mon, 7 Jul 2008 12:51:39 -0400
Subject: [Tutor] search path
In-Reply-To: <-312724930840827361@unknownmsgid>
References: <-312724930840827361@unknownmsgid>
Message-ID: <16651e80807070951i5b3602bcteaf36d9faf8451b1@mail.gmail.com>

On Sun, Jul 6, 2008 at 3:47 PM, Robert Johansson
<robert.johansson at math.umu.se> wrote:
> Running the script file she gets error messages claiming that the textfiles
> cannot be found when they are to be opened with
> fileid=file('textfilename.txt','r') even though the same thing works fine on
> my system. Anyone how knows what the cause of this is?

Are you sure the filename is correct?  As I understand it, Window's
filesystems are case insensitive, so 'textfilename.txt' would also
work for files named 'TextFileName.txt', or 'textfilename.TXT', etc.
I believe the Mac's filesystem is case sensitive, so all of those
names would be different files, and could in fact all reside in the
same directory together.

-- 
Jerry

From srilyk at gmail.com  Mon Jul  7 18:58:28 2008
From: srilyk at gmail.com (W W)
Date: Mon, 7 Jul 2008 11:58:28 -0500
Subject: [Tutor] New to pythong
In-Reply-To: <BLU105-W38914C642F2EA8B0D18713DE940@phx.gbl>
References: <BLU105-W38914C642F2EA8B0D18713DE940@phx.gbl>
Message-ID: <333efb450807070958o5ee0aedbo5b9d5f9c60114fa9@mail.gmail.com>

A quick google search for "Python tutorial" will yeild several results.

I recommend "Think Python" -  http://greenteapress.com/thinkpython/

HTH,
Wayne

On Mon, Jul 7, 2008 at 11:40 AM, Jeremiah Stack <ttlingit at hotmail.com> wrote:
>
>
> Hello everybody:
>
> I am new to this mailing list, and it said that i could the simplest of
> questions. So i was wondering if anyone could be so kind as to e-mail me a
> project idea or something to go out an learn to do in python. I don't know
> any languages, but i am definitely not computer illiterate. i have read so
> many tutorial about getting started but so far that is where the tutorial
> have left me ( how to print  "Hello World") and such.
>
> Any ideas great thanks.
>
>
>
> ________________________________
> Making the world a better place one message at a time. Check out the i'm
> Talkathon.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>



-- 
To be considered stupid and to be told so is more painful than being
called gluttonous, mendacious, violent, lascivious, lazy, cowardly:
every weakness, every vice, has found its defenders, its rhetoric, its
ennoblement and exaltation, but stupidity hasn't. - Primo Levi

From monjissvel at googlemail.com  Mon Jul  7 19:20:21 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Mon, 7 Jul 2008 17:20:21 +0000
Subject: [Tutor] graphs & diagrams in python
In-Reply-To: <1c2a2c590807061935p534280u7091b5522c634697@mail.gmail.com>
References: <e2f191310807041254i518e93bfsa35c6a30e86e036d@mail.gmail.com>
	<1c2a2c590807050616i402dc7bfy63f8809f2fc8eb09@mail.gmail.com>
	<1c2a2c590807061935p534280u7091b5522c634697@mail.gmail.com>
Message-ID: <e2f191310807071020y2b9dd431i1e11267956aa570d@mail.gmail.com>

>
> I have done well with matplotlib.
>

Thanks for the large options, I went for matplotlib too as I liked it more
than the other options, & also with my later readings I realized it was the
best. Later I will update this discussion with some examples I used.


2008/7/7 Kent Johnson <kent37 at tds.net>:

> On Sat, Jul 5, 2008 at 9:16 AM, Kent Johnson <kent37 at tds.net> wrote:
> > On Fri, Jul 4, 2008 at 3:54 PM, Monika Jisswel
> > <monjissvel at googlemail.com> wrote:
> >> Hi Again,
> >>
> >> What is the best library for drawing graphs & diagrams to ilustrate some
> >> statistics ?
> >
> > A few possibilities here:
> > http://wiki.python.org/moin/GraphicsAndImages
>
> Here is a longer list of plotting and visualization tools:
> http://code.enthought.com/chaco/
> http://gnuplot-py.sourceforge.net/
> http://newcenturycomputers.net/projects/gdmodule.html
> http://www.slac.stanford.edu/grp/ek/hippodraw/
> http://mayavi.sourceforge.net/index.html
> http://home.gna.org/pychart/
> http://www.pyngl.ucar.edu/
> http://www.tarind.com/depgraph.html
> https://svn.enthought.com/enthought/wiki/TVTK
> http://vpython.org/
> http://pyqwt.sourceforge.net/home.html
> http://home.gna.org/veusz/
> http://www.dislin.de/
> http://oss.oetiker.ch/rrdtool/
>
> I have done well with matplotlib.
> Kent
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080707/6984c7ac/attachment.htm>

From monjissvel at googlemail.com  Mon Jul  7 19:33:37 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Mon, 7 Jul 2008 17:33:37 +0000
Subject: [Tutor] New to pythong
In-Reply-To: <333efb450807070958o5ee0aedbo5b9d5f9c60114fa9@mail.gmail.com>
References: <BLU105-W38914C642F2EA8B0D18713DE940@phx.gbl>
	<333efb450807070958o5ee0aedbo5b9d5f9c60114fa9@mail.gmail.com>
Message-ID: <e2f191310807071033g36c431dam49898fa704679141@mail.gmail.com>

you can start with stuff you need like,  for example write a program that
scans your hard disk & tells you the details about pdf, jpg, zip, avi files
that you have, with creation date and sizes.
when you need help write us.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080707/5b037b90/attachment.htm>

From marc.tompkins at gmail.com  Mon Jul  7 19:43:43 2008
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Mon, 7 Jul 2008 10:43:43 -0700
Subject: [Tutor] New to pythong
In-Reply-To: <BLU105-W38914C642F2EA8B0D18713DE940@phx.gbl>
References: <BLU105-W38914C642F2EA8B0D18713DE940@phx.gbl>
Message-ID: <40af687b0807071043m13bab78bw2d4fea1adc76d001@mail.gmail.com>

On Mon, Jul 7, 2008 at 9:40 AM, Jeremiah Stack <ttlingit at hotmail.com> wrote:

>
>
> Hello everybody:
>
> I am new to this mailing list, and it said that i could the simplest of
> questions. So i was wondering if anyone could be so kind as to e-mail me a
> project idea or something to go out an learn to do in python. I don't know
> any languages, but i am definitely not computer illiterate. i have read so
> many tutorial about getting started but so far that is where the tutorial
> have left me ( how to print  "Hello World") and such.
>
> Any ideas great thanks.
>
>
First of all, I mean no offense to the OP.  However, this question comes up
a lot on this list, and it always bugs me.  People decide they want to learn
Python, and then ask strangers to give them a reason to do it.  I may be
totally wrong about this, but it doesn't seem like a good way to learn
_anything_, let alone a programming language.  The most important element
for success is enthusiasm, and how can you generate any enthusiasm working
on somebody else's homework project?  Unless you learn best under external
discipline, in which case I suggest you take a class...

My advice to all potential Pythonistas who want to learn on their own: think
of a problem you need to solve, or a cool game you've wanted to implement,
or a tool you want but don't have.  In my own case, I had a project I needed
to do (printing mailing labels from records in an old proprietary database)
that was going to suck if I used only the tools I already had.  I'd been
wanting to get into Python, and I decided to use Python to do the job and
learn as I went.  It was WONDERFUL, and I've been in love with Python ever
since.  (Yes, I've used it for fun stuff since then, but my first experience
was of Python saving me hours and hours of pain.)

If you don't have a professional task that you could apply Python to, just
look around your environment for a day or so looking for problems to solve.
(My favorite example of this, although it's a very silly program and written
in JavaScript besides, is Roast Beef's "Eggs and Milk Minder" from
Achewood<http://achewood.com/index.php?date=05082002>.)


Just my &euro;0.0075...

-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080707/0149df50/attachment-0001.htm>

From monjissvel at googlemail.com  Mon Jul  7 19:52:53 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Mon, 7 Jul 2008 17:52:53 +0000
Subject: [Tutor] file object in memory
In-Reply-To: <48716042.9010006@groktech.org>
References: <e2f191310807040916q447b6145xf797f03171f91490@mail.gmail.com>
	<486E9B40.5080708@gmail.com>
	<e2f191310807041518x4da72763q9636d44d8debea32@mail.gmail.com>
	<48716042.9010006@groktech.org>
Message-ID: <e2f191310807071052u7ffffa52x3715b84df6fbecb8@mail.gmail.com>

I didn't know about tempfile.NamedTemporaryFile ! looks nice because you
don't care about the file anymore, you just use it.
another solution could be to wrap the data (that is each line in the file
still in memory) into mysql statements such as 'insert into table xxxx (aa,
bb, cc) values ( 11, 22, 33)' & pipe it to mysql directly, it will be slow
for tasks like a load but i don't deal with more than 4000 per time & thats
every 15 Minutes.


2008/7/7 Martin Walsh <mwalsh at groktech.org>:

> Monika Jisswel wrote:
> > You know bob, you are very clever, I have used RAM disk for realtime
> > recording of audio before but it never occured to me to use it for light
> > jobs like this one, I just compeletely ignored it as an option & by the
> > way this openes a lot of doors for many of my other programs.
> >
> > but wouldn't it be very nice if there  was a way of creating a file
> > object inside python ? something like :
> > myfile = mkfile('some_string')
> > & we're done ?
>
> If I understand what you're after, perhaps tempfile.NamedTemporaryFile
> is close. Granted it creates a 'real' file, subject to filesystem
> performance, but it is automatically deleted when closed.
>
> ---
>
> Also, while I wouldn't recommend it, I thought it might be worth
> mentioning that you can specify a named pipe (or fifo) with mysql 'load
> data' -- although this may be limited to *nix or Mac, I'm not sure.
>
> It is a tricky dance since, IIUC, the mysql process has to open the
> named pipe for reading before you can write to it, else the write will
> block waiting for a reader and your program will hang. My first thought
> would be to spawn a subprocess of the mysql client, or mysqlimport, to
> start the read, then write data to the named pipe. Something like the
> following (untested):
>
> ...
>
> fifoname = '/tmp/mysql.fifo'
> if os.path.exists(fifoname):
>    os.remove(fifoname)
> os.mkfifo(fifoname)
>
> sql = """\
> "load data local infile '%s' into table statistics
>    fields terminated by '\\t' lines terminated by '\\n';"
> """ % fifoname
>
> conninfo[sql] = sql
> mysqlcmd = \
>  'mysql %(dbname)s -h %(host)s -u %(user)s -e %(sql)s' % conninfo
>
> mysqlp = sp.Popen(mysqlcmd, stdout=sp.PIPE, shell=True)
>
> # should be ready to write
> fifofp = file(fifoname, 'w')
> p1 = sp.Popen(somecmd1, stdout=fifofp, shell=True)
> fifofp.close()
>
> mysqlp.wait()
>
> ...
>
> Seems like an awful lot of work, for questionable gain. I would use a
> regular file. If you're concerned about performance, Bob's ramdisk
> suggestion seems more appropriate.
>
> HTH,
> Marty
>
> >
> >
> >     I don't think there is a pure Pythonic way. Have you considered
> >     using a RamDisk? http://en.wikipedia.org/wiki/RAM_disk for general
> >     details.
> >
> >
> http://www.codeguru.com/cpp/w-p/system/devicedriverdevelopment/article.php/c5789/
> >     for a Windows Ram Disk driver installer. I just tried it - it works
> >     like a charm.
> >
> >     HTH.
> >
> >     --
> >     Bob Gailer
> >     919-636-4239 Chapel Hill, NC
> _______________________________________________
> 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/20080707/f677a0cd/attachment.htm>

From bermanrl at embarqmail.com  Mon Jul  7 19:56:00 2008
From: bermanrl at embarqmail.com (Robert Berman)
Date: Mon, 07 Jul 2008 13:56:00 -0400
Subject: [Tutor] New to Python
Message-ID: <487258B0.4010909@embarqmail.com>

An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080707/f03b707b/attachment.htm>

From alan.gauld at btinternet.com  Mon Jul  7 20:28:13 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 7 Jul 2008 19:28:13 +0100
Subject: [Tutor] New to pythong
References: <BLU105-W38914C642F2EA8B0D18713DE940@phx.gbl>
	<40af687b0807071043m13bab78bw2d4fea1adc76d001@mail.gmail.com>
Message-ID: <g4tn7t$s5s$1@ger.gmane.org>

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

> First of all, I mean no offense to the OP.  However, this question 
> comes up
> a lot on this list, and it always bugs me.  People decide they want 
> to learn
> Python, and then ask strangers to give them a reason to do it.

I know what you mean Marc but I don't think these beginners
are asking for a reason - they want to know how to programme.
They know that programmers can do all sorts of cool things
with computers. But the bsaic tutorials don't usually teach
you enough to know where to even start on wruiting a new
GUI based application or game. So where do you go after
you learn the basics? Remember these are often complete
beginners who have never used any kind of programming
language before. Its like learning the scales on a piano,
now how do I learn a tune?

> My advice to all potential Pythonistas who want to learn on their 
> own: think
> of a problem you need to solve, or a cool game you've wanted to 
> implement,
> or a tool you want but don't have.

I agree this is best. Provided the expectation level is kept in check.
For example if someone decided to write a WYSIWYG desktop
publishing programme as a first step after doing my tutor they would
very soon get discouraged and give up. But if they took a simple
home brewed lay-out language and translated it into HTML, maybe
based on CSS stylesheets then its probably within their grasp.

> In my own case, I had a project I needed to do (printing mailing
> labels from records in an old proprietary database)
> that was going to suck if I used only the tools I already had.

And that' a good exercise. But a beginner usually isn't even
sure if Python could tackle such a project or where to start.

> If you don't have a professional task that you could apply Python 
> to, just
> look around your environment for a day or so looking for problems to 
> solve.

Again good advice if you have even a basic idea of what programming
can achieve. But you need that concept first. It' one reason that 
overly
basic or overly theoretical programming tutorials can lead to 
problems.
Its also why in my tutor I provide several suggested projects and
enhancements to the examples I give. Plus I try to introduce the
practical elements into the examples I give rather than using,
for example, purely math based ones. (And yes I know most math
problems have practical applications, but not for most amateurs!)

In the meantime lets encourage these beginners to think up their
own problems but at the same time give them ideas as for typical
tasks that are within their reach.

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



From airchia at gmail.com  Mon Jul  7 20:29:14 2008
From: airchia at gmail.com (Nick Scholtes)
Date: Mon, 7 Jul 2008 13:29:14 -0500
Subject: [Tutor] New to pythong
In-Reply-To: <40af687b0807071043m13bab78bw2d4fea1adc76d001@mail.gmail.com>
References: <BLU105-W38914C642F2EA8B0D18713DE940@phx.gbl>
	<40af687b0807071043m13bab78bw2d4fea1adc76d001@mail.gmail.com>
Message-ID: <a2a149b80807071129q1630545cmc1f539e04267b78e@mail.gmail.com>

Thanks for the info on the Think Python book, and thanks Jeremiah, for
posing this question. That book is one of the best Python learning resources
I've yet found! Makes it really easy to understand!

Nick


On Mon, Jul 7, 2008 at 12:43 PM, Marc Tompkins <marc.tompkins at gmail.com>
wrote:

> On Mon, Jul 7, 2008 at 9:40 AM, Jeremiah Stack <ttlingit at hotmail.com>
> wrote:
>
>>
>>
>> Hello everybody:
>>
>> I am new to this mailing list, and it said that i could the simplest of
>> questions. So i was wondering if anyone could be so kind as to e-mail me a
>> project idea or something to go out an learn to do in python. I don't know
>> any languages, but i am definitely not computer illiterate. i have read so
>> many tutorial about getting started but so far that is where the tutorial
>> have left me ( how to print  "Hello World") and such.
>>
>> Any ideas great thanks.
>>
>>
> First of all, I mean no offense to the OP.  However, this question comes up
> a lot on this list, and it always bugs me.  People decide they want to learn
> Python, and then ask strangers to give them a reason to do it.  I may be
> totally wrong about this, but it doesn't seem like a good way to learn
> _anything_, let alone a programming language.  The most important element
> for success is enthusiasm, and how can you generate any enthusiasm working
> on somebody else's homework project?  Unless you learn best under external
> discipline, in which case I suggest you take a class...
>
> My advice to all potential Pythonistas who want to learn on their own:
> think of a problem you need to solve, or a cool game you've wanted to
> implement, or a tool you want but don't have.  In my own case, I had a
> project I needed to do (printing mailing labels from records in an old
> proprietary database) that was going to suck if I used only the tools I
> already had.  I'd been wanting to get into Python, and I decided to use
> Python to do the job and learn as I went.  It was WONDERFUL, and I've been
> in love with Python ever since.  (Yes, I've used it for fun stuff since
> then, but my first experience was of Python saving me hours and hours of
> pain.)
>
> If you don't have a professional task that you could apply Python to, just
> look around your environment for a day or so looking for problems to solve.
> (My favorite example of this, although it's a very silly program and written
> in JavaScript besides, is Roast Beef's "Eggs and Milk Minder" from
> Achewood <http://achewood.com/index.php?date=05082002>.)
>
> Just my &euro;0.0075...
>
> --
> www.fsrtechnologies.com
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Art: bellsoffreedom.cgsociety.org/gallery/

Blog: cognitivealchemy.blogspot.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080707/dc56a1bb/attachment-0001.htm>

From bhaaluu at gmail.com  Mon Jul  7 20:46:41 2008
From: bhaaluu at gmail.com (bhaaluu)
Date: Mon, 7 Jul 2008 14:46:41 -0400
Subject: [Tutor] New to pythong
In-Reply-To: <BLU105-W38914C642F2EA8B0D18713DE940@phx.gbl>
References: <BLU105-W38914C642F2EA8B0D18713DE940@phx.gbl>
Message-ID: <ea979d70807071146l4e7c8ce5je851b2fa96c2bcdc@mail.gmail.com>

On Mon, Jul 7, 2008 at 12:40 PM, Jeremiah Stack <ttlingit at hotmail.com> wrote:
>
>
> Hello everybody:
>
> I am new to this mailing list, and it said that i could the simplest of
> questions. So i was wondering if anyone could be so kind as to e-mail me a
> project idea or something to go out an learn to do in python. I don't know
> any languages, but i am definitely not computer illiterate. i have read so
> many tutorial about getting started but so far that is where the tutorial
> have left me ( how to print  "Hello World") and such.
>
> Any ideas great thanks.
>

Hi J

Take a look at this stuff:
The book is old, based on ancient line-numbered BASIC.

I started out trying to learn about Text Adventure Games.

So the 'project' is to make the games described in the book
run in Python. There are five games. I got the first three
working, and started on the fourth, then got busy with
other things. However, you can read the book, take apart
the source code I've done, put it back together, modify it,
whatever. It's a fun beginner project, if you're interested
in Text Adventure Games.

http://www.geocities.com/ek.bhaaluu/python/index.html

Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m
In a world without fences, who needs Gates?
Kid on Bus: What are you gonna do today, Napoleon?
Napoleon Dynamite: Whatever I feel like I wanna do. Gosh!

From chester_lab at fltg.net  Mon Jul  7 22:13:04 2008
From: chester_lab at fltg.net (FT)
Date: Mon, 7 Jul 2008 16:13:04 -0400
Subject: [Tutor] New to pythong
References: <BLU105-W38914C642F2EA8B0D18713DE940@phx.gbl><40af687b0807071043m13bab78bw2d4fea1adc76d001@mail.gmail.com>
	<a2a149b80807071129q1630545cmc1f539e04267b78e@mail.gmail.com>
Message-ID: <004401c8e06d$e258d9f0$0501a8c0@brucetower>


Hi!

    
    Yes, Mark had something to say, and so did Alan. Games are a good start, also a home need, or a business need. 
    The way I started Python was games. The Yhatzee game, then my Star Trek game, converted over from the original basic game. Then the battleship game, the board game, which required people to call out grid places to see if a ship was hit...
    Since I am visually impaired, and sounds are all I need, then the first games are all sound effects and voices. Then the need for a sighted person to understand, then the visual, buttons and menu's come in. Then the rest is your imagination.

    For when learning each level of python a new need arises. I solved the event issue I raised last by playing with the details of events, understanding what is needed, and reading the formats and playing with them to see the results. Many commands, just select which works best.

    For when writing python programs you must understand the dictionary and list formats. They come in handy. As does the list comprehension idea and it's format.

    Many things to try and do. Just have to come up with a need, or fun. The rest of the imagination is yours.

    Just remember that at first the program is large, bulky, then once other formats and commands are learned, the program gets smaller, then larger to fit more options, then smaller...

    Think of a game to play and then expand on it.

        Bruce




Thanks for the info on the Think Python book, and thanks Jeremiah, for posing this question. That book is one of the best Python learning resources I've yet found! Makes it really easy to understand!

Nick



On Mon, Jul 7, 2008 at 12:43 PM, Marc Tompkins <marc.tompkins at gmail.com> wrote:

  On Mon, Jul 7, 2008 at 9:40 AM, Jeremiah Stack <ttlingit at hotmail.com> wrote:



    Hello everybody:

    I am new to this mailing list, and it said that i could the simplest of questions. So i was wondering if anyone could be so kind as to e-mail me a project idea or something to go out an learn to do in python. I don't know any languages, but i am definitely not computer illiterate. i have read so many tutorial about getting started but so far that is where the tutorial have left me ( how to print  "Hello World") and such. 

    Any ideas great thanks.



  First of all, I mean no offense to the OP.  However, this question comes up a lot on this list, and it always bugs me.  People decide they want to learn Python, and then ask strangers to give them a reason to do it.  I may be totally wrong about this, but it doesn't seem like a good way to learn _anything_, let alone a programming language.  The most important element for success is enthusiasm, and how can you generate any enthusiasm working on somebody else's homework project?  Unless you learn best under external discipline, in which case I suggest you take a class...

  My advice to all potential Pythonistas who want to learn on their own: think of a problem you need to solve, or a cool game you've wanted to implement, or a tool you want but don't have.  In my own case, I had a project I needed to do (printing mailing labels from records in an old proprietary database) that was going to suck if I used only the tools I already had.  I'd been wanting to get into Python, and I decided to use Python to do the job and learn as I went.  It was WONDERFUL, and I've been in love with Python ever since.  (Yes, I've used it for fun stuff since then, but my first experience was of Python saving me hours and hours of pain.)

  If you don't have a professional task that you could apply Python to, just look around your environment for a day or so looking for problems to solve.  (My favorite example of this, although it's a very silly program and written in JavaScript besides, is Roast Beef's "Eggs and Milk Minder" from Achewood.)  

  Just my &euro;0.0075...


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080707/390b6ad9/attachment.htm>

From ttlingit at hotmail.com  Mon Jul  7 22:07:55 2008
From: ttlingit at hotmail.com (Jeremiah Stack)
Date: Mon, 7 Jul 2008 13:07:55 -0700
Subject: [Tutor] New to python(g)=python" g=(embarrassing)
In-Reply-To: <e2f191310807071033g36c431dam49898fa704679141@mail.gmail.com>
References: <BLU105-W38914C642F2EA8B0D18713DE940@phx.gbl>
	<333efb450807070958o5ee0aedbo5b9d5f9c60114fa9@mail.gmail.com> 
	<e2f191310807071033g36c431dam49898fa704679141@mail.gmail.com>
Message-ID: <BLU105-W381BADAB2635A20A99C6F2DE940@phx.gbl>

Hey

I want to thank you all for your patience, suggestions, constructive  criticism, and idea  builders!
I now have good thoughts to start, i will now try some of the suggested tutorials and activities.
For me before the sugestions the turorials were like reading the sentence "the tree is tall and black" without knowing what tree, tall, and black are or why i needed to know that. 
Now i have a goal in mind something i think will be neat to work for. Hopefully now i will be able to pick up the concepts.

No programming background, working on my math along with my degree. imberising 

Thanks everyone

(i don't know if I'm supposed to say thank you as that might get redundant)



Date: Mon, 7 Jul 2008 17:33:37 +0000
From: monjissvel at googlemail.com
To: tutor at python.org
Subject: Re: [Tutor] New to pythong

you can start with stuff you need like,  for example write a program that scans your hard disk & tells you the details about pdf, jpg, zip, avi files that you have, with creation date and sizes.
when you need help write us.




_________________________________________________________________
The i?m Talkaton. Can 30-days of conversation change the world?
http://www.imtalkathon.com/?source=EML_WLH_Talkathon_ChangeWorld
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080707/07058d24/attachment.htm>

From chester_lab at fltg.net  Mon Jul  7 22:26:08 2008
From: chester_lab at fltg.net (FT)
Date: Mon, 7 Jul 2008 16:26:08 -0400
Subject: [Tutor] New to pythong
References: <BLU105-W38914C642F2EA8B0D18713DE940@phx.gbl>
Message-ID: <006301c8e06f$b53f37f0$0501a8c0@brucetower>


Hello everybody:

I am new to this mailing list, and it said that i could the simplest of questions. So i was wondering if anyone could be so kind as to e-mail me a project idea or something to go out an learn to do in python. I don't know any languages, but i am definitely not computer illiterate. i have read so many tutorial about getting started but so far that is where the tutorial have left me ( how to print  "Hello World") and such. 

Any ideas great thanks.

Hi!

    Someone posted the description on how to fid and list files. This is one you could look at, study, and then expand on it. I added the file search as well.

    In each module you can expand and do much more with it, but when dealing with files and directories you must remember that you can erase a lot of stuff if you're not careful.


    Enjoy, Bruce



import sys, os   # imports all the functions in the os module (operating system functions)
cwd = os.getcwd()   # gets the current working directory and places it in the variable cwd
print "Enter file to search for: "
file2find = str(raw_input("__>"))
if file2find=="":
    sys.exit()
dirFiles = open( "filelist.txt","w")  # creates the file filelist.txt ready for writing using the variable dirFiles
# the walk function returns the current directory in root, the directories in dirs
# and the files in root in files. By using the for loop it traverses every folder
# from the starting folder.
c=0  #Count the files found!
for root, dirs, files in os.walk(cwd):
#    dirFiles.write(root + "\n")   # writes to dirFiles.txt the current directory name
    i=0   #file count for directory to save directory path if found!
    for theFiles in files:      # will iterate all the files in the current directory
        if file2find in theFiles:
            i+=1
            c+=1
            if i==1:
                dirFiles.write(root + "\n")   # writes to dirFiles.txt the current directory name
            dirFiles.write( "___________ " + theFiles + "\n") # writes the filename to dirlist.txt. the
dirFiles.close() # Cleanly saves and closes the file dirlist.txt
# Note: the "\n" in the write lines adds the newline character so that the next write starts on a newline


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080707/30eca10b/attachment-0001.htm>
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: DirWalk4File.py
URL: <http://mail.python.org/pipermail/tutor/attachments/20080707/30eca10b/attachment-0002.txt>
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: DirWalk.py
URL: <http://mail.python.org/pipermail/tutor/attachments/20080707/30eca10b/attachment-0003.txt>

From marc.tompkins at gmail.com  Mon Jul  7 22:28:43 2008
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Mon, 7 Jul 2008 13:28:43 -0700
Subject: [Tutor] New to python(g)=python" g=(embarrassing)
In-Reply-To: <BLU105-W381BADAB2635A20A99C6F2DE940@phx.gbl>
References: <BLU105-W38914C642F2EA8B0D18713DE940@phx.gbl>
	<333efb450807070958o5ee0aedbo5b9d5f9c60114fa9@mail.gmail.com>
	<e2f191310807071033g36c431dam49898fa704679141@mail.gmail.com>
	<BLU105-W381BADAB2635A20A99C6F2DE940@phx.gbl>
Message-ID: <40af687b0807071328y4bd55f51w60b5092b5ec53e7c@mail.gmail.com>

I did wonder whether there was a joke there...  is the Pythong the hot new
trend in beachwear?

On a creepier note, if you make the mistake of going to python dot com
instead of dot org, a Pythong is the least of your worries...  eeewww.
-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080707/672b6494/attachment.htm>

From airchia at gmail.com  Mon Jul  7 23:14:44 2008
From: airchia at gmail.com (Nick Scholtes)
Date: Mon, 7 Jul 2008 16:14:44 -0500
Subject: [Tutor] New to python(g)=python" g=(embarrassing)
In-Reply-To: <40af687b0807071328y4bd55f51w60b5092b5ec53e7c@mail.gmail.com>
References: <BLU105-W38914C642F2EA8B0D18713DE940@phx.gbl>
	<333efb450807070958o5ee0aedbo5b9d5f9c60114fa9@mail.gmail.com>
	<e2f191310807071033g36c431dam49898fa704679141@mail.gmail.com>
	<BLU105-W381BADAB2635A20A99C6F2DE940@phx.gbl>
	<40af687b0807071328y4bd55f51w60b5092b5ec53e7c@mail.gmail.com>
Message-ID: <a2a149b80807071414y1cbc017bi88447d4a17a30b5a@mail.gmail.com>

Thank you so much for that horrendous imagery. I think I'll go learn C#
instead.   : )

Nick



On Mon, Jul 7, 2008 at 3:28 PM, Marc Tompkins <marc.tompkins at gmail.com>
wrote:

> I did wonder whether there was a joke there...  is the Pythong the hot new
> trend in beachwear?
>
> On a creepier note, if you make the mistake of going to python dot com
> instead of dot org, a Pythong is the least of your worries...  eeewww.
> --
> www.fsrtechnologies.com
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Art: bellsoffreedom.cgsociety.org/gallery/

Blog: cognitivealchemy.blogspot.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080707/88c615a2/attachment.htm>

From david at abbottdavid.com  Tue Jul  8 00:18:40 2008
From: david at abbottdavid.com (David)
Date: Mon, 07 Jul 2008 18:18:40 -0400
Subject: [Tutor] While loop counter
Message-ID: <48729640.2030800@abbottdavid.com>

Hi, I am trying to get a while loop that will execute 5 time then stop.

#!/usr/bin/python
# Filename myfirstclass.py
#
# A Little digital clock

from time_class import Time
import sys
import time

mytime = Time()

print "Can you tell me the time (24h)?"
hour = input("Give the hour: ")
minute = input("Give the minutes: ")
second = input("Give the seconds: ")

mytime.set_time(hour, minute, second)
#counter = 0
#while counter < 5 :
#    counter = counter + 1
while True:
    mytime.tick()
    mytime.print_time()
    time.sleep(1) # Sleep for 1 second
counter = 0
while counter < 5 :
    counter = counter + 1

Here is the class;

#!/usr/bin/python
# Filename: time_class.py

class Time:

    def __init__(self):
        self.__hour = 0
        self.__minute = 0
        self.__second = 0

    def set_time(self, hour, minute, second):
        self.set_hour(hour)
        self.set_minute(minute)
        self.set_second(second)

    def set_hour(self, hour):
        if 0 <= hour and hour < 24:
            self.__hour = hour

    def set_minute(self, minute):
        if 0 <= minute and minute < 60:
          self.__minute = minute
   
    def set_second(self, second):
        if 0 <= second and second < 60:
            self.__second = second

    def tick(self):
        self.__second += 1
        self.__minute += self.__second / 60
        self.__hour += self.__minute / 60
       
        self.__hour = self.__hour % 24
        self.__minute = self.__minute % 60
        self.__second = self.__second % 60
       
       
    def print_time(self):
        print '%02d:%02d:%02d' % (self.__hour, self.__minute, self.__second)

Thanks, very new to Python.
-david

-- 
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com


From john at fouhy.net  Tue Jul  8 00:40:19 2008
From: john at fouhy.net (John Fouhy)
Date: Tue, 8 Jul 2008 10:40:19 +1200
Subject: [Tutor] While loop counter
In-Reply-To: <48729640.2030800@abbottdavid.com>
References: <48729640.2030800@abbottdavid.com>
Message-ID: <5e58f2e40807071540l6fefef5al10883e71bb07b1ca@mail.gmail.com>

On 08/07/2008, David <david at abbottdavid.com> wrote:
> Hi, I am trying to get a while loop that will execute 5 time then stop.

Hi David,

The standard pattern is like this:

i = 0
while i < 5:
    # the stuff you want to do goes here
    i = i + 1

Note that if you know exactly how many times you will execute your
loop, you should use a for loop instead:

for i in range(5):
    # the stuff you want to do goes here

HTH!

-- 
John.

From alan.gauld at btinternet.com  Tue Jul  8 02:24:26 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 8 Jul 2008 01:24:26 +0100
Subject: [Tutor] While loop counter
References: <48729640.2030800@abbottdavid.com>
Message-ID: <g4uc3q$20d$1@ger.gmane.org>

"David" <david at abbottdavid.com> wrote

> Hi, I am trying to get a while loop that will execute 5 time then 
> stop.

Copngratulations, you have succeeded.
Unfortunately nothing happens inside your loop. I suspect you
actually want to execute some code 5 times?

> #counter = 0
> #while counter < 5 :
> #    counter = counter + 1

Yep, this would have done it.

> while True:
>    mytime.tick()
>    mytime.print_time()
>    time.sleep(1) # Sleep for 1 second

And this loop runs forever because you never break
out of it.

> counter = 0
> while counter < 5 :
>    counter = counter + 1

If you did get out of the infinite loop above then  this one does do 
it too.
But all it does is increment the counter. If you want code to be 
executed
it must also be inside the loop (ie inside the indented code section).

So what I think you wanted would be:

counter = 0
while counter < 5:
    mytime.tick()
    mytime.print_time()
    time.sleep(1) # Sleep for 1 second
    counter = counter + 1

But since its for a fixed number of iterations you are better
off using a for loop:

for counter in range(5)
    mytime.tick()
    mytime.print_time()
    time.sleep(1) # Sleep for 1 second

Note we don't need to increment the counter in this version.

See the loops section of my tutorial for more about for
and while loops.

HTH,

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



From jtp at nc.rr.com  Tue Jul  8 03:10:57 2008
From: jtp at nc.rr.com (James)
Date: Mon, 7 Jul 2008 21:10:57 -0400
Subject: [Tutor] python + http authentication (with cherrypy)
Message-ID: <e107b4ff0807071810o4c18314ale806bd34c0c9ce98@mail.gmail.com>

Hi All,

I'm writing a web application in CherryPy. What a beautiful thing it
is to write Python code and get a simple yet powerful web output. :)

The web application needs to have some decent level of security and
authentication implemented.

The big issue here is that the user password is stored in a database
and algorithmically calculated as follows:
md5( md5( $password ) + salt ) )

The salt is also stored in the database (which I have full access to).
I can easily use the md5 library to compare what a user gives me and
see if that's the correct password (based on the salt and the stored
password in the database). I'm unsure, however, how to go about
implementing security into my web application.

CherryPy obviously has a 'session' library in it. But in the periods
of time I've researched writing web applications in the past
(primarily when dealing with PHP), there was always great debate in
how to write a "good" secure web application. (i.e., it becomes tricky
when determining what precisely you should be passing around in terms
of session variables).

Thoughts? Am I going about this the wrong way? It would be much easier
to use either digest or basic http authentication mechanisms, but I
don't think that this is possible because of the fact that the
password is double-hashed in the database (or am I wrong?).

Any help appreciated. :o)

-j

From kent37 at tds.net  Tue Jul  8 03:54:13 2008
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 7 Jul 2008 21:54:13 -0400
Subject: [Tutor] python + http authentication (with cherrypy)
In-Reply-To: <e107b4ff0807071810o4c18314ale806bd34c0c9ce98@mail.gmail.com>
References: <e107b4ff0807071810o4c18314ale806bd34c0c9ce98@mail.gmail.com>
Message-ID: <1c2a2c590807071854j797d9f9fsd3457b554c591bab@mail.gmail.com>

On Mon, Jul 7, 2008 at 9:10 PM, James <jtp at nc.rr.com> wrote:
> Hi All,
>
> I'm writing a web application in CherryPy. What a beautiful thing it
> is to write Python code and get a simple yet powerful web output. :)
>
> The web application needs to have some decent level of security and
> authentication implemented.
>
> The big issue here is that the user password is stored in a database
> and algorithmically calculated as follows:
> md5( md5( $password ) + salt ) )

> CherryPy obviously has a 'session' library in it. But in the periods
> of time I've researched writing web applications in the past
> (primarily when dealing with PHP), there was always great debate in
> how to write a "good" secure web application. (i.e., it becomes tricky
> when determining what precisely you should be passing around in terms
> of session variables).

A typical usage is to have a session cookie that is a key into some
kind of server storage, e.g. a database table. The cookie itself
doesn't contain any information.

You might want to look at TurboGears, it uses CherryPy so it might not
be too hard  to migrate your code, and it includes an identity
subsystem that supports user-written authentication backends. See for
example
http://docs.turbogears.org/1.0/GettingStartedWithIdentity
http://docs.turbogears.org/1.0/IdentityRecipes?action=show&redirect=1.0%2FIdentityRecipies#authenticating-against-an-external-password-source

Kent

From reed at reedobrien.com  Tue Jul  8 03:48:20 2008
From: reed at reedobrien.com (Reed O'Brien)
Date: Mon, 7 Jul 2008 21:48:20 -0400
Subject: [Tutor] python + http authentication (with cherrypy)
In-Reply-To: <e107b4ff0807071810o4c18314ale806bd34c0c9ce98@mail.gmail.com>
References: <e107b4ff0807071810o4c18314ale806bd34c0c9ce98@mail.gmail.com>
Message-ID: <EF3B3127-16A5-4A09-9717-C4698D8A6A4A@reedobrien.com>

On Jul 7, 2008, at 9:10 PM, James wrote:

> Hi All,
>
> I'm writing a web application in CherryPy. What a beautiful thing it
> is to write Python code and get a simple yet powerful web output. :)
>
> The web application needs to have some decent level of security and
> authentication implemented.
>
> The big issue here is that the user password is stored in a database
> and algorithmically calculated as follows:
> md5( md5( $password ) + salt ) )
>
>
> The salt is also stored in the database (which I have full access to).
> I can easily use the md5 library to compare what a user gives me and
> see if that's the correct password (based on the salt and the stored
> password in the database). I'm unsure, however, how to go about
> implementing security into my web application.

I had to do some stuff with salted hashed passwords a few months back  
and noted some stuff here:
http://reedobrien.blogspot.com/2008/01/seeded-salted-sha-passwords.html

md5 hash length would be 16 instead of sha's 20 IIRC... but otherwise  
I hope it helps you.

>
>
> CherryPy obviously has a 'session' library in it. But in the periods
> of time I've researched writing web applications in the past
> (primarily when dealing with PHP), there was always great debate in
> how to write a "good" secure web application. (i.e., it becomes tricky
> when determining what precisely you should be passing around in terms
> of session variables).
>
> Thoughts? Am I going about this the wrong way? It would be much easier
> to use either digest or basic http authentication mechanisms, but I
> don't think that this is possible because of the fact that the
> password is double-hashed in the database (or am I wrong?).
>
> Any help appreciated. :o)
>
> -j
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


From david at abbottdavid.com  Tue Jul  8 04:04:17 2008
From: david at abbottdavid.com (David)
Date: Mon, 07 Jul 2008 22:04:17 -0400
Subject: [Tutor] While loop counter
In-Reply-To: <g4uc3q$20d$1@ger.gmane.org>
References: <48729640.2030800@abbottdavid.com> <g4uc3q$20d$1@ger.gmane.org>
Message-ID: <4872CB21.6080806@abbottdavid.com>

Thank you John & Allen,

See the loops section of my tutorial for more about for
and while loops.

Yes, great tutorial, just getting it to sink in, now thats the problem :)


From kf9150 at gmail.com  Tue Jul  8 05:41:58 2008
From: kf9150 at gmail.com (Kelie)
Date: Tue, 8 Jul 2008 03:41:58 +0000 (UTC)
Subject: [Tutor] How to create array of variants?
Message-ID: <loom.20080708T032359-542@post.gmane.org>

Hello group,

I'm trying to translate the following VB code into Python and not sure how to
create an array of variants. 

Thanks for your help!

VB Code:
Sub SetXdata()
    Dim lineObj As AcadLine
    Set lineObj = ThisDrawing.ModelSpace.Item(0)
    
    Dim DataType(0 To 1) As Integer
    Dim Data(0 To 1) As Variant
    
    DataType(0) = 1001: Data(0) = "Test_Application"
    DataType(1) = 1070: Data(1) = 600
   
    lineObj.SetXdata DataType, Data
End Sub

Python code
import array
import comtypes.client

def SetXData():
    activedoc =
comtypes.client.GetActiveObject("AutoCAD.Application").ActiveDocument
    line = activedoc.ModelSpace.Item(0)

    dataType = array.array('i', [1001, 1070])
    dataValue = array.array('?', ['Test_Application', 600]) #What should I use
for the type code?

    line.SetXData(dataType, dataValue)

if __name__ == "__main__":
    SetXData()



From john at fouhy.net  Tue Jul  8 05:56:03 2008
From: john at fouhy.net (John Fouhy)
Date: Tue, 8 Jul 2008 15:56:03 +1200
Subject: [Tutor] How to create array of variants?
In-Reply-To: <loom.20080708T032359-542@post.gmane.org>
References: <loom.20080708T032359-542@post.gmane.org>
Message-ID: <5e58f2e40807072056k56baa4cdoa756c33f557907f0@mail.gmail.com>

On 08/07/2008, Kelie <kf9150 at gmail.com> wrote:
>  I'm trying to translate the following VB code into Python and not sure how to
>  create an array of variants.

I'm not sure what an array of variants in VB is -- perhaps an array
that can contain objects of any type?

>  Python code
>  import array

You may not need to use the array module -- the array module is
specifically for arrays of numerics in situations where performance
matters.  In general in Python, you get array-like behaviour using
lists.  Lists can hold objects of any type.

For example:

>>> myList = [100, 'Test application']
>>> myList[0]
100
>>> myList[1]
'Test application'

I recommend reading a python tutorial if this is new to you.

-- 
John.

From cspears2002 at yahoo.com  Tue Jul  8 06:52:28 2008
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Mon, 7 Jul 2008 21:52:28 -0700 (PDT)
Subject: [Tutor] line class
Message-ID: <223394.35925.qm@web51605.mail.re2.yahoo.com>

For problem 13-6 out of Core Python Programming, I created a line class that consists of two points.  The line class has the following methods: __repr__, length, and slope.  Here is the code:

#!/usr/bin/python

import sys,math

class Point(object):
    def __init__(self, x=0.0,y=0.0):
        self.x = float(x)
	self.y = float(y)
	
    def __repr__(self):
        coord = (self.x,self.y)
	return coord
	
    def __str__(self):
	point_str = "(%f,%f)" % (self.x, self.y)
	return point_str
	
class Line(object):
    def __init__(self, p1, p2):
        self.p1 = Point(x1,y1)
	self.p2 = Point(x2,y2)
	
    def __str__(self):
        x1,y1 = self.p1.x,self.p1.y
	x2,y2 = self.p2.x,self.p2.y
	line = "((%f,%f),(%f,%f))" % (x1,y1,x2,y2)
	return line
     
    __repr__ = __str__
    
    def length(self):
        dist_x = abs(self.p2.x - self.p1.x)
	dist_y = abs(self.p2.y - self.p1.y)
        dist_x_squared = dist_x ** 2
        dist_y_squared = dist_y ** 2
	line_length = math.sqrt(dist_x_squared + dist_y_squared)
        return line_length
	
    def slope(self):
        dist_y = self.p2.y - self.p1.y
	dist_x = self.p2.x - self.p1.x
	line_slope = dist_y/dist_x
	return line_slope
	
if __name__ == '__main__':
    print "Creating a Line"
    
    x1 = raw_input("Enter a x1 value: ")
    y1 = raw_input("Enter a y1 value: ")
    p1 = Point(x1,y1)
    #print p1
    
    x2 = raw_input("Enter a x2 value: ")
    y2 = raw_input("Enter a y2 value: ")
    p2 = Point(x2,y2)
    #print p2
    
    line = Line(p1,p2)
    
    print "What are the lines attributes?"
    print "Select one:"
    print "1) Display line"
    print "2) Display line's length"
    print "3) Display line's slope"
    print "4) Quit program"
    choice_string = raw_input("Make a choice: ")
    
    try:
        choice = int(choice_string)
    except ValueError:
        sys.exit("Not an integer!  Goodbye!")
    
    if choice == 1:
        print line
    elif choice == 2:
        line_length = line.length()
        print "Length is %f " % line_length
    elif choice == 3:
        line_slope = line.slope()
        print "Slope is %f " % line_slope
    elif choice == 4:
        print "Goodbye!"
    else:
        sys.exit("Wrong response Goodbye!")

For the most part, my script works fairly well except under the following circumstances:

Creating a Line
Enter a x1 value: 0
Enter a y1 value: 0
Enter a x2 value: 0
Enter a y2 value: 1
What are the lines attributes?
Select one:
1) Display line
2) Display line's length
3) Display line's slope
4) Quit program
Make a choice: 3
Traceback (most recent call last):
  File "line.py", line 79, in ?
    line_slope = line.slope()
  File "line.py", line 42, in slope
    line_slope = dist_y/dist_x
ZeroDivisionError: float division

Basically, if the two the x values are the same, I will get a ZeroDivisionError.  A line in this case would simply point straight up.  What would slope be in this case?  I will admit that this is probably a math problem not a programming one, but I decided to run it by you anyway.

Thanks.


      

From faheem at atlantiscomputing.com  Tue Jul  8 06:52:33 2008
From: faheem at atlantiscomputing.com (Faheem)
Date: Tue, 8 Jul 2008 10:22:33 +0530
Subject: [Tutor] Unzipping a list
Message-ID: <20080708102233.7715f1db@rental-faheem.bangalore.atlantiscomputing.com>

hey all,
 How can i pass the elements of a list in the follwoing manner?
  
 L =['ask'.'tell','repeat','sell']
 
 To illustrate my question:
 how can i pass the above list as follows
 
"/some/program/run -o ask tell repeat sell"

thanks in advance

From john at fouhy.net  Tue Jul  8 07:10:50 2008
From: john at fouhy.net (John Fouhy)
Date: Tue, 8 Jul 2008 17:10:50 +1200
Subject: [Tutor] line class
In-Reply-To: <223394.35925.qm@web51605.mail.re2.yahoo.com>
References: <223394.35925.qm@web51605.mail.re2.yahoo.com>
Message-ID: <5e58f2e40807072210r552ba3eu2404cb5dbc3e27fd@mail.gmail.com>

On 08/07/2008, Christopher Spears <cspears2002 at yahoo.com> wrote:
>  Basically, if the two the x values are the same, I will get a ZeroDivisionError.  A line in this
> case would simply point straight up.  What would slope be in this case?  I will admit that
> this is probably a math problem not a programming one, but I decided to run it by you
> anyway.

The slope in this case is undefined.  Throwing an exception seems to
be a pretty reasonable way of dealing with this case, to be honest.
(although if you're keen, you could define your own
"UndefinedSlopeError" or "VerticalLineError" exception and raise that
instead of the ZeroDivisionError)

-- 
John.

From faheem at atlantiscomputing.com  Tue Jul  8 09:50:32 2008
From: faheem at atlantiscomputing.com (Faheem)
Date: Tue, 8 Jul 2008 13:20:32 +0530
Subject: [Tutor] Unzipping a list
In-Reply-To: <20080708102233.7715f1db@rental-faheem.bangalore.atlantiscomputing.com>
References: <20080708102233.7715f1db@rental-faheem.bangalore.atlantiscomputing.com>
Message-ID: <20080708132032.295daef7@rental-faheem.bangalore.atlantiscomputing.com>

Hey all,

If anyone is interested I found this while googling

answers= ['ask'.'tell','repeat','sell']
 
def unzip(answers): 
  unzipped = "".join(answers) # if all items are strings
  unzipped = ", ".join(map(str, answers))
  unzipped = " ".join(str(v) for v in answers if v > 0)
  return unzipped 

will give the following

  ask tell repeat sell

 :)

> hey all,
>  How can i pass the elements of a list in the follwoing manner?
>   
>  L =['ask'.'tell','repeat','sell']
>  
>  To illustrate my question:
>  how can i pass the above list as follows
>  
> "/some/program/run -o ask tell repeat sell"
> 
> thanks in advance

From alan.gauld at btinternet.com  Tue Jul  8 10:01:18 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 8 Jul 2008 09:01:18 +0100
Subject: [Tutor] line class
References: <223394.35925.qm@web51605.mail.re2.yahoo.com>
Message-ID: <g4v6sf$4oj$1@ger.gmane.org>


"Christopher Spears" <cspears2002 at yahoo.com> wrote

> class Point(object):
>    def __init__(self, x=0.0,y=0.0):

> class Line(object):
>    def __init__(self, p1, p2):
>        self.p1 = Point(x1,y1)
> self.p2 = Point(x2,y2)

This is wrong I suspect.

You are passing two point objects into the constructor but
never using them. Instead you use the global variables
x1, etc to initialise the line. This means that all lines
will be the same!

I suspect it should be:

def __init__(self,p1,p2):
    self.p1 = p1
    self.p2 = p2

And since a line should not have zero length (although
you might argue with that!) you could also check if
p1==p2

def __init__(self,p1,p2):
     if p1 == p2:
         raise ValueError, "Line cannot have zero length"
    self.p1 = p1
    self.p2 = p2


> if __name__ == '__main__':
>    print "Creating a Line"
>
>    x1 = raw_input("Enter a x1 value: ")
>    y1 = raw_input("Enter a y1 value: ")
>    p1 = Point(x1,y1)
>    #print p1
>
>    x2 = raw_input("Enter a x2 value: ")
>    y2 = raw_input("Enter a y2 value: ")
>    p2 = Point(x2,y2)
>    #print p2
>
>    line = Line(p1,p2)

So although you pass p1,p2, here they are redundant
because you are using x,y above directly.



> Enter a x1 value: 0
> Enter a y1 value: 0
> Enter a x2 value: 0
> Enter a y2 value: 1
> Traceback (most recent call last):
>  File "line.py", line 79, in ?
>    line_slope = line.slope()
>  File "line.py", line 42, in slope
>    line_slope = dist_y/dist_x
> ZeroDivisionError: float division
>
> Basically, if the two the x values are the same, I will get a 
> ZeroDivisionError.
> A line in this case would simply point straight up.  What would 
> slope be
> in this case?

It would be infinite which most programming languages, including
Python, cannot represent. So you need to trap the error and report
the problem or return some arbitrary infinity flag.

HTH,

Alan G.



From kf9150 at gmail.com  Tue Jul  8 11:00:59 2008
From: kf9150 at gmail.com (Kelie)
Date: Tue, 8 Jul 2008 09:00:59 +0000 (UTC)
Subject: [Tutor] How to create array of variants?
References: <loom.20080708T032359-542@post.gmane.org>
	<5e58f2e40807072056k56baa4cdoa756c33f557907f0@mail.gmail.com>
Message-ID: <loom.20080708T085708-817@post.gmane.org>

John,

Thanks for your reply. I'm aware of list, tuple, sets, etc. and have tried them,
which results in an error: Invalid argument type in SetXData method. My
understanding is that I do need an array here. Just don't know the correct way
of doing it.


From andreengels at gmail.com  Tue Jul  8 11:15:25 2008
From: andreengels at gmail.com (Andre Engels)
Date: Tue, 8 Jul 2008 11:15:25 +0200
Subject: [Tutor] How to create array of variants?
In-Reply-To: <loom.20080708T085708-817@post.gmane.org>
References: <loom.20080708T032359-542@post.gmane.org>
	<5e58f2e40807072056k56baa4cdoa756c33f557907f0@mail.gmail.com>
	<loom.20080708T085708-817@post.gmane.org>
Message-ID: <6faf39c90807080215v70dee900j2a353cc2df907ea8@mail.gmail.com>

On Tue, Jul 8, 2008 at 11:00 AM, Kelie <kf9150 at gmail.com> wrote:
> John,
>
> Thanks for your reply. I'm aware of list, tuple, sets, etc. and have tried them,
> which results in an error: Invalid argument type in SetXData method. My
> understanding is that I do need an array here. Just don't know the correct way
> of doing it.

So what does the code of line.SetXData(dataType, dataValue) look like?
>From that code you should be able to discern what argument type is
wanted.


-- 
Andre Engels, andreengels at gmail.com
ICQ: 6260644 -- Skype: a_engels

From kent37 at tds.net  Tue Jul  8 12:23:49 2008
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 8 Jul 2008 06:23:49 -0400
Subject: [Tutor] line class
In-Reply-To: <223394.35925.qm@web51605.mail.re2.yahoo.com>
References: <223394.35925.qm@web51605.mail.re2.yahoo.com>
Message-ID: <1c2a2c590807080323p555b45d1n18912e7a2fc64aee@mail.gmail.com>

On Tue, Jul 8, 2008 at 12:52 AM, Christopher Spears
<cspears2002 at yahoo.com> wrote:
> For problem 13-6 out of Core Python Programming, I created a line class that consists of two points.  The line class has the following methods: __repr__, length, and slope.  Here is the code:

>    def __repr__(self):
>        coord = (self.x,self.y)
>        return coord

This should be return str(coord); __repr__() should return a string,
not a tuple.

> Basically, if the two the x values are the same, I will get a ZeroDivisionError.  A line in this case would simply point straight up.  What would slope be in this case?  I will admit that this is probably a math problem not a programming one, but I decided to run it by you anyway.

The slope is infinity (or undefined). On some platforms and Python
versions you can use float('inf') to represent positive infinity so
you could return that if it is supported.
http://www.python.org/dev/peps/pep-0754/ (note this PEP was rejected)

Kent

From kent37 at tds.net  Tue Jul  8 12:25:57 2008
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 8 Jul 2008 06:25:57 -0400
Subject: [Tutor] line class
In-Reply-To: <g4v6sf$4oj$1@ger.gmane.org>
References: <223394.35925.qm@web51605.mail.re2.yahoo.com>
	<g4v6sf$4oj$1@ger.gmane.org>
Message-ID: <1c2a2c590807080325p781e377clfa6c7d6f27f7d79@mail.gmail.com>

On Tue, Jul 8, 2008 at 4:01 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:

> def __init__(self,p1,p2):
>   self.p1 = p1
>   self.p2 = p2
>
> And since a line should not have zero length (although
> you might argue with that!) you could also check if
> p1==p2

In this case he should define Point.__cmp__() so the comparison is by
value rather than identity.

Kent

From lie.1296 at gmail.com  Sun Jul  6 11:09:11 2008
From: lie.1296 at gmail.com (Lie Ryan)
Date: Sun, 06 Jul 2008 16:09:11 +0700
Subject: [Tutor] Tutor Digest, Vol 53, Issue 13
In-Reply-To: <mailman.403.1215122758.20627.tutor@python.org>
References: <mailman.403.1215122758.20627.tutor@python.org>
Message-ID: <1215335351.7801.8.camel@lieryan-laptop>

> Message: 5
> Date: Fri, 04 Jul 2008 00:29:03 +0800
> From: Dong Li <dongli2020 at gmail.com>
> Subject: Re: [Tutor] Question about string
> To: tutor at python.org
> Message-ID: <1215102543.13683.4.camel at localhost.localdomain>
> Content-Type: text/plain
> 
> 
> > Date: Thu, 3 Jul 2008 10:18:23 +0100
> > From: "Alan Gauld" <alan.gauld at btinternet.com>
> > Subject: Re: [Tutor] Question about string
> > To: tutor at python.org
> > Message-ID: <g4i5h5$1cc$1 at ger.gmane.org>
> > Content-Type: text/plain; format=flowed; charset="iso-8859-1";
> >       reply-type=original
> > 
> > 
> > "Dong Li" <dongli2020 at gmail.com> wrote
> > 
> > > I am new to python, so what I ask may be so basic. I don't know
> the
> > > difference between
> > >
> > > s = 'a' 'b'
> > > and
> > > s = 'a'+'b'
> > >
> > > They have the same results. Thanks for relying!
> > 
> > I think the differencec is that the first is purely a syntax thing
> so
> > the interpreter does the work of joining the strings together before
> > processing the result as a single string whereas the second the
> > two strings are treated separately and actual string addition
> > (concatenation) is done which is a much more expensive
> > operation in terms of computer power.
> > 
> > The first is only possible if you have literal strings but the
> second
> > can be used for variables:
> > 
> > s1 = 'a'
> > s2 = 'b'
> > s = s1 s2     # doesn't work
> > s = s1 + s2   # works
> > 
> > HTH,
> > 
> > -- 
> > Alan Gauld
> > Author of the Learn to Program web site
> > http://www.freenetpages.co.uk/hp/alan.gauld 
> > 
> 
> > ------------------------------
> 
> > Date: Thu, 3 Jul 2008 09:53:07 +0000
> > From: "Monika Jisswel" <monjissvel at googlemail.com>
> > Subject: Re: [Tutor] Question about string
> > To: tutor at python.org
> > Message-ID:
> >       <e2f191310807030253p681550d0t76e69a4080055584 at mail.gmail.com>
> > Content-Type: text/plain; charset="iso-8859-1"
> > 
> > Python is one of the smartest languages, it does many things for the
> > programmer  (I don't know but this might be what they mean with
> > Batteries-Included) , & you have just scratched the surface of it,
> here
> > python concatenated your strings together for you, later you will
> meet list
> > comprehention & other stuff that actually does most of the
> programing logic
> > for you for free.
> > -------------- next part --------------
> > An HTML attachment was scrubbed...
> > URL:
> <http://mail.python.org/pipermail/tutor/attachments/20080703/9c54d12a/attachment-0001.htm>
> > 
> > ------------------------------
> 
> Thank you for excellent explanations! I have been attracted by python
> more and more!

The string implicit string concatenation exist for things like verbose
re (regular expression):

import re
re.compile(
'<'     # Start opening tag
'\s*'   # Arbitrary whitespace
'(.*?)' # tagname
?'\s*'   # Arbitrary whitespace
'(.*?)' # Values
'>',    # Start closing tag
re.VERBOSE
)

Without the implicit string concatenation, that re would have to be
written like this:

?import re
re.compile(
'<'     + \  # Start opening tag
'\s*'?   + \  # Arbitrary whitespace
'(.*?)'? + \  # tagname
?'\s*'?   + \  # Arbitrary whitespace
'(.*?)'? + \  # Values
'>',    # Start closing tag
re.VERBOSE
)

or in one long lines, and comment is thus impossible.


From monjissvel at googlemail.com  Tue Jul  8 13:04:04 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Tue, 8 Jul 2008 11:04:04 +0000
Subject: [Tutor] How to create array of variants?
In-Reply-To: <e2f191310807080403t4468c2c4seae2ae39d2d4e493@mail.gmail.com>
References: <loom.20080708T032359-542@post.gmane.org>
	<5e58f2e40807072056k56baa4cdoa756c33f557907f0@mail.gmail.com>
	<loom.20080708T085708-817@post.gmane.org>
	<6faf39c90807080215v70dee900j2a353cc2df907ea8@mail.gmail.com>
	<e2f191310807080403t4468c2c4seae2ae39d2d4e493@mail.gmail.com>
Message-ID: <e2f191310807080404k73196980n3ab0a1d10eb3c282@mail.gmail.com>

Comment : I never did any VB so I am not sure if I understand you.

supposing your data comes like this :

python code :

Data = ( ('A', 1), ('B', 2), ('C', 3), ('D', 4) )
> #you can create a list of the items like this :
>
> List_Letters = [ x[0] for x in Data]
> List_Numbers = [ x[1] for x in Data]
>

hope this helps.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080708/9f54bb19/attachment.htm>

From kent37 at tds.net  Tue Jul  8 13:23:09 2008
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 8 Jul 2008 07:23:09 -0400
Subject: [Tutor] Tutor Digest, Vol 53, Issue 13
In-Reply-To: <1215335351.7801.8.camel@lieryan-laptop>
References: <mailman.403.1215122758.20627.tutor@python.org>
	<1215335351.7801.8.camel@lieryan-laptop>
Message-ID: <1c2a2c590807080423vb995b9ah5e03946f47d02935@mail.gmail.com>

On Sun, Jul 6, 2008 at 5:09 AM, Lie Ryan <lie.1296 at gmail.com> wrote:

> The string implicit string concatenation exist for things like verbose
> re (regular expression):
>
> import re
> re.compile(
> '<'     # Start opening tag
> '\s*'   # Arbitrary whitespace
> '(.*?)' # tagname
> ?'\s*'   # Arbitrary whitespace
> '(.*?)' # Values
> '>',    # Start closing tag
> re.VERBOSE
> )

VERBOSE regular expressions can contain comments; this could be written as
re.compile('''
<     # Start opening tag
\s*   # Arbitrary whitespace
(.*?) # tagname
?\s*   # Arbitrary whitespace
(.*?) # Values
>''',    # Start closing tag
re.VERBOSE
)

Kent

From Mike.Hansen at atmel.com  Tue Jul  8 16:23:21 2008
From: Mike.Hansen at atmel.com (Hansen, Mike)
Date: Tue, 8 Jul 2008 08:23:21 -0600
Subject: [Tutor] Exploring the Standard Library
In-Reply-To: <1215282216.6950.27.camel@poisontongue>
References: <1215282216.6950.27.camel@poisontongue>
Message-ID: <7941B2693F32294AAF16C26B679A258D02D140F2@csomb01.corp.atmel.com>

> [mailto:tutor-bounces at python.org] On Behalf Of Nathan Farrar
> Sent: Saturday, July 05, 2008 12:24 PM
> To: Python Tutor
> Subject: [Tutor] Exploring the Standard Library
> 
> I'd like to spend some time exploring the standard library.  
> I'm running python on Ubuntu.  How would I find the location 
> of the modules (find / -name "os.py" does not yield results)?
> 
> Thanks!
> Nathan 
> 

I'm a bit behind on reading the tutor list. I don't think I saw anyone
mention "The eff-bot guide to the standard library". Granted, it might
be a little dated, but I suspect that most of the modules haven't
changed that much since it was written. I like it because it has
example code.

http://effbot.org/zone/librarybook-index.htm

Mike

From Mike.Hansen at atmel.com  Tue Jul  8 16:30:01 2008
From: Mike.Hansen at atmel.com (Hansen, Mike)
Date: Tue, 8 Jul 2008 08:30:01 -0600
Subject: [Tutor] New to pythong
In-Reply-To: <40af687b0807071043m13bab78bw2d4fea1adc76d001@mail.gmail.com>
References: <BLU105-W38914C642F2EA8B0D18713DE940@phx.gbl>
	<40af687b0807071043m13bab78bw2d4fea1adc76d001@mail.gmail.com>
Message-ID: <7941B2693F32294AAF16C26B679A258D02D14109@csomb01.corp.atmel.com>

>Subject: Re: [Tutor] New to pythong 
>Hello everybody: 
> 
>I am new to this mailing list, and it said that i could the simplest of
questions. So i was wondering if anyone could be so kind as to e-mail me
a project idea or something to go out an learn to do in python. I don't
know any languages, but i am definitely not computer illiterate. i have
read so many tutorial about getting started but so far that is where the
tutorial have left me ( how to print  "Hello World") and such. 

> 
>Any ideas great thanks. 

There's some ideas on the tutor FAQ: 

http://effbot.org/pyfaq/tutor-im-learning-python-what-should-i-program.h
tm 

Mike 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080708/392851b4/attachment.htm>

From mail at timgolden.me.uk  Tue Jul  8 16:32:08 2008
From: mail at timgolden.me.uk (Tim Golden)
Date: Tue, 08 Jul 2008 15:32:08 +0100
Subject: [Tutor] Exploring the Standard Library
In-Reply-To: <7941B2693F32294AAF16C26B679A258D02D140F2@csomb01.corp.atmel.com>
References: <1215282216.6950.27.camel@poisontongue>
	<7941B2693F32294AAF16C26B679A258D02D140F2@csomb01.corp.atmel.com>
Message-ID: <48737A68.4050702@timgolden.me.uk>

Hansen, Mike wrote:
>> [mailto:tutor-bounces at python.org] On Behalf Of Nathan Farrar
>> Sent: Saturday, July 05, 2008 12:24 PM
>> To: Python Tutor
>> Subject: [Tutor] Exploring the Standard Library
>>
>> I'd like to spend some time exploring the standard library.  
>> I'm running python on Ubuntu.  How would I find the location 
>> of the modules (find / -name "os.py" does not yield results)?
>>
>> Thanks!
>> Nathan 
>>
> 
> I'm a bit behind on reading the tutor list. I don't think I saw anyone
> mention "The eff-bot guide to the standard library". Granted, it might
> be a little dated, but I suspect that most of the modules haven't
> changed that much since it was written. I like it because it has
> example code.
> 
> http://effbot.org/zone/librarybook-index.htm

And if anyone wants the paper version, I've a copy I'll happily
pass on for the cost of the postage. (I'm based in the UK).

TJG

From dfjennings at gmail.com  Tue Jul  8 15:14:40 2008
From: dfjennings at gmail.com (Don Jennings)
Date: Tue, 8 Jul 2008 09:14:40 -0400
Subject: [Tutor] build list of non-empty variables
Message-ID: <22ce67f0807080614g758ea82eg5b16439a8ae7e14e@mail.gmail.com>

Hi, folks.

>From within a class, I want to return a string with data from non-empty
variables in a class.

I could create a list of all the variables and then iterate over them,
dropping the ones which are empty, then join() and return them; however, I
am guessing there is another way to get that list of variables or to
accomplish my goal. Suggestions?

Thanks!
Don
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080708/108d52cc/attachment.htm>

From ptmcg at austin.rr.com  Tue Jul  8 17:15:09 2008
From: ptmcg at austin.rr.com (Paul McGuire)
Date: Tue, 8 Jul 2008 10:15:09 -0500
Subject: [Tutor] line class
In-Reply-To: <mailman.2068.1215529012.20627.tutor@python.org>
References: <mailman.2068.1215529012.20627.tutor@python.org>
Message-ID: <6923C1AE467E4E8480A7D7152ED6F899@AWA2>

> 
> > def __init__(self,p1,p2):
> >   self.p1 = p1
> >   self.p2 = p2
> >
> > And since a line should not have zero length (although you might argue 
> > with that!) you could also check if
> > p1==p2
> 
> In this case he should define Point.__cmp__() so the comparison is by
value rather than identity.
> 
> Kent
> 

I'd also suggest that in defining __cmp__ that the OP's test for equality
should comprehend some kind of epsilon value, if the x-y coordinates are
going to be floating point numbers.  It is very easy in graphical apps to
get tripped up by floating point round-off.  Here is a contrived but simple
demonstration:

>>> x = 1
>>> for i in range(10): x -= 0.1
...
>>> x
1.3877787807814457e-016
>>> x == 0
False

So instead of "if p1.x == p2.x" you should use "if abs(p1.x-p2.x) <
EPSILON", and define EPSILON to something in the range of 1e-13 or so.

-- Paul


From alan.gauld at btinternet.com  Tue Jul  8 17:53:04 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 8 Jul 2008 16:53:04 +0100
Subject: [Tutor] Unzipping a list
References: <20080708102233.7715f1db@rental-faheem.bangalore.atlantiscomputing.com>
	<20080708132032.295daef7@rental-faheem.bangalore.atlantiscomputing.com>
Message-ID: <g502h0$b4k$1@ger.gmane.org>


"Faheem" <faheem at atlantiscomputing.com> wrote 

> If anyone is interested I found this while googling
> 
> answers= ['ask'.'tell','repeat','sell']
> 
> def unzip(answers): 
>  unzipped = "".join(answers) # if all items are strings
>  unzipped = ", ".join(map(str, answers))
>  unzipped = " ".join(str(v) for v in answers if v > 0)
>  return unzipped 
> 
> will give the following
> 
>  ask tell repeat sell

But in this particular case so would

' '.join(answers)

wouldn't it?

Alan G.


From kent37 at tds.net  Tue Jul  8 17:56:53 2008
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 8 Jul 2008 11:56:53 -0400
Subject: [Tutor] build list of non-empty variables
In-Reply-To: <22ce67f0807080614g758ea82eg5b16439a8ae7e14e@mail.gmail.com>
References: <22ce67f0807080614g758ea82eg5b16439a8ae7e14e@mail.gmail.com>
Message-ID: <1c2a2c590807080856y620e7bcdj63a9e3215c8c80c6@mail.gmail.com>

On Tue, Jul 8, 2008 at 9:14 AM, Don Jennings <dfjennings at gmail.com> wrote:
> Hi, folks.
>
> From within a class, I want to return a string with data from non-empty
> variables in a class.
>
> I could create a list of all the variables and then iterate over them,
> dropping the ones which are empty, then join() and return them; however, I
> am guessing there is another way to get that list of variables or to
> accomplish my goal. Suggestions?

It would help to see code that works according to your suggestion.

Where do the variables come from? Do you mean a list of all the
attributes in an instance of a class? A list comprehension is often
useful for creating a filtered list but I don't know if it will work
for you without understanding better what you want to do.

Kent

From alan.gauld at btinternet.com  Tue Jul  8 18:03:42 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 8 Jul 2008 17:03:42 +0100
Subject: [Tutor] line class
References: <223394.35925.qm@web51605.mail.re2.yahoo.com>
Message-ID: <g5034v$dhk$1@ger.gmane.org>


"Christopher Spears" <cspears2002 at yahoo.com> wrote


> class Point(object):
>    def __init__(self, x=0.0,y=0.0):
>        self.x = float(x)
> self.y = float(y)
> 
>    def __repr__(self):
>        coord = (self.x,self.y)
> return coord

You could add a couple of methods here to get deltaX and 
deltaY values Or even define __sub__ to return a tuple

This would save you pokintg about inside the Point objects 
in line which is a design anti-pattern in OOP terms.

> class Line(object):
>    def length(self):
>        dist_x = abs(self.p2.x - self.p1.x)
>        dist_y = abs(self.p2.y - self.p1.y)

You don;t bneed the abs() since when you square them 
you will always get a positive number.

>        dist_x_squared = dist_x ** 2
>        dist_y_squared = dist_y ** 2
>        line_length = math.sqrt(dist_x_squared + dist_y_squared)
>        return line_length

With __sub__ defined you could write:

def length(self):
     dx,dy = self.p1 - self.p2
     return (dx**2 + dy **2) ** 0.5

Let objects do it to themselves - the law of demeter.

>    def slope(self):
>        dist_y = self.p2.y - self.p1.y
>        dist_x = self.p2.x - self.p1.x
>        line_slope = dist_y/dist_x
>        return line_slope

And this becomes

def slope(self):
       dx,dy = self.p1 - self.p2
       return dy/dx

Just a thought. Get the objects to do the work not 
the using methods

HTH,

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


From kf9150 at gmail.com  Tue Jul  8 18:33:57 2008
From: kf9150 at gmail.com (Kelie)
Date: Tue, 8 Jul 2008 16:33:57 +0000 (UTC)
Subject: [Tutor] How to create array of variants?
References: <loom.20080708T032359-542@post.gmane.org>
	<5e58f2e40807072056k56baa4cdoa756c33f557907f0@mail.gmail.com>
	<loom.20080708T085708-817@post.gmane.org>
	<6faf39c90807080215v70dee900j2a353cc2df907ea8@mail.gmail.com>
Message-ID: <loom.20080708T163126-238@post.gmane.org>

Andre Engels <andreengels <at> gmail.com> writes:
> 
> So what does the code of line.SetXData(dataType, dataValue) look like?
> >From that code you should be able to discern what argument type is
> wanted.
> 

Thanks Andre. I don't know how the correct code should look like in Python. In
VB, I've posted the code in my original question. Since I'm using comtypes, I
looked up the generated module and this is what I can find about this SetXData
method:

COMMETHOD([dispid(1027), helpstring(u'Sets the extended data (XData) associated
with an object')], HRESULT, 'SetXData',
              ( ['in'], VARIANT, 'XDataType' ),
              ( ['in'], VARIANT, 'XDataValue' )),




From monjissvel at googlemail.com  Tue Jul  8 20:40:30 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Tue, 8 Jul 2008 18:40:30 +0000
Subject: [Tutor] build list of non-empty variables
In-Reply-To: <1c2a2c590807080856y620e7bcdj63a9e3215c8c80c6@mail.gmail.com>
References: <22ce67f0807080614g758ea82eg5b16439a8ae7e14e@mail.gmail.com>
	<1c2a2c590807080856y620e7bcdj63a9e3215c8c80c6@mail.gmail.com>
Message-ID: <e2f191310807081140w972a9c1m847e3406fe3ce58@mail.gmail.com>

list comprehention :  [ x for x in LIST if x != '' ]
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080708/76f668e6/attachment.htm>

From jeff at drinktomi.com  Tue Jul  8 21:34:59 2008
From: jeff at drinktomi.com (Jeff Younker)
Date: Tue, 8 Jul 2008 12:34:59 -0700
Subject: [Tutor] Inheritance help
In-Reply-To: <1c2a2c590807021920oda701d3xaed31fb339d5988@mail.gmail.com>
References: <18240495.post@talk.nabble.com> <g4h8kh$oje$1@ger.gmane.org>
	<1c2a2c590807021920oda701d3xaed31fb339d5988@mail.gmail.com>
Message-ID: <8F8E65C0-338B-45C2-B00A-26E8FC620324@drinktomi.com>

> Hmm. I don't understand the LSP to make any requirements on the
> constructors. It says that instances of a subclass should be
> substitutable for instances of the base class, it doesn't say anthing
> how the instances are created.

Constructors as a separate language entity is an idea born of C++,
Java, etc.  In Python classes are first-class values and constructors
are (mostly) normal methods with a funky name, so the LSP applies
to them just like any other method in a class.

-jeff


From alan.gauld at btinternet.com  Tue Jul  8 22:20:53 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 8 Jul 2008 21:20:53 +0100
Subject: [Tutor] How to create array of variants?
References: <loom.20080708T032359-542@post.gmane.org>
Message-ID: <g50i76$6u6$1@ger.gmane.org>


"Kelie" <kf9150 at gmail.com> wrote

> I'm trying to translate the following VB code into Python and not 
> sure how to
> create an array of variants.

An array of variants in Python is a list.
But I'm not sure why you think you need one?

> VB Code:
> Sub SetXdata()
>    Dim lineObj As AcadLine
>    Set lineObj = ThisDrawing.ModelSpace.Item(0)
>
>    Dim DataType(0 To 1) As Integer
>    Dim Data(0 To 1) As Variant
>
>    DataType(0) = 1001: Data(0) = "Test_Application"
>    DataType(1) = 1070: Data(1) = 600

So this is basically setting up two lists where
the DataType is an integer and the Data is  - in
these cases - a string or an integer.

>    lineObj.SetXdata DataType, Data

So if you pass in two Python lists containing:

DataType = [1001,1070]
Data = ["Test_Application", 600]

Does it work?

If not what error do you get? (The full text please)

> import comtypes.client
>
> def SetXData():
>    activedoc =
> comtypes.client.GetActiveObject("AutoCAD.Application").ActiveDocument
>    line = activedoc.ModelSpace.Item(0)
>
>    dataType = array.array('i', [1001, 1070])
>    dataValue = array.array('?', ['Test_Application', 600]) #What 
> should I use
> for the type code?

I don;t think you use an array here. An array in this context expects
a homogenous set of data. You need a mixed set. So a normal list
is most likely construct to use.

Alternatively does comtypes have a mechanism for converting Python
types to VB/COM Variants?

Alan G




From bgailer at gmail.com  Tue Jul  8 22:49:57 2008
From: bgailer at gmail.com (bob gailer)
Date: Tue, 08 Jul 2008 16:49:57 -0400
Subject: [Tutor] build list of non-empty variables
In-Reply-To: <e2f191310807081140w972a9c1m847e3406fe3ce58@mail.gmail.com>
References: <22ce67f0807080614g758ea82eg5b16439a8ae7e14e@mail.gmail.com>	<1c2a2c590807080856y620e7bcdj63a9e3215c8c80c6@mail.gmail.com>
	<e2f191310807081140w972a9c1m847e3406fe3ce58@mail.gmail.com>
Message-ID: <4873D2F5.6070608@gmail.com>

Monika Jisswel wrote:
> list comprehention :  [ x for x in LIST if x != '' ]

or just [ x for x in LIST if x ]

-- 
Bob Gailer
919-636-4239 Chapel Hill, NC


From cspears2002 at yahoo.com  Wed Jul  9 00:29:00 2008
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Tue, 8 Jul 2008 15:29:00 -0700 (PDT)
Subject: [Tutor] line class
Message-ID: <954065.88496.qm@web51610.mail.re2.yahoo.com>

I have been reading everyone's comments on my line class.  I have decided to implement some of the suggestions.  Someone suggested that I create a Point.__cmp__ method.  Here is what I have so far:

def __cmp__(self, other):
        if self.x == other.x and self.y == other.y:
	    return 0
	elif self.x < other.x and self.y < other.y:
	    return -1
	elif self.x > other.x and self.y > other.y:
	    return 1

Figuring out the results for the above situations was easy.  However, what should I do with the following situations:
self.x > other.x and self.y < other.y
self.x < other.x and self.y > other.y

Thanks.



      

From marc.tompkins at gmail.com  Wed Jul  9 01:00:31 2008
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Tue, 8 Jul 2008 16:00:31 -0700
Subject: [Tutor] line class
In-Reply-To: <954065.88496.qm@web51610.mail.re2.yahoo.com>
References: <954065.88496.qm@web51610.mail.re2.yahoo.com>
Message-ID: <40af687b0807081600w33b3ed73n46f19d052f46f4c8@mail.gmail.com>

On Tue, Jul 8, 2008 at 3:29 PM, Christopher Spears <cspears2002 at yahoo.com>
wrote:

> I have been reading everyone's comments on my line class.  I have decided
> to implement some of the suggestions.  Someone suggested that I create a
> Point.__cmp__ method.  Here is what I have so far:
>
> def __cmp__(self, other):
>        if self.x == other.x and self.y == other.y:
>            return 0
>        elif self.x < other.x and self.y < other.y:
>            return -1
>        elif self.x > other.x and self.y > other.y:
>            return 1
>
> Figuring out the results for the above situations was easy.  However, what
> should I do with the following situations:
> self.x > other.x and self.y < other.y
> self.x < other.x and self.y > other.y
>

Sorry to jump in late - I missed the first part of the discussion - but what
do you want to achieve with a Point.__cmp__ method?

Is it just to determine whether two points are identical - in which case I'd
write it like so:
def __cmp__(self, other):
    if (self.x == other.x) and (self.y == other.y):
        return True
    else:
        return False


Or are you trying to determine the slope of the line between two points, in
which case I'd write it like this:
def __cmp__(self, other):
    if self.x == other.x:
        return False # points are identical, or one above the other - slope
is undefined
    else:
        return (self.y - other.y) / (self.x - other.x) # rise over run

or... or... or...  First decide what you want out of it, then write the
function/method to give you the result you want.

-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080708/b0eafb16/attachment.htm>

From kf9150 at gmail.com  Wed Jul  9 01:31:36 2008
From: kf9150 at gmail.com (Kelie)
Date: Tue, 8 Jul 2008 23:31:36 +0000 (UTC)
Subject: [Tutor] How to create array of variants?
References: <loom.20080708T032359-542@post.gmane.org>
	<g50i76$6u6$1@ger.gmane.org>
Message-ID: <loom.20080708T231100-274@post.gmane.org>

Alan Gauld <alan.gauld <at> btinternet.com> writes:
> So if you pass in two Python lists containing:
> 
> DataType = [1001,1070]
> Data = ["Test_Application", 600]
> 
> Does it work?
> 
> If not what error do you get? (The full text please)
> 

Thanks Alan. This is the error I got:

Traceback (most recent call last):
  File "C:\Python25\codes\autocad\setxdata2.py", line 13, in <module>
    SetXData()
  File "C:\Python25\codes\autocad\setxdata2.py", line 10, in SetXData
    line.SetXData(dataType, dataValue)
_ctypes.COMError: (-2145320939, None, (u'Invalid argument type in SetXData
method', u'AutoCAD.Application', u'C:\\Program Files\\AutoCAD
2008\\HELP\\OLE_ERR.CHM', -2145320939, None))

> Alternatively does comtypes have a mechanism for converting Python
> types to VB/COM Variants?
> 

I think comtypes or pywin32 do take care of some conversion between Python 
types and VB types. But they don't work with AutoCAD.

Btw, this is the working code to draw a point in AutoCAD and you can't replace
pt = array.array('d', [0,0,0]) with pt = [0,0,0]. The latter gives an error:
COMError: (-2147024809, 'The parameter is incorrect.', (None, None, None, 0, 
None))

import array
import comtypes.client
acadApp = comtypes.client.GetActiveObject("AutoCAD.Application")
ms = acadApp.ActiveDocument.ModelSpace
pt = array.array('d', [0,0,0])
ms.AddPoint(pt)
print "Done."


From john at fouhy.net  Wed Jul  9 01:52:54 2008
From: john at fouhy.net (John Fouhy)
Date: Wed, 9 Jul 2008 11:52:54 +1200
Subject: [Tutor] How to create array of variants?
In-Reply-To: <loom.20080708T231100-274@post.gmane.org>
References: <loom.20080708T032359-542@post.gmane.org>
	<g50i76$6u6$1@ger.gmane.org> <loom.20080708T231100-274@post.gmane.org>
Message-ID: <5e58f2e40807081652n453f2099q79f7a4fc36109a9e@mail.gmail.com>

On 09/07/2008, Kelie <kf9150 at gmail.com> wrote:
> I think comtypes or pywin32 do take care of some conversion between Python
>  types and VB types. But they don't work with AutoCAD.

Hi Kelie,

This is a short excerpt from _Python Programming on Win32_:

"""In many cases, PythonCOM can translate between Python objects and
VARIANT structures seamlessly.  When you call a COM object and pass a
Python object, PythonCOM automatically creates a VARIANT of the right
type and passes the VARIANT to COM.
[...]
Python object type: Any other python sequence.
VARIANT type: An array of VARIANTs; each element of the sequence is
translated using this table.
[...]
In some cases, these translations aren't suitable; for example, a COM
object may be picky about the VARIANT types passed and accept only a
VT_I2 integer, not a VT_I4 integer.  This should be considered a bug
in the COM object, but it does happen.  In this case, you must use
earlybound COM by using MakePy. [...] If you can't use MakePy for your
COM object, you must get your hands dirty and use the
PyIDispatch.InvokeTypes() method manually; this is how MakePy gets the
behaviour it does.  The use of InvokeTypes() is beyond the scope of
this book."""

I think your question is beyond the scope of this mailing list :-)  I
think there's a mailing list dedicated to python on Windows; you might
do better there.

From dfjennings at gmail.com  Wed Jul  9 00:35:45 2008
From: dfjennings at gmail.com (Don Jennings)
Date: Tue, 8 Jul 2008 18:35:45 -0400
Subject: [Tutor] build list of non-empty variables
In-Reply-To: <1c2a2c590807080856y620e7bcdj63a9e3215c8c80c6@mail.gmail.com>
References: <22ce67f0807080614g758ea82eg5b16439a8ae7e14e@mail.gmail.com>
	<1c2a2c590807080856y620e7bcdj63a9e3215c8c80c6@mail.gmail.com>
Message-ID: <22ce67f0807081535t56792aebm58b5250e1d3fb228@mail.gmail.com>

("Duh! Code would be good," says newbie to himself.)

Here's an example from django which I am using, but I asked on this list
since it seems more related to python than the web framework:

class Contact(models.Model):
    first_name = models.CharField(max_length=30, blank=True)
    last_name = models.CharField(max_length=30, blank=True)
    email = models.EmailField(blank=True)
    phone = models.PhoneNumberField()

    def __unicode__(self):
        l=[self.first_name, self.last_name, self.email, self.phone]
        res=[]

        for x in l:
            if x != '':
                res.append(x)

        return ';'.join(res)

Thanks!
Don


On Tue, Jul 8, 2008 at 11:56 AM, Kent Johnson <kent37 at tds.net> wrote:

> On Tue, Jul 8, 2008 at 9:14 AM, Don Jennings <dfjennings at gmail.com> wrote:
> > Hi, folks.
> >
> > From within a class, I want to return a string with data from non-empty
> > variables in a class.
> >
> > I could create a list of all the variables and then iterate over them,
> > dropping the ones which are empty, then join() and return them; however,
> I
> > am guessing there is another way to get that list of variables or to
> > accomplish my goal. Suggestions?
>
> It would help to see code that works according to your suggestion.
>
> Where do the variables come from? Do you mean a list of all the
> attributes in an instance of a class? A list comprehension is often
> useful for creating a filtered list but I don't know if it will work
> for you without understanding better what you want to do.
>
> Kent
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080708/cb1a7113/attachment.htm>

From robert.johansson at math.umu.se  Tue Jul  8 23:19:07 2008
From: robert.johansson at math.umu.se (Robert Johansson)
Date: Tue, 8 Jul 2008 23:19:07 +0200
Subject: [Tutor] character encoding
Message-ID: <003401c8e140$45d4a720$d17df560$@johansson@math.umu.se>

Hi, I'm puzzled by the character encodings which I get when I use Python
with IDLE. The string '\xf6' represents a letter in the Swedish alphabet
when coded with utf8. On our computer with MacOSX this gets coded as
'\xc3\xb6' which is a string of length 2. I have configured IDLE to encode
utf8 but it doesn't make any difference. 

 

This works fine on my PC with WinXP but other things are strange there. When
I write a documentation for my functions in Swedish it gets completely
mashed up.

 

Regards/Robert     

 

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080708/26bfb8ed/attachment.htm>

From kent37 at tds.net  Wed Jul  9 03:32:17 2008
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 8 Jul 2008 21:32:17 -0400
Subject: [Tutor] character encoding
In-Reply-To: <8388674783944291767@unknownmsgid>
References: <8388674783944291767@unknownmsgid>
Message-ID: <1c2a2c590807081832l773df800r42aacaae492d3ff1@mail.gmail.com>

On Tue, Jul 8, 2008 at 5:19 PM, Robert Johansson
<robert.johansson at math.umu.se> wrote:
> Hi, I'm puzzled by the character encodings which I get when I use Python
> with IDLE. The string '\xf6' represents a letter in the Swedish alphabet
> when coded with utf8. On our computer with MacOSX this gets coded as
> '\xc3\xb6' which is a string of length 2. I have configured IDLE to encode
> utf8 but it doesn't make any difference.

I think you may be a bit confused about utf-8. '\xf6' is not a utf-8
character. U00F6 is the Unicode (not utf-8) codepoint for LATIN SMALL
LETTER O WITH DIAERESIS. '\xf6' is also the Latin-1 encoding of this
character. The utf-8 encoding of this character is the two-byte
sequence '\xc3\xb6'.

Can you give some more specific details about what you do and what you
see? Also you might want to do some background reading on Unicode;
this is a good place to start:
http://www.joelonsoftware.com/articles/Unicode.html

Kent

From kent37 at tds.net  Wed Jul  9 03:34:47 2008
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 8 Jul 2008 21:34:47 -0400
Subject: [Tutor] build list of non-empty variables
In-Reply-To: <22ce67f0807081535t56792aebm58b5250e1d3fb228@mail.gmail.com>
References: <22ce67f0807080614g758ea82eg5b16439a8ae7e14e@mail.gmail.com>
	<1c2a2c590807080856y620e7bcdj63a9e3215c8c80c6@mail.gmail.com>
	<22ce67f0807081535t56792aebm58b5250e1d3fb228@mail.gmail.com>
Message-ID: <1c2a2c590807081834ld5ccc19i1ec997e8eb6ee197@mail.gmail.com>

On Tue, Jul 8, 2008 at 6:35 PM, Don Jennings <dfjennings at gmail.com> wrote:

>     def __unicode__(self):
>         l=[self.first_name, self.last_name, self.email, self.phone]
>         res=[]
>
>         for x in l:
>             if x != '':
>                 res.append(x)
>
>         return ';'.join(res)

return ';'.join(x for x in l if x)
will work.

Kent

From john at fouhy.net  Wed Jul  9 03:35:48 2008
From: john at fouhy.net (John Fouhy)
Date: Wed, 9 Jul 2008 13:35:48 +1200
Subject: [Tutor] build list of non-empty variables
In-Reply-To: <4873D2F5.6070608@gmail.com>
References: <22ce67f0807080614g758ea82eg5b16439a8ae7e14e@mail.gmail.com>
	<1c2a2c590807080856y620e7bcdj63a9e3215c8c80c6@mail.gmail.com>
	<e2f191310807081140w972a9c1m847e3406fe3ce58@mail.gmail.com>
	<4873D2F5.6070608@gmail.com>
Message-ID: <5e58f2e40807081835p16c41c78l17e3087d717340fd@mail.gmail.com>

On 09/07/2008, bob gailer <bgailer at gmail.com> wrote:
>  or just [ x for x in LIST if x ]

or filter(None, LIST).  But that's a bit obscure.

(fractionally faster, though, according to my brief experiment with timeit)

-- 
John.

From kent37 at tds.net  Wed Jul  9 03:37:04 2008
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 8 Jul 2008 21:37:04 -0400
Subject: [Tutor] line class
In-Reply-To: <954065.88496.qm@web51610.mail.re2.yahoo.com>
References: <954065.88496.qm@web51610.mail.re2.yahoo.com>
Message-ID: <1c2a2c590807081837t2ab49f00wc13b2f30f95c5248@mail.gmail.com>

On Tue, Jul 8, 2008 at 6:29 PM, Christopher Spears
<cspears2002 at yahoo.com> wrote:
> I have been reading everyone's comments on my line class.  I have decided to implement some of the suggestions.  Someone suggested that I create a Point.__cmp__ method.  Here is what I have so far:
>
> def __cmp__(self, other):
>        if self.x == other.x and self.y == other.y:
>            return 0
>        elif self.x < other.x and self.y < other.y:
>            return -1
>        elif self.x > other.x and self.y > other.y:
>            return 1
>
> Figuring out the results for the above situations was easy.  However, what should I do with the following situations:
> self.x > other.x and self.y < other.y
> self.x < other.x and self.y > other.y

It might be easier to define __eq__ and __ne__ instead of __cmp__ if
you just want to test for equality. Otherwise you can pick an
arbitrary ordering or see if there is something that makes sense to
the rest of your application.

Kent

From ptmcg at austin.rr.com  Wed Jul  9 03:45:41 2008
From: ptmcg at austin.rr.com (Paul McGuire)
Date: Tue, 8 Jul 2008 20:45:41 -0500
Subject: [Tutor] line class
In-Reply-To: <mailman.2178.1215550211.20627.tutor@python.org>
References: <mailman.2178.1215550211.20627.tutor@python.org>
Message-ID: <220E00558EB141B9A297BB922FE2129B@AWA2>

> def length(self):
>      dx,dy = self.p1 - self.p2
>      return (dx**2 + dy **2) ** 0.5

How about:

def length(self):
     return math.hypot( *(self.p1 - self.p2) )

Compiled C code will be much faster than squaring and square rooting.

-- Paul


From john at fouhy.net  Wed Jul  9 04:11:48 2008
From: john at fouhy.net (John Fouhy)
Date: Wed, 9 Jul 2008 14:11:48 +1200
Subject: [Tutor] line class
In-Reply-To: <220E00558EB141B9A297BB922FE2129B@AWA2>
References: <mailman.2178.1215550211.20627.tutor@python.org>
	<220E00558EB141B9A297BB922FE2129B@AWA2>
Message-ID: <5e58f2e40807081911x2b6aef10kf11115a5fd180f5a@mail.gmail.com>

On 09/07/2008, Paul McGuire <ptmcg at austin.rr.com> wrote:
> > def length(self):
>  >      dx,dy = self.p1 - self.p2
>  >      return (dx**2 + dy **2) ** 0.5
>
> How about:
>
>  def length(self):
>      return math.hypot( *(self.p1 - self.p2) )
>
>  Compiled C code will be much faster than squaring and square rooting.

Well, here's what I get:

Morpork:~ repton$ python -m timeit -s 'dx, dy = (8, 5)' '(dx**2 + dy**2)**0.5'
1000000 loops, best of 3: 0.555 usec per loop
Morpork:~ repton$ python -m timeit -s 'dx, dy = (8, 5)' -s 'import
math' 'math.hypot(dx, dy)'
1000000 loops, best of 3: 0.6 usec per loop

YMMV, but it doesn't make a strong case for "much faster".

(if I make a local reference to math.hypot, I can save 0.1 usec, which
puts the math.hypot technique in the lead, at the expense of
readability:

Morpork:~ repton$ python -m timeit -s 'dx, dy = (8, 5)' -s 'import
math' -s 'hyp = math.hypot' 'hyp(dx, dy)'
1000000 loops, best of 3: 0.501 usec per loop
)

-- 
John.

From eric at ericabrahamsen.net  Wed Jul  9 05:05:48 2008
From: eric at ericabrahamsen.net (Eric Abrahamsen)
Date: Wed, 9 Jul 2008 11:05:48 +0800
Subject: [Tutor] character encoding
In-Reply-To: <1c2a2c590807081832l773df800r42aacaae492d3ff1@mail.gmail.com>
References: <8388674783944291767@unknownmsgid>
	<1c2a2c590807081832l773df800r42aacaae492d3ff1@mail.gmail.com>
Message-ID: <AAED01F0-FEFF-41CD-A43B-8C403E21412F@ericabrahamsen.net>

As for other resources, I recently came across this:
http://farmdev.com/talks/unicode/

This was the first explanation that really made me understand the  
difference between Unicode and utf-8 (and realize that I'd been using  
the terms 'encode' and 'decode' backwards!). Anyway, just one more  
resource.

E


On Jul 9, 2008, at 9:32 AM, Kent Johnson wrote:

> On Tue, Jul 8, 2008 at 5:19 PM, Robert Johansson
> <robert.johansson at math.umu.se> wrote:
>> Hi, I'm puzzled by the character encodings which I get when I use  
>> Python
>> with IDLE. The string '\xf6' represents a letter in the Swedish  
>> alphabet
>> when coded with utf8. On our computer with MacOSX this gets coded as
>> '\xc3\xb6' which is a string of length 2. I have configured IDLE to  
>> encode
>> utf8 but it doesn't make any difference.
>
> I think you may be a bit confused about utf-8. '\xf6' is not a utf-8
> character. U00F6 is the Unicode (not utf-8) codepoint for LATIN SMALL
> LETTER O WITH DIAERESIS. '\xf6' is also the Latin-1 encoding of this
> character. The utf-8 encoding of this character is the two-byte
> sequence '\xc3\xb6'.
>
> Can you give some more specific details about what you do and what you
> see? Also you might want to do some background reading on Unicode;
> this is a good place to start:
> http://www.joelonsoftware.com/articles/Unicode.html
>
> Kent
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


From akanksha.kumar14 at yahoo.com  Wed Jul  9 05:50:03 2008
From: akanksha.kumar14 at yahoo.com (Akanskha Kumar)
Date: Tue, 8 Jul 2008 20:50:03 -0700 (PDT)
Subject: [Tutor] (no subject)
Message-ID: <798383.17170.qm@web45606.mail.sp1.yahoo.com>

how to make a game tree for a tic tac toe game


      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080708/aa4c345b/attachment.htm>

From wescpy at gmail.com  Wed Jul  9 08:12:24 2008
From: wescpy at gmail.com (wesley chun)
Date: Tue, 8 Jul 2008 23:12:24 -0700
Subject: [Tutor] character encoding
In-Reply-To: <1c2a2c590807081832l773df800r42aacaae492d3ff1@mail.gmail.com>
References: <8388674783944291767@unknownmsgid>
	<1c2a2c590807081832l773df800r42aacaae492d3ff1@mail.gmail.com>
Message-ID: <78b3a9580807082312g2dfbe0fcqb21d32b5d91294f1@mail.gmail.com>

>  > Hi, I'm puzzled by the character encodings which I get when I use Python
>  > with IDLE. The string '\xf6' represents a letter in the Swedish alphabet
>  > when coded with utf8. On our computer with MacOSX this gets coded as
>  > '\xc3\xb6' which is a string of length 2. I have configured IDLE to encode
>  > utf8 but it doesn't make any difference.
>
> I think you may be a bit confused about utf-8. '\xf6' is not a utf-8
>  character. U00F6 is the Unicode (not utf-8) codepoint for LATIN SMALL
>  LETTER O WITH DIAERESIS. '\xf6' is also the Latin-1 encoding of this
>  character. The utf-8 encoding of this character is the two-byte
>  sequence '\xc3\xb6'.
>
> Also you might want to do some background reading on Unicode;
>  this is a good place to start:
>  http://www.joelonsoftware.com/articles/Unicode.html

kent is quite correct, and here is some Python code to demo it:

>>> x = u'\xf6'
>>> x
u'\xf6'
>>> print x
?
>>> y = x.encode('utf-8')
>>> y
'\xc3\xb6'
>>> print y
?

in the code above, our source string 'x' is a Unicode string, which is
"pure," meaning that it has not been encoded by any codec. we encode
this Unicode string into a UTF-8 binary string 'y', which takes up 2
bytes as Kent has mentioned already. we are able to dump the variables
as well as print them fine to the screen because our terminal was set
to UTF-8.

if we switch our terminal output to Latin-1, then we can view it that
way -- notice that the Latin-1 encoding only takes 1 byte instead of 2
for UTF-8:

>>> z = x.encode('latin-1')
>>> z
'\xf6'
>>> print z
?

here's another recommended Unicode document that is slightly more
Python-oriented:
http://wiki.pylonshq.com/display/pylonsdocs/Unicode

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

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

From alan.gauld at btinternet.com  Wed Jul  9 09:05:57 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 9 Jul 2008 08:05:57 +0100
Subject: [Tutor] line class
References: <954065.88496.qm@web51610.mail.re2.yahoo.com>
Message-ID: <g51o0m$8r4$1@ger.gmane.org>


"Christopher Spears" <cspears2002 at yahoo.com> wrote

> def __cmp__(self, other):
>        if self.x == other.x and self.y == other.y:
>     return 0
> elif self.x < other.x and self.y < other.y:
>     return -1
> elif self.x > other.x and self.y > other.y:
>     return 1

Rather than comparing in that manner I'd take a different approach.
I'd measure the length from the origin thus any point that was inside
the circle upon whose ciorcumference the point sits is less than
the point. Any point on the circumference is equal and any point
outside the circle is greater...

[ Another approach with similar results is to convert the coordinates
into complex numbers and then use the complex number cmp method
to compare those. ]

Alan G.



From dfjennings at gmail.com  Wed Jul  9 04:43:32 2008
From: dfjennings at gmail.com (Don Jennings)
Date: Tue, 8 Jul 2008 22:43:32 -0400
Subject: [Tutor] build list of non-empty variables
In-Reply-To: <1c2a2c590807081834ld5ccc19i1ec997e8eb6ee197@mail.gmail.com>
References: <22ce67f0807080614g758ea82eg5b16439a8ae7e14e@mail.gmail.com>
	<1c2a2c590807080856y620e7bcdj63a9e3215c8c80c6@mail.gmail.com>
	<22ce67f0807081535t56792aebm58b5250e1d3fb228@mail.gmail.com>
	<1c2a2c590807081834ld5ccc19i1ec997e8eb6ee197@mail.gmail.com>
Message-ID: <22ce67f0807081943j3eba6127wd73002da68b0134e@mail.gmail.com>

Ah! A list comprehension. Not at that point in the learning python book,
yet, but I will be soon. Thanks!
Don

On Tue, Jul 8, 2008 at 9:34 PM, Kent Johnson <kent37 at tds.net> wrote:

> On Tue, Jul 8, 2008 at 6:35 PM, Don Jennings <dfjennings at gmail.com> wrote:
>
> >     def __unicode__(self):
> >         l=[self.first_name, self.last_name, self.email, self.phone]
> >         res=[]
> >
> >         for x in l:
> >             if x != '':
> >                 res.append(x)
> >
> >         return ';'.join(res)
>
> return ';'.join(x for x in l if x)
> will work.
>
> Kent
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080708/9d2bddc8/attachment.htm>

From kent37 at tds.net  Wed Jul  9 14:36:27 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 9 Jul 2008 08:36:27 -0400
Subject: [Tutor] line class
In-Reply-To: <g51o0m$8r4$1@ger.gmane.org>
References: <954065.88496.qm@web51610.mail.re2.yahoo.com>
	<g51o0m$8r4$1@ger.gmane.org>
Message-ID: <1c2a2c590807090536j6fb8dae9of5bc5320b5ea6cb6@mail.gmail.com>

On Wed, Jul 9, 2008 at 3:05 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> Rather than comparing in that manner I'd take a different approach.
> I'd measure the length from the origin thus any point that was inside
> the circle upon whose ciorcumference the point sits is less than
> the point. Any point on the circumference is equal and any point
> outside the circle is greater...

That will allow points with different x and y values to compare equal
which would be a strange definition of equality.

> [ Another approach with similar results is to convert the coordinates
> into complex numbers and then use the complex number cmp method
> to compare those.

That just raises the question of how do complex numbers compare?

Kent

From kf9150 at gmail.com  Wed Jul  9 18:25:31 2008
From: kf9150 at gmail.com (Kelie)
Date: Wed, 9 Jul 2008 16:25:31 +0000 (UTC)
Subject: [Tutor] How to create array of variants?
References: <loom.20080708T032359-542@post.gmane.org>
	<5e58f2e40807072056k56baa4cdoa756c33f557907f0@mail.gmail.com>
	<loom.20080708T085708-817@post.gmane.org>
	<6faf39c90807080215v70dee900j2a353cc2df907ea8@mail.gmail.com>
	<e2f191310807080403t4468c2c4seae2ae39d2d4e493@mail.gmail.com>
	<e2f191310807080404k73196980n3ab0a1d10eb3c282@mail.gmail.com>
Message-ID: <loom.20080709T162436-653@post.gmane.org>

Monika Jisswel <monjissvel <at> googlemail.com> writes:

> 
> 
> Comment : I never did any VB so I am not sure if I understand you.supposing
your data comes like this :python code : 
> 
> 
> Data = ( ('A', 1), ('B', 2), ('C', 3), ('D', 4) )#you can create a list of the
items like this : List_Letters = [ x[0] for x in Data]List_Numbers = [ x[1] for
x in Data]
> 
> hope this helps.
> 
> 

Monika, Thanks for your reply. I've tried using the list data type, but it does
not work in this case.




From nnolie at gmail.com  Wed Jul  9 18:39:00 2008
From: nnolie at gmail.com (Jeremiah Stack)
Date: Wed, 9 Jul 2008 08:39:00 -0800
Subject: [Tutor] Python Characteristics.
Message-ID: <b6b4302a0807090939h4855e400xcf61b6373f0df59@mail.gmail.com>

Hello All,

I was pondering something. when you are in the live environment receiving
immediate feedback is it basically a compiler (or program), responding to
what the user inputs, or is it like the bash shell where I could tell it to
search the file system for a certain file?

Or how does python interact with the environment it is in?

If those are too broad of questions just pass.


Sorry for the illiterate questions.

Thanks
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080709/5593b195/attachment.htm>

From steve at alchemy.com  Wed Jul  9 18:45:29 2008
From: steve at alchemy.com (Steve Willoughby)
Date: Wed, 09 Jul 2008 09:45:29 -0700
Subject: [Tutor] Python Characteristics.
In-Reply-To: <b6b4302a0807090939h4855e400xcf61b6373f0df59@mail.gmail.com>
References: <b6b4302a0807090939h4855e400xcf61b6373f0df59@mail.gmail.com>
Message-ID: <4874EB29.1080107@alchemy.com>

Jeremiah Stack wrote:
> Hello All,
> 
> I was pondering something. when you are in the live environment receiving
> immediate feedback is it basically a compiler (or program), responding to
> what the user inputs, or is it like the bash shell where I could tell it to
> search the file system for a certain file?

Yes.

:)

That's sort of a philosophical question, at least from one point of 
view.  Python compiles the source code you give it before running it. 
With the interactive mode, it's simply compiling lines of code on the 
fly as you input them, and executing them, and printing the return value 
of each statement you type, rather than having you prepare them in a 
file and feeding them to it all at once.  Otherwise everything's 
identical as far as what the system is doing and how it interacts with 
the environment.

So it's not like a shell in that respect, (unlike, say, tclsh is for the 
TCL interactive environment).  Certainly, however, you could write 
Python code to interact with the file system in any manner you choose, 
and that code would work equally well at the interactive prompt and as 
part of a stored program file.

> Or how does python interact with the environment it is in?
> 
> If those are too broad of questions just pass.



> 
> Sorry for the illiterate questions.
> 
> Thanks
> 
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


From alan.gauld at btinternet.com  Wed Jul  9 20:17:26 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 9 Jul 2008 19:17:26 +0100
Subject: [Tutor] line class
References: <954065.88496.qm@web51610.mail.re2.yahoo.com><g51o0m$8r4$1@ger.gmane.org>
	<1c2a2c590807090536j6fb8dae9of5bc5320b5ea6cb6@mail.gmail.com>
Message-ID: <g52vbo$m8h$1@ger.gmane.org>

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

> That just raises the question of how do complex numbers compare?

Usually based on magnitude alone.
That's why I said the results would be equivalent to the length of 
a point approach. You assume that any point on the same sperical 
locus is equal.  At least on my engineering course :-)


I confess I haven't tried it to see if Python implements cmp for 
the complex type.

>>> c < d
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: no ordering relation is defined for complex numbers
>>>

Apparently not! :-/

Alan G


From kent37 at tds.net  Wed Jul  9 20:24:20 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 9 Jul 2008 14:24:20 -0400
Subject: [Tutor] line class
In-Reply-To: <g52vbo$m8h$1@ger.gmane.org>
References: <954065.88496.qm@web51610.mail.re2.yahoo.com>
	<g51o0m$8r4$1@ger.gmane.org>
	<1c2a2c590807090536j6fb8dae9of5bc5320b5ea6cb6@mail.gmail.com>
	<g52vbo$m8h$1@ger.gmane.org>
Message-ID: <1c2a2c590807091124n3545612bs12696935d54d4734@mail.gmail.com>

On Wed, Jul 9, 2008 at 2:17 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> "Kent Johnson" <kent37 at tds.net> wrote
>>
>> That just raises the question of how do complex numbers compare?
>
> Usually based on magnitude alone.
> That's why I said the results would be equivalent to the length of a point
> approach. You assume that any point on the same sperical locus is equal.  At
> least on my engineering course :-)

That seems a pretty strange definition of equal, that makes (1, 0) == (0, 1).

Kent

From alan.gauld at btinternet.com  Wed Jul  9 20:20:35 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 9 Jul 2008 19:20:35 +0100
Subject: [Tutor] build list of non-empty variables
References: <22ce67f0807080614g758ea82eg5b16439a8ae7e14e@mail.gmail.com><1c2a2c590807080856y620e7bcdj63a9e3215c8c80c6@mail.gmail.com><22ce67f0807081535t56792aebm58b5250e1d3fb228@mail.gmail.com><1c2a2c590807081834ld5ccc19i1ec997e8eb6ee197@mail.gmail.com>
	<22ce67f0807081943j3eba6127wd73002da68b0134e@mail.gmail.com>
Message-ID: <g52vhl$mue$1@ger.gmane.org>


"Don Jennings" <dfjennings at gmail.com> wrote

>> return ';'.join(x for x in l if x)

> Ah! A list comprehension. Not at that point in the learning python 
> book,

Not quite, I believe its called a generator expression. Its like
a list comprehension but without the [] around it.

In fact I guess you could say that the new definition of a list
comprehension is

[ generator expression]

But if I'm wrong someone will explain why I'm sure! :-)

Alan G.



From alan.gauld at btinternet.com  Wed Jul  9 20:34:15 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 9 Jul 2008 19:34:15 +0100
Subject: [Tutor] Python Characteristics.
References: <b6b4302a0807090939h4855e400xcf61b6373f0df59@mail.gmail.com>
Message-ID: <g530b9$qb5$1@ger.gmane.org>


"Jeremiah Stack" <nnolie at gmail.com> wrote

> I was pondering something. when you are in the live environment 
> receiving
> immediate feedback is it basically a compiler (or program), 
> responding to
> what the user inputs,

Yes, technically its an interpreter rather than a compiler, although 
there
is an intermediate compilation step involved in the interpretation!
But it is the same python program used to interpret scripts, it just
reads its input from stdin rather than from a text file.

> or is it like the bash shell where I could tell it to
> search the file system for a certain file?

You can interact with the operating system and file system using
modules such as os etc. But you can't do it directly as you can
in bash. But that is because bash has built in capability to execute
external commands, otherwise bash is an interpreter too, albeit
with a much more limited syntax and general capability. Bash's
power is in calling external commands. Python's power is in
creating commands!

> Or how does python interact with the environment it is in?

As above, it reads input from a file (foo.py) or from stdin.
It compiles the instructions too byte code.
If the file is being imported as a module it saves the bytecode
as a compiled file (foo.pyc) and uses that the next time it
imports the same module, provided the module has not been
changed - ie. it checks the datestamps!.
It then interprets the byte code much as does Java's JVM.
If the file is not being imported then it just executes the
internal byte code block by block.

There are various actions at startup time that influence the
operation of the interpreter, ie. its environment, but you can
read about all of these issues on the Python web site. There
is copious documentation on such things.

You can also use pythons introspection capabilities to explorte
much of it - for example you can decompile the .pyc byte code
into Python's pseudo assembler. You can find out which file
a particular module is from. etc.

> If those are too broad of questions just pass.

They are ok.

Alan G. 



From chester_lab at fltg.net  Wed Jul  9 20:42:16 2008
From: chester_lab at fltg.net (FT)
Date: Wed, 9 Jul 2008 14:42:16 -0400
Subject: [Tutor] Text Editor With Speech
References: <b6b4302a0807090939h4855e400xcf61b6373f0df59@mail.gmail.com>
	<4874EB29.1080107@alchemy.com>
Message-ID: <000601c8e1f3$8a63adb0$0501a8c0@brucetower>


Hi!

    I am coming closer to the talking editor and voice adjustments inside my
editor/talking module.

    When reading the events over and over again I am slowly understanding
who wants what. Inside an editor there are key commands that do certain
things and I try to give some voice to them.

    Below I do not use the OnKey function yet, but will erase the comments
and such and only have a say key inside with a toggle on/off for key typing.
Before this was the only event call with keys, now it is only for say key
pressed in the future.

    At the moment I use the KEY_UP event to look at what was done by the
editor after the key is released. This allows no need for location
calculations since the move has been made and the final position in most
cases has been done.

    So, I moved the values for all line parms over to the OnKey_Up function
so I know where the pointer is at.

    I do a word forward and back inside of this function so the word forward
and back are pronounced.

    You may replace the speech engine with the pyTTS if you so desire. But I
have not added the method for pitch to there module, so the pitch adjustment
would not work.

    I mention this because I have not done a dictionary for the engine, so
some things get pronounced a little different. Like AM for the time does not
come out as A.M. nor am, but likes to take the m out for something else.
Little things like that.

        Anyway, this is the latest using events and have removed the button
list. I left the textctrl control methods in the 2 function calls for future
usage and reference.

    Enjoy.

        Bruce

#Editor.py
import wx
import os
import Sapi5
tts = Sapi5.Create( {"name":"Mary"})
purge = tts._purge
async = tts._async
punc = tts._punc
ID=0
HK=1
KH=2
MK=3
MF=4
MF2=5
DW_ID=1000
class MainWindow(wx.Frame):
    def __init__(self, parent, id, title):
        self.dirname=os.getcwd()  #SEARCH FROM PRESENT DIRECTORY!
        self.filename=""
        self.items4menu = {"File": [
            {ID:102, HK:"&Open", KH:" Open a file to edit", MF:self.OnOpen},
            {ID:103, HK:"&Save", KH:" save file to disk", MF:self.OnSave},
            {ID:104, HK:"&Edit", KH:" Do editing", MF:self.OnEdit},
            {ID:101, HK:"&About", KH:" Information about this program",
MF:self.OnAbout},
            {ID:109, HK:"E&xit", KH:" Terminate the program",
MF:self.OnExit}
        ],  #END OF FILE MENU!
        "Voice": [
            {ID:202, HK:"&Read", KH:" Open a file to read",
MF:self.OnWav2Read},
            {ID:203, HK:"&Save", KH:" save text to audio file",
MF:self.OnSave2Wav},
            {ID:204, HK:"Te&xt", KH:" read text field", MF:self.OnRead},
            {ID:205, HK:"&Quit", KH:" Stop Reading", MF:self.OnQuitRead}
        ],  #END OF VOICE MENU!
        "Settings": [
            {ID:302, HK:"&Speaker", KH:" Name for voice.", MF:self.OnEnter,
MF2:self.OnVoice},
            {ID:303, HK:"&Rate", KH:" Rate for voice.", MF:self.OnEnter,
MF2:self.OnVoice},
            {ID:304, HK:"&Pitch", KH:" Pitch for voice.", MF:self.OnEnter,
MF2:self.OnVoice},
            {ID:305, HK:"&Volume", KH:" Volume for voice.", MF:self.OnEnter,
MF2:self.OnVoice}
        ],  #END OF SETTINGS MENU!
        "Down": [
            {ID:DW_ID, HK:"&Down", KH:" Lower Setting.", MF:self.OnEnter,
MF2:self.OnVoice}
        ]  #END OF DOWN MENU!
        }  #END OF ITEMS FOR MENU!
        wx.Frame.__init__(self, parent, wx.ID_ANY, title)
        self.control = wx.TextCtrl(self, 1, style=wx.TE_MULTILINE)
        self.control.Bind( wx.EVT_KEY_UP, self.OnKey_Up) #, self.control)
#        self.control.Bind( wx.EVT_CHAR, self.OnKey) #, self.control)
        self.CreateStatusBar()  #A Statusbar in the bottom of the window
        #Setting up the menu.
        filemenu = wx.Menu()
        for o in self.items4menu["File"]:
            filemenu.Append( o[ID], o[HK], o[KH])
            filemenu.AppendSeparator()
        voicemenu = wx.Menu()
        for o in self.items4menu["Voice"]:
            voicemenu.Append( o[ID], o[HK], o[KH])
            voicemenu.AppendSeparator()
        self.setting_menu = wx.Menu()
        for o in self.items4menu["Settings"]:
            down_menu = wx.Menu()
            down_menu.Append( o[ID], o[HK], o[KH])
            d = self.items4menu["Down"][0]
            down_menu.Append( d[ID]+o[ID], d[HK], d[KH])
            self.setting_menu.AppendMenu( o[ID], o[HK], down_menu)
            self.setting_menu.AppendSeparator()
        voicemenu.AppendMenu(-1, "&VoiceSettings", self.setting_menu)
        # Creating the menubar.
        menuBar = wx.MenuBar()
        menuBar.Append( filemenu,"&File") # Adding the "filemenu" to the
MenuBar
        menuBar.Append( voicemenu,"&Voice") # Adding the "voicemenu" to the
MenuBar
        self.SetMenuBar( menuBar)  # Adding the MenuBar to the Frame
content.
        self.data4menu = {}
        for o in self.items4menu["File"]:
            wx.EVT_MENU(self, o[ID], o[MF])
            self.data4menu[ o[ID]] = o
        for o in self.items4menu["Voice"]:
            wx.EVT_MENU(self, o[ID], o[MF])
            self.data4menu[ o[ID]] = o
        for o in self.items4menu["Settings"]:
            wx.EVT_MENU(self, o[ID], o[MF2])
            self.data4menu[ o[ID]] = o
            wx.EVT_MENU(self, o[ID]+DW_ID, o[MF2])
            self.data4menu[ o[ID]+DW_ID] = o
        # Use some sizers to see layout options
        self.sizer=wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.control,1,wx.EXPAND)
        #Layout sizers
        self.SetSizer(self.sizer)
        self.SetAutoLayout(1)
        self.sizer.Fit(self)
        self.Show(1)
#SAY LABEL OF MENU ITEM!
    def OnEnter(self, event):
        "WHEN ENTERING SAY LABEL OF BUTTON!"
#        self.button2bind = self.Bind(wx.EVT_BUTTON, self.OnVoice,
id=event.GetId())
        eventType = event.GetEventType()
#        tts.Speak( event.GetPosition())
        label4btn = self.setting_menu.GetLabelText( event.GetId())
        tts.Speak( label4btn, async, punc)
        set_value = " Error In Label!"
        if label4btn == "Down":
            set_value = str(-1)
        if label4btn == "Speaker":
            set_value = tts.getVoiceName()
        elif label4btn == "Rate":
            set_value = str( tts.getRate())
        elif label4btn == "Pitch":
            set_value = str( tts.getPitch())
        elif label4btn == "Volume":
            set_value = str( tts.getVolume()) + "%"
        text = label4btn +" Button " +set_value
        tts.Speak( text, async)
#TEXT CONTROL KEYS!
    def OnKey(self, event):
        "KEY CAPTURE FOR EDITING! MUST USE EVT_CHAR FOR ALL CODES."
        k = event.GetKeyCode()
        m = event.GetModifiers()
        txt = self.control.GetValue()
        event.Skip()
#comment        rk = event.GetRawKeyCode()   #not in all platforms
#comment        uk = event.GetUnicodeKey()  #Not on platforms that unicode
was not installed!#comment
#comment        tts.Speak("%d %d" %  (k,m))
#comment        x2y4m = event.GetPosition()  #Mouse position in event
window, textctrl!
        c = self.control.GetInsertionPoint() #present line column position
when event fired!
        tl = self.control.GetLastPosition()  #last point in textctrl
        colmax, linemax = self.control.PositionToXY( tl)
        col, line = self.control.PositionToXY( c)
        lx = self.control.GetLineLength( line) #length of line specified!
        if k==wx.WXK_LEFT:
            col-=1
            if col < 0:
                col = 0
                line-=1
                if line < 0: line=0
                else: col = self.control.GetLineLength( line); lx=col
        if k==wx.WXK_RIGHT:
            col+=1
            if col > lx:
                col = 0
                line+=1
                if line > linemax: line=linemax; col=colmax
        if k==wx.WXK_UP:
            line-=1
            if line<0: line=0
            lx = self.control.GetLineLength( line) #length of line
specified!
            if col>lx: col=lx
        if k==wx.WXK_DOWN:
            line+=1
            if line>linemax: line=linemax
            lx = self.control.GetLineLength( line) #length of line
specified!
            if col>lx: col=lx
        c = self.control.XYToPosition( col, line)
        cs = self.control.XYToPosition( 0, line)
        ce = self.control.XYToPosition( lx, line)
        if c<0: c=0
        if c>tl: c=tl
        lxy = self.control.PositionToXY( c)
#comment        tts.Speak( "Col %d Line %d" % lxy, async, purge)
#comment        col, line = lxy
        lx = self.control.GetLineLength( line) #length of line specified!
#comment        tts.Speak( " line %d col %d length %d" % (line, col, lx),
async, purge)
#comment        tts.Speak( self.control.HitTest( lxy))  #mouse char pixels
using coordinate values
        ch = self.control.GetRange( c,c+1)
        if ch and ord(ch)==10: ch="Return"
        elif ch and ord(ch)==32: ch="space"
        if k in [wx.WXK_UP, wx.WXK_DOWN]: ch = self.control.GetRange( cs,
ce)
        tts.Speak( " %s " % ch, async, purge)
#comment        if k==wx.WXK_LEFT and ord(ch)==10: c-=1
#comment        if k==wx.WXK_RIGHT and ord(ch)==10: c+=1
#comment        tts.Speak(" %s %d %d" % (ch, c, ord(ch)), async)
#KEY UP OR KEY RELEASED!
    def OnKey_Up(self, event):
        "SAY CHAR OR LINE ON WHEN KEY RELEASED!"
        event.Skip()
        k = event.GetKeyCode()
        m = event.GetModifiers()
        txt = self.control.GetValue()
        c = self.control.GetInsertionPoint() #present line column position
when event fired!
        tl = self.control.GetLastPosition()  #last point in textctrl
        colmax, linemax = self.control.PositionToXY( tl)
        col, line = self.control.PositionToXY( c)
        lx = self.control.GetLineLength( line) #length of line specified!
#comment        c = self.control.XYToPosition( col, line)  #CURSOR POSITION!
        cs = self.control.XYToPosition( 0, line)  #LINE START!
        ce = self.control.XYToPosition( lx, line)  #LINE END!
        ch = self.control.GetRange( c,c+1)
        if ch:
            if ord(ch)==10: ch="Return"
            elif ord(ch)==wx.WXK_SPACE: ch="space"
        elif c==tl and k in [wx.WXK_RIGHT, wx.WXK_END]: ch="end of text"
        if c<tl and event.ControlDown() and k in [wx.WXK_LEFT,
wx.WXK_RIGHT]:
            for i in range(c+1, c+lx-col):
                ch2 = self.control.GetRange( i,i+1)
                if ch2=="" or ch2 in  "!@ #$%^&*()[]{}_.,;:": break
                else: ch+=ch2
        if k in [wx.WXK_UP, wx.WXK_DOWN, wx.WXK_PAGEUP, wx.WXK_PAGEDOWN]: ch
= self.control.GetRange( cs,ce)
        if k in [wx.WXK_INSERT, wx.WXK_DELETE, wx.WXK_HOME, wx.WXK_END,
wx.WXK_LEFT, wx.WXK_RIGHT, wx.WXK_UP, wx.WXK_DOWN, wx.WXK_PAGEUP,
wx.WXK_PAGEDOWN]:
            tts.Speak( " %s " % ch, async, punc, purge)
# VOICE SETTINGS!
    def OnVoice(self, event):
        "BUTTON CLICKED ON AND IN FUTURE GET BUTTON POS!"
#comment        tts.Speak( 'Event Name: %s Time Stamp: %s ' %
(event.GetClassName(), event.GetTimestamp()))
#comment        print 'Event Name: %s Time Stamp: %s ' %
(event.GetClassName(), event.GetTimestamp())
#comment IF KEY EVENT:
#comment        key = event.GetKeyCode()
#comment        pos = event.GetPositionTuple()
        eventType = event.GetEventType()
#comment        if eventType == wx.EVT_BUTTON: print "Mouse! "
        eventName = event.GetClassName()
        eventId = event.GetId()
#comment        tts.Speak( event.GetEventType())
#comment        self.control.SetValue( eventName)
#comment: CHECKING ID AND SETTING DIRECTION!
#comment        tts.Speak( self.data4menu[ event.GetId()][HK])
        label4btn = self.setting_menu.GetLabelText( eventId)
        dir = 1
        if label4btn == "Down":
            dir = -1
            label4btn = self.setting_menu.GetLabelText( eventId-DW_ID)
        set_value = "Error! Wrong Button!"
        if label4btn == "Speaker":
            value = tts.getVoiceNum() + dir
            if value < 1:               value += 0
            if value >= tts.getVoiceCount():
                value = tts.getVoiceCount()-1
            tts.setVoice( value)
            set_value = tts.getVoiceName()
        elif label4btn == "Rate":
            value = tts.getRate()
            value += dir
            if value > 10: value = 10
            if value < -10: value = -10
            tts.setRate( value)
            set_value = str( value)
        elif label4btn == "Pitch":
            value = tts.getPitch()
            value += dir
            if value > 10: value = 10
            if value < -10: value = -10
            tts.setPitch( value)
            set_value = str( value)
        elif label4btn == "Volume":
            value = tts.getVolume()
            value += 10*dir
            if value > 100: value = 100
            if value < 0:
                tts.setVolume( 50)
                tts.Speak( "Volume Minimum!")
                value = 0
            tts.setVolume( value)
            set_value = str( value)+"%"
        tts.Speak( set_value, async)
    def OnAbout(self,e):
        "A dialog box saying what the editor is about!"
        text = " A sample editor with voice \n in wxPython."
        tts.Speak( "About A Sample Editor!"+text)
        d= wx.MessageDialog( self, text, "About Sample Editor", wx.OK)
                            # Create a message dialog box
        d.ShowModal() # Shows it
        d.Destroy() # finally destroy it when finished.
    def OnExit(self,e):
        self.Close(True)  # Close the frame.
    def OnOpen(self,e):
        """ Open a file"""
        self.setFilePath( "o")
        f=open(os.path.join(self.dirname, self.filename),'r')
        self.control.SetValue(f.read())
        f.close()
    def OnSave(self,e):
        """ Save a file"""
        self.setFilePath( "s")
        f=open(os.path.join(self.dirname, self.filename),'w')
#       self.control.SetValue(f.read())
        f.write( self.control.GetValue())
        f.close()
    def setFilePath(self, type4file=""):
        " Search directory for path and file name!"
        fn=self.filename
        t4f = wx.OPEN
        if type4file[0] in "sS":
            t4f = wx.SAVE|wx.FD_OVERWRITE_PROMPT
#            fn = self.filename
        dlg = wx.FileDialog(self, self.filename +" or Choose a file",
self.dirname, fn, "*.*", t4f)
        if dlg.ShowModal() == wx.ID_OK:
            self.filename = dlg.GetFilename()
            self.dirname = dlg.GetDirectory()
        dlg.Destroy()
    def OnWav2Read(self,e):
        """ Open a file to read"""
        self.setFilePath( "o")
        tts.SpeakFromWav( os.path.join(self.dirname, self.filename), async,
purge)
    def OnSave2Wav(self,e):
        """ Save text to a wav file"""
        self.setFilePath( "s")
        tts.SpeakToWav( os.path.join(self.dirname, self.filename),
self.control.GetValue())
    def OnRead(self,e):
        """ Read the text"""
        tts.Speak( self.control.GetValue(), async, purge)
    def OnQuitRead(self,e):
        """ Quit the reading of the text"""
        tts.Speak( " Talking Stopped!", purge)
    def OnEdit(self,e):
        """ Edit the file"""
        self.control.SetFocus()
app = wx.PySimpleApp()
frame = MainWindow(None, -1, "Sample editor")
app.MainLoop()
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: Editor.py
URL: <http://mail.python.org/pipermail/tutor/attachments/20080709/2d011c6e/attachment-0001.txt>

From mail at timgolden.me.uk  Wed Jul  9 21:11:25 2008
From: mail at timgolden.me.uk (Tim Golden)
Date: Wed, 09 Jul 2008 20:11:25 +0100
Subject: [Tutor] build list of non-empty variables
In-Reply-To: <g52vhl$mue$1@ger.gmane.org>
References: <22ce67f0807080614g758ea82eg5b16439a8ae7e14e@mail.gmail.com><1c2a2c590807080856y620e7bcdj63a9e3215c8c80c6@mail.gmail.com><22ce67f0807081535t56792aebm58b5250e1d3fb228@mail.gmail.com><1c2a2c590807081834ld5ccc19i1ec997e8eb6ee197@mail.gmail.com>	<22ce67f0807081943j3eba6127wd73002da68b0134e@mail.gmail.com>
	<g52vhl$mue$1@ger.gmane.org>
Message-ID: <48750D5D.7060902@timgolden.me.uk>

Alan Gauld wrote:
> In fact I guess you could say that the new definition of a list
> comprehension is
> 
> [ generator expression]

Well, not if sure if you meant that literally, but
it's certainly not: that would be a list whose one
item was a generator expression:

<code>
squares = (x * x for x in range (10))
l = [squares]

print len (l)
print l[0]

</code>

But a list comp *is* (in effect) the same as:

<code>
squares = (x * x for x in range (10))
l = list (squares)

print len (l)
print l[0]

</code>


TJG

From mikem at blazenetme.net  Wed Jul  9 23:02:20 2008
From: mikem at blazenetme.net (Mike Meisner)
Date: Wed, 9 Jul 2008 17:02:20 -0400
Subject: [Tutor] Problem with creating class instance
Message-ID: <001a01c8e207$15686230$08a305cf@Parents>

I've just started using classes in Python.

The basic goal is to develop a script that tracks individual player stats for poker tournaments.  This involves nesting a class within a class within a class.  The Player class incorporates a Stats class (three instances for three different game types) and the Stats class incorporates a Details class (three instances for three different game phases).

In creating a Player instance,  that instance can create the Stats class, but when creating the first instance within the Stats class of a Details class, it fails with the following traceback:

Traceback (most recent call last):
  File "C:\Python25\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 309, in RunScript
    debugger.run(codeObject, __main__.__dict__, start_stepping=0)
  File "C:\Python25\Lib\site-packages\pythonwin\pywin\debugger\__init__.py", line 60, in run
    _GetCurrentDebugger().run(cmd, globals,locals, start_stepping)
  File "C:\Python25\Lib\site-packages\pythonwin\pywin\debugger\debugger.py", line 624, in run
    exec cmd in globals, locals
  File "C:\Documents and Settings\Mike and Patsy\Desktop\pk\pkutilities.py", line 140, in <module>
    initplayers(playernames)
  File "C:\Documents and Settings\Mike and Patsy\Desktop\pk\pkutilities.py", line 119, in initplayers
    gameplayers[name] = Player(name)
  File "C:\Documents and Settings\Mike and Patsy\Desktop\pk\pkutilities.py", line 8, in __init__
    self.stat[0] = Stats('holdem', name)
  File "C:\Documents and Settings\Mike and Patsy\Desktop\pk\pkutilities.py", line 29, in __init__
    self.gamephase[0] = Details('full')
IndexError: list assignment index out of range


The appropriate code segments defining the classes and the calling function follow:

class Player():

    def __init__(self,name):
        self.name = name
        self.stat[0] = Stats('holdem', name)
        self.stat[1] = Stats('omahah', name)
        self.stat[2] = Stats('omahahl', name)
        

class Stats():
    
    def __init__(self, type, name):
        self.name = name
        self.gametype = type
        self.totalgames = 0
        self.totalgamestofinish = 0
        self.totalfinish = 0
        self.gamephase[0] = Details('full')    # this is the line which fails
        self.gamephase[1] = Details('mid')
        self.gamephase[2] = Details('end')

class Details():
    def __init__(self, type):
        self.type = type
        self.totalhands = 0
        self.VPIPhands = 0
        self.VPIPcount = 0
        self.VPSBhands = 0
        self.VPSBcount = 0
        self.flopseen = 0
        self.turnseen = 0
        self.riverseen = 0
        self.preflopraise = 0
        self.flopraise = 0
        self.turnraise = 0
        self.riverraise = 0
        self.winpreflop = 0
        self.winflop = 0
        self.winturn = 0
        self.winriver = 0

# this is the function that creates the Player instance
def initplayers(playernames):
    global db, gameplayers

    db = shelve.open('playerstats.dat')
    for i in range(len(playernames)):
        name = playernames[i]
        if db.has_key(name):
            gameplayers[name] = db[name]
        else:
            gameplayers[name] = Player(name)   # this line creates the Player instance
            db[name] = gameplayers[name]

I don't see how the "list assignment index" can be out of range, so I assume there's an earlier error that I can't find or a syntax error that I'm overlooking.

Can anyone point out where I'm going wrong?

And, if you can recommend a better way to organize the data, feel free.

Thanks for your help.

Mike
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080709/4c077411/attachment.htm>

From mlangford.cs03 at gtalumni.org  Wed Jul  9 23:11:26 2008
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Wed, 9 Jul 2008 17:11:26 -0400
Subject: [Tutor] Python Characteristics.
In-Reply-To: <g530b9$qb5$1@ger.gmane.org>
References: <b6b4302a0807090939h4855e400xcf61b6373f0df59@mail.gmail.com>
	<g530b9$qb5$1@ger.gmane.org>
Message-ID: <82b4f5810807091411l56d4296dpa03df36da505b46e@mail.gmail.com>

To add to Alan:

On Wed, Jul 9, 2008 at 2:34 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> You can interact with the operating system and file system using
> modules such as os etc. But you can't do it directly as you can
> in bash. But that is because bash has built in capability to execute
> external commands, otherwise bash is an interpreter too, albeit
> with a much more limited syntax and general capability. Bash's
> power is in calling external commands. Python's power is in
> creating commands!
>
>

You can *make* it more like a shell (if that's what you're looking
for) by using ipython: http://ipython.scipy.org/

A large percentage of python developers use IPython (the I stands for
interactive, I think).


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

From kent37 at tds.net  Wed Jul  9 23:46:17 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 9 Jul 2008 17:46:17 -0400
Subject: [Tutor] Problem with creating class instance
In-Reply-To: <001a01c8e207$15686230$08a305cf@Parents>
References: <001a01c8e207$15686230$08a305cf@Parents>
Message-ID: <1c2a2c590807091446p376480c3o7a2d97f81384402@mail.gmail.com>

On Wed, Jul 9, 2008 at 5:02 PM, Mike Meisner <mikem at blazenetme.net> wrote:

> In creating a Player instance,  that instance can create the Stats class,
> but when creating the first instance within the Stats class of a Details
> class, it fails with the following traceback:
>
> Traceback (most recent call last):

>   File "C:\Documents and Settings\Mike and Patsy\Desktop\pk\pkutilities.py",
> line 29, in __init__
>     self.gamephase[0] = Details('full')
> IndexError: list assignment index out of range
>
>
> The appropriate code segments defining the classes and the calling function
> follow:

> class Stats():
>
>     def __init__(self, type, name):
>         self.name = name
>         self.gametype = type
>         self.totalgames = 0
>         self.totalgamestofinish = 0
>         self.totalfinish = 0
>         self.gamephase[0] = Details('full')    # this is the line which
> fails

You don't show how self.gamephase is initialized. I assume you say
something like
  self.gamephase = []
because if you didn't initialize it at all you would get a NameError
rather than IndexError.

You can't assign to a list element that doesn't exist, it will raise
IndexError; e.g.
In [19]: phase = []

In [20]: phase[0] = 'test'
---------------------------------------------------------------------------
<type 'exceptions.IndexError'>            Traceback (most recent call last)

/Users/kent/<ipython console> in <module>()

<type 'exceptions.IndexError'>: list assignment index out of range

You can append to the list:
In [21]: phase.append('test')

Now it has a zeroth element:
In [22]: phase[0]
Out[22]: 'test'

but a simpler solution might be just to create the list with the
elements you want:

self.gamephase = [ Details('full') , Details('mid'), Details('end') ]

>     for i in range(len(playernames)):
>         name = playernames[i]

Write this as
  for name in playernames:

> I don't see how the "list assignment index" can be out of range, so I assume
> there's an earlier error that I can't find or a syntax error that I'm
> overlooking.

No, if it says the index is out of range, it probably is. This might
be a symptom of an earlier error but you should believe the error
message.

A syntax error will prevent the program from running at all.

Kent

From alan.gauld at btinternet.com  Thu Jul 10 02:12:00 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 10 Jul 2008 01:12:00 +0100
Subject: [Tutor] line class
References: <954065.88496.qm@web51610.mail.re2.yahoo.com><g51o0m$8r4$1@ger.gmane.org><1c2a2c590807090536j6fb8dae9of5bc5320b5ea6cb6@mail.gmail.com><g52vbo$m8h$1@ger.gmane.org>
	<1c2a2c590807091124n3545612bs12696935d54d4734@mail.gmail.com>
Message-ID: <g53k4i$v4f$1@ger.gmane.org>

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

>> Usually based on magnitude alone.
>
> That seems a pretty strange definition of equal, that makes (1, 0) 
> == (0, 1).

Yes I know! But actually in many engineering situations where phase
is not important it's a good first approximation (for example power
calculation in a single phase AC circuit - you only care about the
magnitude of the current not it's phase.) Of course in other cases
its wildly wrong so you need to apply with caution. In those cases
comparison has to be defined arbitrarily to fit the scenario - but 
that's
common practice in engineering. Adapting the rules of math to
suit is all part of the fun! -)

Alan G. 



From alan.gauld at btinternet.com  Thu Jul 10 02:17:23 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 10 Jul 2008 01:17:23 +0100
Subject: [Tutor] build list of non-empty variables
References: <22ce67f0807080614g758ea82eg5b16439a8ae7e14e@mail.gmail.com><1c2a2c590807080856y620e7bcdj63a9e3215c8c80c6@mail.gmail.com><22ce67f0807081535t56792aebm58b5250e1d3fb228@mail.gmail.com><1c2a2c590807081834ld5ccc19i1ec997e8eb6ee197@mail.gmail.com>	<22ce67f0807081943j3eba6127wd73002da68b0134e@mail.gmail.com><g52vhl$mue$1@ger.gmane.org>
	<48750D5D.7060902@timgolden.me.uk>
Message-ID: <g53kel$vpc$1@ger.gmane.org>


"Tim Golden" <mail at timgolden.me.uk> wrote 

>> In fact I guess you could say that the new definition of a list
>> comprehension is
>> 
>> [ generator expression]
> 
> Well, not if sure if you meant that literally

No I meant in syntactic terms.
We usually define an LC as

[ expr for vars in sequence if expr ]

or somesuch imprecise gobbledy gook ;-).

Now we can define the generator expr (syntax) as

        expr for vars in sequence if expr 

and the LC as

        [ gen expr ]

> <code>
> squares = (x * x for x in range (10))
> l = [squares]

But doesn't that generate a tuple (because of the parens)?
And if you remove the parens you cant assign to the 
variable so you have to [put it in the list literally which becomes

l = [x * x for x in range (10)]

Which is an LC...

Alan G.


From kent37 at tds.net  Thu Jul 10 02:57:27 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 9 Jul 2008 20:57:27 -0400
Subject: [Tutor] build list of non-empty variables
In-Reply-To: <g53kel$vpc$1@ger.gmane.org>
References: <22ce67f0807080614g758ea82eg5b16439a8ae7e14e@mail.gmail.com>
	<1c2a2c590807080856y620e7bcdj63a9e3215c8c80c6@mail.gmail.com>
	<22ce67f0807081535t56792aebm58b5250e1d3fb228@mail.gmail.com>
	<1c2a2c590807081834ld5ccc19i1ec997e8eb6ee197@mail.gmail.com>
	<22ce67f0807081943j3eba6127wd73002da68b0134e@mail.gmail.com>
	<g52vhl$mue$1@ger.gmane.org> <48750D5D.7060902@timgolden.me.uk>
	<g53kel$vpc$1@ger.gmane.org>
Message-ID: <1c2a2c590807091757x445d05ecsc12017a3f7aa824f@mail.gmail.com>

On Wed, Jul 9, 2008 at 8:17 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> No I meant in syntactic terms.
> We usually define an LC as
>
> [ expr for vars in sequence if expr ]
>
> or somesuch imprecise gobbledy gook ;-).
>
> Now we can define the generator expr (syntax) as
>
>       expr for vars in sequence if expr
> and the LC as
>
>       [ gen expr ]

The gen exp needs the parens. You could possibly have an intermediate
term that can be put inside () or [].

The actual formal syntax definitions for the two are slightly different:
http://docs.python.org/ref/lists.html
http://docs.python.org/ref/genexpr.html

Presumably this means there is something that is syntactically allowed
in one form and not the other, but I can't figure out what it might
be.

>> <code>
>> squares = (x * x for x in range (10))
>> l = [squares]
>
> But doesn't that generate a tuple (because of the parens)?

No, the parens are required for, and create, a generator expression.
In [23]: squares = (x * x for x in range (10))

In [24]: squares
Out[24]: <generator object at 0x126ae90>

Kent

From john at fouhy.net  Thu Jul 10 03:38:33 2008
From: john at fouhy.net (John Fouhy)
Date: Thu, 10 Jul 2008 13:38:33 +1200
Subject: [Tutor] build list of non-empty variables
In-Reply-To: <1c2a2c590807091757x445d05ecsc12017a3f7aa824f@mail.gmail.com>
References: <22ce67f0807080614g758ea82eg5b16439a8ae7e14e@mail.gmail.com>
	<1c2a2c590807080856y620e7bcdj63a9e3215c8c80c6@mail.gmail.com>
	<22ce67f0807081535t56792aebm58b5250e1d3fb228@mail.gmail.com>
	<1c2a2c590807081834ld5ccc19i1ec997e8eb6ee197@mail.gmail.com>
	<22ce67f0807081943j3eba6127wd73002da68b0134e@mail.gmail.com>
	<g52vhl$mue$1@ger.gmane.org> <48750D5D.7060902@timgolden.me.uk>
	<g53kel$vpc$1@ger.gmane.org>
	<1c2a2c590807091757x445d05ecsc12017a3f7aa824f@mail.gmail.com>
Message-ID: <5e58f2e40807091838m49792522q8b2bfd2a6030b6de@mail.gmail.com>

On 10/07/2008, Kent Johnson <kent37 at tds.net> wrote:
>  The actual formal syntax definitions for the two are slightly different:
>  http://docs.python.org/ref/lists.html
>  http://docs.python.org/ref/genexpr.html
>
>  Presumably this means there is something that is syntactically allowed
>  in one form and not the other, but I can't figure out what it might
>  be.

Is the generator expression grammar right?  How do I parse, e.g.,
'(x+1 for x in range(10))'?  Seems like there's nothing there for
'range(10)'.  Like it should replace 'or_test' with 'old_expression'.

At any rate, here is one difference:

>>> a = range(5)
>>> b = range(5, 10)
>>> [x for x in a, b]
[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
>>> (x for x in a, b)
  File "<stdin>", line 1
    (x for x in a, b)
                 ^
SyntaxError: invalid syntax

(I'm not sure I've ever used a list comprehension like that)

-- 
John.

From kent37 at tds.net  Thu Jul 10 04:16:37 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 9 Jul 2008 22:16:37 -0400
Subject: [Tutor] build list of non-empty variables
In-Reply-To: <5e58f2e40807091838m49792522q8b2bfd2a6030b6de@mail.gmail.com>
References: <22ce67f0807080614g758ea82eg5b16439a8ae7e14e@mail.gmail.com>
	<1c2a2c590807080856y620e7bcdj63a9e3215c8c80c6@mail.gmail.com>
	<22ce67f0807081535t56792aebm58b5250e1d3fb228@mail.gmail.com>
	<1c2a2c590807081834ld5ccc19i1ec997e8eb6ee197@mail.gmail.com>
	<22ce67f0807081943j3eba6127wd73002da68b0134e@mail.gmail.com>
	<g52vhl$mue$1@ger.gmane.org> <48750D5D.7060902@timgolden.me.uk>
	<g53kel$vpc$1@ger.gmane.org>
	<1c2a2c590807091757x445d05ecsc12017a3f7aa824f@mail.gmail.com>
	<5e58f2e40807091838m49792522q8b2bfd2a6030b6de@mail.gmail.com>
Message-ID: <1c2a2c590807091916n4cea8b6fj8a05dc4b4971d281@mail.gmail.com>

On Wed, Jul 9, 2008 at 9:38 PM, John Fouhy <john at fouhy.net> wrote:
> On 10/07/2008, Kent Johnson <kent37 at tds.net> wrote:
>>  The actual formal syntax definitions for the two are slightly different:
>>  http://docs.python.org/ref/lists.html
>>  http://docs.python.org/ref/genexpr.html

> Is the generator expression grammar right?  How do I parse, e.g.,
> '(x+1 for x in range(10))'?  Seems like there's nothing there for
> 'range(10)'.  Like it should replace 'or_test' with 'old_expression'.

I can't figure out how to parse that either, as a gen exp or a list comp.

Kent

From john at fouhy.net  Thu Jul 10 04:32:13 2008
From: john at fouhy.net (John Fouhy)
Date: Thu, 10 Jul 2008 14:32:13 +1200
Subject: [Tutor] build list of non-empty variables
In-Reply-To: <1c2a2c590807091916n4cea8b6fj8a05dc4b4971d281@mail.gmail.com>
References: <22ce67f0807080614g758ea82eg5b16439a8ae7e14e@mail.gmail.com>
	<22ce67f0807081535t56792aebm58b5250e1d3fb228@mail.gmail.com>
	<1c2a2c590807081834ld5ccc19i1ec997e8eb6ee197@mail.gmail.com>
	<22ce67f0807081943j3eba6127wd73002da68b0134e@mail.gmail.com>
	<g52vhl$mue$1@ger.gmane.org> <48750D5D.7060902@timgolden.me.uk>
	<g53kel$vpc$1@ger.gmane.org>
	<1c2a2c590807091757x445d05ecsc12017a3f7aa824f@mail.gmail.com>
	<5e58f2e40807091838m49792522q8b2bfd2a6030b6de@mail.gmail.com>
	<1c2a2c590807091916n4cea8b6fj8a05dc4b4971d281@mail.gmail.com>
Message-ID: <5e58f2e40807091932he651f2aqc6216db2bb016742@mail.gmail.com>

On 10/07/2008, Kent Johnson <kent37 at tds.net> wrote:
> On Wed, Jul 9, 2008 at 9:38 PM, John Fouhy <john at fouhy.net> wrote:
> > Is the generator expression grammar right?  How do I parse, e.g.,
>  > '(x+1 for x in range(10))'?  Seems like there's nothing there for
>  > 'range(10)'.  Like it should replace 'or_test' with 'old_expression'.
> I can't figure out how to parse that either, as a gen exp or a list comp.

Oh, wait, I got it.  I just didn't follow the chain far enough.

old_expression -> or_test -> and_test -> not_test -> comparison ->
or_expr -> xor_expr -> and_expr -> shift_expr -> a_expr -> m_expr ->
u_expr -> power -> primary -> call (or replace call with atom)

So the other difference between list comprehensions and generator
expressions is that list comprehensions get to use "old_expression"s
whereas generator expressions start with "or_test"s.  An
old_expression can be an old_lambda_form, which means that this is
valid syntax:

>>> [x for x in lambda y: y**2]

whereas this is not:

>>> (x for x in lambda y: y**2)

I'm lost for how to come up with a use for that, though (or even a way
to write code like that without producing a TypeError: 'function'
object is not iterable).

-- 
John.

From fredp101 at mac.com  Thu Jul 10 05:25:31 2008
From: fredp101 at mac.com (Fred @ Mac)
Date: Wed, 09 Jul 2008 20:25:31 -0700
Subject: [Tutor] python beginner
Message-ID: <8150C5F5-9C4F-477A-84CB-72C5E97A8EED@mac.com>

I have an external app that writes out a very basic xml files that  
contains data that needs to be processed. For Example, one type of job  
would be a simple file copy.

So in the XML file there would be (among other bits of information  
about the job) things like

<JobType>CopyFiles</JobType>
<User>Frank</User> ( for who submitted the job.)
<Path>c:\tmp\</Path>
<First Frame>Image_0001.jpg</First Frame>
<Last Frame>Image_0150..jpg</Last Frame>
<DestDir>d:\backup\</DestDir>

I need to learn to write a program that does several things.

First it will scan a directory for these sort of xml data files.

Secondly, it will need a basic interface that lists the jobs in the  
queue, and whether or not they are done being processed.

Thirdly, it will have to support multiple job types. Each job type  
will have its own set of commands to run. The example above would be a  
very simple job that would copy (probably using xcopy) to copy all the  
images in a sequence between frame 0001 and frame 0150 of c:\tmp 
\Image_0001.jpg to d:\backup\. This job type of copy should probably  
also check the destdir to make sure they are identical, and then set  
the status of that job to completed.

Of course to do all of this, it will also need an interface. So  
whatever language/script I use must of course be able to produce a  
sort of small database and interface to keep track of which jobs have  
been processed.

My first question is, what language do you think this sort of thing  
would be best done in. I have some scripting experience in Lua, very  
basic python, and 2 semesters of c++, so i am a NOVICE in all those  
languages, but I understand scripting and programming a little and  
don't think it is too far of a stretch for me to learn how to do this.  
But I want to make sure I start down the right road with the best tool  
for the job, IE: the best language for this sort of program.

Thank you.

From jar_head at fuse.net  Thu Jul 10 06:29:28 2008
From: jar_head at fuse.net (jar_head at fuse.net)
Date: Thu, 10 Jul 2008 0:29:28 -0400
Subject: [Tutor] Basic Help Implementing Saved Scripts
Message-ID: <33126619.1215664168457.JavaMail.root@wmvirt5>

Hi,
     Sorry for this, most likely, idiotic question on my part.  I'm really liking Python and it's ease of use.  My only trouble is that I'm not sure how to use a script that I've saved, during another script located within the same folder.  

The idea is that I want to make a few functions and be able to pull them up within my program without copy and pasting them.  Is it possible in Python?  Do I have to import them?

I've tried looking at tutorials, etc, but I can't find any that are up to date/simple enough to make any sense to me.  I'm running Windows ME and have used IDLE up to this point.

Python is my first language.  I have some knowledge of computers but reading some of the things on the other e-mails sent out, I'm lost.

I'd really appreciate it if someone gave me a very simple, step by step explanation of how to do this.  

Thanks,
-Jay

From john at fouhy.net  Thu Jul 10 06:51:27 2008
From: john at fouhy.net (John Fouhy)
Date: Thu, 10 Jul 2008 16:51:27 +1200
Subject: [Tutor] Basic Help Implementing Saved Scripts
In-Reply-To: <33126619.1215664168457.JavaMail.root@wmvirt5>
References: <33126619.1215664168457.JavaMail.root@wmvirt5>
Message-ID: <5e58f2e40807092151w700f0abdnf802ddb671d5611a@mail.gmail.com>

On 10/07/2008, jar_head at fuse.net <jar_head at fuse.net> wrote:
> Hi,
>      Sorry for this, most likely, idiotic question on my part.  I'm really liking Python and it's
> ease of use.  My only trouble is that I'm not sure how to use a script that I've saved, during
> another script located within the same folder.
>
>  The idea is that I want to make a few functions and be able to pull them up within my
> program without copy and pasting them.  Is it possible in Python?  Do I have to import
> them?

Short answer: Yes.  Check out the tutorial:
http://docs.python.org/tut/node8.html

-- 
John.

From mail at timgolden.me.uk  Thu Jul 10 09:48:30 2008
From: mail at timgolden.me.uk (Tim Golden)
Date: Thu, 10 Jul 2008 08:48:30 +0100
Subject: [Tutor] build list of non-empty variables
In-Reply-To: <g53kel$vpc$1@ger.gmane.org>
References: <22ce67f0807080614g758ea82eg5b16439a8ae7e14e@mail.gmail.com><1c2a2c590807080856y620e7bcdj63a9e3215c8c80c6@mail.gmail.com><22ce67f0807081535t56792aebm58b5250e1d3fb228@mail.gmail.com><1c2a2c590807081834ld5ccc19i1ec997e8eb6ee197@mail.gmail.com>	<22ce67f0807081943j3eba6127wd73002da68b0134e@mail.gmail.com><g52vhl$mue$1@ger.gmane.org>	<48750D5D.7060902@timgolden.me.uk>
	<g53kel$vpc$1@ger.gmane.org>
Message-ID: <4875BECE.4000604@timgolden.me.uk>

Alan Gauld wrote:
> 
> "Tim Golden" <mail at timgolden.me.uk> wrote
>>> In fact I guess you could say that the new definition of a list
>>> comprehension is
>>>
>>> [ generator expression]
>>
>> Well, not if sure if you meant that literally
> 
> No I meant in syntactic terms.

I imagined that that was what you meant. I think
it's been explained further down the thread
(I've only skimmed I'm afraid).


My only further contribution here is a bit of a
caveat when using genexps as a (for me) clearer
form of a list comp, which I blogged about a while 
back (tinyurl link to my own blog):

http://tinyurl.com/6za97g

TJG

From alan.gauld at btinternet.com  Thu Jul 10 10:40:03 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 10 Jul 2008 09:40:03 +0100
Subject: [Tutor] python beginner
References: <8150C5F5-9C4F-477A-84CB-72C5E97A8EED@mac.com>
Message-ID: <g54ht5$4ot$1@ger.gmane.org>

"Fred @ Mac" <fredp101 at mac.com> wrote

> Of course to do all of this, it will also need an interface.

I'm not too sure what you mean by an "interface"?
Do you mean a user interface? It will certainly need one
of those but it could be a command line UI or a text
based UI or a GUI or a Web UI. Or even several of those.

> whatever language/script I use must of course be able to produce a 
> sort of small database and interface to keep track of which jobs 
> have  been processed.

The database could be anything from a simple text file - maybe
in xml - or a full blown relational model. The choice is yours.

> My first question is, what language do you think this sort of thing 
> would be best done in. I have some scripting experience in Lua, very 
> basic python, and 2 semesters of c++

I'd opt for Lua or Python over C++. I know nothing about Lua so
I'd personally endorse Python, but then this is a Python mailing list
so what did you expect? :-).

> languages, but I understand scripting and programming a little and 
> don't think it is too far of a stretch for me to learn how to do 
> this.

Not at all, it's a perfect match for scripting languages like
Python (or Lua).

> But I want to make sure I start down the right road with the best 
> tool  for the job, IE: the best language for this sort of program.

No language is perfect but any one of a dozen scripting languages
could do this. Since you already know a bit of Lua and Python they
are the obvious first choices for you. Since you are posting on the
python tutor list the answer from here is Python! Obviously.

In terms of how to start I'd pick one of your commands and write
a simple text based program to process that command. Then wrap
it up as a function. Repeat for the other commands. Finally write
a UI (either GUI , web or text based) that offers a menu of commands
and call the functions created earlier. Finally build the logging
function to store (and report) status.

Modules you may want to look at include

os, shutil (for file manipulation) elementTree(for XML processing),
sqlite(a database api) and m,aybe Tkinter or CGI (GUI and Web UIs)

Questions can be askwed here as necessary.

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 Jul 10 10:44:16 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 10 Jul 2008 09:44:16 +0100
Subject: [Tutor] Basic Help Implementing Saved Scripts
References: <33126619.1215664168457.JavaMail.root@wmvirt5>
Message-ID: <g54i53$5h2$1@ger.gmane.org>

<jar_head at fuse.net> wrote in message

> The idea is that I want to make a few functions and be able
> to pull them up within my program without copy and pasting them.
> Is it possible in Python?  Do I have to import them?

Yes, you create a module and import the module.

> I've tried looking at tutorials, etc, but I can't find any that are
> up to date/simple enough to make any sense to me.

The simple ones are the non programmers ones listed
on the Python web sirte(including mine!). Module functionality
hasn't changed significantly in over 10 years so they
should all be up to date!

> I'm running Windows ME and have used IDLE up to this point.

Thats fine. Although you may prefer Pythonwin over IDLE.
Which version of Python are you using? That is more relevant.

> I'd really appreciate it if someone gave me a very simple,
> step by step explanation of how to do this.

Read the functions and modules topic of my tutorial
It includes an example of creating a module and using
a function within it.

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



From George.Flaherty at sas.com  Thu Jul 10 16:09:30 2008
From: George.Flaherty at sas.com (George Flaherty)
Date: Thu, 10 Jul 2008 10:09:30 -0400
Subject: [Tutor] Dynamic Method Creation
Message-ID: <F62CC1C9DC2ABC4A8D986537A79D324F0AA2F5509B@MERCMBX14.na.sas.com>

Hello,

I am trying to port over some old code from Ruby into Python.  In my old ruby code I had a UnitTest class that created a bunch of test methods (i.e. def test_MyTestFunction) dynamically through the ruby method define_method(http://www.ruby-doc.org/core/classes/Module.html#M000396).

This functionally allowed me to create any number of methods dynamically within a particular class. My problem is I have never done this nor can find any examples of this within python and I am pretty sure python can handle this?

If anyone could point me in the right direction?
thanks

-george



From Tse.William at ic.gc.ca  Thu Jul 10 17:48:07 2008
From: Tse.William at ic.gc.ca (Tse, William: #CIPO - OPIC)
Date: Thu, 10 Jul 2008 11:48:07 -0400
Subject: [Tutor] Looking for IEEE "double-precision" library
Message-ID: <5A66F7B6A4EF084F9D22810BED690A610A9BEFF3@msg-mb1.icent.ic.gc.ca>

Can anyone tell me where I can download the latest version of the
fpconst.py library ?

This library has a set of constants/functions for working with IEEE754
double-precision special values and provides support for SOAP datatype
specification.  There are older links to the fpconst library that no
longer seem to be accessible but I'm not sure why.  Is the IEEE754 no
longer required ?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080710/2e270a94/attachment.htm>

From bgailer at gmail.com  Thu Jul 10 18:12:31 2008
From: bgailer at gmail.com (bob gailer)
Date: Thu, 10 Jul 2008 12:12:31 -0400
Subject: [Tutor] Dynamic Method Creation
In-Reply-To: <F62CC1C9DC2ABC4A8D986537A79D324F0AA2F5509B@MERCMBX14.na.sas.com>
References: <F62CC1C9DC2ABC4A8D986537A79D324F0AA2F5509B@MERCMBX14.na.sas.com>
Message-ID: <487634EF.1090607@gmail.com>

George Flaherty wrote:
> Hello,
>
> I am trying to port over some old code from Ruby into Python.  In my old ruby code I had a UnitTest class that created a bunch of test methods (i.e. def test_MyTestFunction) dynamically through the ruby method define_method(http://www.ruby-doc.org/core/classes/Module.html#M000396).
>
> This functionally allowed me to create any number of methods dynamically within a particular class. My problem is I have never done this nor can find any examples of this within python and I am pretty sure python can handle this?
>
> If anyone could point me in the right direction?
See the new module's instancemethod method.

 >>> import new
 >>> class A:
...     pass
...
 >>> a=A()
 >>> a.f = new.instancemethod(lambda self:'foo', a, A)
 >>> a.f()
'foo'


-- 
Bob Gailer
919-636-4239 Chapel Hill, NC


From kent37 at tds.net  Thu Jul 10 18:14:01 2008
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 10 Jul 2008 12:14:01 -0400
Subject: [Tutor] Looking for IEEE "double-precision" library
In-Reply-To: <5A66F7B6A4EF084F9D22810BED690A610A9BEFF3@msg-mb1.icent.ic.gc.ca>
References: <5A66F7B6A4EF084F9D22810BED690A610A9BEFF3@msg-mb1.icent.ic.gc.ca>
Message-ID: <1c2a2c590807100914k487951f0l2d2a6532c4af44db@mail.gmail.com>

On Thu, Jul 10, 2008 at 11:48 AM, Tse, William: #CIPO - OPIC
<Tse.William at ic.gc.ca> wrote:
> Can anyone tell me where I can download the latest version of the fpconst.py
> library ?

I find two locations, they appear to be the same:
http://pypi.python.org/pypi/fpconst/
http://bugs.python.org/issue1151323 (see the patch file)

Kent

From alan.gauld at btinternet.com  Thu Jul 10 19:47:43 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 10 Jul 2008 18:47:43 +0100
Subject: [Tutor] Dynamic Method Creation
References: <F62CC1C9DC2ABC4A8D986537A79D324F0AA2F5509B@MERCMBX14.na.sas.com>
Message-ID: <g55i01$npv$1@ger.gmane.org>


"George Flaherty" <George.Flaherty at sas.com> wrote

> ) dynamically through the ruby method define_method(http://www.ruby-
> doc.org/core/classes/Module.html#M000396).
> > This functionally allowed me to create any number of methods
> dynamically within a particular class.
> ....I am pretty sure python can handle this?

I'm less sure. I suspect there are other ways of doing it, but none
so elegant as Ruby. This is one of several areas (IMHO) where Ruby
has learned lessons from Python and improved on it.

There are some things that I think python does better than Ruby
but there are certainly areas where Ruby does it better. Ruby
blocks v Python lambdas for example!

Alan G 



From midnightjulia at gmail.com  Thu Jul 10 22:41:28 2008
From: midnightjulia at gmail.com (Julia)
Date: Thu, 10 Jul 2008 22:41:28 +0200
Subject: [Tutor] Float number accuracy
Message-ID: <fe29bb3a0807101341u3efa0c5ew591f5d07cd93e25a@mail.gmail.com>

I've done this:

>>> c = float
>>> c
<type 'float'>
>>> c = 3.3
>>> c
3.2999999999999998

I've done it with and without the c = float and still it rounds the number
down. Why? And more importantly: is it possible to make Python more
accurate? I need the exact number and not something close to it for my new
application.

I'm looking for a = 3.3 and nothing else :)

Best regards!
/MJ
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080710/9f8b6d8e/attachment.htm>

From motoom at xs4all.nl  Thu Jul 10 22:54:14 2008
From: motoom at xs4all.nl (Michiel Overtoom)
Date: Thu, 10 Jul 2008 22:54:14 +0200
Subject: [Tutor] Float number accuracy
In-Reply-To: <fe29bb3a0807101341u3efa0c5ew591f5d07cd93e25a@mail.gmail.com>
References: <fe29bb3a0807101341u3efa0c5ew591f5d07cd93e25a@mail.gmail.com>
Message-ID: <72DBF0F0-7E68-44AA-BBFF-8EF1F4B6BBBA@xs4all.nl>


On 10-jul-2008, at 22:41, Julia wrote:


> >>> c = 3.3
> >>> c
> 3.2999999999999998
>
> I've done it with and without the c = float and still it rounds the  
> number down. Why? And more importantly: is it possible to make  
> Python more accurate? I need the exact number and not something  
> close to it for my new application.

That's because floats have only a fixed amount of bits to represent  
values, and not all values can be represented exactly, so there  
occurs some rounding errors.

Python can do exact math using the 'decimal' package. See
http://www.python.org/doc/2.4.3/lib/module-decimal.html

Greetings,

From kent37 at tds.net  Thu Jul 10 23:21:58 2008
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 10 Jul 2008 17:21:58 -0400
Subject: [Tutor] Float number accuracy
In-Reply-To: <fe29bb3a0807101341u3efa0c5ew591f5d07cd93e25a@mail.gmail.com>
References: <fe29bb3a0807101341u3efa0c5ew591f5d07cd93e25a@mail.gmail.com>
Message-ID: <1c2a2c590807101421g41747a74n49a08ae7f3f41c46@mail.gmail.com>

On Thu, Jul 10, 2008 at 4:41 PM, Julia <midnightjulia at gmail.com> wrote:
> I've done this:
>
>>>> c = float
>>>> c
> <type 'float'>

This is not needed, Python variables do not have types (it is the
values that have type).

>>>> c = 3.3
>>>> c
> 3.2999999999999998
>
> I've done it with and without the c = float and still it rounds the number
> down. Why?

See http://docs.python.org/tut/node16.html

Kent

From midnightjulia at gmail.com  Fri Jul 11 00:42:01 2008
From: midnightjulia at gmail.com (Julia)
Date: Fri, 11 Jul 2008 00:42:01 +0200
Subject: [Tutor] Float number accuracy
In-Reply-To: <1c2a2c590807101421g41747a74n49a08ae7f3f41c46@mail.gmail.com>
References: <fe29bb3a0807101341u3efa0c5ew591f5d07cd93e25a@mail.gmail.com>
	<1c2a2c590807101421g41747a74n49a08ae7f3f41c46@mail.gmail.com>
Message-ID: <fe29bb3a0807101542n284a23b1h1ad50913d7097e15@mail.gmail.com>

On Thu, Jul 10, 2008 at 11:21 PM, Kent Johnson <kent37 at tds.net> wrote:

> On Thu, Jul 10, 2008 at 4:41 PM, Julia <midnightjulia at gmail.com> wrote:
> > I've done this:
> >
> >>>> c = float
> >>>> c
> > <type 'float'>
>
> This is not needed, Python variables do not have types (it is the
> values that have type).
>

>
> >>>> c = 3.3
> >>>> c
> > 3.2999999999999998
> >
> > I've done it with and without the c = float and still it rounds the
> number
> > down. Why?
>
> See http://docs.python.org/tut/node16.html
>
> Kent


Thanks, I've just found (what seems to be) a workaround :)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080711/c9e18b7e/attachment-0001.htm>

From yxi at att.net  Fri Jul 11 03:46:10 2008
From: yxi at att.net (Yuanxin Xi)
Date: Thu, 10 Jul 2008 18:46:10 -0700 (PDT)
Subject: [Tutor] function for memory usage
Message-ID: <314148.84226.qm@web83821.mail.sp1.yahoo.com>

Hi,
   
  Could anyone please tell me which funtion (or which module) could return the total memory used by current python program? 
   
  Thanks,
   
  Fred
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080710/7ccb181e/attachment.htm>

From cfuller084 at thinkingplanet.net  Thu Jul 10 19:38:46 2008
From: cfuller084 at thinkingplanet.net (Chris Fuller)
Date: Thu, 10 Jul 2008 12:38:46 -0500
Subject: [Tutor] Dynamic Method Creation
In-Reply-To: <F62CC1C9DC2ABC4A8D986537A79D324F0AA2F5509B@MERCMBX14.na.sas.com>
References: <F62CC1C9DC2ABC4A8D986537A79D324F0AA2F5509B@MERCMBX14.na.sas.com>
Message-ID: <200807101238.47224.cfuller084@thinkingplanet.net>

On Thursday 10 July 2008 09:09, George Flaherty wrote:
> Hello,
>
> I am trying to port over some old code from Ruby into Python.  In my old
> ruby code I had a UnitTest class that created a bunch of test methods (i.e.
> def test_MyTestFunction) dynamically through the ruby method
> define_method(http://www.ruby-doc.org/core/classes/Module.html#M000396).
>
> This functionally allowed me to create any number of methods dynamically
> within a particular class. My problem is I have never done this nor can
> find any examples of this within python and I am pretty sure python can
> handle this?
>
> If anyone could point me in the right direction?
> thanks
>
> -george
>

If you have an existing class, you can bind new methods to it by simply using 
setattr().  
>>> class A:
...   pass
...
>>> setattr(A, 'x',lambda self: 'foo')
>>> a=A()
>>> a.x()
'foo'
>>> class B(A):
...  pass
...
>>> b=B()
>>> b.x()
'foo'

You can also use new.classobj() to create arbitrary classes on-the-fly.  See 
the documentation for the  new module, and google "python metaclasses"

Cheers

From drorco at gmail.com  Fri Jul 11 10:11:45 2008
From: drorco at gmail.com (Dror Cohen)
Date: Fri, 11 Jul 2008 11:11:45 +0300
Subject: [Tutor] how can I use the functions inside ITfInputProcessorProfiles
Message-ID: <884670ce0807110111s5edc19c5l32fef101fe79c8fe@mail.gmail.com>

Hi everybody,

I'm trying to use the these functions which are in isnide of
ITfInputProcessorProfiles
http://msdn.microsoft.com/en-us/library/ms538984(VS.85).aspx

I think that its registry key is {892F230F-FE00-4A41-A98E-FCD6DE0D35EF}
(though I don't know if I even need this)

How can I use its function inside of python.
I tried using this by thinking it will get me somewhere (Got no idea if I
was even close)


point = None
Inputpp = pythoncom.MakeIID('{892F230F-FE00-4A41-A98E-FCD6DE0D35EF}')
pythoncom.CoCreateInstance(Inputpp, None, pythoncom.CLSCTX_INPROC_SERVER,
point)

but then I got this error message

 Traceback (most recent call last):
   File "<interactive input>", line 1, in <module>
    TypeError: Only strings and iids can be converted to a CLSID.

I don't mind if you'll show me other ways to use thins function.
All I want to get is the current active language in Windows.

Thanks! :)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080711/d462b499/attachment.htm>

From paul at assured-networks.co.uk  Fri Jul 11 10:58:05 2008
From: paul at assured-networks.co.uk (paul at assured-networks.co.uk)
Date: Fri, 11 Jul 2008 09:58:05 +0100
Subject: [Tutor] Classes
Message-ID: <200807110858.m6B8w5tQ005534@mta3.iomartmail.com>

An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080711/90e6acae/attachment.htm>

From kent37 at tds.net  Fri Jul 11 12:08:27 2008
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 11 Jul 2008 06:08:27 -0400
Subject: [Tutor] Dynamic Method Creation
In-Reply-To: <200807101238.47224.cfuller084@thinkingplanet.net>
References: <F62CC1C9DC2ABC4A8D986537A79D324F0AA2F5509B@MERCMBX14.na.sas.com>
	<200807101238.47224.cfuller084@thinkingplanet.net>
Message-ID: <1c2a2c590807110308m1a629714na1226fcccb36c538@mail.gmail.com>

On Thu, Jul 10, 2008 at 1:38 PM, Chris Fuller
<cfuller084 at thinkingplanet.net> wrote:

> You can also use new.classobj() to create arbitrary classes on-the-fly.  See
> the documentation for the  new module, and google "python metaclasses"

FWIW new.classobj() will create an old-style class. You can create a
new-style class by calling type(  	name, bases, dict) directly.

Kent

From kent37 at tds.net  Fri Jul 11 12:13:15 2008
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 11 Jul 2008 06:13:15 -0400
Subject: [Tutor] Classes
In-Reply-To: <200807110858.m6B8w5tQ005534@mta3.iomartmail.com>
References: <200807110858.m6B8w5tQ005534@mta3.iomartmail.com>
Message-ID: <1c2a2c590807110313h24555e03l9260f5198498d70b@mail.gmail.com>

On Fri, Jul 11, 2008 at 4:58 AM,  <paul at assured-networks.co.uk> wrote:
> 1. What is the difference between a classmethod and a staticmethod, and when
> would i use either?

We discussed this recently:
http://thread.gmane.org/gmane.comp.python.tutor/47054/focus=47108

Kent

From mail at timgolden.me.uk  Fri Jul 11 18:00:45 2008
From: mail at timgolden.me.uk (Tim Golden)
Date: Fri, 11 Jul 2008 17:00:45 +0100
Subject: [Tutor] how can I use the functions inside
	ITfInputProcessorProfiles
In-Reply-To: <884670ce0807110111s5edc19c5l32fef101fe79c8fe@mail.gmail.com>
References: <884670ce0807110111s5edc19c5l32fef101fe79c8fe@mail.gmail.com>
Message-ID: <487783AD.2050408@timgolden.me.uk>

Dror Cohen wrote:
> I'm trying to use the these functions which are in isnide of 
> ITfInputProcessorProfiles
> http://msdn.microsoft.com/en-us/library/ms538984(VS.85).aspx
> 
> I think that its registry key is {892F230F-FE00-4A41-A98E-FCD6DE0D35EF} 
> (though I don't know if I even need this)
> 
> How can I use its function inside of python.
> I tried using this by thinking it will get me somewhere (Got no idea if 
> I was even close)
> 
> 
> point = None
> Inputpp = pythoncom.MakeIID('{892F230F-FE00-4A41-A98E-FCD6DE0D35EF}')
> pythoncom.CoCreateInstance(Inputpp, None, 
> pythoncom.CLSCTX_INPROC_SERVER, point)
> 
> but then I got this error message
> 
>  Traceback (most recent call last):
>    File "<interactive input>", line 1, in <module>
>     TypeError: Only strings and iids can be converted to a CLSID.

This question would probably be better posed to the python-win32
mailing list. People on the tutor list are always ready to be helpful,
but this one's a bit specific.

To answer your question as straightforwardly as possible: the
pywin32 COM extensions can't handle arbitrary COM interfaces.
For that you need to use comtypes [1] (or write your own extension).
The code below works against the current comtypes svn HEAD.

<code>
import ctypes
from ctypes import wintypes
import comtypes

class ITfInputProcessorProfiles  (comtypes.IUnknown):
  _iid_ = comtypes.GUID ("{1F02B6C5-7842-4EE6-8A0B-9A24183A95CA}")
  _idlflags_ = []
  _case_insensitive_ = False
  
  _methods_ = [
    comtypes.COMMETHOD (
      [], comtypes.HRESULT, "GetCurrentLanguage",
      (["out"], ctypes.POINTER (wintypes.LANGID), "pLangId")
    )
  ]

ipp = comtypes.CoCreateInstance (
  comtypes.IID ("{33C53A50-F456-4884-B049-85FD643ECFED}"),
  ITfInputProcessorProfiles
)

langid = wintypes.LANGID (ipp.GetCurrentLanguage ())
print langid

</code>


I get a value of 0, which seems to indicate a major and sub language
of NEUTRAL. I don't really know how languages work on Windows,
and there seem to be too many variants. As an alternative, you
might want to look at the win32api module, which has functions
like GetUserDefaultLangID and GetUserDefaultLCID.

TJG

[1] http://starship.python.net/crew/theller/comtypes/

From alan.gauld at btinternet.com  Fri Jul 11 23:20:56 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 11 Jul 2008 22:20:56 +0100
Subject: [Tutor] Classes
References: <200807110858.m6B8w5tQ005534@mta3.iomartmail.com>
Message-ID: <g58irr$rqv$1@ger.gmane.org>

<paul at assured-networks.co.uk> wrote

> 1. What is the difference between a classmethod and a
> staticmethod, and when would i use either?

Kent pointed you at the recent discussion but from your later
comments I thibnk its pretty safe to say that for now you don't
need to care. The vast majority of classes you build will not
use either of them.

> 2. I want to create an object, presumably a class, to handle
> attributes of an open gl object.

You define a class and then create objects as instances of the class.
The class is a template for creating lots of similar objects. If it
helps you can think of it a bit like defining a function that creates
an empty dictionary. Here is an example of a point class:

def makePoint(x=0,y=0):
    newFoo = { 'X': x, 'Y': y }
    return newFoo

p1 = newFoo(22,66)
p2 = newFoo()

print p1['X']   # prints 22
print p2['Y']    # prints 0 - the default value

This is equivalent to

class Point:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

p1 = Point(22,66)
p2 = Point()

print p1.x
print p2.y

Notice that while it takes more typing to define the class
it takes a lot less to use it - no quotes needed etc. This is a
lot of what OO is about defining structures(classes() that are
easy to use and hide a lot of effort. In fact, in Python, classes
can be thought of as just a very clever type of dictionary.

The other thing about classes is that as well as data they
contain methods. You can make a dictionary hold methods
too but using them is, again, trickier than using the methods
of a class.

> For example, if i wanted to create a 2d square i need 4 points,
> each with an x,y co-ord, and each point could also have an
> optional colour

Or you could have just two diameterically opposite points and
calculate where the others are! - this is how most GUI toolkits
do it. (In fact for a square you can get away with one point plus
a length!) You could also consider a square to be a set of four
lines each with 2 points. The choice of representation is all yours.
One of the key benefits of OO is that the user of your class doesn't
even need to know or care if you provide enough methods...

Also, do the points have colours? Or do the lines have colours?
Or does the square have a single border colour? Again, the choice
is yours. And if you provide the methods the user need not know
nor care.

> , in the form (1.0, 1.0, 1.0), each of these items is then passed
> to the 'drawing' function to actually draw the square or polygon 
> etc.

So to define a class to your spec we could define a POint:

class Point:
    def __init__(self, x, y, col):
        self.x = x
        self.y = y
        self.col = col

class Square:
     def __init__(self,p1,p2,p3,p4):
          self.points = [p1,p2,p3,p4]
     def draw(self):
          myTookKitDrawSquare(p1.x,p1.y, p1.col,
                                            p2.x,p2.y, p2.col,
                                            p3.x,p3.y, p3.col,
                                            p4.x,p4.y, p4.col)


s1 = Square(Point(0,0,'red'), Point(0,55, 'blue'), 
Point(55,0,'green'),Point(55,55,'red'))
s2 = Square(Point(0,0,'white'), Point(0,5, 'grey), 
Point(5,0,'green'),Point(5,5,'black'))

for shape in [s1,s2]:
     shape.draw()

> My question is how do i design the appropriate class to do this,
> i have coded these with lists at the moment

Does the above (untested!) example give you an idea? (Its far from
perfect but deliberately made as simple as I could and as close to
your model as I could)

There is no great magic about OOP its just a convenient way of
packaging data and the functions that operate on that data into
a single entity - this is encapsulation. You can then pass the
resultant objects around as a unit. You can also ignore whats
inside and focus on using the methods - this is called abstraction.
And if a number of classes share the same set of methods
you can even ignore the types of the objects(within the group)
and this is whats called polymorphism. Lots of jargon for what
are basically simple concepts

> open gl uses the same attribute name for each, ie glVertex2i
> and glColor3f, and am not sure how to pass this correctly,

I'm no OpenGL expert and not sure I understand your
question here.

    glColor3f(1.0, 0.0, 0.0)
    glVertex2i(l[0], l[1])

These would I think be the equivalent of the function that
I called "myTookKitDrawSquare" in the example above.

> This is based on a square, but i would like to change the
> number of vertices using a for loop, i am just unsure how
> to get the variables into the correct places.

You could define a polygon class that takes list of points
as its constructor. [Note: Thre is a long running debate in
OOP circles about whether squares etc are subtypes
rectangles which are subtypes of polygons or peers of
them. Its very philosophical and a bit like asking whether
the chicken or egg came first! Beware of analysis paralysis!]

HTH,


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



From cspears2002 at yahoo.com  Sat Jul 12 01:54:18 2008
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Fri, 11 Jul 2008 16:54:18 -0700 (PDT)
Subject: [Tutor] stack class
Message-ID: <116719.91906.qm@web51611.mail.re2.yahoo.com>

For another Core Python Programming question, I created a stack class.  I then put the class into a script to test it:

#!/usr/bin/python

class Stack(list):
    def isempty(self):
        length = len(self)
        if length == 0:
	    return True
	else:
	    return False
	    
    def peek(self):
        length = len(self)
	if length == 0:
	    return 0
	else:
	    last_index = length - 1
            return self[last_index]
    
    def stackpop(self):
        length = len(self)
	if length == 0:
	    print "Empty list!"
	else:
	    last_index = length - 1
	    stackpop_val = self[last_index]
	    self = self[:last_index]
	    return stackpop_val
    
    def push(self, value):
        return self.append(value)
	
if __name__ == '__main__':
    x = True
    stack = Stack()
    print "Pick an option to modify stack: "
    while x == True:
	print "1) Peek at the last value"
	print "2) Pop off the last value"
	print "3) Push a value on the stack"
	print "4) Quit Program"
	choice_string = raw_input("Make a choice: ")
    
        try:
            choice = int(choice_string)
        except ValueError:
            sys.exit("Not an integer!  Goodbye!")
  
        if choice == 1:
	    if stack.isempty():
	        print "Stack is empty"
	    else:
                peek_val = stack.peek()
	        print peek_val
        elif choice == 2:
	    if "pop" in dir(list):
                pop_val = stack.pop()
	        print pop_val
	    else:
	        pop_val = stack.stackpop()
		print pop_val
        elif choice == 3:
	    push_val = raw_input("Push this value on stack: ")
            stack.push(push_val)
	    print stack
        elif choice == 4:
            print "Goodbye!"
	    x = False
        else:
	    x = False
            sys.exit("Wrong response Goodbye!")

According to the question, I should test if the pop() function is available.  If that function is not available, the stack should use a pop() method of my own design.  I think I solved the problem, but I am not sure how to test it because Python 2.4 is installed on my computer.


      

From alan.gauld at btinternet.com  Sat Jul 12 02:43:47 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 12 Jul 2008 01:43:47 +0100
Subject: [Tutor] stack class
References: <116719.91906.qm@web51611.mail.re2.yahoo.com>
Message-ID: <g58uo7$oic$1@ger.gmane.org>


"Christopher Spears" <cspears2002 at yahoo.com> wrote

> I created a stack class.  I then put the class into a script to test 
> it:

I'll assume the crazy indentation is due to email errors.

> class Stack(list):
>    def isempty(self):
>        length = len(self)
>        if length == 0:
>     return True
> else:
>     return False


return len(self) == 0

does the same thing in one line

>    def peek(self):
>        length = len(self)
> if length == 0:
>     return 0
> else:
>     last_index = length - 1
>            return self[last_index]

if len(self) > 0:
    return self[-1]
else:
    return 0

does the same thing

>    def stackpop(self):
>        length = len(self)
> if length == 0:
>     print "Empty list!"
> else:
>     last_index = length - 1
>     stackpop_val = self[last_index]
>     self = self[:last_index]
>     return stackpop_val

if len(self) > 0:
    stackpop_val = self[-1]
    self = self[:-1]
    return stackpop_val

printing is a bad idea since it will limit reusability. The default
is to return None which a class user can detect. Alternatively
raise an IndexError instead.

>    def push(self, value):
>        return self.append(value)

append just returns None so there is no need to include the
return. Just perform the append.

> if __name__ == '__main__':
>    x = True
>    stack = Stack()
>    print "Pick an option to modify stack: "
>    while x == True:
> print "1) Peek at the last value"
> print "2) Pop off the last value"
> print "3) Push a value on the stack"
> print "4) Quit Program"
> choice_string = raw_input("Make a choice: ")
>
>        try:
>            choice = int(choice_string)
>        except ValueError:
>            sys.exit("Not an integer!  Goodbye!")
>
>        if choice == 1:
>     if stack.isempty():
>         print "Stack is empty"
>     else:
>                peek_val = stack.peek()
>         print peek_val
>        elif choice == 2:
>     if "pop" in dir(list):
>                pop_val = stack.pop()
>         print pop_val
>     else:
>         pop_val = stack.stackpop()
> print pop_val
>        elif choice == 3:
>     push_val = raw_input("Push this value on stack: ")
>            stack.push(push_val)
>     print stack
>        elif choice == 4:
>            print "Goodbye!"
>     x = False
>        else:
>     x = False
>            sys.exit("Wrong response Goodbye!")
>
>  I am not sure how to test it because Python 2.4 is
> installed on my computer.

To fully test it you obviously need 2 versions of python
one with and one without pop. The only alternartive is to
delete pop from the built in list class on one test run.
But that might be tricky to do as pop is readonly....
ie I don't know how! :-)

The best alternative I can do is to define your own
pop to be None. That will mask the inherited method.
You can then check if Stack.pop is callable. If not call
your version.

HTH,

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



From ceasar102 at yahoo.com  Sat Jul 12 08:17:27 2008
From: ceasar102 at yahoo.com (ammar azif)
Date: Fri, 11 Jul 2008 23:17:27 -0700 (PDT)
Subject: [Tutor] Launching default web browsers.
Message-ID: <430928.80413.qm@web56811.mail.re3.yahoo.com>

Hi,

I am going to develop an application that will launch the user's computer default web browser pointing to a URL. How to do this in python and which library should I use? Also, my development platform is Linux but the application is targeted to run in Windows platform. Is there any major platform dependent barriers that I will face?

Thanks.? 



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080711/f3791c37/attachment-0001.htm>

From reed at reedobrien.com  Sat Jul 12 08:39:33 2008
From: reed at reedobrien.com (Reed O'Brien)
Date: Sat, 12 Jul 2008 02:39:33 -0400
Subject: [Tutor] stack class
In-Reply-To: <116719.91906.qm@web51611.mail.re2.yahoo.com>
References: <116719.91906.qm@web51611.mail.re2.yahoo.com>
Message-ID: <88788019-06E0-4F4B-8527-C2EB644ABE10@reedobrien.com>

On Jul 11, 2008, at 7:54 PM, Christopher Spears wrote:

> For another Core Python Programming question, I created a stack  
> class.  I then put the class into a script to test it:

I understand that this is an exercise; but I think it might be  
interesting for you to also look at collections.deque
http://docs.python.org/lib/deque-objects.html

>
>
> #!/usr/bin/python
>
> class Stack(list):
>    def isempty(self):
>        length = len(self)
>        if length == 0:
> 	    return True
> 	else:
> 	    return False
> 	
>    def peek(self):
>        length = len(self)
> 	if length == 0:
> 	    return 0
> 	else:
> 	    last_index = length - 1
>            return self[last_index]
>
>    def stackpop(self):
>        length = len(self)
> 	if length == 0:
> 	    print "Empty list!"
> 	else:
> 	    last_index = length - 1
> 	    stackpop_val = self[last_index]
> 	    self = self[:last_index]
> 	    return stackpop_val
>
>    def push(self, value):
>        return self.append(value)
> 	
> if __name__ == '__main__':
>    x = True
>    stack = Stack()
>    print "Pick an option to modify stack: "
>    while x == True:
> 	print "1) Peek at the last value"
> 	print "2) Pop off the last value"
> 	print "3) Push a value on the stack"
> 	print "4) Quit Program"
> 	choice_string = raw_input("Make a choice: ")
>
>        try:
>            choice = int(choice_string)
>        except ValueError:
>            sys.exit("Not an integer!  Goodbye!")
>
>        if choice == 1:
> 	    if stack.isempty():
> 	        print "Stack is empty"
> 	    else:
>                peek_val = stack.peek()
> 	        print peek_val
>        elif choice == 2:
> 	    if "pop" in dir(list):
>                pop_val = stack.pop()
> 	        print pop_val
> 	    else:
> 	        pop_val = stack.stackpop()
> 		print pop_val
>        elif choice == 3:
> 	    push_val = raw_input("Push this value on stack: ")
>            stack.push(push_val)
> 	    print stack
>        elif choice == 4:
>            print "Goodbye!"
> 	    x = False
>        else:
> 	    x = False
>            sys.exit("Wrong response Goodbye!")
>
> According to the question, I should test if the pop() function is  
> available.  If that function is not available, the stack should use  
> a pop() method of my own design.  I think I solved the problem, but  
> I am not sure how to test it because Python 2.4 is installed on my  
> computer.
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


From alan.gauld at btinternet.com  Sat Jul 12 09:54:20 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 12 Jul 2008 08:54:20 +0100
Subject: [Tutor] Launching default web browsers.
References: <430928.80413.qm@web56811.mail.re3.yahoo.com>
Message-ID: <g59nvg$9h5$1@ger.gmane.org>


"ammar azif" <ceasar102 at yahoo.com> wrote

> I am going to develop an application that will launch the
> user's computer default web browser pointing to a URL.
>  How to do this in python and which library should I use?

Look at the webbrowser module, it is intended to do just that.

> Also, my development platform is Linux but the application
> is targeted to run in Windows platform. Is there any major
> platform dependent barriers that I will face?

There will almost inevitably be some issues but a lot will
depend on the browsers in use as well. If everyone is using
Firefox or IE then its likely to work fairly well, but if there
is a big mix of browsers I suspect you might have some
headaches.

I suggest you try a very simple script initially and see how
well it works with your users.

Alan G





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


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



From alan.gauld at btinternet.com  Sat Jul 12 13:51:52 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 12 Jul 2008 12:51:52 +0100
Subject: [Tutor] Classes
References: <200807110858.m6B8w5tQ005534@mta3.iomartmail.com>
	<g58irr$rqv$1@ger.gmane.org>
Message-ID: <g5a5ss$9ra$1@ger.gmane.org>


"Alan Gauld" <alan.gauld at btinternet.com> wrote 

> class Square:
>     def __init__(self,p1,p2,p3,p4):
>          self.points = [p1,p2,p3,p4]
>     def draw(self):
>          myTookKitDrawSquare(p1.x,p1.y, p1.col,
>                                            p2.x,p2.y, p2.col,
>                                            p3.x,p3.y, p3.col,
>                                            p4.x,p4.y, p4.col)

Oops! The p1.x etc should of course have been
self.points[0].x etc draw cannot use the point
parameters from init! 

Alan G.


From eric at ericabrahamsen.net  Sat Jul 12 14:55:02 2008
From: eric at ericabrahamsen.net (Eric Abrahamsen)
Date: Sat, 12 Jul 2008 20:55:02 +0800
Subject: [Tutor] splits and pops
Message-ID: <3BAA0261-E474-434F-989E-98F93CDB93E1@ericabrahamsen.net>

I have a horribly stupid text parsing problem that is driving me  
crazy, and making me think my Python skills have a long, long way to  
go...

What I've got is a poorly-though-out SQL dump, in the form of a text  
file, where each record is separated by a newline, and each field in  
each record is separated by a tab. BUT, and this is what sinks me,  
there are also newlines within some of the fields. Newlines are not  
'safe' ? they could appear anywhere ? but tabs are 'safe' ? they only  
appear as field delimiters.

There are nine fields per record. All I can think to do is read the  
file in as a string, then split on tabs. That gives me a list where  
every eighth item is a string like this: u'last-field\nfirst-field'.  
Now I want to iterate through the list of strings, taking every eighth  
item, splitting it on '\n', and replacing it with the two resulting  
strings. Then I'll have the proper flat list where every nine list  
items constitutes one complete record, and I'm good to go from there.

I've been fooling around with variations on the following (assuming  
splitlist = fullstring.split('\t')):

for x in xrange(8, sys.maxint, 8):
     try:
         splitlist[x:x] = splitlist.pop(x).split('\n')
     except IndexError:
         break

The first line correctly steps over all the list items that need to be  
split, but I can't come up with a line that correctly replaces those  
list items with the two strings I want. Either the cycle goes off and  
splits the wrong strings, or I get nested list items, which is not  
what I want. Can someone please point me in the right direction here?

Thanks,
Eric

From bgailer at gmail.com  Sat Jul 12 15:44:06 2008
From: bgailer at gmail.com (bob gailer)
Date: Sat, 12 Jul 2008 09:44:06 -0400
Subject: [Tutor] splits and pops
In-Reply-To: <3BAA0261-E474-434F-989E-98F93CDB93E1@ericabrahamsen.net>
References: <3BAA0261-E474-434F-989E-98F93CDB93E1@ericabrahamsen.net>
Message-ID: <4878B526.1000803@gmail.com>

Eric Abrahamsen wrote:
> I have a horribly stupid text parsing problem that is driving me 
> crazy, and making me think my Python skills have a long, long way to 
> go...
>
> What I've got is a poorly-though-out SQL dump, in the form of a text 
> file, where each record is separated by a newline, and each field in 
> each record is separated by a tab. BUT, and this is what sinks me, 
> there are also newlines within some of the fields. Newlines are not 
> 'safe' ? they could appear anywhere ? but tabs are 'safe' ? they only 
> appear as field delimiters.
>
> There are nine fields per record. All I can think to do is read the 
> file in as a string, then split on tabs. That gives me a list where 
> every eighth item is a string like this: u'last-field\nfirst-field'. 
> Now I want to iterate through the list of strings, taking every eighth 
> item, splitting it on '\n', and replacing it with the two resulting 
> strings. Then I'll have the proper flat list where every nine list 
> items constitutes one complete record, and I'm good to go from there.
>
> I've been fooling around with variations on the following (assuming 
> splitlist = fullstring.split('\t')):
>
> for x in xrange(8, sys.maxint, 8):
>     try:
>         splitlist[x:x] = splitlist.pop(x).split('\n')
>     except IndexError:
>         break
>
> The first line correctly steps over all the list items that need to be 
> split, but I can't come up with a line that correctly replaces those 
> list items with the two strings I want. Either the cycle goes off and 
> splits the wrong strings, or I get nested list items, which is not 
> what I want. Can someone please point me in the right direction here? 
I  tried a simple case with fullstring = 
"11\t12\t13\t\n14\t15\t16\t17\t18\t19\n21\t22\t23\t24\t25\t26\t27\t28\t29"
Your spec is a little vague "each field in each record is separated by a 
tab". I assumed that to mean "fields in each record are separated by tabs".
The result was ['11', '12', '13', '\n14', '15', '16', '17', '18', '19', 
'21', '22', '23', '24', '25', '26', '27', '28', '29']
which I had expected.

Give us an example of text for which it does not work.
>
>


-- 
Bob Gailer
919-636-4239 Chapel Hill, NC


From paul at assured-networks.co.uk  Sat Jul 12 15:47:16 2008
From: paul at assured-networks.co.uk (Paul Melvin)
Date: Sat, 12 Jul 2008 14:47:16 +0100
Subject: [Tutor] Classes v2, thoughts/suggestions please
Message-ID: <000301c8e425$cc469600$64d3c200$@co.uk>

Thanks to Alans insights i have come up with a working class for a square,
overcomplicated probably but it lays the groundwork for my polygon class
which will iterate over something to generate an n-sided polygon.
If anyone is interested in actually running/testing this you need to get
hold of pgylet 1.1, http://pyglet.org/
I would welcome any suggestions/improvements etc as my class knowledge is
still somewhat lacking :-) 
I was thinking about using *args to get maybe the colour information in, not
sure if i could do it with the points, is this a good idea/possible?
And how can i go about testing that i get appropriate values during the
testing/building phase (generally speaking), is it lots of print/return
statements and then remove them?
Thanks
paul
#!/usr/bin/env python

from pyglet.gl import *

class Point:
    '''This init contains the x,y co-ordinates
       and the colour/transparency objects
       cr is red, cg is green, cb is blue and ct is transparency
       a value or 1.0, 1.0, 1.0, 1.0 is white/0% transparent'''
    def __init__(self, x=0, y=0, cr=1.0, cg=1.0, cb=1.0, ct=1.0):
        self.x = x
        self.y = y
        self.cr = cr
        self.cg = cg
        self.cb = cb
        self.ct = ct
        self.col = (cr, cg, cb, ct)

class Square:
    '''First version, requires four points, an optional filled field
       and an optional line width field.
       The next version will iterate over a loop to allow the
       construction of polygons'''
    def __init__(self, p1, p2, p3, p4, filled=True, line_width=1):
        self.points = [p1,p2,p3,p4]
        self.filled = filled
        self.line_width = line_width
    def draw(self):
        draw_square(self.points[0].x, self.points[0].y, self.points[0].col,
self.points[1].x,self.points[1].y, self.points[1].col, self.points[2].x,
self.points[2].y, self.points[2].col, self.points[3].x, self.points[3].y,
self.points[3].col, self.filled, self.line_width)
        
def draw_square(x0, y0, col0, x1, y1, col1, x2, y2, col2, x3, y3, col3,
filled=True, line_width=1):
    
    if filled:
        glBegin(GL_QUADS)
    else:
        glLineWidth(line_width)
        glBegin(GL_LINE_LOOP)
    
    glColor4f(col0[0], col0[1], col0[2], col0[3])
    glVertex2i(int(x0), int(y0))
    glColor4f(col1[0], col1[1], col1[2], col1[3])
    glVertex2i(int(x1), int(y1))
    glColor4f(col2[0], col2[1], col2[2], col2[3])
    glVertex2i(int(x2), int(y2))
    glColor4f(col3[0], col3[1], col3[2], col3[3])
    glVertex2i(int(x3), int(y3))
    glEnd()
    if not filled and line_width != 1:  # reset to default
        glLineWidth(1)

if __name__ == '__main__':
    from pyglet import window
    
    window  = window.Window(250, 250)
    s1 = Square(Point(50,50,cg=0.0,cb=0.0), Point(200,50,cr=0.0,cb=0.0),
Point(200,200,cr=0.0,cg=0.0), Point(50,200), filled=False, line_width=2)
    
    @window.event
    def on_draw():
        window.clear()
        s1.draw()
        
    pyglet.app.run()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080712/84cb7fed/attachment-0001.htm>

From bgailer at gmail.com  Sat Jul 12 16:28:54 2008
From: bgailer at gmail.com (bob gailer)
Date: Sat, 12 Jul 2008 10:28:54 -0400
Subject: [Tutor] splits and pops
In-Reply-To: <07746D51-A33F-4B0B-A657-97D3D862EE55@ericabrahamsen.net>
References: <3BAA0261-E474-434F-989E-98F93CDB93E1@ericabrahamsen.net>
	<4878B526.1000803@gmail.com>
	<07746D51-A33F-4B0B-A657-97D3D862EE55@ericabrahamsen.net>
Message-ID: <4878BFA6.9090306@gmail.com>

Please reply to the list and not just me. That way we all get to 
contribute and to learn.

Eric Abrahamsen wrote:
> Sorry I haven't explained this clearly, it's just one more symptom of 
> my confusion... Your example has a tab between records as well as 
> between fields: 

That's not how I see it! Look again:

"11\t12\t13\t\n14\t15\t16\t17\t18\t19\n21\t22\t23\t24\t25\t26\t27\t28\t29"

> my text file had tabs only between fields, and only a newline between 
> records.
>
> The test string I was practicing with was this:
>
> test = 'one\ttwo\tthree\nfour\tfive\tsix'
>
> split on tabs produced this:
>
> test = ['one', 'two', 'three\nfour', 'five', 'six']
>
> My loop (breaking test[2] on '\n') worked fine with this test, which 
> was what confused me. I only realized what the problem was when I 
> tried it on a test like this:
>
> test = ['one', 'two', 'three\nfour', 'five', 'six', 'seven\neight', 
> 'nine']
>
> That showed me that I needed to step one extra item, in order to reach 
> the next item that needed to be split. My brain still hurts.
>
>
> E
>
> On Jul 12, 2008, at 9:44 PM, bob gailer wrote:
>
>> Eric Abrahamsen wrote:
>>> I have a horribly stupid text parsing problem that is driving me 
>>> crazy, and making me think my Python skills have a long, long way to 
>>> go...
>>>
>>> What I've got is a poorly-though-out SQL dump, in the form of a text 
>>> file, where each record is separated by a newline, and each field in 
>>> each record is separated by a tab. BUT, and this is what sinks me, 
>>> there are also newlines within some of the fields. Newlines are not 
>>> 'safe' ? they could appear anywhere ? but tabs are 'safe' ? they 
>>> only appear as field delimiters.
>>>
>>> There are nine fields per record. All I can think to do is read the 
>>> file in as a string, then split on tabs. That gives me a list where 
>>> every eighth item is a string like this: u'last-field\nfirst-field'. 
>>> Now I want to iterate through the list of strings, taking every 
>>> eighth item, splitting it on '\n', and replacing it with the two 
>>> resulting strings. Then I'll have the proper flat list where every 
>>> nine list items constitutes one complete record, and I'm good to go 
>>> from there.
>>>
>>> I've been fooling around with variations on the following (assuming 
>>> splitlist = fullstring.split('\t')):
>>>
>>> for x in xrange(8, sys.maxint, 8):
>>>    try:
>>>        splitlist[x:x] = splitlist.pop(x).split('\n')
>>>    except IndexError:
>>>        break
>>>
>>> The first line correctly steps over all the list items that need to 
>>> be split, but I can't come up with a line that correctly replaces 
>>> those list items with the two strings I want. Either the cycle goes 
>>> off and splits the wrong strings, or I get nested list items, which 
>>> is not what I want. Can someone please point me in the right 
>>> direction here?
>> I  tried a simple case with fullstring = 
>> "11\t12\t13\t\n14\t15\t16\t17\t18\t19\n21\t22\t23\t24\t25\t26\t27\t28\t29" 
>>
>> Your spec is a little vague "each field in each record is separated 
>> by a tab". I assumed that to mean "fields in each record are 
>> separated by tabs".
>> The result was ['11', '12', '13', '\n14', '15', '16', '17', '18', 
>> '19', '21', '22', '23', '24', '25', '26', '27', '28', '29']
>> which I had expected.
>>
>> Give us an example of text for which it does not work.
>>>
>>>
>>
>>
>> -- 
>> Bob Gailer
>> 919-636-4239 Chapel Hill, NC
>>
>
>


-- 
Bob Gailer
919-636-4239 Chapel Hill, NC


From kent37 at tds.net  Sat Jul 12 16:56:27 2008
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 12 Jul 2008 10:56:27 -0400
Subject: [Tutor] splits and pops
In-Reply-To: <3BAA0261-E474-434F-989E-98F93CDB93E1@ericabrahamsen.net>
References: <3BAA0261-E474-434F-989E-98F93CDB93E1@ericabrahamsen.net>
Message-ID: <1c2a2c590807120756y40d3649cve8b972889bca4f8f@mail.gmail.com>

On Sat, Jul 12, 2008 at 8:55 AM, Eric Abrahamsen
<eric at ericabrahamsen.net> wrote:

> I've been fooling around with variations on the following (assuming
> splitlist = fullstring.split('\t')):
>
> for x in xrange(8, sys.maxint, 8):
>    try:
>        splitlist[x:x] = splitlist.pop(x).split('\n')
>    except IndexError:
>        break
>
> The first line correctly steps over all the list items that need to be
> split, but I can't come up with a line that correctly replaces those list
> items with the two strings I want. Either the cycle goes off and splits the
> wrong strings, or I get nested list items, which is not what I want. Can
> someone please point me in the right direction here?

The problem is that once you substitute a split field, the indices of
the remaining fields change so you are not looking at the right ones.
Some possibilities:
- work from the back of the list so the indices of the fields to be
processed don't change
- build a new list as you go
- keep track of an offset that you add to the index

The second one would be something like this (untested):
result = []
for i, value in enumerate(splitlist):
  if (i+1) % 8 == 0:
    result.extend(value.split('\n'))
  else:
    result.append(value)

Kent

From deaddy at gmx.de  Sat Jul 12 18:19:57 2008
From: deaddy at gmx.de (Marcel Wunderlich)
Date: Sat, 12 Jul 2008 18:19:57 +0200
Subject: [Tutor] splits and pops
In-Reply-To: <3BAA0261-E474-434F-989E-98F93CDB93E1@ericabrahamsen.net>
References: <3BAA0261-E474-434F-989E-98F93CDB93E1@ericabrahamsen.net>
Message-ID: <op.ud6szhydzxtkpx@localhost>

Hi Eric,

I tried following and it seems to work:

fullstring = """l1r1	ll1r2	l1r3	l1
r4	l1r5
l2r1	l2r3	l3
r3	l2r4	l2r5
l3r1	l3r2	l3r3	l3r4	l3r5
"""
# This should be a string like your's. "\t"-seperated columns,  
"\n"-seperated
# rows, with "\n" in some columns.

rowlength = 5
# for you it would be 9, but I was lazy when I wrote the string

prefetch = ""
lines = []
i = 0
for tab in fullstring.split("\t"):
	if i < rowlength-1:	#i.e. working on all but the last column
		# offtopic: is the last comment correct English?
		prefetch += tab + "\t" # +"\t" because split removes the tab
		i += 1
	else: # last column
		prefetch += tab[:tab.find("\n")]
		lines.append(prefetch)
		prefetch = tab[(tab.find("\n")+2):] #adding the first column without the  
"\n"
		i = 1 #since we already added the first column

# End

After that "print lines" produces following output:
['l1r1\tll1r2\tl1r3\tl1\nr4\tl1r5', '2r1l2r3\tl3\nr3\tl2r4\tl2r5',  
'3r1l3r2\tl3r3\tl3r4\tl3r5']
So you've got a list of the lines. Instead of Strings you could also use
lists, by making prefetch a list and instead of adding the tabs, appending  
it.

However, I assumed that the new row is seperated by the first linebreak.
If that's not the case, I think that you have to check for multiple  
linebreaks
and if that's true, choose manually which one to select.

Hope this helps,

Marcel

> I have a horribly stupid text parsing problem that is driving me crazy,  
> and making me think my Python skills have a long, long way to go...
>
> What I've got is a poorly-though-out SQL dump, in the form of a text  
> file, where each record is separated by a newline, and each field in  
> each record is separated by a tab. BUT, and this is what sinks me, there  
> are also newlines within some of the fields. Newlines are not 'safe' ?  
> they could appear anywhere ? but tabs are 'safe' ? they only appear as  
> field delimiters.
>
> There are nine fields per record. All I can think to do is read the file  
> in as a string, then split on tabs. That gives me a list where every  
> eighth item is a string like this: u'last-field\nfirst-field'. Now I  
> want to iterate through the list of strings, taking every eighth item,  
> splitting it on '\n', and replacing it with the two resulting strings.  
> Then I'll have the proper flat list where every nine list items  
> constitutes one complete record, and I'm good to go from there.
>
> I've been fooling around with variations on the following (assuming  
> splitlist = fullstring.split('\t')):
>
> for x in xrange(8, sys.maxint, 8):
>      try:
>          splitlist[x:x] = splitlist.pop(x).split('\n')
>      except IndexError:
>          break
>
> The first line correctly steps over all the list items that need to be  
> split, but I can't come up with a line that correctly replaces those  
> list items with the two strings I want. Either the cycle goes off and  
> splits the wrong strings, or I get nested list items, which is not what  
> I want. Can someone please point me in the right direction here?
>
> Thanks,
> Eric
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor



From alan.gauld at btinternet.com  Sat Jul 12 19:08:25 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 12 Jul 2008 18:08:25 +0100
Subject: [Tutor] Classes v2, thoughts/suggestions please
References: <000301c8e425$cc469600$64d3c200$@co.uk>
Message-ID: <g5aoed$2p3$1@ger.gmane.org>


"Paul Melvin" <paul at assured-networks.co.uk> wrote

>  i have come up with a working class for a square,

Well done. It might not be the most elegant solution on the
inside but it isn't too bad from the users point of view and thats
what you should aim for IMHO.

> I was thinking about using *args to get maybe the colour
> information in,

I would define polygon to take a list of points as a parameter
of init so you put the onus on the user to pass in  tbe points
in a list. That makes the init method easy:

Class Polygon:
    def __init__(self, pList, filled=True, line_width=1):
        self.points = pList
        self.filled = filled
        self.line_width = line_width

Your draw method is as before but instead of repeating
the code 4 times just put it into a loop that iterates over
the points list, something like:

def draw(self):
    if self.filled:
        glBegin(GL_QUADS)
    else:
        glLineWidth(self.line_width)
        glBegin(GL_LINE_LOOP)
    for p in self.pList
        glColor4f(p.col[0], p.col[1], p.col[2], p.col[3])
        glVertex2i(int(p.x), int(p.y))
    glEnd()
    if not filled and line_width != 1:  # reset to default
        glLineWidth(1)

Note that I put it as the draw method not as a separate
function. There is little point in having a class then calling
a separate function to which you have to pass all the
data in the class!

> And how can i go about testing that i get appropriate values during 
> the
> testing/building phase (generally speaking), is it lots of 
> print/return
> statements and then remove them?

I'm not sure what you mean by "appropriate values" in this context.
Since you are drawing graphics I suspect you will have to just
draw them in a simple canvas and visually ensure the result is
what you expect?

You could try implementing a __str__ method in each class that
lets you print out a nicely formatted report of the Point and/or
Polygon data, which would allow you to do:

p = Point(.....)
print p
s = Polygon([p,p2,p3,p4])
print s

That would allow you to see what the graphic parameters will
be before drawing.

HTH,

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



From paul at assured-networks.co.uk  Sat Jul 12 19:56:09 2008
From: paul at assured-networks.co.uk (Paul Melvin)
Date: Sat, 12 Jul 2008 18:56:09 +0100
Subject: [Tutor] Classes v2, thoughts/suggestions please
In-Reply-To: <g5aoed$2p3$1@ger.gmane.org>
References: <000301c8e425$cc469600$64d3c200$@co.uk>
	<g5aoed$2p3$1@ger.gmane.org>
Message-ID: <002001c8e448$91353260$b39f9720$@co.uk>

> -----Original Message-----
> From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On
> Behalf Of Alan Gauld
> Sent: 12 July 2008 18:08
> To: tutor at python.org
> Subject: Re: [Tutor] Classes v2, thoughts/suggestions please
> 
> 
> "Paul Melvin" <paul at assured-networks.co.uk> wrote
> 
> >  i have come up with a working class for a square,
> 
> Well done. It might not be the most elegant solution on the
> inside but it isn't too bad from the users point of view and thats
> what you should aim for IMHO.
> 
> > I was thinking about using *args to get maybe the colour
> > information in,
> 
> I would define polygon to take a list of points as a parameter
> of init so you put the onus on the user to pass in  tbe points
> in a list. That makes the init method easy:
> 
> Class Polygon:
>     def __init__(self, pList, filled=True, line_width=1):
>         self.points = pList
>         self.filled = filled
>         self.line_width = line_width
> 
> Your draw method is as before but instead of repeating
> the code 4 times just put it into a loop that iterates over
> the points list, something like:
> 
> def draw(self):
>     if self.filled:
>         glBegin(GL_QUADS)
>     else:
>         glLineWidth(self.line_width)
>         glBegin(GL_LINE_LOOP)
>     for p in self.pList
>         glColor4f(p.col[0], p.col[1], p.col[2], p.col[3])
>         glVertex2i(int(p.x), int(p.y))
>     glEnd()
>     if not filled and line_width != 1:  # reset to default
>         glLineWidth(1)
> 
> Note that I put it as the draw method not as a separate
> function. There is little point in having a class then calling
> a separate function to which you have to pass all the
> data in the class!
> 
> > And how can i go about testing that i get appropriate values during
> > the
> > testing/building phase (generally speaking), is it lots of
> > print/return
> > statements and then remove them?
> 
> I'm not sure what you mean by "appropriate values" in this context.
> Since you are drawing graphics I suspect you will have to just
> draw them in a simple canvas and visually ensure the result is
> what you expect?
> 
> You could try implementing a __str__ method in each class that
> lets you print out a nicely formatted report of the Point and/or
> Polygon data, which would allow you to do:
> 
> p = Point(.....)
> print p
> s = Polygon([p,p2,p3,p4])
> print s
> 
> That would allow you to see what the graphic parameters will
> be before drawing.
> 
> HTH,
> 
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
> 
Thanks again for your help, as for 'appropriate' values, in this specific
case it would be numbers but I am also interested in the general design
process, ie how you check your code during design/coding, is it print
statements for example?

Before I start on my polygon class, Alan did mention that it was not
'elegant' which i know as I am only starting and I thought of it as dirty
but working, can someone tell me how I could improve this code or write
better code in the future

Cheers

paul
 

__________ Information from ESET Smart Security, version of virus signature
database 3263 (20080711) __________

The message was checked by ESET Smart Security.

http://www.eset.com
 


From rdm at rcblue.com  Sat Jul 12 22:01:17 2008
From: rdm at rcblue.com (Dick Moores)
Date: Sat, 12 Jul 2008 13:01:17 -0700
Subject: [Tutor] Another assert() question
Message-ID: <20080712200130.13A131E4008@bag.python.org>

An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080712/3ec22d84/attachment.htm>

From dyoo at cs.wpi.edu  Sat Jul 12 22:24:04 2008
From: dyoo at cs.wpi.edu (Danny Yoo)
Date: Sat, 12 Jul 2008 16:24:04 -0400
Subject: [Tutor] Another assert() question
In-Reply-To: <20080712200130.13A131E4008@bag.python.org>
References: <20080712200130.13A131E4008@bag.python.org>
Message-ID: <d06401780807121324v7af4d7c6hbcd954c9ead37c72@mail.gmail.com>

> In my code I have
>
> assert(len(list(set(colors_used_this_cycle))) ==
> len(colors_used_this_cycle), "A color has been used twice!")
>
> But it doesn't work. Cases where a color has been used more than once go
> right through it


Let's try a simple example.


Go back to the structure of an assert statement.

    assert condition[, expression]   ## template

Let's think of a very simple condition.  How about False?  Let's
replace the "condition" part above with False, and not provide an
expression yet.

>>> assert False
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError


Ok, good.  Now let's try to also fill in an expression.  Let's have
the expression be "I expected this".  So we look back at our template:

    assert condition[, expression]   ## template

We're going to substitute False as our condition, and "I expected
this" as our expression.


>>> assert False, "I expected this."
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: I expected this.


That also seems to work.

If the expression gets a little more complicated, the form of the
assertion statement still stays the same.  Let's say that we're
checking to see that the square root of -1 is 1j.  The condition we're
checking is:

    (cmath.sqrt(-1) == 1j)

and the expression is "Bad math."  Then:

>>> import cmath
>>> assert (cmath.sqrt(-1) == 1j), "Bad math"
>>>

We didn't see anything, so the assertion's condition is true.  Let's
artificially induce it to fail.


>>> assert (cmath.sqrt(1) == 1j), "Bad math"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: Bad math


Can you go through a similar exercise with your own condition and
expression?  Isolate the condition part of what you want to test, the
expression part that you want to show, and then just plug directly
into the assert template.



(The problem here is that you've run across one of the edge cases in
Python's syntax involving parenthesized expressions.  Anyone who says
that you can disregard parentheses in Python is not telling the
truth.)

From motoom at xs4all.nl  Sat Jul 12 22:28:08 2008
From: motoom at xs4all.nl (Michiel Overtoom)
Date: Sat, 12 Jul 2008 22:28:08 +0200
Subject: [Tutor] Another assert() question
Message-ID: <2.2.32.20080712202808.0115e1a0@pop.xs4all.nl>

Dick wrote:

> I was hoping to put some sort of explanation of failure in an 
> assert statement. But how to do it?
> So I'd like to know what that 'expression' in the syntax can be, 
> and how to use it.

I think it would help if you separate the detection of duplicate colors from
the assert statement.
It all looks a bit convoluted now, and I'm missing the context in which this
all happens.
First detect the presence of duplicate colors in a True/False variable, then
use that variable in an assert.

Oh, and by the way, you don't have to convert a set to list to be able to
take it's length.

  colors=["red","blue","green","blue","yellow","blue"]
  duplicatesfound = len(set(colors)) != len(colors)
  assert not duplicatesfound, "A color has been used more than once"

Exercise left for the reader: Report which colors were used more than once.

And do me a favor, post in plain text, not HTML.

Greetings,

-- 
"The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing." - Vinod Vallopillil
http://www.catb.org/~esr/halloween/halloween4.html


From kent37 at tds.net  Sat Jul 12 22:34:00 2008
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 12 Jul 2008 16:34:00 -0400
Subject: [Tutor] Another assert() question
In-Reply-To: <20080712200130.13A131E4008@bag.python.org>
References: <20080712200130.13A131E4008@bag.python.org>
Message-ID: <1c2a2c590807121334t40ac6656la0dad0d2b3832ec7@mail.gmail.com>

On Sat, Jul 12, 2008 at 4:01 PM, Dick Moores <rdm at rcblue.com> wrote:
> _Python in a NutShell_, p. 138 has a bit on the assert statement which I
> don't completely understand.
>
> It says the syntax is
>
> assert condition[, expression]
>
> I was hoping to put some sort of explanation of failure in an assert
> statement. But how to do it?
>
> In my code I have
>
> assert(len(list(set(colors_used_this_cycle))) ==
> len(colors_used_this_cycle), "A color has been used twice!")

Leave out the outermost parentheses, assert is a statement, not a function call.

In [2]: assert(False, "Asserted false")

This is "assert condition" where the condition is a tuple with two
elements, hence true so there is no output.

In [3]: assert False, "Asserted false"
---------------------------------------------------------------------------
<type 'exceptions.AssertionError'>        Traceback (most recent call last)

/Users/kent/<ipython console> in <module>()

<type 'exceptions.AssertionError'>: Asserted false

This is the form with an optional expression and works the way you want.

Kent

From kent37 at tds.net  Sat Jul 12 22:35:08 2008
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 12 Jul 2008 16:35:08 -0400
Subject: [Tutor] Classes v2, thoughts/suggestions please
In-Reply-To: <000301c8e425$cc469600$64d3c200$@co.uk>
References: <000301c8e425$cc469600$64d3c200$@co.uk>
Message-ID: <1c2a2c590807121335rfc9d1c9j18fef034aafb7c4c@mail.gmail.com>

On Sat, Jul 12, 2008 at 9:47 AM, Paul Melvin
<paul at assured-networks.co.uk> wrote:

> And how can i go about testing that i get appropriate values during the
> testing/building phase (generally speaking), is it lots of print/return
> statements and then remove them?

Take a look at the doctest and unittest modules, that is a better approach.

Kent

From rdm at rcblue.com  Sat Jul 12 23:35:44 2008
From: rdm at rcblue.com (Dick Moores)
Date: Sat, 12 Jul 2008 14:35:44 -0700
Subject: [Tutor] Another assert() question
In-Reply-To: <2.2.32.20080712202808.0115e1a0@pop.xs4all.nl>
References: <2.2.32.20080712202808.0115e1a0@pop.xs4all.nl>
Message-ID: <20080712213733.5490F1E4008@bag.python.org>

At 01:28 PM 7/12/2008, Michiel Overtoom wrote:
>Dick wrote:
>
> > I was hoping to put some sort of explanation of failure in an
> > assert statement. But how to do it?
> > So I'd like to know what that 'expression' in the syntax can be,
> > and how to use it.
>
>I think it would help if you separate the detection of duplicate colors from
>the assert statement.

Given the name of the list variable, and the expression "Used a color twice!",
it doesn't seem necessary. But maybe I'm missing something.

>It all looks a bit convoluted now, and I'm missing the context in which this
>all happens.

Here it is. <http://py77.python.pastebin.com/f342197d>

>First detect the presence of duplicate colors in a True/False variable, then
>use that variable in an assert.
>
>Oh, and by the way, you don't have to convert a set to list to be able to
>take it's length.

I'm glad to know that. Thanks!

>   colors=["red","blue","green","blue","yellow","blue"]
>   duplicatesfound = len(set(colors)) != len(colors)
>   assert not duplicatesfound, "A color has been used more than once"
>
>Exercise left for the reader: Report which colors were used more than once.

For this program, I don't care. But I'll work on it.

>And do me a favor, post in plain text, not HTML.

HTML? Please explain.

Dick 


From rdm at rcblue.com  Sat Jul 12 23:43:20 2008
From: rdm at rcblue.com (Dick Moores)
Date: Sat, 12 Jul 2008 14:43:20 -0700
Subject: [Tutor] Another assert() question
In-Reply-To: <d06401780807121324v7af4d7c6hbcd954c9ead37c72@mail.gmail.co
 m>
References: <20080712200130.13A131E4008@bag.python.org>
	<d06401780807121324v7af4d7c6hbcd954c9ead37c72@mail.gmail.com>
Message-ID: <20080712214331.DDD5B1E4007@bag.python.org>

At 01:24 PM 7/12/2008, Danny Yoo wrote:
>Content-Transfer-Encoding: 7bit
>Content-Disposition: inline
>
> > In my code I have
> >
> > assert(len(list(set(colors_used_this_cycle))) ==
> > len(colors_used_this_cycle), "A color has been used twice!")
> >
> > But it doesn't work. Cases where a color has been used more than once go
> > right through it
>
>
>Let's try a simple example.
>
>
>Go back to the structure of an assert statement.
>
>     assert condition[, expression]   ## template
>
>Let's think of a very simple condition.  How about False?  Let's
>replace the "condition" part above with False, and not provide an
>expression yet.
>
> >>> assert False
>Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>AssertionError
>
>
>Ok, good.  Now let's try to also fill in an expression.  Let's have
>the expression be "I expected this".  So we look back at our template:
>
>     assert condition[, expression]   ## template
>
>We're going to substitute False as our condition, and "I expected
>this" as our expression.
>
>
> >>> assert False, "I expected this."
>Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>AssertionError: I expected this.
>
>
>That also seems to work.
>
>If the expression gets a little more complicated, the form of the
>assertion statement still stays the same.  Let's say that we're
>checking to see that the square root of -1 is 1j.  The condition we're
>checking is:
>
>     (cmath.sqrt(-1) == 1j)
>
>and the expression is "Bad math."  Then:
>
> >>> import cmath
> >>> assert (cmath.sqrt(-1) == 1j), "Bad math"
> >>>
>
>We didn't see anything, so the assertion's condition is true.  Let's
>artificially induce it to fail.
>
>
> >>> assert (cmath.sqrt(1) == 1j), "Bad math"
>Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>AssertionError: Bad math
>
>
>Can you go through a similar exercise with your own condition and
>expression?  Isolate the condition part of what you want to test, the
>expression part that you want to show, and then just plug directly
>into the assert template.

You can see my solution at 
<http://py77.python.pastebin.com/f342197d>, the highlighted line, line 117.

>(The problem here is that you've run across one of the edge cases in
>Python's syntax involving parenthesized expressions.  Anyone who says
>that you can disregard parentheses in Python is not telling the
>truth.)

Thanks for all all those easy steps, Danny. Very clear.

Dick



From rdm at rcblue.com  Sun Jul 13 00:03:10 2008
From: rdm at rcblue.com (Dick Moores)
Date: Sat, 12 Jul 2008 15:03:10 -0700
Subject: [Tutor] Another assert() question
In-Reply-To: <1c2a2c590807121334t40ac6656la0dad0d2b3832ec7@mail.gmail.co
 m>
References: <20080712200130.13A131E4008@bag.python.org>
	<1c2a2c590807121334t40ac6656la0dad0d2b3832ec7@mail.gmail.com>
Message-ID: <20080712220325.0BC6F1E4007@bag.python.org>

At 01:34 PM 7/12/2008, Kent Johnson wrote:
>On Sat, Jul 12, 2008 at 4:01 PM, Dick Moores <rdm at rcblue.com> wrote:
> > _Python in a NutShell_, p. 138 has a bit on the assert statement which I
> > don't completely understand.
> >
> > It says the syntax is
> >
> > assert condition[, expression]
> >
> > I was hoping to put some sort of explanation of failure in an assert
> > statement. But how to do it?
> >
> > In my code I have
> >
> > assert(len(list(set(colors_used_this_cycle))) ==
> > len(colors_used_this_cycle), "A color has been used twice!")
>
>Leave out the outermost parentheses, assert is a statement, not a 
>function call.

Ah. OK.

>In [2]: assert(False, "Asserted false")
>
>This is "assert condition" where the condition is a tuple with two
>elements, hence true so there is no output.

In [13]: assert(3 < 2 , "qwerty")

In [14]:

I don't understand that logic. Could you unpack it for me?


>In [3]: assert False, "Asserted false"
>---------------------------------------------------------------------------
><type 'exceptions.AssertionError'>        Traceback (most recent call last)
>
>/Users/kent/<ipython console> in <module>()
>
><type 'exceptions.AssertionError'>: Asserted false
>
>This is the form with an optional expression and works the way you want.

In [14]: assert 3 < 2, "Bad math"
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)

E:\Python25\Scripts\<ipython console> in <module>()

AssertionError: Bad math

In [15]:

Yes.

Thanks, Kent.

Dick 


From kent37 at tds.net  Sun Jul 13 04:39:14 2008
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 12 Jul 2008 22:39:14 -0400
Subject: [Tutor] Another assert() question
In-Reply-To: <20080712220325.0BC6F1E4007@bag.python.org>
References: <20080712200130.13A131E4008@bag.python.org>
	<1c2a2c590807121334t40ac6656la0dad0d2b3832ec7@mail.gmail.com>
	<20080712220325.0BC6F1E4007@bag.python.org>
Message-ID: <1c2a2c590807121939l14a5090awbf0a7f9f394fefd8@mail.gmail.com>

On Sat, Jul 12, 2008 at 6:03 PM, Dick Moores <rdm at rcblue.com> wrote:
> At 01:34 PM 7/12/2008, Kent Johnson wrote:

>> In [2]: assert(False, "Asserted false")
>>
>> This is "assert condition" where the condition is a tuple with two
>> elements, hence true so there is no output.
>
> In [13]: assert(3 < 2 , "qwerty")
>
> In [14]:
>
> I don't understand that logic. Could you unpack it for me?

(False, "Asserted false") is a tuple containing two values, False and
"Asserted false".

"assert x" evaluates x as a boolean; if it evaluates to False, the
assertion is raised. A tuple with two elements will always evaluate to
True so the assertion is never raised.

Kent

From rdm at rcblue.com  Sun Jul 13 05:10:55 2008
From: rdm at rcblue.com (Dick Moores)
Date: Sat, 12 Jul 2008 20:10:55 -0700
Subject: [Tutor] Another assert() question
In-Reply-To: <1c2a2c590807121939l14a5090awbf0a7f9f394fefd8@mail.gmail.co
 m>
References: <20080712200130.13A131E4008@bag.python.org>
	<1c2a2c590807121334t40ac6656la0dad0d2b3832ec7@mail.gmail.com>
	<20080712220325.0BC6F1E4007@bag.python.org>
	<1c2a2c590807121939l14a5090awbf0a7f9f394fefd8@mail.gmail.com>
Message-ID: <20080713031114.E53F91E4016@bag.python.org>

At 07:39 PM 7/12/2008, Kent Johnson wrote:
>On Sat, Jul 12, 2008 at 6:03 PM, Dick Moores <rdm at rcblue.com> wrote:
> > At 01:34 PM 7/12/2008, Kent Johnson wrote:
>
> >> In [2]: assert(False, "Asserted false")
> >>
> >> This is "assert condition" where the condition is a tuple with two
> >> elements, hence true so there is no output.
> >
> > In [13]: assert(3 < 2 , "qwerty")
> >
> > In [14]:
> >
> > I don't understand that logic. Could you unpack it for me?
>
>(False, "Asserted false") is a tuple containing two values, False and
>"Asserted false".
>
>"assert x" evaluates x as a boolean; if it evaluates to False, the
>assertion is raised. A tuple with two elements will always evaluate to
>True so the assertion is never raised.

But why will a tuple with two elements will always evaluate to
True?

In [2]: (3,5) == True
Out[2]: False
In [3]: ("qwerty", "asdfg") == True
Out[3]: False
In [4]:

Dick



From marc.tompkins at gmail.com  Sun Jul 13 05:46:14 2008
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Sat, 12 Jul 2008 20:46:14 -0700
Subject: [Tutor] Another assert() question
In-Reply-To: <20080713031114.E53F91E4016@bag.python.org>
References: <20080712200130.13A131E4008@bag.python.org>
	<1c2a2c590807121334t40ac6656la0dad0d2b3832ec7@mail.gmail.com>
	<20080712220325.0BC6F1E4007@bag.python.org>
	<1c2a2c590807121939l14a5090awbf0a7f9f394fefd8@mail.gmail.com>
	<20080713031114.E53F91E4016@bag.python.org>
Message-ID: <40af687b0807122046i1fc3b1cbtc62130988794c91e@mail.gmail.com>

On Sat, Jul 12, 2008 at 8:10 PM, Dick Moores <rdm at rcblue.com> wrote:

> But why will a tuple with two elements will always evaluate to
> True?
>
> In [2]: (3,5) == True
> Out[2]: False
> In [3]: ("qwerty", "asdfg") == True
> Out[3]: False
> In [4]:
>
>
The value formally known as True is only one member of the set of things
that don't evaluate to False...  Confused yet?

Anyway, this might make it a bit clearer:

>>> (3,2) == True
False
>>> if (3,2): print "Tru, dat"
...
Tru, dat
>>>

In other words, "(3,2)" isn't exactly the same as "True" - but it doesn't
evaluate to False, either, so it's true.

It's a bit like arguments about the nature of Good and Evil, I'd say.
-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080712/c0f6c208/attachment-0001.htm>

From mwalsh at groktech.org  Sun Jul 13 06:07:36 2008
From: mwalsh at groktech.org (Martin Walsh)
Date: Sat, 12 Jul 2008 23:07:36 -0500
Subject: [Tutor] Another assert() question
In-Reply-To: <20080713031114.E53F91E4016@bag.python.org>
References: <20080712200130.13A131E4008@bag.python.org>	<1c2a2c590807121334t40ac6656la0dad0d2b3832ec7@mail.gmail.com>	<20080712220325.0BC6F1E4007@bag.python.org>	<1c2a2c590807121939l14a5090awbf0a7f9f394fefd8@mail.gmail.com>
	<20080713031114.E53F91E4016@bag.python.org>
Message-ID: <48797F88.9070100@groktech.org>

Dick Moores wrote:
> At 07:39 PM 7/12/2008, Kent Johnson wrote:
>> On Sat, Jul 12, 2008 at 6:03 PM, Dick Moores <rdm at rcblue.com> wrote:
>> > At 01:34 PM 7/12/2008, Kent Johnson wrote:
>>
>> >> In [2]: assert(False, "Asserted false")
>> >>
>> >> This is "assert condition" where the condition is a tuple with two
>> >> elements, hence true so there is no output.
>> >
>> > In [13]: assert(3 < 2 , "qwerty")
>> >
>> > In [14]:
>> >
>> > I don't understand that logic. Could you unpack it for me?
>>
>> (False, "Asserted false") is a tuple containing two values, False and
>> "Asserted false".
>>
>> "assert x" evaluates x as a boolean; if it evaluates to False, the
>> assertion is raised. A tuple with two elements will always evaluate to
>> True so the assertion is never raised.
> 
> But why will a tuple with two elements will always evaluate to
> True?
> 
> In [2]: (3,5) == True
> Out[2]: False
> In [3]: ("qwerty", "asdfg") == True
> Out[3]: False
> In [4]:

You might find it easier to think about this way:

In [1]: bool((3, 5))
Out[1]: True

In [2]: bool(("qwerty", "asdfg"))
Out[2]: True

More info here:
http://docs.python.org/lib/truth.html
http://docs.python.org/lib/node34.html

HTH,
Marty

From alan.gauld at btinternet.com  Sun Jul 13 09:50:17 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 13 Jul 2008 08:50:17 +0100
Subject: [Tutor] Another assert() question
References: <20080712200130.13A131E4008@bag.python.org><1c2a2c590807121334t40ac6656la0dad0d2b3832ec7@mail.gmail.com><20080712220325.0BC6F1E4007@bag.python.org><1c2a2c590807121939l14a5090awbf0a7f9f394fefd8@mail.gmail.com>
	<1c2a2c590807121939l14a5090awbf0a7f9f394fefd8@mail.gmail.co m>
	<20080713031114.E53F91E4016@bag.python.org>
Message-ID: <g5cc3t$qpb$1@ger.gmane.org>

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

> But why will a tuple with two elements will always evaluate to
> True?

Thats the rule for evaluationg collections in Python.
An empty collection is False. Anything else is therefore true

if []: -> false

if [1,2]: -> true

if (): -> false

if (1,2) - True

if "": -> False

if "foo": -> True

Does that help?

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


From ceasar102 at yahoo.com  Sun Jul 13 14:54:42 2008
From: ceasar102 at yahoo.com (ammar azif)
Date: Sun, 13 Jul 2008 05:54:42 -0700 (PDT)
Subject: [Tutor] Program launcher in taskbar
Message-ID: <192432.74397.qm@web56805.mail.re3.yahoo.com>

Hi,

Is is possible to place my program icon in the system tray portion of the taskbar(like instant messaging applications)? The program will be launched by clicking on the icon. How to do this in python and which module should I use?



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080713/0fa14b00/attachment.htm>

From motoom at xs4all.nl  Sun Jul 13 16:00:06 2008
From: motoom at xs4all.nl (Michiel Overtoom)
Date: Sun, 13 Jul 2008 16:00:06 +0200
Subject: [Tutor] Program launcher in taskbar
Message-ID: <2.2.32.20080713140006.011f0614@pop.xs4all.nl>

Ammar wrote...

> Is is possible to place my program icon in the system tray portion 
> of the taskbar (like instant messaging applications)? 
> The program will be launched by clicking on the icon. How to 
> do this in python and which module should I use?

Are you on a Windows machine?  Then you might want to look at the
'win32gui_taskbar.py' example in the
'C:\Ap\Python\Lib\site-packages\win32\Demos' directory. This assumes you
have Mark Hammond's "Python for Windows Extensions" installed:
http://sourceforge.net/projects/pywin32/

Greetings,

-- 
"The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing." - Vinod Vallopillil
http://www.catb.org/~esr/halloween/halloween4.html


From ptader at linuxscope.com  Sun Jul 13 16:18:40 2008
From: ptader at linuxscope.com (Paul Tader)
Date: Sun, 13 Jul 2008 09:18:40 -0500 (CDT)
Subject: [Tutor] pyopenssl - extracting email certificates information
Message-ID: <44149.24.15.234.107.1215958720.squirrel@mail.linuxscope.com>

Given a raw email I've been able to extract the cryptographic signature
(in encoded or decoded format) into a string.  I would like to like to use
the pyopenssl crypto module
(http://pyopenssl.sourceforge.net/pyOpenSSL.html/openssl.html) to further
extract things like the Signing Authority and the DN subject. So far the
"object orientating" part of python is something I haven't fully grasped
yet so I don't know how to load my certificate string into the pyopenssl
objects so that I can apply its methods.

It's not pretty, but what I have so far...


import os
import sys
import re
import base64

f = open("test.mail", "r")
contents = f.read()
r1 = re.compile('MI.{70}')
r2 = re.compile('AAAAAAAA')
s1 = r1.search(contents)
a = int(s1.start())
s2 = r2.search(contents, a)
b = int(s2.end())
hash = contents[a:b]
encoded = "begin-base64 644 signature.out\n" + hash + "\n===="
decoded = base64.decodestring(encoded)

f.close()



From ceasar102 at yahoo.com  Sun Jul 13 16:26:12 2008
From: ceasar102 at yahoo.com (ammar azif)
Date: Sun, 13 Jul 2008 07:26:12 -0700 (PDT)
Subject: [Tutor] Program launcher in taskbar
In-Reply-To: <2.2.32.20080713140006.011f0614@pop.xs4all.nl>
Message-ID: <253024.88950.qm@web56809.mail.re3.yahoo.com>

Hi,

I am running ubuntu as my development platform but the application is targeted for windows machine. Is there any platform dependent library that can help me do this? 
--- On Sun, 7/13/08, Michiel Overtoom <motoom at xs4all.nl> wrote:
From: Michiel Overtoom <motoom at xs4all.nl>
Subject: Re: [Tutor] Program launcher in taskbar
To: tutor at python.org
Date: Sunday, July 13, 2008, 9:00 AM

Ammar wrote...

> Is is possible to place my program icon in the system tray portion 
> of the taskbar (like instant messaging applications)? 
> The program will be launched by clicking on the icon. How to 
> do this in python and which module should I use?

Are you on a Windows machine?  Then you might want to look at the
'win32gui_taskbar.py' example in the
'C:\Ap\Python\Lib\site-packages\win32\Demos'
directory. This assumes you
have Mark Hammond's "Python for Windows Extensions" installed:
http://sourceforge.net/projects/pywin32/

Greetings,

-- 
"The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing." - Vinod Vallopillil
http://www.catb.org/~esr/halloween/halloween4.html

_______________________________________________
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/20080713/5a6b0041/attachment.htm>

From clazzt at arnet.com.ar  Sun Jul 13 16:38:38 2008
From: clazzt at arnet.com.ar (claxo)
Date: Sun, 13 Jul 2008 11:38:38 -0300
Subject: [Tutor] sys.platform in win XP 64 and vista 64?
Message-ID: <20080713143852.462B11E4002@bag.python.org>


Im correct in that sys.platform will return 'win32' even in 64bits XP-Vista (except for Cygwin builds)?
In the python docs for 2.4 - 2.5 I havent found conclusive data; the docs for 2.6 seems to imply that.



From alan.gauld at btinternet.com  Sun Jul 13 18:35:09 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 13 Jul 2008 17:35:09 +0100
Subject: [Tutor] Program launcher in taskbar
References: <2.2.32.20080713140006.011f0614@pop.xs4all.nl>
	<253024.88950.qm@web56809.mail.re3.yahoo.com>
Message-ID: <g5das2$6he$1@ger.gmane.org>

"ammar azif" <ceasar102 at yahoo.com> wrote 

> I am running ubuntu as my development platform but 
> the application is targeted for windows machine. 
> Is there any platform dependent library that can help me 

Assuming you mean platform *independent* library I suspect 
the answer is no. Things like the taskbar are very platform 
dependent, indeed many (most?) Linux environments don't 
even have a taskbar, or if they do its a user configurable item.

I may be provred wrong but I'll be surprised to find such a 
thing in platform independent form. At best you might find 
one that works on Windows/Gnome or Windows/KDE or 
possibly all three. But it would not cover Enlightenment, 
IceWM, etc...

Alan G.



From rdm at rcblue.com  Sun Jul 13 20:34:32 2008
From: rdm at rcblue.com (Dick Moores)
Date: Sun, 13 Jul 2008 11:34:32 -0700
Subject: [Tutor] Another assert() question
In-Reply-To: <g5cc3t$qpb$1@ger.gmane.org>
References: <20080712200130.13A131E4008@bag.python.org>
	<1c2a2c590807121334t40ac6656la0dad0d2b3832ec7@mail.gmail.com>
	<20080712220325.0BC6F1E4007@bag.python.org>
	<1c2a2c590807121939l14a5090awbf0a7f9f394fefd8@mail.gmail.com>
	<1c2a2c590807121939l14a5090awbf0a7f9f394fefd8@mail.gmail.co m>
	<20080713031114.E53F91E4016@bag.python.org>
	<g5cc3t$qpb$1@ger.gmane.org>
Message-ID: <20080713183444.C4C151E4002@bag.python.org>

An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080713/19d9fefb/attachment.htm>

From steve at alchemy.com  Sun Jul 13 20:44:38 2008
From: steve at alchemy.com (Steve Willoughby)
Date: Sun, 13 Jul 2008 11:44:38 -0700
Subject: [Tutor] Another assert() question
In-Reply-To: <20080713183444.C4C151E4002@bag.python.org>
References: <20080712200130.13A131E4008@bag.python.org>	<1c2a2c590807121334t40ac6656la0dad0d2b3832ec7@mail.gmail.com>	<20080712220325.0BC6F1E4007@bag.python.org>	<1c2a2c590807121939l14a5090awbf0a7f9f394fefd8@mail.gmail.com>	<1c2a2c590807121939l14a5090awbf0a7f9f394fefd8@mail.gmail.co
	m>	<20080713031114.E53F91E4016@bag.python.org>	<g5cc3t$qpb$1@ger.gmane.org>
	<20080713183444.C4C151E4002@bag.python.org>
Message-ID: <487A4D16.5060000@alchemy.com>

Dick Moores wrote:
> Yes! A rule, not logic. I'm not contradicting Kent, just helping myself 
> understand. First the rule, then logic in the application of the rule. 
> And I assume the rule is there in Python because it makes things work 
> better.

Yes, so a statement like "if foo:" becomes an idiom for "if the 
collection foo has stuff in it:" which is handy whether foo is a text 
string or a list of objects.


From rdm at rcblue.com  Sun Jul 13 21:09:12 2008
From: rdm at rcblue.com (Dick Moores)
Date: Sun, 13 Jul 2008 12:09:12 -0700
Subject: [Tutor] Another assert() question
In-Reply-To: <487A4D16.5060000@alchemy.com>
References: <20080712200130.13A131E4008@bag.python.org>
	<1c2a2c590807121334t40ac6656la0dad0d2b3832ec7@mail.gmail.com>
	<20080712220325.0BC6F1E4007@bag.python.org>
	<1c2a2c590807121939l14a5090awbf0a7f9f394fefd8@mail.gmail.com>
	<1c2a2c590807121939l14a5090awbf0a7f9f394fefd8@mail.gmail.co m>
	<20080713031114.E53F91E4016@bag.python.org>
	<g5cc3t$qpb$1@ger.gmane.org>
	<20080713183444.C4C151E4002@bag.python.org>
	<487A4D16.5060000@alchemy.com>
Message-ID: <20080713190926.D06451E4002@bag.python.org>

An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080713/d0ccb8f3/attachment.htm>

From mwalsh at groktech.org  Sun Jul 13 21:40:00 2008
From: mwalsh at groktech.org (Martin Walsh)
Date: Sun, 13 Jul 2008 14:40:00 -0500
Subject: [Tutor] Another assert() question
In-Reply-To: <20080713190926.D06451E4002@bag.python.org>
References: <20080712200130.13A131E4008@bag.python.org>	<1c2a2c590807121334t40ac6656la0dad0d2b3832ec7@mail.gmail.com>	<20080712220325.0BC6F1E4007@bag.python.org>	<1c2a2c590807121939l14a5090awbf0a7f9f394fefd8@mail.gmail.com>	<1c2a2c590807121939l14a5090awbf0a7f9f394fefd8@mail.gmail.co
	m>	<20080713031114.E53F91E4016@bag.python.org>	<g5cc3t$qpb$1@ger.gmane.org>	<20080713183444.C4C151E4002@bag.python.org>	<487A4D16.5060000@alchemy.com>
	<20080713190926.D06451E4002@bag.python.org>
Message-ID: <487A5A10.5010003@groktech.org>

Dick Moores wrote:
> At 11:44 AM 7/13/2008, Steve Willoughby wrote:
>> Dick Moores wrote:
>>> Yes! A rule, not logic. I'm not contradicting Kent, just helping
>>> myself understand. First the rule, then logic in the application of
>>> the rule. And I assume the rule is there in Python because it makes
>>> things work better.
>>
>> Yes, so a statement like "if foo:" becomes an idiom for "if the
>> collection foo has stuff in it:" which is handy whether foo is a text
>> string or a list of objects.
> 
> Yes, I've been using that, a bit uneasily.
> 
> One question about the data I listed. Why is bool(set([])) false,
> whereas bool([[]]) is true?

In the first example you're passing an empty list to the set
constructor, and getting back an empty set object. In the second, you're
providing a list with one element, which just so happens to be an empty
list, but it doesn't matter -- since the outer list is not empty.
Perhaps a better comparison would be bool(list([])) => False.

HTH,
Marty

From deaddy at gmx.de  Sun Jul 13 21:41:58 2008
From: deaddy at gmx.de (Marcel Wunderlich)
Date: Sun, 13 Jul 2008 21:41:58 +0200
Subject: [Tutor] Another assert() question
In-Reply-To: <20080713190926.D06451E4002@bag.python.org>
References: <20080712200130.13A131E4008@bag.python.org>
	<1c2a2c590807121334t40ac6656la0dad0d2b3832ec7@mail.gmail.com>
	<20080712220325.0BC6F1E4007@bag.python.org>
	<1c2a2c590807121939l14a5090awbf0a7f9f394fefd8@mail.gmail.com>
	<1c2a2c590807121939l14a5090awbf0a7f9f394fefd8@mail.gmail.co m>
	<20080713031114.E53F91E4016@bag.python.org>
	<g5cc3t$qpb$1@ger.gmane.org>
	<20080713183444.C4C151E4002@bag.python.org>
	<487A4D16.5060000@alchemy.com>
	<20080713190926.D06451E4002@bag.python.org>
Message-ID: <op.ud8wz70vzxtkpx@localhost>

Hi Dick,

because set(list) creates an unsorted collection without duplicate entrys  
of the items in the list.
If you pass an empty list, the resulting set will also be an empty  
collection.
A list containing an empty list evaluates non false, since it's not empty.  
Maybe it helps you to compare them with the len-command.
len(set([])) returns 0, len([[]]) returns 1.

Marcel

> At 11:44 AM 7/13/2008, Steve Willoughby wrote:
>
> Dick Moores wrote:
>
> Yes! A rule, not logic. I'm not contradicting Kent, just helping myself
> understand. First the rule, then logic in the application of the rule.  
> And I
> assume the rule is there in Python because it makes things work better.
> Yes, so a statement like "if foo:" becomes an idiom for "if the  
> collection foo
> has stuff in it:" which is handy whether foo is a text string or a list  
> of
> objects.
> Yes, I've been using that, a bit uneasily.
>
> One question about the data I listed. Why is bool(set([])) false,  
> whereas bool([[]])
> is true?
>
> Dick



From rdm at rcblue.com  Sun Jul 13 21:50:19 2008
From: rdm at rcblue.com (Dick Moores)
Date: Sun, 13 Jul 2008 12:50:19 -0700
Subject: [Tutor] Another assert() question
In-Reply-To: <487A5A10.5010003@groktech.org>
References: <20080712200130.13A131E4008@bag.python.org>
	<1c2a2c590807121334t40ac6656la0dad0d2b3832ec7@mail.gmail.com>
	<20080712220325.0BC6F1E4007@bag.python.org>
	<1c2a2c590807121939l14a5090awbf0a7f9f394fefd8@mail.gmail.com>
	<1c2a2c590807121939l14a5090awbf0a7f9f394fefd8@mail.gmail.co m>
	<20080713031114.E53F91E4016@bag.python.org>
	<g5cc3t$qpb$1@ger.gmane.org>
	<20080713183444.C4C151E4002@bag.python.org>
	<487A4D16.5060000@alchemy.com>
	<20080713190926.D06451E4002@bag.python.org>
	<487A5A10.5010003@groktech.org>
Message-ID: <20080713195101.0BB381E4002@bag.python.org>

At 12:40 PM 7/13/2008, Martin Walsh wrote:
>Dick Moores wrote:
> > At 11:44 AM 7/13/2008, Steve Willoughby wrote:
> >> Dick Moores wrote:
> >>> Yes! A rule, not logic. I'm not contradicting Kent, just helping
> >>> myself understand. First the rule, then logic in the application of
> >>> the rule. And I assume the rule is there in Python because it makes
> >>> things work better.
> >>
> >> Yes, so a statement like "if foo:" becomes an idiom for "if the
> >> collection foo has stuff in it:" which is handy whether foo is a text
> >> string or a list of objects.
> >
> > Yes, I've been using that, a bit uneasily.
> >
> > One question about the data I listed. Why is bool(set([])) false,
> > whereas bool([[]]) is true?
>
>In the first example you're passing an empty list to the set
>constructor, and getting back an empty set object. In the second, you're
>providing a list with one element, which just so happens to be an empty
>list, but it doesn't matter -- since the outer list is not empty.
>Perhaps a better comparison would be bool(list([])) => False.

My thanks to you and to Marcel Wunderlich, for helping me understand 
why bool(set([])) is false. You guys are good!

Dick



From rdm at rcblue.com  Sun Jul 13 22:06:10 2008
From: rdm at rcblue.com (Dick Moores)
Date: Sun, 13 Jul 2008 13:06:10 -0700
Subject: [Tutor] Another assert() question
In-Reply-To: <40af687b0807122046i1fc3b1cbtc62130988794c91e@mail.gmail.co
 m>
References: <20080712200130.13A131E4008@bag.python.org>
	<1c2a2c590807121334t40ac6656la0dad0d2b3832ec7@mail.gmail.com>
	<20080712220325.0BC6F1E4007@bag.python.org>
	<1c2a2c590807121939l14a5090awbf0a7f9f394fefd8@mail.gmail.com>
	<20080713031114.E53F91E4016@bag.python.org>
	<40af687b0807122046i1fc3b1cbtc62130988794c91e@mail.gmail.com>
Message-ID: <20080713200633.F1F121E4002@bag.python.org>

An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080713/a19c64e2/attachment.htm>

From marc.tompkins at gmail.com  Sun Jul 13 22:19:31 2008
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Sun, 13 Jul 2008 13:19:31 -0700
Subject: [Tutor] Another assert() question
In-Reply-To: <20080713200633.F1F121E4002@bag.python.org>
References: <20080712200130.13A131E4008@bag.python.org>
	<1c2a2c590807121334t40ac6656la0dad0d2b3832ec7@mail.gmail.com>
	<20080712220325.0BC6F1E4007@bag.python.org>
	<1c2a2c590807121939l14a5090awbf0a7f9f394fefd8@mail.gmail.com>
	<20080713031114.E53F91E4016@bag.python.org>
	<40af687b0807122046i1fc3b1cbtc62130988794c91e@mail.gmail.com>
	<20080713200633.F1F121E4002@bag.python.org>
Message-ID: <40af687b0807131319l1b61f35exaee7695e6e8d81b2@mail.gmail.com>

On Sun, Jul 13, 2008 at 1:06 PM, Dick Moores <rdm at rcblue.com> wrote:

>  In other words, "(3,2)" isn't exactly the same as "True" - but it doesn't
> evaluate to False, either, so it's true.
>
>
> So what does (3,2) evaluate to? Or is that a meaningless question? However
> in the following example, "What does z evaluate to?" seems to have a
> meaning, and the answer is not "True" or "False". z evaluates to 12, right?
> Or is there an ambiguity in "evaluate" in Python that is well-understood and
> doesn't cause a problem?
>
> In [28]: x,y = 3,4
>
> In [29]: z = x*y
>
> In [30]: z
> Out[30]: 12
>
> In [31]: bool(z)
> Out[31]: True
>
> In [32]: z == True
> Out[32]: False
>
> In [33]: z == False
> Out[33]: False
>
> Dick
>

It's a matter of context, and a conflation of the phrase "evaluates to" with
"equals" or "is".

In the context of truth or falsehood, "X evaluates to" is the same as
"bool(X)".
In the context of arithmetic, "X evaluates to..." is the same as "X
equals..."  (Then we can go one step further and decide whether the result
is equal to 0, and if it is, then the expression "evaluates to" False.)
In the context of tuples, I can't even get my head around what "evaluates
to" would mean.  (3,2) evaluates to... well, (3,2).  It is what it is.


-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080713/9a409df2/attachment.htm>

From marc.tompkins at gmail.com  Sun Jul 13 22:23:07 2008
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Sun, 13 Jul 2008 13:23:07 -0700
Subject: [Tutor] Fwd:  Another assert() question
In-Reply-To: <40af687b0807131322k238e78abw72c1da7847178703@mail.gmail.com>
References: <20080712200130.13A131E4008@bag.python.org>
	<1c2a2c590807121334t40ac6656la0dad0d2b3832ec7@mail.gmail.com>
	<20080712220325.0BC6F1E4007@bag.python.org>
	<1c2a2c590807121939l14a5090awbf0a7f9f394fefd8@mail.gmail.com>
	<20080713031114.E53F91E4016@bag.python.org>
	<40af687b0807122046i1fc3b1cbtc62130988794c91e@mail.gmail.com>
	<20080713200633.F1F121E4002@bag.python.org>
	<40af687b0807131321p76e1f5e9kd767b0169c51be4b@mail.gmail.com>
	<40af687b0807131322k238e78abw72c1da7847178703@mail.gmail.com>
Message-ID: <40af687b0807131323o4f0489cfq4e1f9fad0041bcc7@mail.gmail.com>

Forgot to send to the list...


On Sun, Jul 13, 2008 at 1:06 PM, Dick Moores <rdm at rcblue.com> wrote:

> Or is there an ambiguity in "evaluate" in Python that is well-understood
> and doesn't cause a problem?
>

I should simply have said: "evaluate" is not a word IN Python (although
"eval()" is, but that's a different topic) - it's a word we use when we talk
ABOUT Python, and its meaning is not cast in stone.


-- 
www.fsrtechnologies.com



-- 
www.fsrtechnologies.com



-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080713/033e50e4/attachment.htm>

From bgailer at gmail.com  Mon Jul 14 00:57:33 2008
From: bgailer at gmail.com (bob gailer)
Date: Sun, 13 Jul 2008 18:57:33 -0400
Subject: [Tutor] Another assert() question
In-Reply-To: <20080713200633.F1F121E4002@bag.python.org>
References: <20080712200130.13A131E4008@bag.python.org>	<1c2a2c590807121334t40ac6656la0dad0d2b3832ec7@mail.gmail.com>	<20080712220325.0BC6F1E4007@bag.python.org>	<1c2a2c590807121939l14a5090awbf0a7f9f394fefd8@mail.gmail.com>	<20080713031114.E53F91E4016@bag.python.org>	<40af687b0807122046i1fc3b1cbtc62130988794c91e@mail.gmail.com>
	<20080713200633.F1F121E4002@bag.python.org>
Message-ID: <487A885D.6070801@gmail.com>

When all else fails RTFM:

5.10 Boolean operations
....
"In the context of Boolean operations, and also when expressions are 
used by control flow statements, the following values are interpreted as 
false: |False|, |None|, numeric zero of all types, and empty strings and 
containers (including strings, tuples, lists, dictionaries, sets and 
frozensets). All other values are interpreted as true."

-- 
Bob Gailer
919-636-4239 Chapel Hill, NC


From jtp at nc.rr.com  Mon Jul 14 01:27:08 2008
From: jtp at nc.rr.com (James)
Date: Sun, 13 Jul 2008 19:27:08 -0400
Subject: [Tutor] Check Number of Parameters Passed In
Message-ID: <e107b4ff0807131627y2148845fy88ea0a1c05d824ce@mail.gmail.com>

Hi All,

I'm writing a function that has optional paramters (i.e., "foo(
parameter , optionalParameter = None , optionalParameter2 = None )").

Is there some way inside of foo() that I can check to see how many
parameters have been passed in? I want to check to ensure that only
*one* optional parameter is passed in (and if more than one is passed
in, do some sort of error handling).

Thanks!
- j

From kent37 at tds.net  Mon Jul 14 01:48:56 2008
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 13 Jul 2008 19:48:56 -0400
Subject: [Tutor] Check Number of Parameters Passed In
In-Reply-To: <e107b4ff0807131627y2148845fy88ea0a1c05d824ce@mail.gmail.com>
References: <e107b4ff0807131627y2148845fy88ea0a1c05d824ce@mail.gmail.com>
Message-ID: <1c2a2c590807131648k7624460bg60f8260460da6046@mail.gmail.com>

On Sun, Jul 13, 2008 at 7:27 PM, James <jtp at nc.rr.com> wrote:
> Hi All,
>
> I'm writing a function that has optional paramters (i.e., "foo(
> parameter , optionalParameter = None , optionalParameter2 = None )").
>
> Is there some way inside of foo() that I can check to see how many
> parameters have been passed in? I want to check to ensure that only
> *one* optional parameter is passed in (and if more than one is passed
> in, do some sort of error handling).

Inside foo(), the optionalParameters will always be defined. Just
check if they are both None:

if optionalParameter is not None and optionalParameter2 is not None:
  print "Error, only one optional parameter can be provided."

Kent

From zachriggle at gmail.com  Mon Jul 14 01:38:44 2008
From: zachriggle at gmail.com (Zach Riggle)
Date: Sun, 13 Jul 2008 18:38:44 -0500
Subject: [Tutor] Overriding Methods
Message-ID: <89C29F1D-75FB-43F3-8CB0-F535A4502B44@gmail.com>

I am implementing an application using XML-RPC, and would like to be  
able to differentiate between multiple clients.  The best way to do  
this that I could think of would be to simply pass some unique  
identifier along with each call over XML-RPC.  However, this could get  
to be a bit cumbersome, and I'd rather not have to worry about it  
after setting it once (the unique ID on the client-side, that is).

In my particular situation, all of the exposed functions are actually  
methods of a class that inherits from SimpleXMLRPCServer (just to keep  
things nice and simple).

Example:
class X(SimpleXMLRPCServer:
   def someMethod(self, uniqID, someVal):
     ...
     return foo

I would like to create a similar wrapper for xmlrpclib.ServerProxy  
that automatically fills the 'uniqID' field with each call over XMLRPC.

For example, instead of
conn = ServerProxy(someURL)
conn.someMethod(myUniqID, blah)

I would like to be able to do the following...
conn = ServerProxyWrapper(someURL)
conn.setUniqID(myUniqID)
conn.someMethod(blah)

How would I go about implementing this?

Thanks,
Zach

From rdm at rcblue.com  Mon Jul 14 02:08:23 2008
From: rdm at rcblue.com (Dick Moores)
Date: Sun, 13 Jul 2008 17:08:23 -0700
Subject: [Tutor] Another assert() question
In-Reply-To: <487A885D.6070801@gmail.com>
References: <20080712200130.13A131E4008@bag.python.org>
	<1c2a2c590807121334t40ac6656la0dad0d2b3832ec7@mail.gmail.com>
	<20080712220325.0BC6F1E4007@bag.python.org>
	<1c2a2c590807121939l14a5090awbf0a7f9f394fefd8@mail.gmail.com>
	<20080713031114.E53F91E4016@bag.python.org>
	<40af687b0807122046i1fc3b1cbtc62130988794c91e@mail.gmail.com>
	<20080713200633.F1F121E4002@bag.python.org>
	<487A885D.6070801@gmail.com>
Message-ID: <20080714000835.1A1DF1E4002@bag.python.org>

At 03:57 PM 7/13/2008, bob gailer wrote:
>When all else fails RTFM:
>
>5.10 Boolean operations
>....
>"In the context of Boolean operations, and also when expressions are 
>used by control flow statements, the following values are 
>interpreted as false: |False|, |None|, numeric zero of all types, 
>and empty strings and containers (including strings, tuples, lists, 
>dictionaries, sets and frozensets). All other values are interpreted as true."

<http://docs.python.org/ref/Booleans.html>

Pretty cryptic, to me at least. Take one of those 2-element tuples, 
that started all this, (3,5). So because it's a non-empty container 
it's value is interpreted as true. That implies (to me at least), 
that it has a value, if unknown (or is it simply (3,5)?) ; however, 
regardless of this value, it is interpreted as true.

To repeat Lutz:

===================================
In Python, as in most programming languages, an integer 0 represents 
false, and an integer 1 represents true. In addition, though, Python 
recognizes any empty data structure as false, and any nonempty data 
structure as true. More generally, the notions of true and false are 
intrinsic properties of every object in Python -- each object is 
either true or false, as follows:

-- Numbers are true if nonzero.
-- Other objects are true if nonempty.
===================================

He follows that with a list of objects and their "truth values", a 
much more suitable term here than "value", IMHO. Take that z of a 
previous post: z's value is 12; z's truth value is True.

I'll presumptuously, brazenly go further: I have 2 quarrels with 5.10:
1. "interpret" is misleading. Revise, substituting "consider".
2. "value" is misleading. Revise, substituting "truth value".

Dick





>--
>Bob Gailer
>919-636-4239 Chapel Hill, NC
>


From bgailer at gmail.com  Mon Jul 14 03:05:37 2008
From: bgailer at gmail.com (bob gailer)
Date: Sun, 13 Jul 2008 21:05:37 -0400
Subject: [Tutor] Check Number of Parameters Passed In
In-Reply-To: <e107b4ff0807131627y2148845fy88ea0a1c05d824ce@mail.gmail.com>
References: <e107b4ff0807131627y2148845fy88ea0a1c05d824ce@mail.gmail.com>
Message-ID: <487AA661.8060109@gmail.com>

James wrote:
> Hi All,
>
> I'm writing a function that has optional paramters (i.e., "foo(
> parameter , optionalParameter = None , optionalParameter2 = None )").
>
> Is there some way inside of foo() that I can check to see how many
> parameters have been passed in? I want to check to ensure that only
> *one* optional parameter is passed in (and if more than one is passed
> in, do some sort of error handling).
>
> Thanks!
> - j
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   
As an alternative to Kent's suggestion consider:

def foo(parameter, *args)

args will be a tuple with 0, 1 or more items in it.

So you can test for len(args) == 1


-- 
Bob Gailer
919-636-4239 Chapel Hill, NC


From kent37 at tds.net  Mon Jul 14 04:25:21 2008
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 13 Jul 2008 22:25:21 -0400
Subject: [Tutor] Check Number of Parameters Passed In
In-Reply-To: <487AA661.8060109@gmail.com>
References: <e107b4ff0807131627y2148845fy88ea0a1c05d824ce@mail.gmail.com>
	<487AA661.8060109@gmail.com>
Message-ID: <1c2a2c590807131925ha4eb427hbbcef411248fd9e2@mail.gmail.com>

On Sun, Jul 13, 2008 at 9:05 PM, bob gailer <bgailer at gmail.com> wrote:
> As an alternative to Kent's suggestion consider:
>
> def foo(parameter, *args)
>
> args will be a tuple with 0, 1 or more items in it.
>
> So you can test for len(args) == 1

Presumably the OP wants to distinguish between op1 and op2, so my guess is that
def foo(parameter, **kwargs)
would be more appropriate. (kwargs will be a dict containing any
keyword parameters.)

Kent

From nibudh at gmail.com  Mon Jul 14 09:29:16 2008
From: nibudh at gmail.com (nibudh)
Date: Mon, 14 Jul 2008 17:29:16 +1000
Subject: [Tutor] parsing sendmail logs
Message-ID: <77f8f7c30807140029w4c2d003cg8c49b8c08e140dd8@mail.gmail.com>

Hi List,

I'm looking for some support libraries that will help me to parse sendmail
logs.

I'm confused about whether i need a "parser" per se, and if i do which
parser to use. I found this website
http://nedbatchelder.com/text/python-parsers.html which compares a slew of
python parsers.

Initially I'm wanting to be able to report on who the recipients of a
particular email where based on an email address or host.
Another report I'm interested in creating is who sent email to a particular
email address.

These simple reports i have written already using unix tools like grep,
sort, awk :

---
1. grep  'email_address' ../maillog* |awk '{print $6}' |sort -u |awk -F:
'{print $1}' >phis.txt
2. for i in `cat ./phis.txt` ; do grep $i ../maillog* >>./maillog; done
3. grep "to=<" maillog |awk '{print $7}' |sort -u >recipients

'email _address' is user supplied and it would be nice to default to just
maillog but to let the user specify maillog.* or maillog.[1..6]

I whipped these up in a few minutes.
'phis.txt' contains a unique list of message ID's
'maillog' is a filtered raw log of matching lines based on the message ID's.
'recipients' gives me a list of email addresses, sometimes with multiple
email addresses on one line comma separated.
---

I really want to just tidy this up into a python script as a programming
exercise.

so that's the background.

How do i go about representing the structure of the sendmail log file to my
script. I'm imagining having to filter through the logs and building up some
kind of data structure which i can use to report from. should this just be
as simple as a dash of regex and str.split() ? or are there better tools
that provide a richer framework to work within?

I would love to extend or write further scripts to analyze the logs and pick
up things like someone suddenly emailing to 500 people. but crawling before
running seems like the order of the day.

Cheers,

nibudh.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080714/3a4b2679/attachment.htm>

From alan.gauld at btinternet.com  Mon Jul 14 09:51:28 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 14 Jul 2008 08:51:28 +0100
Subject: [Tutor] Another assert() question
References: <20080712200130.13A131E4008@bag.python.org><1c2a2c590807121334t40ac6656la0dad0d2b3832ec7@mail.gmail.com><20080712220325.0BC6F1E4007@bag.python.org><1c2a2c590807121939l14a5090awbf0a7f9f394fefd8@mail.gmail.com><20080713031114.E53F91E4016@bag.python.org><40af687b0807122046i1fc3b1cbtc62130988794c91e@mail.gmail.com><20080713200633.F1F121E4002@bag.python.org><487A885D.6070801@gmail.com>
	<20080714000835.1A1DF1E4002@bag.python.org>
Message-ID: <g5f0i1$4f5$1@ger.gmane.org>

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

>>5.10 Boolean operations
>>....
>>"In the context of Boolean operations, and also when expressions are 
>>used by control flow statements, the following values are 
>>interpreted as false: |False|, |None|, numeric zero of all types, 
>>and empty strings and containers (including strings, tuples, lists, 
>>dictionaries, sets and frozensets). All other values are interpreted 
>>as true."

> I'll presumptuously, brazenly go further: I have 2 quarrels with 
> 5.10:
> 1. "interpret" is misleading. Revise, substituting "consider".
> 2. "value" is misleading. Revise, substituting "truth value".

I wouldn't argue with your complaint on 'value' but it seems to me 
that
interpret is exactly the ruight word fopr two reasons:
1) The action is performed by the Python interpreter so technically
    it is being interpreted, and

2) interpretation is a more or less mechanical process. 'Consider'
    implies some measure of intelligence. Computers are machines
    and devoid of intelligence therefore the more mechanistic
    'interpret' is the appropriate term.

Basically it is just an arbitrary rule that the interpretation engine
follows. Different compilers/interpreters use different rules. This
happens to be Pythons interpretation.

Alan G 



From rdm at rcblue.com  Mon Jul 14 11:19:50 2008
From: rdm at rcblue.com (Dick Moores)
Date: Mon, 14 Jul 2008 02:19:50 -0700
Subject: [Tutor] Another assert() question
In-Reply-To: <g5f0i1$4f5$1@ger.gmane.org>
References: <20080712200130.13A131E4008@bag.python.org>
	<1c2a2c590807121334t40ac6656la0dad0d2b3832ec7@mail.gmail.com>
	<20080712220325.0BC6F1E4007@bag.python.org>
	<1c2a2c590807121939l14a5090awbf0a7f9f394fefd8@mail.gmail.com>
	<20080713031114.E53F91E4016@bag.python.org>
	<40af687b0807122046i1fc3b1cbtc62130988794c91e@mail.gmail.com>
	<20080713200633.F1F121E4002@bag.python.org>
	<487A885D.6070801@gmail.com>
	<20080714000835.1A1DF1E4002@bag.python.org>
	<g5f0i1$4f5$1@ger.gmane.org>
Message-ID: <20080714092001.CF9711E4002@bag.python.org>

At 12:51 AM 7/14/2008, Alan Gauld wrote:
>"Dick Moores" <rdm at rcblue.com> wrote
>
>>>5.10 Boolean operations
>>>....
>>>"In the context of Boolean operations, and also when expressions 
>>>are used by control flow statements, the following values are 
>>>interpreted as false: |False|, |None|, numeric zero of all types, 
>>>and empty strings and containers (including strings, tuples, 
>>>lists, dictionaries, sets and frozensets). All other values are 
>>>interpreted as true."
>
>>I'll presumptuously, brazenly go further: I have 2 quarrels with 5.10:
>>1. "interpret" is misleading. Revise, substituting "consider".
>>2. "value" is misleading. Revise, substituting "truth value".
>
>I wouldn't argue with your complaint on 'value' but it seems to me that
>interpret is exactly the ruight word fopr two reasons:
>1) The action is performed by the Python interpreter so technically
>    it is being interpreted, and
>
>2) interpretation is a more or less mechanical process. 'Consider'
>    implies some measure of intelligence. Computers are machines
>    and devoid of intelligence therefore the more mechanistic
>    'interpret' is the appropriate term.
>
>Basically it is just an arbitrary rule that the interpretation engine
>follows. Different compilers/interpreters use different rules. This
>happens to be Pythons interpretation.
>
>Alan G

Thanks, Alan G. You've calmed me down.

Dick



From kent37 at tds.net  Mon Jul 14 12:47:15 2008
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 14 Jul 2008 06:47:15 -0400
Subject: [Tutor] parsing sendmail logs
In-Reply-To: <77f8f7c30807140029w4c2d003cg8c49b8c08e140dd8@mail.gmail.com>
References: <77f8f7c30807140029w4c2d003cg8c49b8c08e140dd8@mail.gmail.com>
Message-ID: <1c2a2c590807140347m31569475iae4b1dfcb35241ec@mail.gmail.com>

On Mon, Jul 14, 2008 at 3:29 AM, nibudh <nibudh at gmail.com> wrote:
> Hi List,
>
> I'm looking for some support libraries that will help me to parse sendmail
> logs.

Lire looks like it might be useful:
http://www.logreport.org/lire.html

> Initially I'm wanting to be able to report on who the recipients of a
> particular email where based on an email address or host.
> Another report I'm interested in creating is who sent email to a particular
> email address.
>
> These simple reports i have written already using unix tools like grep,
> sort, awk :
>
> ---
> 1. grep  'email_address' ../maillog* |awk '{print $6}' |sort -u |awk -F:
> '{print $1}' >phis.txt
> 2. for i in `cat ./phis.txt` ; do grep $i ../maillog* >>./maillog; done
> 3. grep "to=<" maillog |awk '{print $7}' |sort -u >recipients
>
> 'email _address' is user supplied and it would be nice to default to just
> maillog but to let the user specify maillog.* or maillog.[1..6]
>
> How do i go about representing the structure of the sendmail log file to my
> script. I'm imagining having to filter through the logs and building up some
> kind of data structure which i can use to report from. should this just be
> as simple as a dash of regex and str.split() ? or are there better tools
> that provide a richer framework to work within?

These should all be pretty straightforward to program in Python using
standard facilities for file reading and writing, lists and
dictionaries, and string operations. You probably don't need regular
expressions unless you want to build a regex that will find all mail
ids of interest.

To begin with I don't think you need to be parsing the log lines into
a structure. If you decide that is useful, you might want to look at
the loghetti project as a starting point. It parses web server logs
but it might be a useful model.
http://code.google.com/p/loghetti/

Kent

From cbc at unc.edu  Mon Jul 14 15:03:12 2008
From: cbc at unc.edu (Chris Calloway)
Date: Mon, 14 Jul 2008 09:03:12 -0400
Subject: [Tutor] BootCampArama Final Reminder
Message-ID: <133D5724-86B9-482C-9BE4-B175CCDC6E99@unc.edu>

Final reminder, we're in the last two weeks of open registration for  
PyCamp, Plone Boot Camp, and Advanced Plone Boot Camp:

http://trizpug.org/boot-camp/2008/

Registration is now open for:

PyCamp: Python Boot Camp, August 4 - 8

Plone Boot Camp: Customizing Plone, July 28 - August 1

Advanced Plone Boot Camp: Plone 3 Techniques, August 4 - 7

All of these take place on the campus of the University of North  
Carolina at Chapel Hill in state of the art high tech classrooms, with  
free mass transit, low-cost accommodations with free wireless, and  
convenient dining options.

Plone Boot Camp is taught by Joel Burton, twice chair of the Plone  
Foundation. Joel has logged more the 200 days at the head of Plone  
classrooms on four continents. See plonebootcamps.com for dozens of  
testimonials from Joel's students.

PyCamp is taught by Chris Calloway, facilitator for TriZPUG and  
application analyst for the Southeast Coastal Ocean Observing System.  
Chris has developed PyCamp for over 1500 hours on behalf of Python  
user groups. Early bird registration runs through June 30. So register  
today!

PyCamp is TriZPUG's Python Boot Camp, which takes a programmer  
familiar with basic programming concepts to the status of Python  
developer with one week of training. If you have previous scripting or  
programming experience and want to step into Python programming as  
quickly and painlessly as possible, this boot camp is for you. PyCamp  
is also the perfect follow-on to Plone Boot Camp: Customizing Plone  
the previous week.

At Plone Boot Camp: Customizing Plone you will learn the essentials  
you need to build your Plone site and deploy it. This course is the  
most popular in the Plone world--for a good reason: it teaches you  
practical skills in a friendly, hands-on format. This bootcamp is  
aimed at:
     * people with HTML or web design experience
     * people with some or no Python experience
     * people with some or no Zope/Plone experience
It covers using Plone, customizing, and deploying Plone sites.

At Advanced Plone Boot Camp: Plone 3 Techniques you will learn to  
build a site using the best practices of Plone 3 as well as advance  
your skills in scripting and developing for Plone. The course covers  
the new technologies in Plone 3.0 and 3.1intended for site integrators  
and developers: our new portlet infrastructure, viewlets, versioning,  
and a friendly introduction to Zope 3 component architecture. Now,  
updated for Plone 3.1! The course is intended for people who have  
experience with the basics of Plone site development and HTML/CSS. It  
will cover what you need to know to take advantage of these new  
technologies in Plone 3.

For more information contact: info at trizpug.org

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

From monjissvel at googlemail.com  Mon Jul 14 20:10:49 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Mon, 14 Jul 2008 18:10:49 +0000
Subject: [Tutor] parsing sendmail logs
In-Reply-To: <1c2a2c590807140347m31569475iae4b1dfcb35241ec@mail.gmail.com>
References: <77f8f7c30807140029w4c2d003cg8c49b8c08e140dd8@mail.gmail.com>
	<1c2a2c590807140347m31569475iae4b1dfcb35241ec@mail.gmail.com>
Message-ID: <e2f191310807141110n985be8fwace998044c06c15c@mail.gmail.com>

lire & logethy are an option.
but if you want to go on your own I believe awk, grep, sort  are extremely
extremely  extremely (yes 3 times !) powerfulI tools, so giving them up is a
bad decision I guess either talking about thier speed or what they would
allow you to do in few lines of code.  so  what I would advice is to  write
a python program that uses them thru subprocess module, this way you have
the best of both worlds, finaly you should set up some sort of database to
hold your data & to have a real-time  view of whats going on.
so what modules you need ? :

subprocess :  running awk & grep.
csv : for loading data from the resulting files.
MySQLdb : to connect to mysql db
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080714/7dbfece1/attachment.htm>

From bryan.fodness at gmail.com  Tue Jul 15 00:41:40 2008
From: bryan.fodness at gmail.com (Bryan Fodness)
Date: Mon, 14 Jul 2008 18:41:40 -0400
Subject: [Tutor] manipulating a string
Message-ID: <fbf64d2b0807141541o7f462e3x17cd6c7dd8b752b4@mail.gmail.com>

I have a string (column names) that I need to split.

D_H = 'D 5 10 15 20 25 30 35 40 D Upper D Lower'

I cannot do a simple list(D_H).split because the last two strings have a
space between them (D Upper and D Lower are two, not four labels).

Any suggestions?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080714/20a8262b/attachment.htm>

From nibudh at gmail.com  Tue Jul 15 01:57:04 2008
From: nibudh at gmail.com (nibudh)
Date: Tue, 15 Jul 2008 09:57:04 +1000
Subject: [Tutor] parsing sendmail logs
In-Reply-To: <1c2a2c590807140347m31569475iae4b1dfcb35241ec@mail.gmail.com>
References: <77f8f7c30807140029w4c2d003cg8c49b8c08e140dd8@mail.gmail.com>
	<1c2a2c590807140347m31569475iae4b1dfcb35241ec@mail.gmail.com>
Message-ID: <77f8f7c30807141657m30f350a3qf29425b3ee108035@mail.gmail.com>

On Mon, Jul 14, 2008 at 8:47 PM, Kent Johnson <kent37 at tds.net> wrote:

> Lire looks like it might be useful:
> http://www.logreport.org/lire.html
>

I have seen lire, of course it's Perl, but looking over the source would
give me some ideas. In fact from a practical point of view if it does the
job i should look into it more :-)

 -- snip

> How do i go about representing the structure of the sendmail log file to
> my
> > script. I'm imagining having to filter through the logs and building up
> some
> > kind of data structure which i can use to report from. should this just
> be
> > as simple as a dash of regex and str.split() ? or are there better tools
> > that provide a richer framework to work within?
>
> These should all be pretty straightforward to program in Python using
> standard facilities for file reading and writing, lists and
> dictionaries, and string operations. You probably don't need regular
> expressions unless you want to build a regex that will find all mail
> ids of interest.
>

I will probably want to do something like this, extract the mail ids and use
those filter the logs further.


>
> To begin with I don't think you need to be parsing the log lines into
> a structure. If you decide that is useful, you might want to look at
> the loghetti project as a starting point. It parses web server logs
> but it might be a useful model.
> http://code.google.com/p/loghetti/
>
> Kent
>

thanks for the pointer. loghetti looks interesting I've downloaded the
source and from a quick review i can imagine extending this to be sendmail
aware.

Cheers,

nibudh.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080715/a89927e8/attachment.htm>

From nibudh at gmail.com  Tue Jul 15 02:25:08 2008
From: nibudh at gmail.com (nibudh)
Date: Tue, 15 Jul 2008 10:25:08 +1000
Subject: [Tutor] parsing sendmail logs
In-Reply-To: <e2f191310807141110n985be8fwace998044c06c15c@mail.gmail.com>
References: <77f8f7c30807140029w4c2d003cg8c49b8c08e140dd8@mail.gmail.com>
	<1c2a2c590807140347m31569475iae4b1dfcb35241ec@mail.gmail.com>
	<e2f191310807141110n985be8fwace998044c06c15c@mail.gmail.com>
Message-ID: <77f8f7c30807141725m51c0ef14t31f23a8381c5633@mail.gmail.com>

On Tue, Jul 15, 2008 at 4:10 AM, Monika Jisswel <monjissvel at googlemail.com>
wrote:

> lire & logethy are an option.
> but if you want to go on your own I believe awk, grep, sort  are extremely
> extremely  extremely (yes 3 times !) powerfulI tools, so giving them up is a
> bad decision I guess either talking about thier speed or what they would
> allow you to do in few lines of code.

Hi monika,

You are right. awk, grep and sort etc. are extremely powerful. As a unix
sysadmin i use them everyday. I guess i'm looking for a couple of simple
projects to strengthen my python scripting. so whilst i usually look for the
best tool for the job in this case python is my hammer and everything looks
like a nail <grin>



> so  what I would advice is to  write a python program that uses them thru
> subprocess module, this way you have the best of both worlds, finaly you
> should set up some sort of database to hold your data & to have a real-time
> view of whats going on.
>

>
Initially i was thinking of writing some python scripts to do some of the
automation tasks that i have a need to do. I'll still do this because i want
to write more code to keep the practice up.

But what I'd really like to do is write some scripts that analyze my email
logs and catch anomalies and report them to me. Like someone emailing 500
recipients in a day or one external person emailing 500 of my users.

so thinking it through, my first thought was how do i get the data from the
mail logfiles into usable state for analysis?

It seems some people just break down the data with regex.

I made an assumption that because i wanted to parse (in a generic sense) the
sendmail logs then perhaps using a "parser" would be of some benefit. But
from researching this angle, there are a lot of choices and  "parser land"
has lots of terminology that i just simply don't understand yet.

I guess I'm trying to figure out what i don't know.

Any pragmatic advice on building or working with a framework to get to the
point where i can do analysis on my logs would be cool.

Cheers,

nibudh.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080715/ce19fd55/attachment-0001.htm>

From carroll at tjc.com  Tue Jul 15 09:21:23 2008
From: carroll at tjc.com (Terry Carroll)
Date: Tue, 15 Jul 2008 00:21:23 -0700 (PDT)
Subject: [Tutor] Anyone using tarfile?
Message-ID: <Pine.LNX.4.44.0807150004070.11613-100000@violet.rahul.net>

I'm trying to use tarfile with no luck.  Anyone on this list used it 
successfully?

Here's a sample program pared down to illustrate the error.  I'm 
arbitrarily trying to extract the 4th TARred file in the tarball (a file 
that I know from other debugging efforts is data/c410951c, and that I can 
see by inspection does exist in the tarball). 

My code (file playtar.py):

import tarfile, os
TARFILENAME = "freedb-update-20080601-20080708.tar.bz2"
assert os.path.exists(TARFILENAME)
assert tarfile.is_tarfile(TARFILENAME)

tf = tarfile.open(TARFILENAME, "r:bz2")
tf.debug=3 ; tf.errorlevel=2
tmembers = tf.getmembers()
sample = tmembers[4]
RC = tf.extract(sample)

The result:

C:\test\freedb>playtar.py
Traceback (most recent call last):
  File "C:\test\freedb\playtar.py", line 10, in <module>
    RC = tf.extract(sample)
  File "C:\Python25\lib\tarfile.py", line 1495, in extract
    self._extract_member(tarinfo, os.path.join(path, tarinfo.name))
  File "C:\Python25\lib\tarfile.py", line 1562, in _extract_member
    if upperdirs and not os.path.exists(upperdirs):
  File "C:\Python25\lib\ntpath.py", line 255, in exists
    st = os.stat(path)
TypeError: stat() argument 1 must be (encoded string without NULL bytes), 
not str

The file comes from here: http://ftp.freedb.org/pub/freedb/

The bzip2 compression is unrelated to this.  If I manually bunzip the .bz2 
file to a plain old tar file (and open it with mode "r" instead of 
"r:bz2"), I get an identical error.

During some earlier poking around, I see some interesting things: instead 
of sample.name being "data/c410951c" (13 characters) or "/data/c410951c" 
(14 characters) as I would expect, it's a 169-character string: "                                                       
11034624707 11032232071 /data/c410951c".  I think those are zeroes, not 
blanks. 

Curiously, there is also another attribute named "prefix" that is not
documented in the tarfile.py documentation.  "prefix" is a 155-character
string that is equal to the first 155 characters of this oddly-too-long
name.  In fact, if you cut off this "prefix" from the name, you're left
with "/data/c410951c", whic his kind of what I was expecting name to be in
the first place.

The deeper I look into this, the more mystified I become.  Any ideas?


From alan.gauld at btinternet.com  Tue Jul 15 09:47:13 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 15 Jul 2008 08:47:13 +0100
Subject: [Tutor] parsing sendmail logs
References: <77f8f7c30807140029w4c2d003cg8c49b8c08e140dd8@mail.gmail.com><1c2a2c590807140347m31569475iae4b1dfcb35241ec@mail.gmail.com>
	<e2f191310807141110n985be8fwace998044c06c15c@mail.gmail.com>
Message-ID: <g5hkm3$lhn$1@ger.gmane.org>

"Monika Jisswel" <monjissvel at googlemail.com> wrote

> but if you want to go on your own I believe awk, grep, sort  are 
> extremely
> extremely  extremely (yes 3 times !) powerfulI tools, so giving them 
> up is a
> ...
> a python program that uses them thru subprocess module,

I am a big fan of awk but I'd never write a Python script
to call an awk script vias subprocess unless the awk script already
existed and was very big. There is nothing that awk can do that
Python cannot and the amount of code is about the same in each case.
And the overhead of starting a new awk process from subprocess
is quite high and then you have the additional overhead of getting
the input/output data transferred. It is all a very cumbersome process
that is not justified IMHO unless the awk code already exists
and is too big to rewrite. (The same applies to sort/grep if the 
Python
script has to use the data otherwise sort is a valid option).

Does that mean you can't combine awk/python - no. If you are
not using the awk data in the python script then run awk separately
to Python but in that case use bash or ksh to coordinate not Python.
But I struggle to think of a good case for using awk via subprocess
(or os.system/popen etc).

Alan G. 



From alan.gauld at btinternet.com  Tue Jul 15 09:53:01 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 15 Jul 2008 08:53:01 +0100
Subject: [Tutor] manipulating a string
References: <fbf64d2b0807141541o7f462e3x17cd6c7dd8b752b4@mail.gmail.com>
Message-ID: <g5hl0v$mg6$1@ger.gmane.org>


"Bryan Fodness" <bryan.fodness at gmail.com> wrote

>I have a string (column names) that I need to split.
>
> D_H = 'D 5 10 15 20 25 30 35 40 D Upper D Lower'

I assume you are reading this from a file or network and therefore
don't actually know in advance what the list contains?
(Otherwise just do it manually!)

> I cannot do a simple list(D_H).split because the last two strings 
> have a
> space between them (D Upper and D Lower are two, not four labels).

If the format is constant and it is always the last 2 fields that
have that format then just split into a list then combine the last
two elements. If you don;t know which elements will contain
spaces then you are sunk I think because there is no obvious
data pattern to determine which items should be joined. Or is there,
but you haven't told us - like the second word always being a
string rather than a letter/number?

We may need more information.

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



From metolone+gmane at gmail.com  Tue Jul 15 10:06:41 2008
From: metolone+gmane at gmail.com (Mark Tolonen)
Date: Tue, 15 Jul 2008 01:06:41 -0700
Subject: [Tutor] manipulating a string
References: <fbf64d2b0807141541o7f462e3x17cd6c7dd8b752b4@mail.gmail.com>
Message-ID: <g5hlqe$oud$1@ger.gmane.org>


"Bryan Fodness" <bryan.fodness at gmail.com> wrote in message 
news:fbf64d2b0807141541o7f462e3x17cd6c7dd8b752b4 at mail.gmail.com...
> I have a string (column names) that I need to split.
>
> D_H = 'D 5 10 15 20 25 30 35 40 D Upper D Lower'
>
> I cannot do a simple list(D_H).split because the last two strings have a 
> space between them (D Upper and D Lower are two, not four labels).
>
> Any suggestions?

How was the string built?  Is it possible to delimit the columns with 
something besides a space, since a space is a valid character in a column 
name.  Baring that, adding a little knowledge of the string is needed:

>>> import re
>>> D_H = 'D 5 10 15 20 25 30 35 40 D Upper D Lower'
>>> print re.split(r'\s(?![UL])',D_H) # split on spaces not followed by U or 
>>> L.
['D', '5', '10', '15', '20', '25', '30', '35', '40', 'D Upper', 'D Lower']

--
Mark



From kent37 at tds.net  Tue Jul 15 13:01:03 2008
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 15 Jul 2008 07:01:03 -0400
Subject: [Tutor] Anyone using tarfile?
In-Reply-To: <Pine.LNX.4.44.0807150004070.11613-100000@violet.rahul.net>
References: <Pine.LNX.4.44.0807150004070.11613-100000@violet.rahul.net>
Message-ID: <1c2a2c590807150401l50555febmf5588cc5092d904e@mail.gmail.com>

On Tue, Jul 15, 2008 at 3:21 AM, Terry Carroll <carroll at tjc.com> wrote:

> C:\test\freedb>playtar.py
> Traceback (most recent call last):
>  File "C:\test\freedb\playtar.py", line 10, in <module>
>    RC = tf.extract(sample)
>  File "C:\Python25\lib\tarfile.py", line 1495, in extract
>    self._extract_member(tarinfo, os.path.join(path, tarinfo.name))
>  File "C:\Python25\lib\tarfile.py", line 1562, in _extract_member
>    if upperdirs and not os.path.exists(upperdirs):
>  File "C:\Python25\lib\ntpath.py", line 255, in exists
>    st = os.stat(path)
> TypeError: stat() argument 1 must be (encoded string without NULL bytes),
> not str

The problem seems to be in the file path. Have you successfully
untarred the file using a different tool? Have you tried downloading
the file again?

What version of Python are you using? I have 2.5.2 and the line
numbers in my tarfile.py are quite different than yours. The changelog
for Python 2.5.2 shows many fixes to tarfile so an upgrade may be in
order.
http://www.python.org/download/releases/2.5.2/NEWS.txt

> During some earlier poking around, I see some interesting things: instead
> of sample.name being "data/c410951c" (13 characters) or "/data/c410951c"
> (14 characters) as I would expect, it's a 169-character string: "
> 11034624707 11032232071 /data/c410951c".  I think those are zeroes, not
> blanks.
>
> Curiously, there is also another attribute named "prefix" that is not
> documented in the tarfile.py documentation.  "prefix" is a 155-character
> string that is equal to the first 155 characters of this oddly-too-long
> name.  In fact, if you cut off this "prefix" from the name, you're left
> with "/data/c410951c", whic his kind of what I was expecting name to be in
> the first place.

My version of the source picks up a prefix string and adds it to the
start of the path unless the file is a "GNU sparse" file.

Kent

From monjissvel at googlemail.com  Tue Jul 15 13:15:58 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Tue, 15 Jul 2008 11:15:58 +0000
Subject: [Tutor] parsing sendmail logs
In-Reply-To: <77f8f7c30807141725m51c0ef14t31f23a8381c5633@mail.gmail.com>
References: <77f8f7c30807140029w4c2d003cg8c49b8c08e140dd8@mail.gmail.com>
	<1c2a2c590807140347m31569475iae4b1dfcb35241ec@mail.gmail.com>
	<e2f191310807141110n985be8fwace998044c06c15c@mail.gmail.com>
	<77f8f7c30807141725m51c0ef14t31f23a8381c5633@mail.gmail.com>
Message-ID: <e2f191310807150415m516fefddxcd1922dc6b1de3ee@mail.gmail.com>

>
> but in that case use bash or ksh


Hi Alan,

to say the truth I never  thought about "additional overhead of getting the
input/output data transferred" because the suprocess itself will contain the
(bash)pipe to redirect output to the next utility used not the python
subprocess.PIPE pipe so it will be like one subprocess with each utility
piping stdout to the next as if run from the shell, what python comes in for
? well, its always sweet to work with python as it will allow you to make
whatever logic you have in yoru head into real life with ease and at the end
of the subprocess you can always parse the stdout using python this time &
load results to some database.

I have to say that I have seen awk, grep & sort, wc, work on files of
handreds of Mbytes in a matter of 1 or 2 seconds ... why would I replace
such a fast tools ?

Alan do you think python can beat awk in speed when it comes to replacing
text ?  I always wanted to know it !

Any pragmatic advice on building or working with a framework to get to the
> point where i can do analysis on my logs would be cool.


ok ! so your program parses sendmail log,  returns some data, your python
program will then parse this data & depending on results will either send an
email saying 'everything OK' or  will take measures like run a
subprocess.Popen('/etc/init.d/sendmail stop', shell = 1)  or add some email
address or hostname or ip to spamassassin  lack list & reload it ...

but some problems will rise when we talk about the frequency you will run
your  scans ? every  1 minute ?  every 5 minutes ?  500 mails would  be
recieved by then so it would be of no use.

this said this program cannot be used for real time problem detection
effectively ... but it will be very effective for end-of-day statistics ...
that's why programs such as spamassassin were creatd i guess ...
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080715/b6fd2627/attachment.htm>

From mwalsh at groktech.org  Tue Jul 15 15:26:16 2008
From: mwalsh at groktech.org (Martin Walsh)
Date: Tue, 15 Jul 2008 08:26:16 -0500
Subject: [Tutor] parsing sendmail logs
In-Reply-To: <e2f191310807150415m516fefddxcd1922dc6b1de3ee@mail.gmail.com>
References: <77f8f7c30807140029w4c2d003cg8c49b8c08e140dd8@mail.gmail.com>	<1c2a2c590807140347m31569475iae4b1dfcb35241ec@mail.gmail.com>	<e2f191310807141110n985be8fwace998044c06c15c@mail.gmail.com>	<77f8f7c30807141725m51c0ef14t31f23a8381c5633@mail.gmail.com>
	<e2f191310807150415m516fefddxcd1922dc6b1de3ee@mail.gmail.com>
Message-ID: <487CA578.7060300@groktech.org>

Monika Jisswel wrote:
> to say the truth I never  thought about "additional overhead of getting
> the input/output data transferred" because the suprocess itself will
> contain the (bash)pipe to redirect output to the next utility used not
> the python subprocess.PIPE pipe so it will be like one subprocess with
> each utility piping stdout to the next as if run from the shell, what

I agree with Alan. Personally, I find trying to replace shell scripts
with python code, just plain awk-ward ... ahem, please forgive the pun.
:) No doubt the subprocess module is quite handy. But in this case it
would be hard to beat a shell script, for simplicity, with a chain of
subprocess.Popen calls. I realize this is subjective, of course.

> python comes in for ? well, its always sweet to work with python as it
> will allow you to make whatever logic you have in yoru head into real
> life with ease and at the end of the subprocess you can always parse the
> stdout using python this time & load results to some database.

If you follow the unix philosophy(tm) it might make more sense to pipe
the result (of a shell pipeline) to a python script that does only the
database load.

> 
> I have to say that I have seen awk, grep & sort, wc, work on files of
> handreds of Mbytes in a matter of 1 or 2 seconds ... why would I replace
> such a fast tools ?

I can think of a few reasons, not the least of which is the OP's -- as
"a programming exercise".

> 
> Alan do you think python can beat awk in speed when it comes to
> replacing text ?  I always wanted to know it !
> 

Well, maybe. But IMHO, the the question should really be is python 'fast
enough'. Especially when you consider how the OP is using awk in the
first place. But the only way to know, is to try it out.

>     Any pragmatic advice on building or working with a framework to get
>     to the point where i can do analysis on my logs would be cool.
> 

As an exercise, I think it would be a reasonable approach to write
python derivatives of the shell commands being used, perhaps tailored to
the data set, to get a feel for working with text data in python. Then
ask questions here if you get stuck, or need optimization advice. I
think you'll find you can accomplish this with just a few lines of
python code for each (sort -u, grep, awk '{print $n}', etc), given your
use of the commands in the examples provided. Write each as a function,
and you'll end up with code you can reuse for other log analysis
projects. Bonus!

HTH,
Marty


From bryan.fodness at gmail.com  Tue Jul 15 16:55:44 2008
From: bryan.fodness at gmail.com (Bryan Fodness)
Date: Tue, 15 Jul 2008 10:55:44 -0400
Subject: [Tutor] accessing string in list
Message-ID: <fbf64d2b0807150755n74fb1045l365a66658144b7a1@mail.gmail.com>

I have a list of labels for a data file,

test = ['depth', '4', '6', '10', '15', '20', '30', '40', 'angle']

I would like to get the string of the first value that is greater than a
known value and the previous string.

If I have 15.8, I would like to get the index of '20' and '15'.  I would
also like to make sure that my known value falls in the range 4-40.

I am having trouble with the mixed types.

for i in range(len(test)):
    if Field < int(test[i]):
        print i
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080715/7571575b/attachment.htm>

From malaclypse2 at gmail.com  Tue Jul 15 17:05:28 2008
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Tue, 15 Jul 2008 11:05:28 -0400
Subject: [Tutor] accessing string in list
In-Reply-To: <fbf64d2b0807150755n74fb1045l365a66658144b7a1@mail.gmail.com>
References: <fbf64d2b0807150755n74fb1045l365a66658144b7a1@mail.gmail.com>
Message-ID: <16651e80807150805u183d9e45q1769bfcf6eaf22de@mail.gmail.com>

On Tue, Jul 15, 2008 at 10:55 AM, Bryan Fodness <bryan.fodness at gmail.com> wrote:
> I have a list of labels for a data file,
>
> test = ['depth', '4', '6', '10', '15', '20', '30', '40', 'angle']
>
> I would like to get the string of the first value that is greater than a
> known value and the previous string.
>
> If I have 15.8, I would like to get the index of '20' and '15'.  I would
> also like to make sure that my known value falls in the range 4-40.
>
> I am having trouble with the mixed types.
>
> for i in range(len(test)):
>     if Field < int(test[i]):
>         print i

You can put your conversion into a try/except block and handle the exception:

test = ['depth', '4', '6', '10', '15', '20', '30', '40', 'angle']
my_val = 15.8
for index, value in enumerate(test):
    try:
        if int(value) < my_val:
            print value
    except ValueError:
        pass


-- 
Jerry

From mayankiitd at gmail.com  Tue Jul 15 17:51:58 2008
From: mayankiitd at gmail.com (Mayank Agarwal)
Date: Tue, 15 Jul 2008 21:21:58 +0530
Subject: [Tutor] getting error in uploading a file
Message-ID: <58ebdc1a0807150851r45bda7a8hfa38f85be1b08faa@mail.gmail.com>

Hi,
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080715/8b86c3dd/attachment.htm>

From mayankiitd at gmail.com  Tue Jul 15 17:53:43 2008
From: mayankiitd at gmail.com (Mayank Agarwal)
Date: Tue, 15 Jul 2008 21:23:43 +0530
Subject: [Tutor] getting error in uploading a file
In-Reply-To: <58ebdc1a0807150851r45bda7a8hfa38f85be1b08faa@mail.gmail.com>
References: <58ebdc1a0807150851r45bda7a8hfa38f85be1b08faa@mail.gmail.com>
Message-ID: <58ebdc1a0807150853l7775603kbe3a3e575ec88a6a@mail.gmail.com>

Hi,
i am getting error in uploading a file from python script.

the error is follwing:

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>500 Internal Server Error</title>
</head><body>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error or
misconfiguration and was unable to complete
your request.</p>
<p>Please contact the server administrator,
 root at localhost and inform them of the time the error occurred,
and anything you might have done that may have
caused the error.</p>
<p>More information about this error may be available
in the server error log.</p>
<hr>
<address>Apache/2.0.52 (Red Hat) Server at 10.72.147.89 Port 80</address>
</body></html>

can you tell me what is meaning of this error
Thanks
Mayank
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080715/ca0c7397/attachment-0001.htm>

From srilyk at gmail.com  Tue Jul 15 18:22:01 2008
From: srilyk at gmail.com (W W)
Date: Tue, 15 Jul 2008 11:22:01 -0500
Subject: [Tutor] getting error in uploading a file
In-Reply-To: <58ebdc1a0807150853l7775603kbe3a3e575ec88a6a@mail.gmail.com>
References: <58ebdc1a0807150851r45bda7a8hfa38f85be1b08faa@mail.gmail.com>
	<58ebdc1a0807150853l7775603kbe3a3e575ec88a6a@mail.gmail.com>
Message-ID: <333efb450807150922n5e2abc1egad6010dd76345151@mail.gmail.com>

On Tue, Jul 15, 2008 at 10:53 AM, Mayank Agarwal <mayankiitd at gmail.com>
wrote:

> Hi,
> i am getting error in uploading a file from python script.
>
> the error is follwing:
>
> <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
> <html><head>
> <title>500 Internal Server Error</title>
> </head><body>
> <h1>Internal Server Error</h1>
> <p>The server encountered an internal error or
> misconfiguration and was unable to complete
> your request.</p>
> <p>Please contact the server administrator,
>  root at localhost and inform them of the time the error occurred,
> and anything you might have done that may have
> caused the error.</p>
> <p>More information about this error may be available
> in the server error log.</p>
> <hr>
> <address>Apache/2.0.52 (Red Hat) Server at 10.72.147.89 Port 80</address>
> </body></html>
>
> can you tell me what is meaning of this error
> Thanks
> Mayank
>

Technically that's an apache error - one with the server that you're
uploading the information *to*.

If the error has nothing to do with your data, it could be any number of
problems that you have no control over. If it's your data, then it may be
malformed, or otherwise corrupted.

HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080715/87fc587c/attachment.htm>

From bgailer at gmail.com  Tue Jul 15 18:33:18 2008
From: bgailer at gmail.com (bob gailer)
Date: Tue, 15 Jul 2008 12:33:18 -0400
Subject: [Tutor] getting error in uploading a file
In-Reply-To: <58ebdc1a0807150853l7775603kbe3a3e575ec88a6a@mail.gmail.com>
References: <58ebdc1a0807150851r45bda7a8hfa38f85be1b08faa@mail.gmail.com>
	<58ebdc1a0807150853l7775603kbe3a3e575ec88a6a@mail.gmail.com>
Message-ID: <487CD14E.1070503@gmail.com>

Mayank Agarwal wrote:
>
>
>
> Hi,
> i am getting error in uploading a file from python script.
>
> the error is follwing:
>
> <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
> <html><head>
> <title>500 Internal Server Error</title>
> </head><body>
> <h1>Internal Server Error</h1>
> <p>The server encountered an internal error or
> misconfiguration and was unable to complete
> your request.</p>
> <p>Please contact the server administrator,
>  root at localhost and inform them of the time the error occurred,
> and anything you might have done that may have
> caused the error.</p>
> <p>More information about this error may be available
> in the server error log.</p>
> <hr>
> <address>Apache/2.0.52 (Red Hat) Server at 10.72.147.89 
> <http://10.72.147.89> Port 80</address>
> </body></html>
>
> can you tell me what is meaning of this error

Note it says "More information about this error may be available in the 
server error log". Take a look at the log.

-- 
Bob Gailer
919-636-4239 Chapel Hill, NC


From dsarmientos at gmail.com  Tue Jul 15 19:01:55 2008
From: dsarmientos at gmail.com (Daniel Sarmiento)
Date: Tue, 15 Jul 2008 12:01:55 -0500
Subject: [Tutor] getting error in uploading a file
Message-ID: <d356a5240807151001j38088873h69e541c434c8a057@mail.gmail.com>

That's a web server error, not a python error.

You can find more information by checking the server's log.

>From the error message it look like you are using apache and red hat. I use
debian and my error logs are stored is in /var/log/apache2 by default.

Check you apache configuration file and find the location of your logs, or
try to find a file named error.log and take a look.


> Hi,
> i am getting error in uploading a file from python script.
>
> the error is follwing:
>
> <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
> <html><head>
> <title>500 Internal Server Error</title>
> </head><body>
> <h1>Internal Server Error</h1>
> <p>The server encountered an internal error or
> misconfiguration and was unable to complete
> your request.</p>
> <p>Please contact the server administrator,
>  root at localhost and inform them of the time the error occurred,
> and anything you might have done that may have
> caused the error.</p>
> <p>More information about this error may be available
> in the server error log.</p>
> <hr>
> <address>Apache/2.0.52 (Red Hat) Server at 10.72.147.89 Port 80</address>
> </body></html>
>
> can you tell me what is meaning of this error
> Thanks
> Mayank
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL: <
> http://mail.python.org/pipermail/tutor/attachments/20080715/ca0c7397/attachment.htm
> >
>
> ------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
> End of Tutor Digest, Vol 53, Issue 53
> *************************************
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080715/884f6802/attachment.htm>

From carroll at tjc.com  Tue Jul 15 19:31:56 2008
From: carroll at tjc.com (Terry Carroll)
Date: Tue, 15 Jul 2008 10:31:56 -0700 (PDT)
Subject: [Tutor] Anyone using tarfile?
In-Reply-To: <1c2a2c590807150401l50555febmf5588cc5092d904e@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0807151016140.21952-100000@violet.rahul.net>

On Tue, 15 Jul 2008, Kent Johnson wrote:

> What version of Python are you using? I have 2.5.2 and the line
> numbers in my tarfile.py are quite different than yours. The changelog
> for Python 2.5.2 shows many fixes to tarfile so an upgrade may be in
> order.

And that was it!  I pulled the most current version from 
http://svn.python.org/view/python/trunk/Lib/tarfile.py , saved it as 
"tarfilex.py" and used "import tarfilex as tarfile", and it's now working.

You know how sometimes when you're a newbie, every time you get an
unexpected result, you jump to "there must be a bug in the program I'm 
using"?  Well, I've been programming long enough that I tend to assume the 
opposite: "I must be doing something wrong."

> My version of the source picks up a prefix string and adds it to the
> start of the path unless the file is a "GNU sparse" file.

I saw that too, but it still struck me as odd.  For one thing, I don't
understand where sparseness of the tar file (which has to do with whether
tar bothers storing all of "sparse" files -- files that have data space
allocated but not initialized) would have anything to do with a file name.  
That's one of the things that led to my "the deeper I look into this, the
more mystified I become" comment.

For another thing, "prefix" still isn't documented; I'd have expected the
variable name to be along the lines of _prefix, or not retained in the
class instance if it wasn't intended for consumption.  But that might just
be my naivete.

Anyway, problem solved.  Thanks, Kent.



From motoom at xs4all.nl  Tue Jul 15 20:08:05 2008
From: motoom at xs4all.nl (Michiel Overtoom)
Date: Tue, 15 Jul 2008 20:08:05 +0200
Subject: [Tutor] accessing string in list
Message-ID: <2.2.32.20080715180805.0131b9e8@pop.xs4all.nl>

Bryan wrote...

>I have a list of labels for a data file,
>test = ['depth', '4', '6', '10', '15', '20', '30', '40', 'angle']
>If I have 15.8, I would like to get the index of '20' and '15'.  I would
>also like to make sure that my known value falls in the range 4-40.

Python has a standard module 'bisect' for that. To get past the string
trouble, you could convert the array on the fly to floats (without the first
and last label, that is). Why not build your labels as a list with numbers
first, then later add the strings at the beginning and the end?  And did you
know that lists can contain both strings and numbers at the same time?

Example:


import bisect

# simple
numbers=[4, 6, 10, 15, 20, 30, 40]
candidate=15.8
print 'insert %g before the %dth element in %s' %
(candidate,bisect.bisect_left(numbers,candidate),numbers)

# complication with strings instead of numbers:
labels=['depth', '4', '6', '10', '15', '20', '30', '40', 'angle']
candidate='15.8'
can=float(candidate)
if can<4 or can>40: raise ValueError('The candidate must be in the range 4-40')
position=bisect.bisect_left([float(x) for x in labels[1:-1]],can)+1
print 'insert %s before the %dth element in %s' % (candidate,position,labels)


prints:

insert 15.8 before the 4th element in [4, 6, 10, 15, 20, 30, 40]
insert 15.8 before the 5th element in ['depth', '4', '6', '10', '15', '20',
'30', '40', 'angle']


Greetings,

-- 
"The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing." - Vinod Vallopillil
http://www.catb.org/~esr/halloween/halloween4.html


From kent37 at tds.net  Tue Jul 15 20:07:59 2008
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 15 Jul 2008 14:07:59 -0400
Subject: [Tutor] Anyone using tarfile?
In-Reply-To: <Pine.LNX.4.44.0807151016140.21952-100000@violet.rahul.net>
References: <1c2a2c590807150401l50555febmf5588cc5092d904e@mail.gmail.com>
	<Pine.LNX.4.44.0807151016140.21952-100000@violet.rahul.net>
Message-ID: <1c2a2c590807151107g2a27214fy3ed9f1b1c6b86f50@mail.gmail.com>

On Tue, Jul 15, 2008 at 1:31 PM, Terry Carroll <carroll at tjc.com> wrote:

> For another thing, "prefix" still isn't documented; I'd have expected the
> variable name to be along the lines of _prefix, or not retained in the
> class instance if it wasn't intended for consumption.  But that might just
> be my naivete.

I guess someone agreed with you. In the current version, 'prefix' is
not an instance attribute, it is just a local variable in a couple of
functions / methods. So there is no need to document it or use a
different name.

Kent

From motoom at xs4all.nl  Tue Jul 15 20:12:53 2008
From: motoom at xs4all.nl (Michiel Overtoom)
Date: Tue, 15 Jul 2008 20:12:53 +0200
Subject: [Tutor] Anyone using tarfile?
Message-ID: <2.2.32.20080715181253.0134b518@pop.xs4all.nl>

Terry wrote...

> Well, I've been programming long enough that I tend to assume the 
> opposite: "I must be doing something wrong."

Yes indeed ;-)  Don't forget that thousands (if not millions) of individuals
all across the internet are using Python and harnessing their collective IQ
to squash every bug that occurs. It's simply amazing hard to find a new bug.


-- 
"The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing." - Vinod Vallopillil
http://www.catb.org/~esr/halloween/halloween4.html


From jeff at drinktomi.com  Tue Jul 15 20:21:56 2008
From: jeff at drinktomi.com (Jeff Younker)
Date: Tue, 15 Jul 2008 11:21:56 -0700
Subject: [Tutor] parsing sendmail logs
In-Reply-To: <77f8f7c30807140029w4c2d003cg8c49b8c08e140dd8@mail.gmail.com>
References: <77f8f7c30807140029w4c2d003cg8c49b8c08e140dd8@mail.gmail.com>
Message-ID: <C5816C01-7216-4C15-A498-F4558FFE0734@drinktomi.com>

On Jul 14, 2008, at 12:29 AM, nibudh wrote:

> Hi List,
>
> I'm looking for some support libraries that will help me to parse  
> sendmail logs.
>
> I'm confused about whether i need a "parser" per se, and if i do  
> which parser to use. I found this website http://nedbatchelder.com/text/python-parsers.html 
>  which compares a slew of python parsers.

Parsers as referenced in your link are intended for heavy-duty lifting
such as parsing programming languages.

Sendmail logs are very simple, so those parsers are vast overkill.    
Split
on whitespace combined with regular expressions should be up to the job.

-jeff

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080715/2ad71f92/attachment-0001.htm>

From mayankiitd at gmail.com  Tue Jul 15 20:41:36 2008
From: mayankiitd at gmail.com (Mayank Agarwal)
Date: Wed, 16 Jul 2008 00:11:36 +0530
Subject: [Tutor] getting error in uploading a file
In-Reply-To: <58ebdc1a0807150851r45bda7a8hfa38f85be1b08faa@mail.gmail.com>
References: <58ebdc1a0807150851r45bda7a8hfa38f85be1b08faa@mail.gmail.com>
Message-ID: <58ebdc1a0807151141v446e3ffcv5634c22b6d70cb29@mail.gmail.com>

Hi,
i have a look on error_log and the error is following:
[Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] (8)Exec format
error: exec of '/etc/httpd/cgi-bin/final.php' failed
[Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] No log handling
enabled - turning on stderr logging
[Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] Cannot find module
(LM-SENSORS-MIB): At line 1 in (none)
[Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] No log handling
enabled - turning on stderr logging
[Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] Cannot find module
(LM-SENSORS-MIB): At line 1 in (none)
[Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] No log handling
enabled - turning on stderr logging
[Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] Cannot find module
(LM-SENSORS-MIB): At line 0 in (none)
[Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] No log handling
enabled - turning on stderr logging
[Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] Cannot find module
(LM-SENSORS-MIB): At line 0 in (none)
[Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] No log handling
enabled - turning on stderr logging
[Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] Cannot find module
(LM-SENSORS-MIB): At line 0 in (none)
[Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] No log handling
enabled - turning on stderr logging
[Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] Cannot find module
(LM-SENSORS-MIB): At line 0 in (none)
[Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] No log handling
enabled - turning on stderr logging
[Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] Cannot find module
(LM-SENSORS-MIB): At line 0 in (none)
[Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] No log handling
enabled - turning on stderr logging
[Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] Cannot find module
(LM-SENSORS-MIB): At line 0 in (none)
[Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] No log handling
enabled - turning on stderr logging
[Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] Cannot find module
(LM-SENSORS-MIB): At line 0 in (none)
[Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] No log handling
enabled - turning on stderr logging
[Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] Cannot find module
(LM-SENSORS-MIB): At line 0 in (none)
[Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] Premature end of
script headers: final.php

can you tell what to do next to remove this error

Thanks,
Mayank

On Tue, Jul 15, 2008 at 9:21 PM, Mayank Agarwal <mayankiitd at gmail.com>
wrote:

>
>
> Hi,
>
>


-- 
Mayank Agarwal
Computer Science
B.Tech,3rd Year, IIT Delhi
M: +919810159706
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080716/15645209/attachment.htm>

From marc.tompkins at gmail.com  Tue Jul 15 20:50:28 2008
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Tue, 15 Jul 2008 11:50:28 -0700
Subject: [Tutor] getting error in uploading a file
In-Reply-To: <58ebdc1a0807151141v446e3ffcv5634c22b6d70cb29@mail.gmail.com>
References: <58ebdc1a0807150851r45bda7a8hfa38f85be1b08faa@mail.gmail.com>
	<58ebdc1a0807151141v446e3ffcv5634c22b6d70cb29@mail.gmail.com>
Message-ID: <40af687b0807151150n76d8e574h82a8f24fd6a60085@mail.gmail.com>

On Tue, Jul 15, 2008 at 11:41 AM, Mayank Agarwal <mayankiitd at gmail.com>
wrote:

> Hi,
> i have a look on error_log and the error is following:
> [Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] (8)Exec format
> error: exec of '/etc/httpd/cgi-bin/final.php' failed
> [Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] No log handling
> enabled - turning on stderr logging
> [Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] Cannot find module
> (LM-SENSORS-MIB): At line 1 in (none)
> [Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] No log handling
> enabled - turning on stderr logging
> [Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] Cannot find module
> (LM-SENSORS-MIB): At line 1 in (none)
> [Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] No log handling
> enabled - turning on stderr logging
> [Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] Cannot find module
> (LM-SENSORS-MIB): At line 0 in (none)
> [Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] No log handling
> enabled - turning on stderr logging
> [Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] Cannot find module
> (LM-SENSORS-MIB): At line 0 in (none)
> [Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] No log handling
> enabled - turning on stderr logging
> [Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] Cannot find module
> (LM-SENSORS-MIB): At line 0 in (none)
> [Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] No log handling
> enabled - turning on stderr logging
> [Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] Cannot find module
> (LM-SENSORS-MIB): At line 0 in (none)
> [Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] No log handling
> enabled - turning on stderr logging
> [Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] Cannot find module
> (LM-SENSORS-MIB): At line 0 in (none)
> [Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] No log handling
> enabled - turning on stderr logging
> [Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] Cannot find module
> (LM-SENSORS-MIB): At line 0 in (none)
> [Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] No log handling
> enabled - turning on stderr logging
> [Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] Cannot find module
> (LM-SENSORS-MIB): At line 0 in (none)
> [Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] No log handling
> enabled - turning on stderr logging
> [Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] Cannot find module
> (LM-SENSORS-MIB): At line 0 in (none)
> [Tue Jul 15 21:17:03 2008] [error] [client 10.73.41.64] Premature end of
> script headers: final.php
>
> can you tell what to do next to remove this error
>

You have two errors there - one, lm-sensors is not installed (that's
hardware monitoring for CPU/motherboard), and "final.php" appears to be
bad.  Neither of them has anything to do with Python.

-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080715/96c95e1b/attachment.htm>

From kent37 at tds.net  Tue Jul 15 20:59:13 2008
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 15 Jul 2008 14:59:13 -0400
Subject: [Tutor] getting error in uploading a file
In-Reply-To: <58ebdc1a0807151141v446e3ffcv5634c22b6d70cb29@mail.gmail.com>
References: <58ebdc1a0807150851r45bda7a8hfa38f85be1b08faa@mail.gmail.com>
	<58ebdc1a0807151141v446e3ffcv5634c22b6d70cb29@mail.gmail.com>
Message-ID: <1c2a2c590807151159v4f1f0288t896002e9be1ce5aa@mail.gmail.com>

On Tue, Jul 15, 2008 at 2:41 PM, Mayank Agarwal <mayankiitd at gmail.com> wrote:
> Hi,
> i have a look on error_log and the error is following:

> can you tell what to do next to remove this error

This is pretty far off-topic for this list, if you need help with
Apache I would prefer you to find it somewhere else.

Kent

From monjissvel at googlemail.com  Tue Jul 15 21:20:15 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Tue, 15 Jul 2008 19:20:15 +0000
Subject: [Tutor] function for memory usage
In-Reply-To: <e2f191310807151219x5281ebc2hcf23df61dbc26303@mail.gmail.com>
References: <314148.84226.qm@web83821.mail.sp1.yahoo.com>
	<e2f191310807151219x5281ebc2hcf23df61dbc26303@mail.gmail.com>
Message-ID: <e2f191310807151220q12217501j7f6fb7e4ffe712b4@mail.gmail.com>

ps -eo pid,ppid,rss,vsize,pcpu,pmem,cmd -ww --sort=pid

I m no genius i found it here :
http://mail.nl.linux.org/linux-mm/2003-03/msg00077.html
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080715/ebcec613/attachment.htm>

From alan.gauld at btinternet.com  Tue Jul 15 21:58:36 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 15 Jul 2008 20:58:36 +0100
Subject: [Tutor] parsing sendmail logs
References: <77f8f7c30807140029w4c2d003cg8c49b8c08e140dd8@mail.gmail.com><1c2a2c590807140347m31569475iae4b1dfcb35241ec@mail.gmail.com><e2f191310807141110n985be8fwace998044c06c15c@mail.gmail.com><77f8f7c30807141725m51c0ef14t31f23a8381c5633@mail.gmail.com>
	<e2f191310807150415m516fefddxcd1922dc6b1de3ee@mail.gmail.com>
Message-ID: <g5ivhe$i0r$1@ger.gmane.org>

"Monika Jisswel" <monjissvel at googlemail.com> wrote

> to say the truth I never  thought about "additional overhead of 
> getting the
> input/output data transferred" because the suprocess itself will 
> contain the
> (bash)pipe to redirect output to the next utility used not the 
> python
> subprocess.PIPE pipe so it will be like one subprocess with each 
> utility
> piping stdout to the next as if run from the shell,

If you run a pipeline chain from within subprocess every part of the
chain will be a separate process, thats a lot of overhead. Thats why
admins tend to prefer writing utilities in Perl rather than bash these 
days.
Also for the pipeline to work every element must work with text
which may notr be the native data type so we have to convert it
to/from ints or floats etc.

But mostly I was thinking about the I/O to//from the Python program.
If the sublprocess or pipeline is feeding data into Python it will 
usually
be much more efficient to store the data directly in Python variables
that to write it to stdout and read it back from stdin (which is what
happens in the pipeline).

> I have to say that I have seen awk, grep & sort, wc, work on files 
> of
> handreds of Mbytes in a matter of 1 or 2 seconds ... why would I 
> replace
> such a fast tools ?

awk is not very fast. It is an interpreted language in the old sense
of interpreted language, it literally ijnterprets line by line. I have 
not
compared awk to Python directly but I hhave compared it to perl
which is around 3 times faster in my experience and more if you
run awk from Perl rather than doing the equivalent in Perl.. Now
Python is usually a littlebit slower than Perl - especially when
using regex - but not that much slower so I'd expect Python to
be about 2 times faster than awk. (Not sure how nawk or gawk
compare, they may be compiled to byte code like perl/python.)

But as you say even awk if gast enough for normal sized use
so unless you are processing large numbers of files spawning
an awk process is probably not a killer, it just seems redundant
given that Python is just as capable for processing text and much
better at processing collections.

> Alan do you think python can beat awk in speed when it
> comes to replacing text ?  I always wanted to know it !

It would be interesting to try but I'd expect it to be significantly
faster, yes.

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



From lsnyder at cheyenneme.com  Tue Jul 15 20:52:43 2008
From: lsnyder at cheyenneme.com (Lauren Snyder)
Date: Tue, 15 Jul 2008 11:52:43 -0700
Subject: [Tutor] Tree Ctrl Data Structure - Help, please!
Message-ID: <BB9ABF5B40378442BE4D220C353230D601BAE7EE@EXCHANGE.cme>

Hello!

 

ACK!!! I am attempting to "AUTO" populate a tree control....

 

Right now I am just focusing on dynamically creating the data structure
(a list of lists) that will later be used to populate the tree control. 

This is where I am stuck! 

 

Based on some research I've done,  I think I want my data structure to
be a series of lists within lists:

 

[ "node1", "node1a", "node1b", ["node1c", "node2", "node2a", "node2b",],
["node1d", ["node2c", "node3", "node3a"], "node2d"], "node1e"]]

 

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

The list above represents this tree structure:

 

Node1

 

Node1a

 

Node1b

 

Node1c

            Node2

            Node2a

            Node2b

 

Node1d

            Node2c

                        Node3

                        Node3a

            Node2d

 

Node1e

 

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

All of my data will be variable and I collect all the node information
via SQL queries. 

But now I have a series of lists:

 

["node1", "node1a", "node1b", "node1c", "node1d", "node1e"]

["node2", "node2a", "node2b", "node2c", "node2d"]

["node3", "node3a"]

 

If I execute my sql queries in a series of nested  'FOR' statements I
get the hierarchy for each node traversal (as shown below) - but not in
tree format. For example "1c" has many branches - so it is returned 3
times. 

 

Node1

Node1a

Node1b

 

Node1c

Node2

 

Node1c

Node2a

 

Node1c

Node2b

 

Node1d

Node2c

Node3

 

Node1d

Node2c

Node3a

 

Node1d

Node2d

 

************************************************************************
******

 

So - my questions:

 

Is there an existing method/class/library that already exists in python
to help me create the data structure I need for my tree structure?

If not, can someone give me some pointers on how to think about this
clearly??  I'm obviously missing some steps!! :-(

 

As an aside, I'm using wxpython for my GUI

Thanks!

Lauren

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080715/e73e4b89/attachment.htm>

From motoom at xs4all.nl  Wed Jul 16 01:28:18 2008
From: motoom at xs4all.nl (Michiel Overtoom)
Date: Wed, 16 Jul 2008 01:28:18 +0200
Subject: [Tutor] Tree Ctrl Data Structure - Help, please!
Message-ID: <2.2.32.20080715232818.0120751c@pop.xs4all.nl>

Lauren wrote...

> Based on some research I've done,  I think I want my data structure to
> be a series of lists within lists:
> [...]
> Can someone give me some pointers on how to think about this
> clearly??  I'm obviously missing some steps!! :-(

I find your example a bit hard to follow.  From the node names I can't
determine a logical hierarchy; it might be the formatting of the email message.
Could you express the way you get your query results in terms of the below
geography names?  Then maybe I can think up a way how to combine those lists
into a tree.

# start of example

# this example uses a hierarchy of three levels: 1) continent, 2)
country/state, and 3) city
geo=[
    "australia",
    "europe",[
        "spain",
        "germany",
        "belgium",
        ],
    "america",[
        "california",[
            "los angeles",
            "san francisco",
            "berkeley"
            ],
        "texas",
        "utah"
        ],
    "asia"
    ]

print "Our geography as a flat list:\n"
print geo


def printlist(lst,indent=0):
    for item in lst:
        if isinstance(item,(list,tuple)):
            printlist(item,indent+1)
        else:
            print "  -> "*indent, item


print "\nOur geography as a tree:\n"
printlist(geo)

# end of example


This prints:

Our geography as a flat list:

['australia', 'europe', ['spain', 'germany', 'belgium'], 'america',
['california', ['los angeles', 'san francisco', 'berkeley'], 'texas',
'utah'], 'asia']

Our geography as a tree:

 australia
 europe
  ->  spain
  ->  germany
  ->  belgium
 america
  ->  california
  ->   ->  los angeles
  ->   ->  san francisco
  ->   ->  berkeley
  ->  texas
  ->  utah
 asia

-- 
"The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing." - Vinod Vallopillil
http://www.catb.org/~esr/halloween/halloween4.html


From john at fouhy.net  Wed Jul 16 02:09:32 2008
From: john at fouhy.net (John Fouhy)
Date: Wed, 16 Jul 2008 12:09:32 +1200
Subject: [Tutor] Tree Ctrl Data Structure - Help, please!
In-Reply-To: <2.2.32.20080715232818.0120751c@pop.xs4all.nl>
References: <2.2.32.20080715232818.0120751c@pop.xs4all.nl>
Message-ID: <5e58f2e40807151709w791560d6p125cb721567daf67@mail.gmail.com>

On 16/07/2008, Michiel Overtoom <motoom at xs4all.nl> wrote:
> Lauren wrote...
>  > Based on some research I've done,  I think I want my data structure to
>  > be a series of lists within lists:
>  # start of example
>
>  # this example uses a hierarchy of three levels: 1) continent, 2)
>  country/state, and 3) city
>  geo=[
>     "australia",
>     "europe",[
>         "spain",
>         "germany",
>         "belgium",
>         ],
>     "america",[
>         "california",[
>             "los angeles",
>             "san francisco",
>             "berkeley"
>             ],
>         "texas",
>         "utah"
>         ],
>     "asia"
>     ]

I think the normal way of representing a tree in python would be as
(value, children) tuples.

In this case, you would have:

geo = [('australia', []), ('europe', [('spain', []), ('germany', []),
('belgium', [])]),
           ('america', [('california', [('los angeles', []), ('san
francisco', [])]),
                             ('texas', [('detroit', [])])]),
           # etc
          ]

This lets you avoid messy isinstance testing to figure out if you've
got a value or a list of children.
(admittedly, it can be hard to keep track of the brackets, but good
indentation and a monospaced font should help out)

-- 
John.

From oltarasenko at gmail.com  Wed Jul 16 08:58:01 2008
From: oltarasenko at gmail.com (Oleg Oltar)
Date: Wed, 16 Jul 2008 09:58:01 +0300
Subject: [Tutor] Unittest. Run test case independently
Message-ID: <b4fc2ad80807152358y4260a001qade3fa24791af513@mail.gmail.com>

Is that possible to run test cases independently (without unittest.main) and
how to do it

E.g. I tried it this way:

import random
import unittest

class TestSequenceFunctions(unittest.TestCase):

    def setUp(self):
        self.seq = range(10)

    def testshuffle(self):
        # make sure the shuffled sequence does not lose any elements
        random.shuffle(self.seq)
        self.seq.sort()
        self.assertEqual(self.seq, range(10))


    def testchoice(self):
        element = random.choice(self.seq)
        self.assert_(element in self.seq)

    def testsample(self):
        self.assertRaises(ValueError, random.sample, self.seq, 20)
        for element in random.sample(self.seq, 5):
            self.assert_(element in self.seq)

if __name__ == '__main__':
    a = TestSequenceFunctions().testchoice().run()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080716/0fcbcfa7/attachment-0001.htm>

From neven.gorsic at gmail.com  Wed Jul 16 13:31:16 2008
From: neven.gorsic at gmail.com (=?ISO-8859-2?Q?Neven_Gor=B9i=E6?=)
Date: Wed, 16 Jul 2008 13:31:16 +0200
Subject: [Tutor] CD ROM Drive
Message-ID: <8acd28da0807160431u14895acev9ca6fb1f15387e41@mail.gmail.com>

Hi!

I am using Python 2.5.2 on WinXP Pro and I want to detect all disk drives.
I have C:, D: and E: hard disks and F: DVD ROM.

When I try to use os.access method with writing checking I get True
testing DVD ROM Drive with DVD media inside (which is not writable).
1. Why? DVD disk is not writable!

>>> import os
>>> print os.access('F:\\',os.W_OK)
True

2. When I remove DVD Disk from the drive I get unswer False.
That is OK. But when I run program with that single command
from Windows Explorer I get Windows alert Window:

"No disk! Please insert a disk into drive F:"

That alert stops program and I must respond with: Cancel, Try again or Continue.
The alert remains even with try, except(WindowsError)

Interesting point is that that alert doesn't pop up before I open DVD
for the first time.
After first inserting and ejecting DVD media alert is here!

It seems that information that is DVD no longer avilable is not
updated accordingly.

How can I avoid that?

3. Are there some other way to get list of all disk drives and DVD ROM drives?
I hoped that I can do that with modules that comes with standard
Python instalation.


Thank you very much for your consideration

Neven
-------------- next part --------------
A non-text attachment was scrubbed...
Name: No Disk.jpg
Type: image/jpeg
Size: 9858 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20080716/caa55a4a/attachment.jpg>

From kent37 at tds.net  Wed Jul 16 13:37:36 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 16 Jul 2008 07:37:36 -0400
Subject: [Tutor] Unittest. Run test case independently
In-Reply-To: <b4fc2ad80807152358y4260a001qade3fa24791af513@mail.gmail.com>
References: <b4fc2ad80807152358y4260a001qade3fa24791af513@mail.gmail.com>
Message-ID: <1c2a2c590807160437p20b5f0eah42c6d2e2bed02939@mail.gmail.com>

On Wed, Jul 16, 2008 at 2:58 AM, Oleg Oltar <oltarasenko at gmail.com> wrote:
> Is that possible to run test cases independently (without unittest.main) and
> how to do it
>
> E.g. I tried it this way:
>
> import random
> import unittest
>
> class TestSequenceFunctions(unittest.TestCase):
>
>     def setUp(self):
>         self.seq = range(10)
>
>     def testchoice(self):
>         element = random.choice(self.seq)
>         self.assert_(element in self.seq)

> if __name__ == '__main__':
>     a = TestSequenceFunctions().testchoice().run()

Try this:
  unittest.main(defaulTest='TestSequenceFunctions.testchoice')

You can run a single test from the command line using nose:
http://somethingaboutorange.com/mrl/projects/nose/#usage

From mail at timgolden.me.uk  Wed Jul 16 14:02:53 2008
From: mail at timgolden.me.uk (Tim Golden)
Date: Wed, 16 Jul 2008 13:02:53 +0100
Subject: [Tutor] CD ROM Drive
In-Reply-To: <8acd28da0807160431u14895acev9ca6fb1f15387e41@mail.gmail.com>
References: <8acd28da0807160431u14895acev9ca6fb1f15387e41@mail.gmail.com>
Message-ID: <487DE36D.5020908@timgolden.me.uk>

Neven Gor?i? wrote:
> Hi!
> 
> I am using Python 2.5.2 on WinXP Pro and I want to detect all disk drives.
> I have C:, D: and E: hard disks and F: DVD ROM.

Use WMI:

http://timgolden.me.uk/python/wmi_cookbook.html#find-drive-types

(mutatis mutandis)


> When I try to use os.access method with writing checking I get True
> testing DVD ROM Drive with DVD media inside (which is not writable).
> 1. Why? DVD disk is not writable!
> 
>>>> import os
>>>> print os.access('F:\\',os.W_OK)
> True

In short because os.access always returns True for
*directories* as opposed to *files* on Windows
because it only checks the read-only flag and the
read-only flag has no real meaning on a directory
on Windows.

> 2. When I remove DVD Disk from the drive I get unswer False.


It returns False when there's no media because that
constitutes an exception from the OS and the function
automatically returns False in that case.

[... snip stuff about "Insert disk..." ...]

Frankly this is a bit tricky. I'm not sure to what extent you can
get in ahead of the shell. A couple of possibilities, assuming
I've understood the situation. You can monitor device insertion
and removal either via the Win32 or shell APIs or via WMI (which, I imagine,
uses that API under the covers). The latest pywin32 modules have
added more support for this kind of thing, which you previously
had to do via ctypes.

If you're interested in pursuing this, I can rustle up some code.

> 3. Are there some other way to get list of all disk drives and DVD ROM drives?
> I hoped that I can do that with modules that comes with standard
> Python instalation.

See above. Although my solution uses external modules[1][2], you *can* do
the same using ctypes, but why bother? Just install the 

TJG

[1] http://pywin32.sf.net
[2] http://timgolden.me.uk/python/wmi.html


From mail at timgolden.me.uk  Wed Jul 16 14:09:06 2008
From: mail at timgolden.me.uk (Tim Golden)
Date: Wed, 16 Jul 2008 13:09:06 +0100
Subject: [Tutor] CD ROM Drive
In-Reply-To: <8acd28da0807160431u14895acev9ca6fb1f15387e41@mail.gmail.com>
References: <8acd28da0807160431u14895acev9ca6fb1f15387e41@mail.gmail.com>
Message-ID: <487DE4E2.9050401@timgolden.me.uk>

Neven Gor?i? wrote:
> That is OK. But when I run program with that single command
> from Windows Explorer I get Windows alert Window:
> 
> "No disk! Please insert a disk into drive F:"
> 
> That alert stops program and I must respond with: Cancel, Try again or Continue.
> The alert remains even with try, except(WindowsError)
> 
> Interesting point is that that alert doesn't pop up before I open DVD
> for the first time.
> After first inserting and ejecting DVD media alert is here!
> 
> It seems that information that is DVD no longer avilable is not
> updated accordingly.
> 
> How can I avoid that?

Ah. Sorry. I just re-read your question. I think you can do what
you want by querying the .MediaLoaded attribute of the 
Win32_CDROMDrive WMI class.

<code>
import wmi

c = wmi.WMI ()
for cdrom in c.Win32_CDROMDrive ():
  print "Drive", cdrom.Drive, "is loaded" if cdrom.MediaLoaded else "is empty"

</code>

TJG

From neven.gorsic at gmail.com  Wed Jul 16 14:40:11 2008
From: neven.gorsic at gmail.com (=?ISO-8859-2?Q?Neven_Gor=B9i=E6?=)
Date: Wed, 16 Jul 2008 14:40:11 +0200
Subject: [Tutor] CD ROM Drive
In-Reply-To: <487DE36D.5020908@timgolden.me.uk>
References: <8acd28da0807160431u14895acev9ca6fb1f15387e41@mail.gmail.com>
	<487DE36D.5020908@timgolden.me.uk>
Message-ID: <8acd28da0807160540y62e3fc26y15b94df6cd2d5109@mail.gmail.com>

On Wed, Jul 16, 2008 at 2:02 PM, Tim Golden <mail at timgolden.me.uk> wrote:
> Neven Gor?i? wrote:
>>
>> Hi!
>>
>> I am using Python 2.5.2 on WinXP Pro and I want to detect all disk drives.
>> I have C:, D: and E: hard disks and F: DVD ROM.
>
> Use WMI:
>
> http://timgolden.me.uk/python/wmi_cookbook.html#find-drive-types
>
> (mutatis mutandis)
>
>
>> When I try to use os.access method with writing checking I get True
>> testing DVD ROM Drive with DVD media inside (which is not writable).
>> 1. Why? DVD disk is not writable!
>>
>>>>> import os
>>>>> print os.access('F:\\',os.W_OK)
>>
>> True
>
> In short because os.access always returns True for
> *directories* as opposed to *files* on Windows
> because it only checks the read-only flag and the
> read-only flag has no real meaning on a directory
> on Windows.
>
>> 2. When I remove DVD Disk from the drive I get unswer False.
>
>
> It returns False when there's no media because that
> constitutes an exception from the OS and the function
> automatically returns False in that case.
>
> [... snip stuff about "Insert disk..." ...]
>
> Frankly this is a bit tricky. I'm not sure to what extent you can
> get in ahead of the shell. A couple of possibilities, assuming
> I've understood the situation. You can monitor device insertion
> and removal either via the Win32 or shell APIs or via WMI (which, I imagine,
> uses that API under the covers). The latest pywin32 modules have
> added more support for this kind of thing, which you previously
> had to do via ctypes.
>
> If you're interested in pursuing this, I can rustle up some code.
>
>> 3. Are there some other way to get list of all disk drives and DVD ROM
>> drives?
>> I hoped that I can do that with modules that comes with standard
>> Python instalation.
>
> See above. Although my solution uses external modules[1][2], you *can* do
> the same using ctypes, but why bother? Just install the
> TJG
>
> [1] http://pywin32.sf.net
> [2] http://timgolden.me.uk/python/wmi.html
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

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

Thank you for your quick answer. I'll try suggested modules and let you now.

Neven

From rdm at rcblue.com  Wed Jul 16 16:55:38 2008
From: rdm at rcblue.com (Dick Moores)
Date: Wed, 16 Jul 2008 07:55:38 -0700
Subject: [Tutor] Does IPython have a "restart"?
Message-ID: <20080716145551.313881E4007@bag.python.org>

I mean something equivalent to what you get when you do a Ctrl+F6 in IDLE:

 >>> import math
 >>> math.log(3)
1.0986122886681098
 >>> =============================================== RESTART 
===============================================
 >>> math.log(3)

Traceback (most recent call last):
   File "<pyshell#9>", line 1, in <module>
     math.log(3)
NameError: name 'math' is not defined
 >>>

Thanks,

Dick Moores


From kent37 at tds.net  Wed Jul 16 19:31:34 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 16 Jul 2008 13:31:34 -0400
Subject: [Tutor] Does IPython have a "restart"?
In-Reply-To: <20080716145551.313881E4007@bag.python.org>
References: <20080716145551.313881E4007@bag.python.org>
Message-ID: <1c2a2c590807161031n2704484cp59e403bab5353d37@mail.gmail.com>

Just quit and relaunch?

Kent

From oltarasenko at gmail.com  Wed Jul 16 20:40:49 2008
From: oltarasenko at gmail.com (Oleg Oltar)
Date: Wed, 16 Jul 2008 21:40:49 +0300
Subject: [Tutor] Unittest
Message-ID: <b4fc2ad80807161140w3d1d0fe5q9d15898969ec3dc7@mail.gmail.com>

Hi I am using unittest framework with selenium.

When I tried this code (my verification point)

        self.assertEqual(True, sel.is_text_present(u"???????? ?????? ??
?????????"), "System didn't give a correct warning about the password
misstype")

Where u"???????? ?????? ?? ?????????" is russian = "Sorry passwords aren't
> equal", and sel.is_text_present - searches text string on the page


The output I get in case of failure was:


Traceback (most recent call last):
  File "./newaccount/Password_matching.py", line 50, in test_passwordMatching
    self.assertEqual(True, sel.is_text_present(u"????????????????
???????????? ???? ??????????????????"), "System didn't give a correct
warning about the password misstype")
AssertionError: System didn't give a correct warning about the password misstype

Is there any way to get normal russian text instead of these strange D
chars "????????...."


Thanks,
Oleg
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080716/99e316ed/attachment.htm>

From neven.gorsic at gmail.com  Wed Jul 16 22:10:22 2008
From: neven.gorsic at gmail.com (=?ISO-8859-2?Q?Neven_Gor=B9i=E6?=)
Date: Wed, 16 Jul 2008 22:10:22 +0200
Subject: [Tutor] CD ROM Drive
In-Reply-To: <8acd28da0807160540y62e3fc26y15b94df6cd2d5109@mail.gmail.com>
References: <8acd28da0807160431u14895acev9ca6fb1f15387e41@mail.gmail.com>
	<487DE36D.5020908@timgolden.me.uk>
	<8acd28da0807160540y62e3fc26y15b94df6cd2d5109@mail.gmail.com>
Message-ID: <8acd28da0807161310n47a7d264sbafd21b57e44f420@mail.gmail.com>

2008/7/16 Neven Gor?i? <neven.gorsic at gmail.com>:
> On Wed, Jul 16, 2008 at 2:02 PM, Tim Golden <mail at timgolden.me.uk> wrote:
>> Neven Gor?i? wrote:
>>>
>>> Hi!
>>>
>>> I am using Python 2.5.2 on WinXP Pro and I want to detect all disk drives.
>>> I have C:, D: and E: hard disks and F: DVD ROM.
>>
>> Use WMI:
>>
>> http://timgolden.me.uk/python/wmi_cookbook.html#find-drive-types
>>
>> (mutatis mutandis)
>>
>>
>>> When I try to use os.access method with writing checking I get True
>>> testing DVD ROM Drive with DVD media inside (which is not writable).
>>> 1. Why? DVD disk is not writable!
>>>
>>>>>> import os
>>>>>> print os.access('F:\\',os.W_OK)
>>>
>>> True
>>
>> In short because os.access always returns True for
>> *directories* as opposed to *files* on Windows
>> because it only checks the read-only flag and the
>> read-only flag has no real meaning on a directory
>> on Windows.
>>
>>> 2. When I remove DVD Disk from the drive I get unswer False.
>>
>>
>> It returns False when there's no media because that
>> constitutes an exception from the OS and the function
>> automatically returns False in that case.
>>
>> [... snip stuff about "Insert disk..." ...]
>>
>> Frankly this is a bit tricky. I'm not sure to what extent you can
>> get in ahead of the shell. A couple of possibilities, assuming
>> I've understood the situation. You can monitor device insertion
>> and removal either via the Win32 or shell APIs or via WMI (which, I imagine,
>> uses that API under the covers). The latest pywin32 modules have
>> added more support for this kind of thing, which you previously
>> had to do via ctypes.
>>
>> If you're interested in pursuing this, I can rustle up some code.
>>
>>> 3. Are there some other way to get list of all disk drives and DVD ROM
>>> drives?
>>> I hoped that I can do that with modules that comes with standard
>>> Python instalation.
>>
>> See above. Although my solution uses external modules[1][2], you *can* do
>> the same using ctypes, but why bother? Just install the
>> TJG
>>
>> [1] http://pywin32.sf.net
>> [2] http://timgolden.me.uk/python/wmi.html
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
> -------------------------------------------
>
> Thank you for your quick answer. I'll try suggested modules and let you now.
>
> Neven
>
----------------------------------


Dear Tim,

wmi package is not only elegant, but also capable of "silent"
interaction with Windows.
It doesn't couse Windows alerts which troubles me workig with
os.path.exists() method!

Thank you very much!


PS. In the begining wmi doesn't worked at all: import wmi passed, but
c = wmi.WMI()
caused a pile of errors. In the end I read Tony Cappellini
recomendation that we "may
need to run makepy manually on one or more of the following type libraries":

Microsoft WMI Scripting Library
WMI ADSI Extension Type Library
WMICntl Type Library

I run PythonWin, select Tools,Com Makepy and selecting previous libraries.

From rdm at rcblue.com  Wed Jul 16 22:31:02 2008
From: rdm at rcblue.com (Dick Moores)
Date: Wed, 16 Jul 2008 13:31:02 -0700
Subject: [Tutor] Does IPython have a "restart"?
In-Reply-To: <1c2a2c590807161031n2704484cp59e403bab5353d37@mail.gmail.co
 m>
References: <20080716145551.313881E4007@bag.python.org>
	<1c2a2c590807161031n2704484cp59e403bab5353d37@mail.gmail.com>
Message-ID: <20080716203114.5A40F1E4016@bag.python.org>

At 10:31 AM 7/16/2008, Kent Johnson wrote:
>Just quit and relaunch?
>
>Kent

Well, if that what Kent, a long-time IPython user does, I guess I'm 
stuck with doing that, but I don't like it.

Dick



From kent37 at tds.net  Wed Jul 16 23:07:28 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 16 Jul 2008 17:07:28 -0400
Subject: [Tutor] Does IPython have a "restart"?
In-Reply-To: <20080716203114.5A40F1E4016@bag.python.org>
References: <20080716145551.313881E4007@bag.python.org>
	<1c2a2c590807161031n2704484cp59e403bab5353d37@mail.gmail.com>
	<20080716203114.5A40F1E4016@bag.python.org>
Message-ID: <1c2a2c590807161407pb6dadafjf9e7d8d23722ef6@mail.gmail.com>

On Wed, Jul 16, 2008 at 4:31 PM, Dick Moores <rdm at rcblue.com> wrote:
> At 10:31 AM 7/16/2008, Kent Johnson wrote:
>>
>> Just quit and relaunch?
>>
>> Kent
>
> Well, if that what Kent, a long-time IPython user does, I guess I'm stuck
> with doing that, but I don't like it.

Actually I don't do that, I suggested that you might. I don't often
have a need to reset the interpreter. Why do you want to? What is
wrong with relaunching?

Kent

From kent37 at tds.net  Wed Jul 16 23:11:47 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 16 Jul 2008 17:11:47 -0400
Subject: [Tutor] Unittest
In-Reply-To: <b4fc2ad80807161140w3d1d0fe5q9d15898969ec3dc7@mail.gmail.com>
References: <b4fc2ad80807161140w3d1d0fe5q9d15898969ec3dc7@mail.gmail.com>
Message-ID: <1c2a2c590807161411w5f23a55dmacc8ad9fa56c0f30@mail.gmail.com>

On Wed, Jul 16, 2008 at 2:40 PM, Oleg Oltar <oltarasenko at gmail.com> wrote:
> Hi I am using unittest framework with selenium.
>
> When I tried this code (my verification point)
>
>         self.assertEqual(True, sel.is_text_present(u"???????? ?????? ??
> ?????????"), "System didn't give a correct warning about the password
> misstype")
>
>> Where u"???????? ?????? ?? ?????????" is russian = "Sorry passwords aren't
>> equal", and sel.is_text_present - searches text string on the page
>
> The output I get in case of failure was:
>
>
> Traceback (most recent call last):
>
>   File "./newaccount/Password_matching.py", line 50, in
> test_passwordMatching
>     self.assertEqual(True, sel.is_text_present(u"????????????????
> ???????????? ???? ? ????????????????"), "System didn't give a correct
> warning about the password misstype")
>
> AssertionError: System didn't give a correct warning about the password
> misstype
>
> Is there any way to get normal russian text instead of these strange D chars
> "????????...."

I don't have the solution but maybe I can give you a useful clue. The
D characters are most likely the utf-8 encoding of the Russian text,
when displayed as if it is latin-1. So something in the system is
converting the text to utf-8 and your console probably has latin-1 or
cp1252 encoding.

Some details might help - how are you running the program - console,
IDLE...? What OS? What are the values of sys.getdefaultencoding() and
sys.stdout.encoding?

Kent

From rdm at rcblue.com  Wed Jul 16 23:28:42 2008
From: rdm at rcblue.com (Dick Moores)
Date: Wed, 16 Jul 2008 14:28:42 -0700
Subject: [Tutor] Does IPython have a "restart"?
In-Reply-To: <1c2a2c590807161407pb6dadafjf9e7d8d23722ef6@mail.gmail.com>
References: <20080716145551.313881E4007@bag.python.org>
	<1c2a2c590807161031n2704484cp59e403bab5353d37@mail.gmail.com>
	<20080716203114.5A40F1E4016@bag.python.org>
	<1c2a2c590807161407pb6dadafjf9e7d8d23722ef6@mail.gmail.com>
Message-ID: <20080716212854.A37781E4003@bag.python.org>

At 02:07 PM 7/16/2008, Kent Johnson wrote:
>On Wed, Jul 16, 2008 at 4:31 PM, Dick Moores <rdm at rcblue.com> wrote:
> > At 10:31 AM 7/16/2008, Kent Johnson wrote:
> >>
> >> Just quit and relaunch?
> >>
> >> Kent
> >
> > Well, if that what Kent, a long-time IPython user does, I guess I'm stuck
> > with doing that, but I don't like it.
>
>Actually I don't do that, I suggested that you might. I don't often
>have a need to reset the interpreter. Why do you want to?

I have a big, 2000-line module, mycalc.py  that is a collection of
useful functions, most written by myself. I often import one or
another function from it and use it in the Ulipad shell. Then I see
that the function needs a small revision. I modify it in the module,
then want to test it and then use the new version in the shell. I'd like
to be able to do this in IPython.

>  What is
>wrong with relaunching?

Hey, IPython is so cool I thought it must have what IDLE has. And 
relaunching takes longer.

Dick


From carroll at tjc.com  Thu Jul 17 00:58:51 2008
From: carroll at tjc.com (Terry Carroll)
Date: Wed, 16 Jul 2008 15:58:51 -0700 (PDT)
Subject: [Tutor] Any way of monitoring a python program's memory utilization?
Message-ID: <Pine.LNX.4.44.0807161521370.10773-100000@violet.rahul.net>

Is there any way of having my program see how much memory it's using?

I'm iterating through a vey large tarfile (uncompressed, it would be about
2.4G, with about 2.5 million files in it) and I can see from some external
monitors that its virtual storage usage just grows and grows, until my
whole system finally grinds to a halt after about 1.2 million members have
been processed.

I'd like to try various strategies, but as I try them I'd like for it to 
monitor its own memory usage so I can assess the different strategies I 
use, and in any event, abort before it gets to the point of hanging my 
system.

Is there anything within Python (I'm on 2.5) that can check this?  Failing 
that, are there any Windows/XP line-oriented commands that I could invoke 
and parse the output of?  (I also have Cygwin installed, in case there are 
any gnu-based commands that woudl work, too.)


From lauren at protopc.com  Thu Jul 17 00:08:36 2008
From: lauren at protopc.com (lauren at protopc.com)
Date: Wed, 16 Jul 2008 16:08:36 -0600 (MDT)
Subject: [Tutor] Tree Ctrl Data Structure - Help, please!
In-Reply-To: <2.2.32.20080715232818.0120751c@pop.xs4all.nl>
References: <2.2.32.20080715232818.0120751c@pop.xs4all.nl>
Message-ID: <38795.69.16.140.5.1216246116.squirrel@www.protopc.com>



Hi!

Thanks for much for your reply! I'm sorry my posting was so
confusing...It's partially because my understanding is so hazy right now.
I'm trying to piece together what I should do next...

Based on your example...
My understanding is that if I desire the following tree control structure
in my GUI:

  australia
  europe
   ->  spain
   ->  germany
   ->  belgium
  north america
   ->  united states
   ->   ->  california
   ->   ->  oregon
   ->   ->  arizona
   ->  canada
  asia

That my nested list will look something like this....(NOTE) I believe that
I will need to include the parent root node IN the list like this (not
outside of it before the children):

geo=[
    "australia",
    ["europe",
        ["spain",
         "germany",
         "belgium",]],
    ["north america",
        ["united states",[
            "california",
             "oregon",
             "arizona"],
        "canada"]],
    "asia"]


Currently the format of my data are lists from queries such as:

Select Distinct(Continent) from world_globe;  --> Query returns a list -->
["australia", "europe", "north america", "asia"]
Select Distinct(Country) from world_globe
where continent = "europe";  --> Query returns a list -->
["spain", "germany", "belgium"]
Select Distinct(State) from world_globe
where country = "united states";  --> Query returns a list -->
["california", "oregon", "arizona"]
ETC....

So my lists are these:
continent = ["australia", "europe", "america", "asia"]
country = [["spain", "germany", "belgium"], ["united states", "canada"]]
state = ["california", "oregon", "arizona"]

So ... what I have:
The data is already split out into nodes. Clearly my tree will be 3 deep.
Continent
    -> Country
        -> State

What I don't have - aka my questions??????:
I think I need a list of nested lists...and they need to be in the proper,
logical order. I can't simply iterate on continent inserting the lists
from Country because they don't associate themselves with the correct
objects. It would become for example:

tree_list = ["australia", ["spain", "germany", "belgium"], "europe",
["united states", "canada"], "america", "asia"

...logically representing this (which is wrong):

australia
    -> spain
    -> germany
    -> belgium
europe
    -> united states
    -> canada
america
asia

Also, I believe that the parent of the children needs to INSIDE a list
with it's children. For example this:

geo = ["australia", ["europe",["spain", "germany", "belgium"]]] <--
Correct (I believe)

NOT THIS...

geo = ["australia", "europe", ["spain", "germany", "belgium"]] <--
Incorrect (I believe)

***********

I need assistance getting from here:

continent = ["australia", "europe", "america", "asia"]
country = [["spain", "germany", "belgium"], ["united states", "canada"]]
state = ["california", "oregon", "arizona"]

To here:

geo=[
    "australia",
    ["europe",
        ["spain",
         "germany",
         "belgium",]],
    ["north america",
        ["united states",[
            "california",
             "oregon",
             "arizona"],
        "canada"]],
    "asia"]


Thanks Again!
Lauren



From alan.gauld at btinternet.com  Thu Jul 17 02:10:32 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 17 Jul 2008 01:10:32 +0100
Subject: [Tutor] Does IPython have a "restart"?
References: <20080716145551.313881E4007@bag.python.org><1c2a2c590807161031n2704484cp59e403bab5353d37@mail.gmail.com><20080716203114.5A40F1E4016@bag.python.org><1c2a2c590807161407pb6dadafjf9e7d8d23722ef6@mail.gmail.com>
	<20080716212854.A37781E4003@bag.python.org>
Message-ID: <g5m2lr$isb$1@ger.gmane.org>


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

Caveat: I have no experience with IPython whatsoever.

> I have a big, 2000-line module, mycalc.py  that is a collection of
> useful functions, most written by myself. I often import one or
> another function from it and use it in the Ulipad shell. Then I see
> that the function needs a small revision. I modify it in the module,
> then want to test it and then use the new version in the shell. I'd 
> like
> to be able to do this in IPython.

OK, If you only import the functions not the whole module reload
won't work. But how about deleting the function and then
re-importing it? Wouldn't that do it?

You could even create a function to do that for you, maybe like:

def restart(fn, mod=mycalc):
    del fn
    from mod import fn
    return fn

And us it like:

>>> from mycalc import foo,restart
>>> foo(42)   # oops wrong result
>>> # go edit foo
>>> foo = restart(foo)
>>> foo(42)   # thats better...

This is untested pseudo code but it should work with a bit of
effort - eg. you may need to use the programatic mechanism for
re importing

Just a thought.

Alan G 



From alan.gauld at btinternet.com  Thu Jul 17 02:19:05 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 17 Jul 2008 01:19:05 +0100
Subject: [Tutor] Any way of monitoring a python program's memory
	utilization?
References: <Pine.LNX.4.44.0807161521370.10773-100000@violet.rahul.net>
Message-ID: <g5m35s$k1f$1@ger.gmane.org>

"Terry Carroll" <carroll at tjc.com> wrote

> Is there anything within Python (I'm on 2.5) that can check this? 
> Failing
> that, are there any Windows/XP line-oriented commands that I could 
> invoke
> and parse the output of?  (I also have Cygwin installed, in case 
> there are
> any gnu-based commands that woudl work, too.)

With cygwin you should have top, vmstat and of course ps.
All of these can monitor system status,. top being very similar to
XPs Task Manager process view but in a text window. vmstat will
not tell you process IDs, just report total usage. And ps is single
shot so you could run it (via subprocess, say) after processing each
100 files or somesuch

Take your pick...

Alan G 



From carroll at tjc.com  Thu Jul 17 02:37:41 2008
From: carroll at tjc.com (Terry Carroll)
Date: Wed, 16 Jul 2008 17:37:41 -0700 (PDT)
Subject: [Tutor] Any way of monitoring a python program's memory
	utilization?
In-Reply-To: <g5m35s$k1f$1@ger.gmane.org>
Message-ID: <Pine.LNX.4.44.0807161733200.10773-100000@violet.rahul.net>

On Thu, 17 Jul 2008, Alan Gauld wrote:

> With cygwin you should have top, vmstat and of course ps.
> All of these can monitor system status,. top being very similar to
> XPs Task Manager process view but in a text window. vmstat will
> not tell you process IDs, just report total usage. And ps is single
> shot so you could run it (via subprocess, say) after processing each
> 100 files or somesuch

ps doesn't show memory usage as far as I can tell (that may be a cygwin 
thing; I see some references online that suggest it can in some 
environments).  I don't have top or vmstat, but I'll look into those.

Thanks.


From lauren at protopc.com  Thu Jul 17 02:45:20 2008
From: lauren at protopc.com (lauren at protopc.com)
Date: Wed, 16 Jul 2008 18:45:20 -0600 (MDT)
Subject: [Tutor] Tree Ctrl Data Structure - Help, please!
In-Reply-To: <5e58f2e40807151709w791560d6p125cb721567daf67@mail.gmail.com>
References: <2.2.32.20080715232818.0120751c@pop.xs4all.nl>
	<5e58f2e40807151709w791560d6p125cb721567daf67@mail.gmail.com>
Message-ID: <34098.69.16.140.5.1216255520.squirrel@www.protopc.com>

Thanks also for your help!

So taking into account that tree data structures can be created as a
nested tuples...

Do you have any pointers on how to get from here

continent = ["australia", "europe", "america", "asia"]
country = [["spain", "germany", "belgium"], ["united states", "canada"]]
state = ["california", "oregon", "arizona"]

To here:

geo=[
    ("australia", []),
    ("europe",
        [("spain",[]),
         ("germany",[]),
         (belgium",[])]),
    ("north america",
        [("united states",[
            ("california",[]),
            ("oregon",[]),
            ("arizona",[])
            ])
        ]),
        ("canada", []),
    ("asia", [])
    ]

??

Thanks Again!
Lauren


>
> I think the normal way of representing a tree in python would be as
> (value, children) tuples.
>
> In this case, you would have:
>
> geo = [('australia', []), ('europe', [('spain', []), ('germany', []),
> ('belgium', [])]),
>            ('america', [('california', [('los angeles', []), ('san
> francisco', [])]),
>                              ('texas', [('detroit', [])])]),
>            # etc
>           ]
>
> This lets you avoid messy isinstance testing to figure out if you've
> got a value or a list of children.
> (admittedly, it can be hard to keep track of the brackets, but good
> indentation and a monospaced font should help out)
>
> --
> John.



From john at fouhy.net  Thu Jul 17 02:56:32 2008
From: john at fouhy.net (John Fouhy)
Date: Thu, 17 Jul 2008 12:56:32 +1200
Subject: [Tutor] Any way of monitoring a python program's memory
	utilization?
In-Reply-To: <Pine.LNX.4.44.0807161733200.10773-100000@violet.rahul.net>
References: <g5m35s$k1f$1@ger.gmane.org>
	<Pine.LNX.4.44.0807161733200.10773-100000@violet.rahul.net>
Message-ID: <5e58f2e40807161756oc680c2dkc73a7a20ffac150d@mail.gmail.com>

On 17/07/2008, Terry Carroll <carroll at tjc.com> wrote:
> ps doesn't show memory usage as far as I can tell (that may be a cygwin
>  thing; I see some references online that suggest it can in some
>  environments).  I don't have top or vmstat, but I'll look into those.

Hmm, yeah, cygwin ps seems quite limited.

tasklist is the Windows version of ps.  You could try something like
'tasklist /FI "IMAGENAME eq python.exe"', though you'd then have to
parse the output.

There's also the WMIC command, which is apparently extremely powerful.
 Look at http://searchsecurity.techtarget.com/tip/0,289483,sid14_gci1303709,00.html
for example.

-- 
John.

From john at fouhy.net  Thu Jul 17 03:04:12 2008
From: john at fouhy.net (John Fouhy)
Date: Thu, 17 Jul 2008 13:04:12 +1200
Subject: [Tutor] Tree Ctrl Data Structure - Help, please!
In-Reply-To: <34098.69.16.140.5.1216255520.squirrel@www.protopc.com>
References: <2.2.32.20080715232818.0120751c@pop.xs4all.nl>
	<5e58f2e40807151709w791560d6p125cb721567daf67@mail.gmail.com>
	<34098.69.16.140.5.1216255520.squirrel@www.protopc.com>
Message-ID: <5e58f2e40807161804k2a7c442bk8cfbb846cbe26d45@mail.gmail.com>

On 17/07/2008, lauren at protopc.com <lauren at protopc.com> wrote:
>  Do you have any pointers on how to get from here
>
>  continent = ["australia", "europe", "america", "asia"]
>  country = [["spain", "germany", "belgium"], ["united states", "canada"]]
>  state = ["california", "oregon", "arizona"]
>
>  To here:
>
> geo=[
>     ("australia", []),
>     ("europe",
>         [("spain",[]),
>          ("germany",[]),
>
>          (belgium",[])]),
>
>     ("north america",
>         [("united states",[
>             ("california",[]),
>             ("oregon",[]),
>             ("arizona",[])
>             ])
>         ]),
>         ("canada", []),
>     ("asia", [])
>     ]
>
>  ??

Hi Lauren,

Basically, there is no way to do that because your lists don't contain
any information about which coutries corerspond to which continents,
et cetera.

>From looking at your other email, my guess is that you want to start
with SQL looking something like this:

select continent, country, state from world_globe

with the intention of getting back data that looks like:

[('America', 'United States', 'California'),
('America', 'United States, 'Texas'),
('America', 'United States, 'Washington'),
('America', 'Canada', 'Ontario'),
('Asia', 'Japan', None),
# etc
]

It would be fairly straightforward to take data looking something like
that and produce a tree.

-- 
John.

From carroll at tjc.com  Thu Jul 17 03:08:04 2008
From: carroll at tjc.com (Terry Carroll)
Date: Wed, 16 Jul 2008 18:08:04 -0700 (PDT)
Subject: [Tutor] Any way of monitoring a python program's memory
	utilization?
In-Reply-To: <5e58f2e40807161756oc680c2dkc73a7a20ffac150d@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0807161804340.10773-100000@violet.rahul.net>

On Thu, 17 Jul 2008, John Fouhy wrote:

> tasklist is the Windows version of ps.  You could try something like
> 'tasklist /FI "IMAGENAME eq python.exe"', though you'd then have to
> parse the output.

Thanks!  I just found that too!  (Alan's suggestiom made me thing of 
googling for "ps equivalent memory", and I found a reference to tasklist.

It's kludgy, but I have a proof-of-concept that only works if there's only 
one instance of Python running:

def memusage():
    import os
    cmd = 'tasklist /fi "IMAGENAME eq python.exe" /FO table /nh'
    output = os.popen(cmd).read()
    processdata = output.split()
    assert len(processdata) ==  6
    memsizeK_str = processdata[4]
    memsizeK_str = memsizeK_str.replace(',','') # get rid of commas
    return int(memsizeK_str)*1024

The obvious thing to do is to also filter by PID, which is the second 
element; Of course that opens a new question: how to find one's own PID 
from within Python.  More googling awaits.....



From kent37 at tds.net  Thu Jul 17 03:09:08 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 16 Jul 2008 21:09:08 -0400
Subject: [Tutor] Does IPython have a "restart"?
In-Reply-To: <g5m2lr$isb$1@ger.gmane.org>
References: <20080716145551.313881E4007@bag.python.org>
	<1c2a2c590807161031n2704484cp59e403bab5353d37@mail.gmail.com>
	<20080716203114.5A40F1E4016@bag.python.org>
	<1c2a2c590807161407pb6dadafjf9e7d8d23722ef6@mail.gmail.com>
	<20080716212854.A37781E4003@bag.python.org>
	<g5m2lr$isb$1@ger.gmane.org>
Message-ID: <1c2a2c590807161809m4a7c5a2em63c930487e02743d@mail.gmail.com>

On Wed, Jul 16, 2008 at 8:10 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> "Dick Moores" <rdm at rcblue.com> wrote
>
> Caveat: I have no experience with IPython whatsoever.
>
>> I have a big, 2000-line module, mycalc.py  that is a collection of
>> useful functions, most written by myself. I often import one or
>> another function from it and use it in the Ulipad shell. Then I see
>> that the function needs a small revision. I modify it in the module,
>> then want to test it and then use the new version in the shell. I'd like
>> to be able to do this in IPython.

I have a different style of working, I guess. I do most work in files.
I use an editor which will easily execute the file and show the
result.

For developing functions I use a unittest, still working from one or
more files. So I rarely have to reload a module explicitly.

> OK, If you only import the functions not the whole module reload
> won't work. But how about deleting the function and then
> re-importing it? Wouldn't that do it?

No, you do have to reload the module.

> You could even create a function to do that for you, maybe like:
>
> def restart(fn, mod=mycalc):
>   del fn
>   from mod import fn
>   return fn

I'm pretty sure that won't work. It needs a reload and the default
value for mod is bound at compile time so it will always be bound to
the old version of mycalc.

Kent

From kent37 at tds.net  Thu Jul 17 03:14:23 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 16 Jul 2008 21:14:23 -0400
Subject: [Tutor] Unittest
In-Reply-To: <1c2a2c590807161411w5f23a55dmacc8ad9fa56c0f30@mail.gmail.com>
References: <b4fc2ad80807161140w3d1d0fe5q9d15898969ec3dc7@mail.gmail.com>
	<1c2a2c590807161411w5f23a55dmacc8ad9fa56c0f30@mail.gmail.com>
Message-ID: <1c2a2c590807161814n7048ec5pdede6c9684e10a47@mail.gmail.com>

Another possibility - do you have a coding declaration in your source
file, something like
# -*- coding: <encoding name> -*-

If so, does the coding declaration match the actual encoding of the file?

Kent

On Wed, Jul 16, 2008 at 5:11 PM, Kent Johnson <kent37 at tds.net> wrote:
> On Wed, Jul 16, 2008 at 2:40 PM, Oleg Oltar <oltarasenko at gmail.com> wrote:
>> Hi I am using unittest framework with selenium.
>>
>> When I tried this code (my verification point)
>>
>>         self.assertEqual(True, sel.is_text_present(u"???????? ?????? ??
>> ?????????"), "System didn't give a correct warning about the password
>> misstype")
>>
>>> Where u"???????? ?????? ?? ?????????" is russian = "Sorry passwords aren't
>>> equal", and sel.is_text_present - searches text string on the page
>>
>> The output I get in case of failure was:
>>
>>
>> Traceback (most recent call last):
>>
>>   File "./newaccount/Password_matching.py", line 50, in
>> test_passwordMatching
>>     self.assertEqual(True, sel.is_text_present(u"????????????????
>> ???????????? ???? ? ????????????????"), "System didn't give a correct
>> warning about the password misstype")
>>
>> AssertionError: System didn't give a correct warning about the password
>> misstype
>>
>> Is there any way to get normal russian text instead of these strange D chars
>> "????????...."
>
> I don't have the solution but maybe I can give you a useful clue. The
> D characters are most likely the utf-8 encoding of the Russian text,
> when displayed as if it is latin-1. So something in the system is
> converting the text to utf-8 and your console probably has latin-1 or
> cp1252 encoding.
>
> Some details might help - how are you running the program - console,
> IDLE...? What OS? What are the values of sys.getdefaultencoding() and
> sys.stdout.encoding?
>
> Kent
>

From carroll at tjc.com  Thu Jul 17 03:19:12 2008
From: carroll at tjc.com (Terry Carroll)
Date: Wed, 16 Jul 2008 18:19:12 -0700 (PDT)
Subject: [Tutor] Any way of monitoring a python program's memory
	utilization?
In-Reply-To: <Pine.LNX.4.44.0807161804340.10773-100000@violet.rahul.net>
Message-ID: <Pine.LNX.4.44.0807161817580.10773-100000@violet.rahul.net>

On Wed, 16 Jul 2008, Terry Carroll wrote:

> The obvious thing to do is to also filter by PID, which is the second 
> element; Of course that opens a new question: how to find one's own PID 
> from within Python.  More googling awaits.....

And, while searching for that, I found out hwo to find memory utilization.  
For those who care:

def memusage():
    import win32process
    current_process = win32process.GetCurrentProcess()
    memory_info = win32process.GetProcessMemoryInfo(current_process)
    return memory_info["WorkingSetSize"]



From lauren at protopc.com  Thu Jul 17 03:38:03 2008
From: lauren at protopc.com (lauren at protopc.com)
Date: Wed, 16 Jul 2008 19:38:03 -0600 (MDT)
Subject: [Tutor] Tree Ctrl Data Structure - Help, please!
In-Reply-To: <5e58f2e40807161804k2a7c442bk8cfbb846cbe26d45@mail.gmail.com>
References: <2.2.32.20080715232818.0120751c@pop.xs4all.nl>
	<5e58f2e40807151709w791560d6p125cb721567daf67@mail.gmail.com>
	<34098.69.16.140.5.1216255520.squirrel@www.protopc.com>
	<5e58f2e40807161804k2a7c442bk8cfbb846cbe26d45@mail.gmail.com>
Message-ID: <38604.69.16.140.5.1216258683.squirrel@www.protopc.com>

John--

Thanks again - I so appreciate your direction!

Okay so i have a list of lists just as you describe below...I hate to make
myself look really stupid...but I don't see how this converts to a tree
structure...I was looking at this earlier and I guess what's confusing me
are the duplicates...do I need to convert the list below into a data
structure of tuples? Can this be plugged straight into a tree control?

Now my question is:

How do I get from here:
 [('north america', 'United States', 'California'),
 ('north america', 'United States, 'Texas'),
 ('north america', 'United States, 'Washington'),
 ('north america', 'Canada', 'Ontario'),
 ('Asia', 'Japan', None),

To Here:
geo=[("north america", [
        ("united states",[
            ("california", []),
            ("oregon", []),
             ("arizona", [])]),
        ("canada", [
            ("Ontario", [])])]),
     ("asia", [
        ("japan", [])])

Lauren


> From looking at your other email, my guess is that you want to start
> with SQL looking something like this:
>
> select continent, country, state from world_globe
>
> with the intention of getting back data that looks like:
>
> [('America', 'United States', 'California'),
> ('America', 'United States, 'Texas'),
> ('America', 'United States, 'Washington'),
> ('America', 'Canada', 'Ontario'),
> ('Asia', 'Japan', None),
> # etc
> ]
>
> It would be fairly straightforward to take data looking something like
> that and produce a tree.
>
> --
> John.
>



From john at fouhy.net  Thu Jul 17 04:03:40 2008
From: john at fouhy.net (John Fouhy)
Date: Thu, 17 Jul 2008 14:03:40 +1200
Subject: [Tutor] Tree Ctrl Data Structure - Help, please!
In-Reply-To: <38604.69.16.140.5.1216258683.squirrel@www.protopc.com>
References: <2.2.32.20080715232818.0120751c@pop.xs4all.nl>
	<5e58f2e40807151709w791560d6p125cb721567daf67@mail.gmail.com>
	<34098.69.16.140.5.1216255520.squirrel@www.protopc.com>
	<5e58f2e40807161804k2a7c442bk8cfbb846cbe26d45@mail.gmail.com>
	<38604.69.16.140.5.1216258683.squirrel@www.protopc.com>
Message-ID: <5e58f2e40807161903w7a1f8ce7lb76d4075e0c8103e@mail.gmail.com>

On 17/07/2008, lauren at protopc.com <lauren at protopc.com> wrote:
>  Okay so i have a list of lists just as you describe below...I hate to make
>  myself look really stupid...but I don't see how this converts to a tree
>  structure...I was looking at this earlier and I guess what's confusing me
>  are the duplicates...do I need to convert the list below into a data
>  structure of tuples? Can this be plugged straight into a tree control?

Ahh, you will have to write a function.  Once you have the data as a
list of tuples, all the information is there, but there is a lot of
redundancy.

You may find it easier to represent your tree as nested dictionaries;
the disadvantage of dictionaries is that they are unordered, but this
may not matter to you.  Here's something for you to try: forget about
states for a moment, just make yourself a list of continents and
countries:

country_tuples = [('north america', 'united states'), ('north
america', 'canada'), ('asia', 'japan'), ('asia', 'china'), ('africa',
'zimbabwe')]  # etc

See if you can convert that to a dictionary like this:

world_dict = { 'north america':['united states', 'canada'],
'asia':['japan', 'china'], 'africa':['zimbabwe'] }

Your function should start like this:

def tupes_to_dict(country_tuples):
    world_dict = {}
    for continent, country in country_tuples:
    # etc
    return world_dict

If you can do that, have a go at applying the same idea to the full
data structure.

-- 
John.

From oltarasenko at gmail.com  Thu Jul 17 05:29:21 2008
From: oltarasenko at gmail.com (Oleg Oltar)
Date: Thu, 17 Jul 2008 06:29:21 +0300
Subject: [Tutor] Unittest
In-Reply-To: <b4fc2ad80807161911y46ce3239v207403c295750c43@mail.gmail.com>
References: <b4fc2ad80807161140w3d1d0fe5q9d15898969ec3dc7@mail.gmail.com>
	<1c2a2c590807161411w5f23a55dmacc8ad9fa56c0f30@mail.gmail.com>
	<1c2a2c590807161814n7048ec5pdede6c9684e10a47@mail.gmail.com>
	<b4fc2ad80807161911y46ce3239v207403c295750c43@mail.gmail.com>
Message-ID: <b4fc2ad80807162029r1bbf3827md3eec2f2eb3f03aa@mail.gmail.com>

Seems need help there. Start getting

Traceback (most recent call last):
  File "./newaccount/Same_domain_name.py", line 56, in
test_create_account_to_check
    print sel.get_text("check_username_block")
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4:
ordinal not in range(128)


when trying to get the text of one of the elements.

How to solve it?

On Thu, Jul 17, 2008 at 5:11 AM, Oleg Oltar <oltarasenko at gmail.com> wrote:

> OK,
>
> I just run the program from terminal. OS: OS X, IDLE = Emacs:).
>
> Yep used the string "# -*- coding: utf-8 -*-" to setup encoding....
>
>
> On Thu, Jul 17, 2008 at 4:14 AM, Kent Johnson <kent37 at tds.net> wrote:
>
>> Another possibility - do you have a coding declaration in your source
>> file, something like
>> # -*- coding: <encoding name> -*-
>>
>> If so, does the coding declaration match the actual encoding of the file?
>>
>> Kent
>>
>> On Wed, Jul 16, 2008 at 5:11 PM, Kent Johnson <kent37 at tds.net> wrote:
>> > On Wed, Jul 16, 2008 at 2:40 PM, Oleg Oltar <oltarasenko at gmail.com>
>> wrote:
>> >> Hi I am using unittest framework with selenium.
>> >>
>> >> When I tried this code (my verification point)
>> >>
>> >>         self.assertEqual(True, sel.is_text_present(u"???????? ?????? ??
>> >> ?????????"), "System didn't give a correct warning about the password
>> >> misstype")
>> >>
>> >>> Where u"???????? ?????? ?? ?????????" is russian = "Sorry passwords
>> aren't
>> >>> equal", and sel.is_text_present - searches text string on the page
>> >>
>> >> The output I get in case of failure was:
>> >>
>> >>
>> >> Traceback (most recent call last):
>> >>
>> >>   File "./newaccount/Password_matching.py", line 50, in
>> >> test_passwordMatching
>> >>     self.assertEqual(True, sel.is_text_present(u"????????????????
>> >> ???????????? ???? ? ????????????????"), "System didn't give a correct
>> >> warning about the password misstype")
>> >>
>> >> AssertionError: System didn't give a correct warning about the password
>> >> misstype
>> >>
>> >> Is there any way to get normal russian text instead of these strange D
>> chars
>> >> "????????...."
>> >
>> > I don't have the solution but maybe I can give you a useful clue. The
>> > D characters are most likely the utf-8 encoding of the Russian text,
>> > when displayed as if it is latin-1. So something in the system is
>> > converting the text to utf-8 and your console probably has latin-1 or
>> > cp1252 encoding.
>> >
>> > Some details might help - how are you running the program - console,
>> > IDLE...? What OS? What are the values of sys.getdefaultencoding() and
>> > sys.stdout.encoding?
>> >
>> > Kent
>> >
>>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080717/76ec9aab/attachment-0001.htm>

From oltarasenko at gmail.com  Thu Jul 17 05:47:29 2008
From: oltarasenko at gmail.com (Oleg Oltar)
Date: Thu, 17 Jul 2008 06:47:29 +0300
Subject: [Tutor] Unittest
In-Reply-To: <b4fc2ad80807162029r1bbf3827md3eec2f2eb3f03aa@mail.gmail.com>
References: <b4fc2ad80807161140w3d1d0fe5q9d15898969ec3dc7@mail.gmail.com>
	<1c2a2c590807161411w5f23a55dmacc8ad9fa56c0f30@mail.gmail.com>
	<1c2a2c590807161814n7048ec5pdede6c9684e10a47@mail.gmail.com>
	<b4fc2ad80807161911y46ce3239v207403c295750c43@mail.gmail.com>
	<b4fc2ad80807162029r1bbf3827md3eec2f2eb3f03aa@mail.gmail.com>
Message-ID: <b4fc2ad80807162047i338faf7ra1253b5dc00c7a1a@mail.gmail.com>

In [1]: import sys

In [2]: sys.getdefaultencoding()
Out[2]: 'ascii'

In [3]: sys.stdout.encoding
Out[3]: 'US-ASCII'

On Thu, Jul 17, 2008 at 6:29 AM, Oleg Oltar <oltarasenko at gmail.com> wrote:

> Seems need help there. Start getting
>
> Traceback (most recent call last):
>   File "./newaccount/Same_domain_name.py", line 56, in
> test_create_account_to_check
>     print sel.get_text("check_username_block")
> UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4:
> ordinal not in range(128)
>
>
> when trying to get the text of one of the elements.
>
> How to solve it?
>
>
> On Thu, Jul 17, 2008 at 5:11 AM, Oleg Oltar <oltarasenko at gmail.com> wrote:
>
>> OK,
>>
>> I just run the program from terminal. OS: OS X, IDLE = Emacs:).
>>
>> Yep used the string "# -*- coding: utf-8 -*-" to setup encoding....
>>
>>
>> On Thu, Jul 17, 2008 at 4:14 AM, Kent Johnson <kent37 at tds.net> wrote:
>>
>>> Another possibility - do you have a coding declaration in your source
>>> file, something like
>>> # -*- coding: <encoding name> -*-
>>>
>>> If so, does the coding declaration match the actual encoding of the file?
>>>
>>> Kent
>>>
>>> On Wed, Jul 16, 2008 at 5:11 PM, Kent Johnson <kent37 at tds.net> wrote:
>>> > On Wed, Jul 16, 2008 at 2:40 PM, Oleg Oltar <oltarasenko at gmail.com>
>>> wrote:
>>> >> Hi I am using unittest framework with selenium.
>>> >>
>>> >> When I tried this code (my verification point)
>>> >>
>>> >>         self.assertEqual(True, sel.is_text_present(u"???????? ??????
>>> ??
>>> >> ?????????"), "System didn't give a correct warning about the password
>>> >> misstype")
>>> >>
>>> >>> Where u"???????? ?????? ?? ?????????" is russian = "Sorry passwords
>>> aren't
>>> >>> equal", and sel.is_text_present - searches text string on the page
>>> >>
>>> >> The output I get in case of failure was:
>>> >>
>>> >>
>>> >> Traceback (most recent call last):
>>> >>
>>> >>   File "./newaccount/Password_matching.py", line 50, in
>>> >> test_passwordMatching
>>> >>     self.assertEqual(True, sel.is_text_present(u"????????????????
>>> >> ???????????? ???? ? ????????????????"), "System didn't give a correct
>>> >> warning about the password misstype")
>>> >>
>>> >> AssertionError: System didn't give a correct warning about the
>>> password
>>> >> misstype
>>> >>
>>> >> Is there any way to get normal russian text instead of these strange D
>>> chars
>>> >> "????????...."
>>> >
>>> > I don't have the solution but maybe I can give you a useful clue. The
>>> > D characters are most likely the utf-8 encoding of the Russian text,
>>> > when displayed as if it is latin-1. So something in the system is
>>> > converting the text to utf-8 and your console probably has latin-1 or
>>> > cp1252 encoding.
>>> >
>>> > Some details might help - how are you running the program - console,
>>> > IDLE...? What OS? What are the values of sys.getdefaultencoding() and
>>> > sys.stdout.encoding?
>>> >
>>> > Kent
>>> >
>>>
>>
>>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080717/43f6c67b/attachment.htm>

From oltarasenko at gmail.com  Thu Jul 17 05:50:38 2008
From: oltarasenko at gmail.com (Oleg Oltar)
Date: Thu, 17 Jul 2008 06:50:38 +0300
Subject: [Tutor] Unittest
In-Reply-To: <b4fc2ad80807162047i338faf7ra1253b5dc00c7a1a@mail.gmail.com>
References: <b4fc2ad80807161140w3d1d0fe5q9d15898969ec3dc7@mail.gmail.com>
	<1c2a2c590807161411w5f23a55dmacc8ad9fa56c0f30@mail.gmail.com>
	<1c2a2c590807161814n7048ec5pdede6c9684e10a47@mail.gmail.com>
	<b4fc2ad80807161911y46ce3239v207403c295750c43@mail.gmail.com>
	<b4fc2ad80807162029r1bbf3827md3eec2f2eb3f03aa@mail.gmail.com>
	<b4fc2ad80807162047i338faf7ra1253b5dc00c7a1a@mail.gmail.com>
Message-ID: <b4fc2ad80807162050s1de6b6aalc86203c7e1fe3df5@mail.gmail.com>

>
> The code

 # -*- coding: utf-8 -*-
#!/usr/bin/python


"""

This test case check how system works in the situation, when user tries to
use already
used username (domain)

We are creating two accounts with such parameters:
1. Sex = Femle
2. Name1=Name2 = foobar%S
3. Pass1 = Name
4. Pass2 = Name
5. Email address1 = Email address2 =  Name at meta.ua


In the test we use verification point - warning message about incorrect
input of domain name and the
sugestion message

"""

from selenium import selenium
import unittest, time, re
import HTMLTestRunner
import config
import Creating_account_basic




class Same_domain_name(unittest.TestCase):

    def setUp(self):
        self.name = "foobar"
        self.email = self.name + "@meta.ua"
        self.verificationErrors = []
        self.selenium = selenium("localhost", 4444,config.browser,
config.link)
        self.selenium.start()

    def test_create_account_to_check(self):
        """Creating sample account for next test"""
        sel = self.selenium
        sel.open("/")
        sel.click(u"link=???????????")
        sel.wait_for_page_to_load("70000")
        sel.click("id_gender_1")
        sel.type("id_first_name", self.name)
        sel.type("id_last_name", self.name)
        sel.type("id_email", self.email)
        sel.type("id_username",  self.name)

#sel.wait_for_condition(sel.is_element_present("check_username_block"),
70000)
        time.sleep(10)
        print "!!!", sel.is_element_present("check_username_block")
        sel.type("id_password",  self.name)
        print sel.get_text("check_username_block").decode('cp-1252')
        sel.type("id_password2", self.name)
        sel.click(u"//input[@value='??????????????????']")
        sel.wait_for_page_to_load("70000")
        if config.debugMode is True:
            time.sleep(5)


    def tearDown(self):
        self.selenium.stop()
        print self.verificationErrors
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":

    unittest.main()
    #HTMLTestRunner.main()



On Thu, Jul 17, 2008 at 6:47 AM, Oleg Oltar <oltarasenko at gmail.com> wrote:

> In [1]: import sys
>
> In [2]: sys.getdefaultencoding()
> Out[2]: 'ascii'
>
> In [3]: sys.stdout.encoding
> Out[3]: 'US-ASCII'
>
>
> On Thu, Jul 17, 2008 at 6:29 AM, Oleg Oltar <oltarasenko at gmail.com> wrote:
>
>> Seems need help there. Start getting
>>
>> Traceback (most recent call last):
>>   File "./newaccount/Same_domain_name.py", line 56, in
>> test_create_account_to_check
>>     print sel.get_text("check_username_block")
>> UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4:
>> ordinal not in range(128)
>>
>>
>> when trying to get the text of one of the elements.
>>
>> How to solve it?
>>
>>
>> On Thu, Jul 17, 2008 at 5:11 AM, Oleg Oltar <oltarasenko at gmail.com>
>> wrote:
>>
>>> OK,
>>>
>>> I just run the program from terminal. OS: OS X, IDLE = Emacs:).
>>>
>>> Yep used the string "# -*- coding: utf-8 -*-" to setup encoding....
>>>
>>>
>>> On Thu, Jul 17, 2008 at 4:14 AM, Kent Johnson <kent37 at tds.net> wrote:
>>>
>>>> Another possibility - do you have a coding declaration in your source
>>>> file, something like
>>>> # -*- coding: <encoding name> -*-
>>>>
>>>> If so, does the coding declaration match the actual encoding of the
>>>> file?
>>>>
>>>> Kent
>>>>
>>>> On Wed, Jul 16, 2008 at 5:11 PM, Kent Johnson <kent37 at tds.net> wrote:
>>>> > On Wed, Jul 16, 2008 at 2:40 PM, Oleg Oltar <oltarasenko at gmail.com>
>>>> wrote:
>>>> >> Hi I am using unittest framework with selenium.
>>>> >>
>>>> >> When I tried this code (my verification point)
>>>> >>
>>>> >>         self.assertEqual(True, sel.is_text_present(u"???????? ??????
>>>> ??
>>>> >> ?????????"), "System didn't give a correct warning about the password
>>>> >> misstype")
>>>> >>
>>>> >>> Where u"???????? ?????? ?? ?????????" is russian = "Sorry passwords
>>>> aren't
>>>> >>> equal", and sel.is_text_present - searches text string on the page
>>>> >>
>>>> >> The output I get in case of failure was:
>>>> >>
>>>> >>
>>>> >> Traceback (most recent call last):
>>>> >>
>>>> >>   File "./newaccount/Password_matching.py", line 50, in
>>>> >> test_passwordMatching
>>>> >>     self.assertEqual(True, sel.is_text_present(u"????????????????
>>>> >> ???????????? ???? ? ????????????????"), "System didn't give a correct
>>>> >> warning about the password misstype")
>>>> >>
>>>> >> AssertionError: System didn't give a correct warning about the
>>>> password
>>>> >> misstype
>>>> >>
>>>> >> Is there any way to get normal russian text instead of these strange
>>>> D chars
>>>> >> "????????...."
>>>> >
>>>> > I don't have the solution but maybe I can give you a useful clue. The
>>>> > D characters are most likely the utf-8 encoding of the Russian text,
>>>> > when displayed as if it is latin-1. So something in the system is
>>>> > converting the text to utf-8 and your console probably has latin-1 or
>>>> > cp1252 encoding.
>>>> >
>>>> > Some details might help - how are you running the program - console,
>>>> > IDLE...? What OS? What are the values of sys.getdefaultencoding() and
>>>> > sys.stdout.encoding?
>>>> >
>>>> > Kent
>>>> >
>>>>
>>>
>>>
>>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080717/ad3aa990/attachment-0001.htm>

From Joel.Levine at Dartmouth.EDU  Thu Jul 17 05:55:58 2008
From: Joel.Levine at Dartmouth.EDU (Joel Levine)
Date: 16 Jul 2008 23:55:58 -0400
Subject: [Tutor] saving postscript graphics
Message-ID: <108759483@newdancer.Dartmouth.EDU>

I am trying to save a Tkinter canvas to a postscript file. 

This script creates an image on screen and it creates a postscript file.  But the image in the file seems to be trashed.  

I'm working on OSX, but similar problems in a larger program failed (same way) in unix.

JL

------------
#DwV_plot000A.py
#drive postscript bug

from Tkinter import *

#Put some stuff on the canvas (from Lutz' Introduction):

canvas=Canvas(width=300, height=300, bg='white')  #0,0 is top left corner
canvas.pack(expand=YES, fill=BOTH)              #increase down, right

canvas.create_line(100,100,200,200)             #fromX, fromY, toX, toY
canvas.create_line(100,200,200,300)             # draw shapes
for i in range(1, 20, 2):
    canvas.create_line(0, i, 50, i)

canvas.create_oval(10,10,200,200, width=2, fill='blue')
widget=Label(canvas, text='Spam', fg='white', bg='black')

#Save it to a postscript file.
# (It saves something, but the format appears to be in error.
canvas.postscript(file='plot001.ps',colormode='color')

mainloop()    

From metolone+gmane at gmail.com  Thu Jul 17 07:13:14 2008
From: metolone+gmane at gmail.com (Mark Tolonen)
Date: Wed, 16 Jul 2008 22:13:14 -0700
Subject: [Tutor] Unittest
References: <b4fc2ad80807161140w3d1d0fe5q9d15898969ec3dc7@mail.gmail.com><1c2a2c590807161411w5f23a55dmacc8ad9fa56c0f30@mail.gmail.com><1c2a2c590807161814n7048ec5pdede6c9684e10a47@mail.gmail.com><b4fc2ad80807161911y46ce3239v207403c295750c43@mail.gmail.com><b4fc2ad80807162029r1bbf3827md3eec2f2eb3f03aa@mail.gmail.com><b4fc2ad80807162047i338faf7ra1253b5dc00c7a1a@mail.gmail.com>
	<b4fc2ad80807162050s1de6b6aalc86203c7e1fe3df5@mail.gmail.com>
Message-ID: <g5mkd5$ont$1@ger.gmane.org>

The Exception is output in the encoding of the source file.  If the terminal you are displaying the exception on is in a different encoding, it will be garbled.  I'm not familiar with OS X's terminal.  Try running python and printing sys.stdout.encoding.

Alternatively, wrap your code in a try/except handler and translate the exception yourself.

    # coding: utf-8
    import traceback
    try:
        raise Exception(u'??????????????????')
    except Exception,e:
        print traceback.format_exc().decode('utf-8')

The last line translates the utf-8 traceback into Unicode.  Printing Unicode will encode the output with the terminal's decoding.  If there are characters it can't display, you'll still get an error, though.  You can be more explicit however:

    print traceback.format_exc().decode('utf-8').encode('cp437','replace')

In this case you'll get ? whenever a character can't be represented in the selected encoding.  cp437, for example, can't display any russian characters, so for me (on Windows) I just get all ???????????.  When I tried it with a character string that could be displayed in cp437, it worked fine:

    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "t4.py", line 4, in <module>
        raise Exception('M???????')
    Exception: M???????

Another option is to redirect the output to a file and read the file with an editor that can display utf-8 (such as Notepad on Windows).

    python testfile.py 2>error.txt          # this redirects stderr to a file.

Hope that helps,
Mark
  "Oleg Oltar" <oltarasenko at gmail.com> wrote in message news:b4fc2ad80807162050s1de6b6aalc86203c7e1fe3df5 at mail.gmail.com...
    The code
   # -*- coding: utf-8 -*-
  #!/usr/bin/python


  """

  This test case check how system works in the situation, when user tries to use already
  used username (domain)

  We are creating two accounts with such parameters:
  1. Sex = Femle
  2. Name1=Name2 = foobar%S 
  3. Pass1 = Name
  4. Pass2 = Name
  5. Email address1 = Email address2 =  Name at meta.ua 


  In the test we use verification point - warning message about incorrect input of domain name and the
  sugestion message

  """

  from selenium import selenium
  import unittest, time, re
  import HTMLTestRunner
  import config
  import Creating_account_basic




  class Same_domain_name(unittest.TestCase):
      
      def setUp(self):        
          self.name = "foobar"
          self.email = self.name + "@meta.ua" 
          self.verificationErrors = []
          self.selenium = selenium("localhost", 4444,config.browser, config.link)
          self.selenium.start()

      def test_create_account_to_check(self):  
          """Creating sample account for next test"""
          sel = self.selenium
          sel.open("/")
          sel.click(u"link=???????????")
          sel.wait_for_page_to_load("70000")
          sel.click("id_gender_1")
          sel.type("id_first_name", self.name)
          sel.type("id_last_name", self.name)
          sel.type("id_email", self.email)
          sel.type("id_username",  self.name)
          #sel.wait_for_condition(sel.is_element_present("check_username_block"), 70000)
          time.sleep(10)
          print "!!!", sel.is_element_present("check_username_block")
          sel.type("id_password",  self.name)
          print sel.get_text("check_username_block").decode('cp-1252')
          sel.type("id_password2", self.name)
          sel.click(u"//input[@value='??????????????????']")
          sel.wait_for_page_to_load("70000")
          if config.debugMode is True:
              time.sleep(5)


      def tearDown(self):
          self.selenium.stop()
          print self.verificationErrors
          self.assertEqual([], self.verificationErrors)

  if __name__ == "__main__":
      
      unittest.main()
      #HTMLTestRunner.main()
   




  On Thu, Jul 17, 2008 at 6:47 AM, Oleg Oltar <oltarasenko at gmail.com> wrote:

    In [1]: import sys

    In [2]: sys.getdefaultencoding()
    Out[2]: 'ascii'

    In [3]: sys.stdout.encoding
    Out[3]: 'US-ASCII'



    On Thu, Jul 17, 2008 at 6:29 AM, Oleg Oltar <oltarasenko at gmail.com> wrote:

      Seems need help there. Start getting


      Traceback (most recent call last):

        File "./newaccount/Same_domain_name.py", line 56, in test_create_account_to_check
          print sel.get_text("check_username_block")
      UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128)


      when trying to get the text of one of the elements. 

      How to solve it?



      On Thu, Jul 17, 2008 at 5:11 AM, Oleg Oltar <oltarasenko at gmail.com> wrote:

        OK,

        I just run the program from terminal. OS: OS X, IDLE = Emacs:).

        Yep used the string "# -*- coding: utf-8 -*-" to setup encoding....



        On Thu, Jul 17, 2008 at 4:14 AM, Kent Johnson <kent37 at tds.net> wrote:

          Another possibility - do you have a coding declaration in your source
          file, something like
          # -*- coding: <encoding name> -*-

          If so, does the coding declaration match the actual encoding of the file?

          Kent


          On Wed, Jul 16, 2008 at 5:11 PM, Kent Johnson <kent37 at tds.net> wrote:
          > On Wed, Jul 16, 2008 at 2:40 PM, Oleg Oltar <oltarasenko at gmail.com> wrote:
          >> Hi I am using unittest framework with selenium.
          >>
          >> When I tried this code (my verification point)
          >>
          >>         self.assertEqual(True, sel.is_text_present(u"???????? ?????? ??
          >> ?????????"), "System didn't give a correct warning about the password
          >> misstype")
          >>
          >>> Where u"???????? ?????? ?? ?????????" is russian = "Sorry passwords aren't
          >>> equal", and sel.is_text_present - searches text string on the page
          >>
          >> The output I get in case of failure was:
          >>
          >>
          >> Traceback (most recent call last):
          >>
          >>   File "./newaccount/Password_matching.py", line 50, in
          >> test_passwordMatching
          >>     self.assertEqual(True, sel.is_text_present(u"????????????????
          >> ???????????? ???? ? ????????????????"), "System didn't give a correct
          >> warning about the password misstype")
          >>
          >> AssertionError: System didn't give a correct warning about the password
          >> misstype
          >>
          >> Is there any way to get normal russian text instead of these strange D chars
          >> "????????...."
          >
          > I don't have the solution but maybe I can give you a useful clue. The
          > D characters are most likely the utf-8 encoding of the Russian text,
          > when displayed as if it is latin-1. So something in the system is
          > converting the text to utf-8 and your console probably has latin-1 or
          > cp1252 encoding.
          >
          > Some details might help - how are you running the program - console,
          > IDLE...? What OS? What are the values of sys.getdefaultencoding() and
          > sys.stdout.encoding?
          >
          > Kent
          >











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


  _______________________________________________
  Tutor maillist  -  Tutor at python.org
  http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080716/61f38856/attachment.htm>

From oltarasenko at gmail.com  Thu Jul 17 08:33:59 2008
From: oltarasenko at gmail.com (Oleg Oltar)
Date: Thu, 17 Jul 2008 09:33:59 +0300
Subject: [Tutor] Unittest
In-Reply-To: <b4fc2ad80807162330g9b93bfeq1e55af9b3ed97400@mail.gmail.com>
References: <b4fc2ad80807161140w3d1d0fe5q9d15898969ec3dc7@mail.gmail.com>
	<1c2a2c590807161411w5f23a55dmacc8ad9fa56c0f30@mail.gmail.com>
	<1c2a2c590807161814n7048ec5pdede6c9684e10a47@mail.gmail.com>
	<b4fc2ad80807161911y46ce3239v207403c295750c43@mail.gmail.com>
	<b4fc2ad80807162029r1bbf3827md3eec2f2eb3f03aa@mail.gmail.com>
	<b4fc2ad80807162047i338faf7ra1253b5dc00c7a1a@mail.gmail.com>
	<b4fc2ad80807162050s1de6b6aalc86203c7e1fe3df5@mail.gmail.com>
	<g5mkd5$ont$1@ger.gmane.org>
	<b4fc2ad80807162330g9b93bfeq1e55af9b3ed97400@mail.gmail.com>
Message-ID: <b4fc2ad80807162333k6badc3d3of87f402003a3a00a@mail.gmail.com>

And in case:
# coding: utf-8

import traceback
try:
    raise Exception(u'?????????')
except Exception,e:
    print traceback.format_exc().decode('utf-8').encode('cp437', 'replace')


Getting

beryl:~ oleg$ python ./wish/newaccount/reg.py
Traceback (most recent call last):
  File "./wish/newaccount/reg.py", line 5, in <module>
    raise Exception(u'?????????')
Exception: <unprintable Exception object>



My console settings:

In [1]: import sys

In [2]: sys.getdefaultencoding()
Out[2]: 'ascii'

In [3]: sys.stdout.encoding
Out[3]: 'US-ASCII'


On Thu, Jul 17, 2008 at 9:30 AM, Oleg Oltar <oltarasenko at gmail.com> wrote:

> OK
> the output:
>
> # coding: utf-8
>>
>> import traceback
>> try:
>>     raise Exception(u'?????????')
>> except Exception,e:
>>     print traceback.format_exc().decode('utf-8')
>>
>
>
> >>> Traceback (most recent call last):
>   File "/var/folders/PC/PCtFE4gQGiqpQymiAScfnk+++TM/-Tmp-/py46506ECT", line
> 7, in <module>
>     print traceback.format_exc().decode('utf-8')
> UnicodeEncodeError: 'ascii' codec can't encode characters in position
> 148-156: ordinal not in range(128)
>
>
>
>
> On Thu, Jul 17, 2008 at 8:13 AM, Mark Tolonen <metolone+gmane at gmail.com<metolone%2Bgmane at gmail.com>>
> wrote:
>
>>  The Exception is output in the encoding of the source file.  If the
>> terminal you are displaying the exception on is in a different encoding, it
>> will be garbled.  I'm not familiar with OS X's terminal.  Try running python
>> and printing sys.stdout.encoding.
>>
>> Alternatively, wrap your code in a try/except handler and translate the
>> exception yourself.
>>
>>     # coding: utf-8
>>     import traceback
>>     try:
>>         raise Exception(u'??????????????????')
>>     except Exception,e:
>>         print traceback.format_exc().decode('utf-8')
>>
>> The last line translates the utf-8 traceback into Unicode.  Printing
>> Unicode will encode the output with the terminal's decoding.  If there are
>> characters it can't display, you'll still get an error, though.  You can be
>> more explicit however:
>>
>>     print traceback.format_exc().decode('utf-8').encode('cp437','replace')
>>
>> In this case you'll get ? whenever a character can't be represented in the
>> selected encoding.  cp437, for example, can't display any russian
>> characters, so for me (on Windows) I just get all ???????????.  When I tried
>> it with a character string that could be displayed in cp437, it worked fine:
>>
>>     Traceback (most recent call last):
>>       File "<stdin>", line 1, in <module>
>>       File "t4.py", line 4, in <module>
>>         raise Exception('M???????')
>>     Exception: M???????
>>
>> Another option is to redirect the output to a file and read the file with
>> an editor that can display utf-8 (such as Notepad on Windows).
>>
>>     python testfile.py 2>error.txt          # this redirects stderr to a
>> file.
>>
>> Hope that helps,
>> Mark
>>
>> "Oleg Oltar" <oltarasenko at gmail.com> wrote in message
>> news:b4fc2ad80807162050s1de6b6aalc86203c7e1fe3df5 at mail.gmail.com...
>>
>>> The code
>>
>>  # -*- coding: utf-8 -*-
>> #!/usr/bin/python
>>
>>
>> """
>>
>> This test case check how system works in the situation, when user tries to
>> use already
>> used username (domain)
>>
>> We are creating two accounts with such parameters:
>> 1. Sex = Femle
>> 2. Name1=Name2 = foobar%S
>> 3. Pass1 = Name
>> 4. Pass2 = Name
>> 5. Email address1 = Email address2 =  Name at meta.ua
>>
>>
>> In the test we use verification point - warning message about incorrect
>> input of domain name and the
>> sugestion message
>>
>> """
>>
>> from selenium import selenium
>> import unittest, time, re
>> import HTMLTestRunner
>> import config
>> import Creating_account_basic
>>
>>
>>
>>
>> class Same_domain_name(unittest.TestCase):
>>
>>     def setUp(self):
>>         self.name = "foobar"
>>         self.email = self.name + "@meta.ua"
>>         self.verificationErrors = []
>>         self.selenium = selenium("localhost", 4444,config.browser,
>> config.link)
>>         self.selenium.start()
>>
>>     def test_create_account_to_check(self):
>>         """Creating sample account for next test"""
>>         sel = self.selenium
>>         sel.open("/")
>>         sel.click(u"link=???????????")
>>         sel.wait_for_page_to_load("70000")
>>         sel.click("id_gender_1")
>>         sel.type("id_first_name", self.name)
>>         sel.type("id_last_name", self.name)
>>         sel.type("id_email", self.email)
>>         sel.type("id_username",  self.name)
>>
>> #sel.wait_for_condition(sel.is_element_present("check_username_block"),
>> 70000)
>>         time.sleep(10)
>>         print "!!!", sel.is_element_present("check_username_block")
>>         sel.type("id_password",  self.name)
>>         print sel.get_text("check_username_block").decode('cp-1252')
>>         sel.type("id_password2", self.name)
>>         sel.click(u"//input[@value='??????????????????']")
>>         sel.wait_for_page_to_load("70000")
>>         if config.debugMode is True:
>>             time.sleep(5)
>>
>>
>>     def tearDown(self):
>>         self.selenium.stop()
>>         print self.verificationErrors
>>         self.assertEqual([], self.verificationErrors)
>>
>> if __name__ == "__main__":
>>
>>     unittest.main()
>>     #HTMLTestRunner.main()
>>
>>
>>
>> On Thu, Jul 17, 2008 at 6:47 AM, Oleg Oltar <oltarasenko at gmail.com>
>> wrote:
>>
>>> In [1]: import sys
>>>
>>> In [2]: sys.getdefaultencoding()
>>> Out[2]: 'ascii'
>>>
>>> In [3]: sys.stdout.encoding
>>> Out[3]: 'US-ASCII'
>>>
>>>
>>> On Thu, Jul 17, 2008 at 6:29 AM, Oleg Oltar <oltarasenko at gmail.com>
>>> wrote:
>>>
>>>> Seems need help there. Start getting
>>>>
>>>> Traceback (most recent call last):
>>>>   File "./newaccount/Same_domain_name.py", line 56, in
>>>> test_create_account_to_check
>>>>     print sel.get_text("check_username_block")
>>>> UnicodeEncodeError: 'ascii' codec can't encode characters in position
>>>> 0-4: ordinal not in range(128)
>>>>
>>>>
>>>> when trying to get the text of one of the elements.
>>>>
>>>> How to solve it?
>>>>
>>>>
>>>> On Thu, Jul 17, 2008 at 5:11 AM, Oleg Oltar <oltarasenko at gmail.com>
>>>> wrote:
>>>>
>>>>> OK,
>>>>>
>>>>> I just run the program from terminal. OS: OS X, IDLE = Emacs:).
>>>>>
>>>>> Yep used the string "# -*- coding: utf-8 -*-" to setup encoding....
>>>>>
>>>>>
>>>>> On Thu, Jul 17, 2008 at 4:14 AM, Kent Johnson <kent37 at tds.net> wrote:
>>>>>
>>>>>> Another possibility - do you have a coding declaration in your source
>>>>>> file, something like
>>>>>> # -*- coding: <encoding name> -*-
>>>>>>
>>>>>> If so, does the coding declaration match the actual encoding of the
>>>>>> file?
>>>>>>
>>>>>> Kent
>>>>>>
>>>>>> On Wed, Jul 16, 2008 at 5:11 PM, Kent Johnson <kent37 at tds.net> wrote:
>>>>>> > On Wed, Jul 16, 2008 at 2:40 PM, Oleg Oltar <oltarasenko at gmail.com>
>>>>>> wrote:
>>>>>> >> Hi I am using unittest framework with selenium.
>>>>>> >>
>>>>>> >> When I tried this code (my verification point)
>>>>>> >>
>>>>>> >>         self.assertEqual(True, sel.is_text_present(u"????????
>>>>>> ?????? ??
>>>>>> >> ?????????"), "System didn't give a correct warning about the
>>>>>> password
>>>>>> >> misstype")
>>>>>> >>
>>>>>> >>> Where u"???????? ?????? ?? ?????????" is russian = "Sorry
>>>>>> passwords aren't
>>>>>> >>> equal", and sel.is_text_present - searches text string on the page
>>>>>> >>
>>>>>> >> The output I get in case of failure was:
>>>>>> >>
>>>>>> >>
>>>>>> >> Traceback (most recent call last):
>>>>>> >>
>>>>>> >>   File "./newaccount/Password_matching.py", line 50, in
>>>>>> >> test_passwordMatching
>>>>>> >>     self.assertEqual(True, sel.is_text_present(u"????????????????
>>>>>> >> ???????????? ???? ? ????????????????"), "System didn't give a
>>>>>> correct
>>>>>> >> warning about the password misstype")
>>>>>> >>
>>>>>> >> AssertionError: System didn't give a correct warning about the
>>>>>> password
>>>>>> >> misstype
>>>>>> >>
>>>>>> >> Is there any way to get normal russian text instead of these
>>>>>> strange D chars
>>>>>> >> "????????...."
>>>>>> >
>>>>>> > I don't have the solution but maybe I can give you a useful clue.
>>>>>> The
>>>>>> > D characters are most likely the utf-8 encoding of the Russian text,
>>>>>> > when displayed as if it is latin-1. So something in the system is
>>>>>> > converting the text to utf-8 and your console probably has latin-1
>>>>>> or
>>>>>> > cp1252 encoding.
>>>>>> >
>>>>>> > Some details might help - how are you running the program - console,
>>>>>> > IDLE...? What OS? What are the values of sys.getdefaultencoding()
>>>>>> and
>>>>>> > sys.stdout.encoding?
>>>>>> >
>>>>>> > Kent
>>>>>> >
>>>>>>
>>>>>
>>>>>
>>>>
>>>
>>  ------------------------------
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080717/f9e91d0f/attachment-0001.htm>

From metolone+gmane at gmail.com  Thu Jul 17 08:55:26 2008
From: metolone+gmane at gmail.com (Mark Tolonen)
Date: Wed, 16 Jul 2008 23:55:26 -0700
Subject: [Tutor] Unittest
References: <b4fc2ad80807161140w3d1d0fe5q9d15898969ec3dc7@mail.gmail.com><1c2a2c590807161411w5f23a55dmacc8ad9fa56c0f30@mail.gmail.com><1c2a2c590807161814n7048ec5pdede6c9684e10a47@mail.gmail.com><b4fc2ad80807161911y46ce3239v207403c295750c43@mail.gmail.com><b4fc2ad80807162029r1bbf3827md3eec2f2eb3f03aa@mail.gmail.com><b4fc2ad80807162047i338faf7ra1253b5dc00c7a1a@mail.gmail.com><b4fc2ad80807162050s1de6b6aalc86203c7e1fe3df5@mail.gmail.com><g5mkd5$ont$1@ger.gmane.org><b4fc2ad80807162330g9b93bfeq1e55af9b3ed97400@mail.gmail.com>
	<b4fc2ad80807162333k6badc3d3of87f402003a3a00a@mail.gmail.com>
Message-ID: <g5mqcp$6qj$1@ger.gmane.org>

OK, your console is set to 'ascii' ('cp437' was my example and is the
Windows console encoding).  'ascii' won't be able to display Russian.
It shouldn't have displayed the "?????????????" characters either.
Are you still running on the same terminal that display those
characters?  Can you change your terminals encoding preference via an
environment variable?
--
Mark
  "Oleg Oltar" <oltarasenko at gmail.com> wrote in message news:b4fc2ad80807162333k6badc3d3of87f402003a3a00a at mail.gmail.com...

  And in case:
  # coding: utf-8


    import traceback 
    try:
        raise Exception(u'?????????')
    except Exception,e:
        print traceback.format_exc().decode('utf-8').encode('cp437', 'replace')


  Getting

  beryl:~ oleg$ python ./wish/newaccount/reg.py
  Traceback (most recent call last):
    File "./wish/newaccount/reg.py", line 5, in <module>
      raise Exception(u'?????????')
  Exception: <unprintable Exception object>



  My console settings:

  In [1]: import sys

  In [2]: sys.getdefaultencoding()
  Out[2]: 'ascii'

  In [3]: sys.stdout.encoding
  Out[3]: 'US-ASCII'



  On Thu, Jul 17, 2008 at 9:30 AM, Oleg Oltar <oltarasenko at gmail.com> wrote:

    OK
    the output:


      # coding: utf-8

      import traceback 
      try:

          raise Exception(u'?????????')

      except Exception,e:
          print traceback.format_exc().decode('utf-8')



    >>> Traceback (most recent call last):

      File "/var/folders/PC/PCtFE4gQGiqpQymiAScfnk+++TM/-Tmp-/py46506ECT", line 7, in <module>

        print traceback.format_exc().decode('utf-8')

    UnicodeEncodeError: 'ascii' codec can't encode characters in position 148-156: ordinal not in range(128) 






    On Thu, Jul 17, 2008 at 8:13 AM, Mark Tolonen <metolone+gmane at gmail.com> wrote:

      The Exception is output in the encoding of the source file.  If the terminal you are displaying the exception on is in a different encoding, it will be garbled.  I'm not familiar with OS X's terminal.  Try running python and printing sys.stdout.encoding.

      Alternatively, wrap your code in a try/except handler and translate the exception yourself.

          # coding: utf-8
          import traceback
          try:
              raise Exception(u'??????????????????')
          except Exception,e:
              print traceback.format_exc().decode('utf-8')

      The last line translates the utf-8 traceback into Unicode.  Printing Unicode will encode the output with the terminal's decoding.  If there are characters it can't display, you'll still get an error, though.  You can be more explicit however:

          print traceback.format_exc().decode('utf-8').encode('cp437','replace')

      In this case you'll get ? whenever a character can't be represented in the selected encoding.  cp437, for example, can't display any russian characters, so for me (on Windows) I just get all ???????????.  When I tried it with a character string that could be displayed in cp437, it worked fine:

          Traceback (most recent call last):

            File "<stdin>", line 1, in <module>
            File "t4.py", line 4, in <module>
              raise Exception('M???????')
          Exception: M???????

      Another option is to redirect the output to a file and read the file with an editor that can display utf-8 (such as Notepad on Windows).

          python testfile.py 2>error.txt          # this redirects stderr to a file.

      Hope that helps,
      Mark
        "Oleg Oltar" <oltarasenko at gmail.com> wrote in message news:b4fc2ad80807162050s1de6b6aalc86203c7e1fe3df5 at mail.gmail.com...
          The code
         # -*- coding: utf-8 -*-
        #!/usr/bin/python


        """

        This test case check how system works in the situation, when user tries to use already
        used username (domain)

        We are creating two accounts with such parameters:
        1. Sex = Femle
        2. Name1=Name2 = foobar%S 
        3. Pass1 = Name
        4. Pass2 = Name
        5. Email address1 = Email address2 =  Name at meta.ua 


        In the test we use verification point - warning message about incorrect input of domain name and the
        sugestion message

        """

        from selenium import selenium
        import unittest, time, re
        import HTMLTestRunner
        import config
        import Creating_account_basic




        class Same_domain_name(unittest.TestCase):
            
            def setUp(self):        
                self.name = "foobar"
                self.email = self.name + "@meta.ua" 
                self.verificationErrors = []
                self.selenium = selenium("localhost", 4444,config.browser, config.link)
                self.selenium.start()

            def test_create_account_to_check(self):  
                """Creating sample account for next test"""
                sel = self.selenium
                sel.open("/")
                sel.click(u"link=???????????")
                sel.wait_for_page_to_load("70000")
                sel.click("id_gender_1")
                sel.type("id_first_name", self.name)
                sel.type("id_last_name", self.name)
                sel.type("id_email", self.email)
                sel.type("id_username",  self.name)
                #sel.wait_for_condition(sel.is_element_present("check_username_block"), 70000)
                time.sleep(10)
                print "!!!", sel.is_element_present("check_username_block")
                sel.type("id_password",  self.name)
                print sel.get_text("check_username_block").decode('cp-1252')
                sel.type("id_password2", self.name)
                sel.click(u"//input[@value='??????????????????']")
                sel.wait_for_page_to_load("70000")
                if config.debugMode is True:
                    time.sleep(5)


            def tearDown(self):
                self.selenium.stop()
                print self.verificationErrors
                self.assertEqual([], self.verificationErrors)

        if __name__ == "__main__":
            
            unittest.main()
            #HTMLTestRunner.main()
         




        On Thu, Jul 17, 2008 at 6:47 AM, Oleg Oltar <oltarasenko at gmail.com> wrote:

          In [1]: import sys

          In [2]: sys.getdefaultencoding()
          Out[2]: 'ascii'

          In [3]: sys.stdout.encoding
          Out[3]: 'US-ASCII' 



          On Thu, Jul 17, 2008 at 6:29 AM, Oleg Oltar <oltarasenko at gmail.com> wrote:

            Seems need help there. Start getting 


            Traceback (most recent call last):

              File "./newaccount/Same_domain_name.py", line 56, in test_create_account_to_check
                print sel.get_text("check_username_block")
            UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128)


            when trying to get the text of one of the elements. 

            How to solve it? 



            On Thu, Jul 17, 2008 at 5:11 AM, Oleg Oltar <oltarasenko at gmail.com> wrote:

              OK,

              I just run the program from terminal. OS: OS X, IDLE = Emacs:).

              Yep used the string "# -*- coding: utf-8 -*-" to setup encoding.... 



              On Thu, Jul 17, 2008 at 4:14 AM, Kent Johnson <kent37 at tds.net> wrote:

                Another possibility - do you have a coding declaration in your source
                file, something like
                # -*- coding: <encoding name> -*-

                If so, does the coding declaration match the actual encoding of the file?

                Kent


                On Wed, Jul 16, 2008 at 5:11 PM, Kent Johnson <kent37 at tds.net> wrote:
                > On Wed, Jul 16, 2008 at 2:40 PM, Oleg Oltar <oltarasenko at gmail.com> wrote:
                >> Hi I am using unittest framework with selenium.
                >>
                >> When I tried this code (my verification point)
                >>
                >>         self.assertEqual(True, sel.is_text_present(u"???????? ?????? ??
                >> ?????????"), "System didn't give a correct warning about the password
                >> misstype")
                >>
                >>> Where u"???????? ?????? ?? ?????????" is russian = "Sorry passwords aren't
                >>> equal", and sel.is_text_present - searches text string on the page
                >>
                >> The output I get in case of failure was:
                >>
                >>
                >> Traceback (most recent call last):
                >>
                >>   File "./newaccount/Password_matching.py", line 50, in
                >> test_passwordMatching
                >>     self.assertEqual(True, sel.is_text_present(u"????????????????
                >> ???????????? ???? ? ????????????????"), "System didn't give a correct
                >> warning about the password misstype")
                >>
                >> AssertionError: System didn't give a correct warning about the password
                >> misstype
                >>
                >> Is there any way to get normal russian text instead of these strange D chars
                >> "????????...."
                >
                > I don't have the solution but maybe I can give you a useful clue. The
                > D characters are most likely the utf-8 encoding of the Russian text,
                > when displayed as if it is latin-1. So something in the system is
                > converting the text to utf-8 and your console probably has latin-1 or
                > cp1252 encoding.
                >
                > Some details might help - how are you running the program - console,
                > IDLE...? What OS? What are the values of sys.getdefaultencoding() and
                > sys.stdout.encoding?
                >
                > Kent
                >











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


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


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








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


  _______________________________________________
  Tutor maillist  -  Tutor at python.org
  http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080716/a5c9fecb/attachment-0001.htm>

From oltarasenko at gmail.com  Thu Jul 17 08:57:36 2008
From: oltarasenko at gmail.com (Oleg Oltar)
Date: Thu, 17 Jul 2008 09:57:36 +0300
Subject: [Tutor] Unittest
In-Reply-To: <b4fc2ad80807162333k6badc3d3of87f402003a3a00a@mail.gmail.com>
References: <b4fc2ad80807161140w3d1d0fe5q9d15898969ec3dc7@mail.gmail.com>
	<1c2a2c590807161411w5f23a55dmacc8ad9fa56c0f30@mail.gmail.com>
	<1c2a2c590807161814n7048ec5pdede6c9684e10a47@mail.gmail.com>
	<b4fc2ad80807161911y46ce3239v207403c295750c43@mail.gmail.com>
	<b4fc2ad80807162029r1bbf3827md3eec2f2eb3f03aa@mail.gmail.com>
	<b4fc2ad80807162047i338faf7ra1253b5dc00c7a1a@mail.gmail.com>
	<b4fc2ad80807162050s1de6b6aalc86203c7e1fe3df5@mail.gmail.com>
	<g5mkd5$ont$1@ger.gmane.org>
	<b4fc2ad80807162330g9b93bfeq1e55af9b3ed97400@mail.gmail.com>
	<b4fc2ad80807162333k6badc3d3of87f402003a3a00a@mail.gmail.com>
Message-ID: <b4fc2ad80807162357o5b97e2f1n56ae3306d66d050@mail.gmail.com>

Ok, seems it's my console setting. Tried console with koi8-r (from
http://vak.ru/doku.php/macosx-russian), and it looks ok there. Mean the
satndard output, but still getting "D" chars instead of russian when trying
to convert it to html via HTMLTestRunner (see
http://tungwaiyip.info/software/HTMLTestRunner.html)

On Thu, Jul 17, 2008 at 9:33 AM, Oleg Oltar <oltarasenko at gmail.com> wrote:

>
> And in case:
> # coding: utf-8
>
> import traceback
> try:
>     raise Exception(u'?????????')
> except Exception,e:
>     print traceback.format_exc().decode('utf-8').encode('cp437', 'replace')
>
>
> Getting
>
> beryl:~ oleg$ python ./wish/newaccount/reg.py
> Traceback (most recent call last):
>   File "./wish/newaccount/reg.py", line 5, in <module>
>     raise Exception(u'?????????')
> Exception: <unprintable Exception object>
>
>
>
> My console settings:
>
> In [1]: import sys
>
> In [2]: sys.getdefaultencoding()
> Out[2]: 'ascii'
>
> In [3]: sys.stdout.encoding
> Out[3]: 'US-ASCII'
>
>
> On Thu, Jul 17, 2008 at 9:30 AM, Oleg Oltar <oltarasenko at gmail.com> wrote:
>
>> OK
>> the output:
>>
>> # coding: utf-8
>>>
>>> import traceback
>>> try:
>>>     raise Exception(u'?????????')
>>> except Exception,e:
>>>     print traceback.format_exc().decode('utf-8')
>>>
>>
>>
>> >>> Traceback (most recent call last):
>>   File "/var/folders/PC/PCtFE4gQGiqpQymiAScfnk+++TM/-Tmp-/py46506ECT",
>> line 7, in <module>
>>     print traceback.format_exc().decode('utf-8')
>> UnicodeEncodeError: 'ascii' codec can't encode characters in position
>> 148-156: ordinal not in range(128)
>>
>>
>>
>>
>> On Thu, Jul 17, 2008 at 8:13 AM, Mark Tolonen <metolone+gmane at gmail.com<metolone%2Bgmane at gmail.com>>
>> wrote:
>>
>>>  The Exception is output in the encoding of the source file.  If the
>>> terminal you are displaying the exception on is in a different encoding, it
>>> will be garbled.  I'm not familiar with OS X's terminal.  Try running python
>>> and printing sys.stdout.encoding.
>>>
>>> Alternatively, wrap your code in a try/except handler and translate the
>>> exception yourself.
>>>
>>>     # coding: utf-8
>>>     import traceback
>>>     try:
>>>         raise Exception(u'??????????????????')
>>>     except Exception,e:
>>>         print traceback.format_exc().decode('utf-8')
>>>
>>> The last line translates the utf-8 traceback into Unicode.  Printing
>>> Unicode will encode the output with the terminal's decoding.  If there are
>>> characters it can't display, you'll still get an error, though.  You can be
>>> more explicit however:
>>>
>>>     print
>>> traceback.format_exc().decode('utf-8').encode('cp437','replace')
>>>
>>> In this case you'll get ? whenever a character can't be represented in
>>> the selected encoding.  cp437, for example, can't display any russian
>>> characters, so for me (on Windows) I just get all ???????????.  When I tried
>>> it with a character string that could be displayed in cp437, it worked fine:
>>>
>>>     Traceback (most recent call last):
>>>       File "<stdin>", line 1, in <module>
>>>       File "t4.py", line 4, in <module>
>>>         raise Exception('M???????')
>>>     Exception: M???????
>>>
>>> Another option is to redirect the output to a file and read the file with
>>> an editor that can display utf-8 (such as Notepad on Windows).
>>>
>>>     python testfile.py 2>error.txt          # this redirects stderr to a
>>> file.
>>>
>>> Hope that helps,
>>> Mark
>>>
>>> "Oleg Oltar" <oltarasenko at gmail.com> wrote in message
>>> news:b4fc2ad80807162050s1de6b6aalc86203c7e1fe3df5 at mail.gmail.com...
>>>
>>>> The code
>>>
>>>  # -*- coding: utf-8 -*-
>>> #!/usr/bin/python
>>>
>>>
>>> """
>>>
>>> This test case check how system works in the situation, when user tries
>>> to use already
>>> used username (domain)
>>>
>>> We are creating two accounts with such parameters:
>>> 1. Sex = Femle
>>> 2. Name1=Name2 = foobar%S
>>> 3. Pass1 = Name
>>> 4. Pass2 = Name
>>> 5. Email address1 = Email address2 =  Name at meta.ua
>>>
>>>
>>> In the test we use verification point - warning message about incorrect
>>> input of domain name and the
>>> sugestion message
>>>
>>> """
>>>
>>> from selenium import selenium
>>> import unittest, time, re
>>> import HTMLTestRunner
>>> import config
>>> import Creating_account_basic
>>>
>>>
>>>
>>>
>>> class Same_domain_name(unittest.TestCase):
>>>
>>>     def setUp(self):
>>>         self.name = "foobar"
>>>         self.email = self.name + "@meta.ua"
>>>         self.verificationErrors = []
>>>         self.selenium = selenium("localhost", 4444,config.browser,
>>> config.link)
>>>         self.selenium.start()
>>>
>>>     def test_create_account_to_check(self):
>>>         """Creating sample account for next test"""
>>>         sel = self.selenium
>>>         sel.open("/")
>>>         sel.click(u"link=???????????")
>>>         sel.wait_for_page_to_load("70000")
>>>         sel.click("id_gender_1")
>>>         sel.type("id_first_name", self.name)
>>>         sel.type("id_last_name", self.name)
>>>         sel.type("id_email", self.email)
>>>         sel.type("id_username",  self.name)
>>>
>>> #sel.wait_for_condition(sel.is_element_present("check_username_block"),
>>> 70000)
>>>         time.sleep(10)
>>>         print "!!!", sel.is_element_present("check_username_block")
>>>         sel.type("id_password",  self.name)
>>>         print sel.get_text("check_username_block").decode('cp-1252')
>>>         sel.type("id_password2", self.name)
>>>         sel.click(u"//input[@value='??????????????????']")
>>>         sel.wait_for_page_to_load("70000")
>>>         if config.debugMode is True:
>>>             time.sleep(5)
>>>
>>>
>>>     def tearDown(self):
>>>         self.selenium.stop()
>>>         print self.verificationErrors
>>>         self.assertEqual([], self.verificationErrors)
>>>
>>> if __name__ == "__main__":
>>>
>>>     unittest.main()
>>>     #HTMLTestRunner.main()
>>>
>>>
>>>
>>> On Thu, Jul 17, 2008 at 6:47 AM, Oleg Oltar <oltarasenko at gmail.com>
>>> wrote:
>>>
>>>> In [1]: import sys
>>>>
>>>> In [2]: sys.getdefaultencoding()
>>>> Out[2]: 'ascii'
>>>>
>>>> In [3]: sys.stdout.encoding
>>>> Out[3]: 'US-ASCII'
>>>>
>>>>
>>>> On Thu, Jul 17, 2008 at 6:29 AM, Oleg Oltar <oltarasenko at gmail.com>
>>>> wrote:
>>>>
>>>>> Seems need help there. Start getting
>>>>>
>>>>> Traceback (most recent call last):
>>>>>   File "./newaccount/Same_domain_name.py", line 56, in
>>>>> test_create_account_to_check
>>>>>     print sel.get_text("check_username_block")
>>>>> UnicodeEncodeError: 'ascii' codec can't encode characters in position
>>>>> 0-4: ordinal not in range(128)
>>>>>
>>>>>
>>>>> when trying to get the text of one of the elements.
>>>>>
>>>>> How to solve it?
>>>>>
>>>>>
>>>>> On Thu, Jul 17, 2008 at 5:11 AM, Oleg Oltar <oltarasenko at gmail.com>
>>>>> wrote:
>>>>>
>>>>>> OK,
>>>>>>
>>>>>> I just run the program from terminal. OS: OS X, IDLE = Emacs:).
>>>>>>
>>>>>> Yep used the string "# -*- coding: utf-8 -*-" to setup encoding....
>>>>>>
>>>>>>
>>>>>> On Thu, Jul 17, 2008 at 4:14 AM, Kent Johnson <kent37 at tds.net> wrote:
>>>>>>
>>>>>>> Another possibility - do you have a coding declaration in your source
>>>>>>> file, something like
>>>>>>> # -*- coding: <encoding name> -*-
>>>>>>>
>>>>>>> If so, does the coding declaration match the actual encoding of the
>>>>>>> file?
>>>>>>>
>>>>>>> Kent
>>>>>>>
>>>>>>> On Wed, Jul 16, 2008 at 5:11 PM, Kent Johnson <kent37 at tds.net>
>>>>>>> wrote:
>>>>>>> > On Wed, Jul 16, 2008 at 2:40 PM, Oleg Oltar <oltarasenko at gmail.com>
>>>>>>> wrote:
>>>>>>> >> Hi I am using unittest framework with selenium.
>>>>>>> >>
>>>>>>> >> When I tried this code (my verification point)
>>>>>>> >>
>>>>>>> >>         self.assertEqual(True, sel.is_text_present(u"????????
>>>>>>> ?????? ??
>>>>>>> >> ?????????"), "System didn't give a correct warning about the
>>>>>>> password
>>>>>>> >> misstype")
>>>>>>> >>
>>>>>>> >>> Where u"???????? ?????? ?? ?????????" is russian = "Sorry
>>>>>>> passwords aren't
>>>>>>> >>> equal", and sel.is_text_present - searches text string on the
>>>>>>> page
>>>>>>> >>
>>>>>>> >> The output I get in case of failure was:
>>>>>>> >>
>>>>>>> >>
>>>>>>> >> Traceback (most recent call last):
>>>>>>> >>
>>>>>>> >>   File "./newaccount/Password_matching.py", line 50, in
>>>>>>> >> test_passwordMatching
>>>>>>> >>     self.assertEqual(True, sel.is_text_present(u"????????????????
>>>>>>> >> ???????????? ???? ? ????????????????"), "System didn't give a
>>>>>>> correct
>>>>>>> >> warning about the password misstype")
>>>>>>> >>
>>>>>>> >> AssertionError: System didn't give a correct warning about the
>>>>>>> password
>>>>>>> >> misstype
>>>>>>> >>
>>>>>>> >> Is there any way to get normal russian text instead of these
>>>>>>> strange D chars
>>>>>>> >> "????????...."
>>>>>>> >
>>>>>>> > I don't have the solution but maybe I can give you a useful clue.
>>>>>>> The
>>>>>>> > D characters are most likely the utf-8 encoding of the Russian
>>>>>>> text,
>>>>>>> > when displayed as if it is latin-1. So something in the system is
>>>>>>> > converting the text to utf-8 and your console probably has latin-1
>>>>>>> or
>>>>>>> > cp1252 encoding.
>>>>>>> >
>>>>>>> > Some details might help - how are you running the program -
>>>>>>> console,
>>>>>>> > IDLE...? What OS? What are the values of sys.getdefaultencoding()
>>>>>>> and
>>>>>>> > sys.stdout.encoding?
>>>>>>> >
>>>>>>> > Kent
>>>>>>> >
>>>>>>>
>>>>>>
>>>>>>
>>>>>
>>>>
>>>  ------------------------------
>>>
>>> _______________________________________________
>>> Tutor maillist  -  Tutor at python.org
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>>
>>> _______________________________________________
>>> Tutor maillist  -  Tutor at python.org
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>>
>>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080717/66c3efc7/attachment-0001.htm>

From rdm at rcblue.com  Thu Jul 17 09:08:04 2008
From: rdm at rcblue.com (Dick Moores)
Date: Thu, 17 Jul 2008 00:08:04 -0700
Subject: [Tutor] Does IPython have a "restart"?
In-Reply-To: <20080716145551.313881E4007@bag.python.org>
References: <20080716145551.313881E4007@bag.python.org>
Message-ID: <20080717070816.B6E9D1E4007@bag.python.org>

At 07:55 AM 7/16/2008, Dick Moores wrote:
>I mean something equivalent to what you get when you do a Ctrl+F6 in IDLE:
>
> >>> import math
> >>> math.log(3)
>1.0986122886681098
> >>> =============================================== RESTART 
> ===============================================
> >>> math.log(3)
>
>Traceback (most recent call last):
>   File "<pyshell#9>", line 1, in <module>
>     math.log(3)
>NameError: name 'math' is not defined
> >>>

===========================================
Got this from the ipython-user list:

Use %reset:

In [1]: import math

In [2]: math.sin(3)
Out[2]: 0.14112000805986721

In [3]: %reset
Once deleted, variables cannot be recovered. Proceed (y/[n])?  y

In [5]: math.sin(3)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)

/home/fperez/Desktop/<ipython console> in <module>()


NameError: name 'math' is not defined



Note that it is  NOT the same though: idle forces a new, fresh python
process, while ipython just clears your current variables.  So things
like reloading extension modules won't work the same way.
================================================

Dick


From metolone+gmane at gmail.com  Thu Jul 17 09:29:36 2008
From: metolone+gmane at gmail.com (Mark Tolonen)
Date: Thu, 17 Jul 2008 00:29:36 -0700
Subject: [Tutor] Unittest
References: <b4fc2ad80807161140w3d1d0fe5q9d15898969ec3dc7@mail.gmail.com><1c2a2c590807161411w5f23a55dmacc8ad9fa56c0f30@mail.gmail.com><1c2a2c590807161814n7048ec5pdede6c9684e10a47@mail.gmail.com><b4fc2ad80807161911y46ce3239v207403c295750c43@mail.gmail.com><b4fc2ad80807162029r1bbf3827md3eec2f2eb3f03aa@mail.gmail.com><b4fc2ad80807162047i338faf7ra1253b5dc00c7a1a@mail.gmail.com><b4fc2ad80807162050s1de6b6aalc86203c7e1fe3df5@mail.gmail.com><g5mkd5$ont$1@ger.gmane.org><b4fc2ad80807162330g9b93bfeq1e55af9b3ed97400@mail.gmail.com><b4fc2ad80807162333k6badc3d3of87f402003a3a00a@mail.gmail.com>
	<b4fc2ad80807162357o5b97e2f1n56ae3306d66d050@mail.gmail.com>
Message-ID: <g5mscr$cbf$1@ger.gmane.org>

You get the "D" characters when decoding Russian encoded in UTF-8 using Latin-1 instead.

# coding: utf-8
x=u'??????????????????'
print x.encode('utf-8').decode('latin-1')
????????????????????????????????????

Check that your html encoding is declared correctly.

--
Mark


  "Oleg Oltar" <oltarasenko at gmail.com> wrote in message news:b4fc2ad80807162357o5b97e2f1n56ae3306d66d050 at mail.gmail.com...
  Ok, seems it's my console setting. Tried console with koi8-r (from http://vak.ru/doku.php/macosx-russian), and it looks ok there. Mean the satndard output, but still getting "D" chars instead of russian when trying to convert it to html via HTMLTestRunner (see http://tungwaiyip.info/software/HTMLTestRunner.html) 


  On Thu, Jul 17, 2008 at 9:33 AM, Oleg Oltar <oltarasenko at gmail.com> wrote:


    And in case:
    # coding: utf-8


      import traceback 
      try:
          raise Exception(u'?????????')
      except Exception,e:

          print traceback.format_exc().decode('utf-8').encode('cp437', 'replace')


    Getting

    beryl:~ oleg$ python ./wish/newaccount/reg.py

    Traceback (most recent call last):

      File "./wish/newaccount/reg.py", line 5, in <module>
        raise Exception(u'?????????')
    Exception: <unprintable Exception object>



    My console settings:


    In [1]: import sys

    In [2]: sys.getdefaultencoding()
    Out[2]: 'ascii'

    In [3]: sys.stdout.encoding
    Out[3]: 'US-ASCII'



    On Thu, Jul 17, 2008 at 9:30 AM, Oleg Oltar <oltarasenko at gmail.com> wrote:

      OK
      the output:


        # coding: utf-8

        import traceback 
        try:

            raise Exception(u'?????????')

        except Exception,e:
            print traceback.format_exc().decode('utf-8')



      >>> Traceback (most recent call last):

        File "/var/folders/PC/PCtFE4gQGiqpQymiAScfnk+++TM/-Tmp-/py46506ECT", line 7, in <module>

          print traceback.format_exc().decode('utf-8')

      UnicodeEncodeError: 'ascii' codec can't encode characters in position 148-156: ordinal not in range(128) 






      On Thu, Jul 17, 2008 at 8:13 AM, Mark Tolonen <metolone+gmane at gmail.com> wrote:

        The Exception is output in the encoding of the source file.  If the terminal you are displaying the exception on is in a different encoding, it will be garbled.  I'm not familiar with OS X's terminal.  Try running python and printing sys.stdout.encoding.

        Alternatively, wrap your code in a try/except handler and translate the exception yourself.

            # coding: utf-8
            import traceback
            try:
                raise Exception(u'??????????????????')
            except Exception,e:
                print traceback.format_exc().decode('utf-8')

        The last line translates the utf-8 traceback into Unicode.  Printing Unicode will encode the output with the terminal's decoding.  If there are characters it can't display, you'll still get an error, though.  You can be more explicit however:

            print traceback.format_exc().decode('utf-8').encode('cp437','replace')

        In this case you'll get ? whenever a character can't be represented in the selected encoding.  cp437, for example, can't display any russian characters, so for me (on Windows) I just get all ???????????.  When I tried it with a character string that could be displayed in cp437, it worked fine:

            Traceback (most recent call last):

              File "<stdin>", line 1, in <module>
              File "t4.py", line 4, in <module>
                raise Exception('M???????')
            Exception: M???????

        Another option is to redirect the output to a file and read the file with an editor that can display utf-8 (such as Notepad on Windows).

            python testfile.py 2>error.txt          # this redirects stderr to a file.

        Hope that helps,
        Mark
          "Oleg Oltar" <oltarasenko at gmail.com> wrote in message news:b4fc2ad80807162050s1de6b6aalc86203c7e1fe3df5 at mail.gmail.com...
            The code
           # -*- coding: utf-8 -*-
          #!/usr/bin/python


          """

          This test case check how system works in the situation, when user tries to use already
          used username (domain)

          We are creating two accounts with such parameters:
          1. Sex = Femle
          2. Name1=Name2 = foobar%S 
          3. Pass1 = Name
          4. Pass2 = Name
          5. Email address1 = Email address2 =  Name at meta.ua 


          In the test we use verification point - warning message about incorrect input of domain name and the
          sugestion message

          """

          from selenium import selenium
          import unittest, time, re
          import HTMLTestRunner
          import config
          import Creating_account_basic




          class Same_domain_name(unittest.TestCase):
              
              def setUp(self):        
                  self.name = "foobar"
                  self.email = self.name + "@meta.ua" 
                  self.verificationErrors = []
                  self.selenium = selenium("localhost", 4444,config.browser, config.link)
                  self.selenium.start()

              def test_create_account_to_check(self):  
                  """Creating sample account for next test"""
                  sel = self.selenium
                  sel.open("/")
                  sel.click(u"link=???????????")
                  sel.wait_for_page_to_load("70000")
                  sel.click("id_gender_1")
                  sel.type("id_first_name", self.name)
                  sel.type("id_last_name", self.name)
                  sel.type("id_email", self.email)
                  sel.type("id_username",  self.name)
                  #sel.wait_for_condition(sel.is_element_present("check_username_block"), 70000)
                  time.sleep(10)
                  print "!!!", sel.is_element_present("check_username_block")
                  sel.type("id_password",  self.name)
                  print sel.get_text("check_username_block").decode('cp-1252')
                  sel.type("id_password2", self.name)
                  sel.click(u"//input[@value='??????????????????']")
                  sel.wait_for_page_to_load("70000")
                  if config.debugMode is True:
                      time.sleep(5)


              def tearDown(self):
                  self.selenium.stop()
                  print self.verificationErrors
                  self.assertEqual([], self.verificationErrors)

          if __name__ == "__main__":
              
              unittest.main()
              #HTMLTestRunner.main()
           




          On Thu, Jul 17, 2008 at 6:47 AM, Oleg Oltar <oltarasenko at gmail.com> wrote:

            In [1]: import sys

            In [2]: sys.getdefaultencoding()
            Out[2]: 'ascii'

            In [3]: sys.stdout.encoding
            Out[3]: 'US-ASCII' 



            On Thu, Jul 17, 2008 at 6:29 AM, Oleg Oltar <oltarasenko at gmail.com> wrote:

              Seems need help there. Start getting 


              Traceback (most recent call last):

                File "./newaccount/Same_domain_name.py", line 56, in test_create_account_to_check
                  print sel.get_text("check_username_block")
              UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128)


              when trying to get the text of one of the elements. 

              How to solve it? 



              On Thu, Jul 17, 2008 at 5:11 AM, Oleg Oltar <oltarasenko at gmail.com> wrote:

                OK,

                I just run the program from terminal. OS: OS X, IDLE = Emacs:).

                Yep used the string "# -*- coding: utf-8 -*-" to setup encoding.... 



                On Thu, Jul 17, 2008 at 4:14 AM, Kent Johnson <kent37 at tds.net> wrote:

                  Another possibility - do you have a coding declaration in your source
                  file, something like
                  # -*- coding: <encoding name> -*-

                  If so, does the coding declaration match the actual encoding of the file?

                  Kent


                  On Wed, Jul 16, 2008 at 5:11 PM, Kent Johnson <kent37 at tds.net> wrote:
                  > On Wed, Jul 16, 2008 at 2:40 PM, Oleg Oltar <oltarasenko at gmail.com> wrote:
                  >> Hi I am using unittest framework with selenium.
                  >>
                  >> When I tried this code (my verification point)
                  >>
                  >>         self.assertEqual(True, sel.is_text_present(u"???????? ?????? ??
                  >> ?????????"), "System didn't give a correct warning about the password
                  >> misstype")
                  >>
                  >>> Where u"???????? ?????? ?? ?????????" is russian = "Sorry passwords aren't
                  >>> equal", and sel.is_text_present - searches text string on the page
                  >>
                  >> The output I get in case of failure was:
                  >>
                  >>
                  >> Traceback (most recent call last):
                  >>
                  >>   File "./newaccount/Password_matching.py", line 50, in
                  >> test_passwordMatching
                  >>     self.assertEqual(True, sel.is_text_present(u"????????????????
                  >> ???????????? ???? ? ????????????????"), "System didn't give a correct
                  >> warning about the password misstype")
                  >>
                  >> AssertionError: System didn't give a correct warning about the password
                  >> misstype
                  >>
                  >> Is there any way to get normal russian text instead of these strange D chars
                  >> "????????...."
                  >
                  > I don't have the solution but maybe I can give you a useful clue. The
                  > D characters are most likely the utf-8 encoding of the Russian text,
                  > when displayed as if it is latin-1. So something in the system is
                  > converting the text to utf-8 and your console probably has latin-1 or
                  > cp1252 encoding.
                  >
                  > Some details might help - how are you running the program - console,
                  > IDLE...? What OS? What are the values of sys.getdefaultencoding() and
                  > sys.stdout.encoding?
                  >
                  > Kent
                  >











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


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


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










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


  _______________________________________________
  Tutor maillist  -  Tutor at python.org
  http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080717/780bfcdb/attachment-0001.htm>

From monjissvel at googlemail.com  Thu Jul 17 09:47:01 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Thu, 17 Jul 2008 07:47:01 +0000
Subject: [Tutor] Any way of monitoring a python program's memory
	utilization?
In-Reply-To: <Pine.LNX.4.44.0807161817580.10773-100000@violet.rahul.net>
References: <Pine.LNX.4.44.0807161804340.10773-100000@violet.rahul.net>
	<Pine.LNX.4.44.0807161817580.10773-100000@violet.rahul.net>
Message-ID: <e2f191310807170047m6a7c306s46eaa14049bae62d@mail.gmail.com>

>
> I'm iterating through a vey large tarfile (uncompressed, it would be about
> 2.4G, with about 2.5 million files in it) and I can see from some external
> monitors that its virtual storage usage just grows and grows, until my
> whole system finally grinds to a halt after about 1.2 million members have
> been processed.


Well, you can check whether your system has reached its limits or not, but
what for ? it will lead you no where as the only sthing you can do is stop
your program (while MEM_stat <= 1G: parse(); else: break) & you don't get
anything done.  I believe installing more memroy in your system is the way
to go, you need to have at least 3G of Memory (memory is cheap these days),
then don't let python use it as you don't know how much memory it will need
for your program's internal routines, but create a virtual drive in memory
(RAM DRIVE) extract the tar file into it &  parse its content as you wish
(ofcourse you can use harddrive too ut its gona be VERY slow (specialy on
Windows)).
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080717/981426ac/attachment.htm>

From carroll at tjc.com  Thu Jul 17 10:12:40 2008
From: carroll at tjc.com (Terry Carroll)
Date: Thu, 17 Jul 2008 01:12:40 -0700 (PDT)
Subject: [Tutor] Any way of monitoring a python program's memory
	utilization?
In-Reply-To: <e2f191310807170047m6a7c306s46eaa14049bae62d@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0807170112190.30663-100000@violet.rahul.net>

On Thu, 17 Jul 2008, Monika Jisswel wrote:

> Well, you can check whether your system has reached its limits or not, but
> what for ? 

So I can debug the problem.


From rdm at rcblue.com  Thu Jul 17 11:54:00 2008
From: rdm at rcblue.com (Dick Moores)
Date: Thu, 17 Jul 2008 02:54:00 -0700
Subject: [Tutor] IPython problem: Difficulty in setting editor to TextPad
Message-ID: <20080717095442.48F0C1E4003@bag.python.org>

Win XP, Python 2.51, IPython 0.84

In my ipy_user_conf.py I have put this line:
ipy_editors.install_editor("C:\Program Files\TextPad 5\TextPad.exe")

I use IPython -debug to start IPython, and this is what it tells me:
'editor': '"C:\\Program Files\\TextPad 5\\textpad.exe"',

but

In [3]: ed versions.py
Editing... > C:\Program Files\TextPad 5\TextPad.exe
'C:\Program' is not recognized as an internal or external command,
operable program or batch file.
done. Executing edited code...
[snip]

It seems obvious that there still is a problem with the spaces in the
path, but I don't know what to do about them.
Help, please.

Dick Moores

============================================
Have you seen the video introducing the terrific and free
IDE, Ulipad? Download it from my website.
<http://www.rcblue.com/u3/>


From oltarasenko at gmail.com  Thu Jul 17 09:01:15 2008
From: oltarasenko at gmail.com (Oleg Oltar)
Date: Thu, 17 Jul 2008 10:01:15 +0300
Subject: [Tutor] Unittest
In-Reply-To: <b4fc2ad80807162358t576e6fb1x62965c27887b530@mail.gmail.com>
References: <b4fc2ad80807161140w3d1d0fe5q9d15898969ec3dc7@mail.gmail.com>
	<b4fc2ad80807161911y46ce3239v207403c295750c43@mail.gmail.com>
	<b4fc2ad80807162029r1bbf3827md3eec2f2eb3f03aa@mail.gmail.com>
	<b4fc2ad80807162047i338faf7ra1253b5dc00c7a1a@mail.gmail.com>
	<b4fc2ad80807162050s1de6b6aalc86203c7e1fe3df5@mail.gmail.com>
	<g5mkd5$ont$1@ger.gmane.org>
	<b4fc2ad80807162330g9b93bfeq1e55af9b3ed97400@mail.gmail.com>
	<b4fc2ad80807162333k6badc3d3of87f402003a3a00a@mail.gmail.com>
	<g5mqcp$6qj$1@ger.gmane.org>
	<b4fc2ad80807162358t576e6fb1x62965c27887b530@mail.gmail.com>
Message-ID: <b4fc2ad80807170001r3b988e33wa073c90929c9811b@mail.gmail.com>

beryl:~ oleg$ env
MANPATH=/usr/share/man:/usr/local/share/man:/usr/X11/man
TERM_PROGRAM=Apple_Terminal
TERM=xterm-color
SHELL=/bin/bash
TMPDIR=/var/folders/PC/PCtFE4gQGiqpQymiAScfnk+++TM/-Tmp-/
Apple_PubSub_Socket_Render=/tmp/launch-UNXiC6/Render
TERM_PROGRAM_VERSION=237
USER=oleg
COMMAND_MODE=unix2003
SSH_AUTH_SOCK=/tmp/launch-hfpsIl/Listeners
__CF_USER_TEXT_ENCODING=0x1F6:0:0
PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin
PWD=/Users/oleg
LANG=ru_RU.UTF-8
SHLVL=1
HOME=/Users/oleg
PYTHONPATH=:/Users/oleg/Documents/wishes_Test
LOGNAME=oleg
DISPLAY=/tmp/launch-1kgALC/:0
SECURITYSESSIONID=a206d0


On Thu, Jul 17, 2008 at 9:58 AM, Oleg Oltar <oltarasenko at gmail.com> wrote:

> See previous message (sent it few seconds ago)
>
>
> On Thu, Jul 17, 2008 at 9:55 AM, Mark Tolonen <metolone+gmane at gmail.com<metolone%2Bgmane at gmail.com>>
> wrote:
>
>>  OK, your console is set to 'ascii' ('cp437' was my example and is the
>> Windows console encoding).  'ascii' won't be able to display Russian.
>> It shouldn't have displayed the "?????????????" characters either.
>> Are you still running on the same terminal that display those
>> characters?  Can you change your terminals encoding preference via an
>> environment variable?
>> --
>> Mark
>>
>> "Oleg Oltar" <oltarasenko at gmail.com> wrote in message
>> news:b4fc2ad80807162333k6badc3d3of87f402003a3a00a at mail.gmail.com...
>>
>> And in case:
>> # coding: utf-8
>>
>> import traceback
>> try:
>>     raise Exception(u'?????????')
>> except Exception,e:
>>     print traceback.format_exc().decode('utf-8').encode('cp437',
>> 'replace')
>>
>>
>> Getting
>>
>> beryl:~ oleg$ python ./wish/newaccount/reg.py
>> Traceback (most recent call last):
>>   File "./wish/newaccount/reg.py", line 5, in <module>
>>     raise Exception(u'?????????')
>> Exception: <unprintable Exception object>
>>
>>
>>
>> My console settings:
>>
>> In [1]: import sys
>>
>> In [2]: sys.getdefaultencoding()
>> Out[2]: 'ascii'
>>
>> In [3]: sys.stdout.encoding
>> Out[3]: 'US-ASCII'
>>
>>
>> On Thu, Jul 17, 2008 at 9:30 AM, Oleg Oltar <oltarasenko at gmail.com>
>> wrote:
>>
>>> OK
>>> the output:
>>>
>>>  # coding: utf-8
>>>>
>>>> import traceback
>>>> try:
>>>>     raise Exception(u'?????????')
>>>> except Exception,e:
>>>>     print traceback.format_exc().decode('utf-8')
>>>>
>>>
>>>
>>> >>> Traceback (most recent call last):
>>>   File "/var/folders/PC/PCtFE4gQGiqpQymiAScfnk+++TM/-Tmp-/py46506ECT",
>>> line 7, in <module>
>>>     print traceback.format_exc().decode('utf-8')
>>> UnicodeEncodeError: 'ascii' codec can't encode characters in position
>>> 148-156: ordinal not in range(128)
>>>
>>>
>>>
>>>
>>> On Thu, Jul 17, 2008 at 8:13 AM, Mark Tolonen <metolone+gmane at gmail.com<metolone%2Bgmane at gmail.com>>
>>> wrote:
>>>
>>>>  The Exception is output in the encoding of the source file.  If the
>>>> terminal you are displaying the exception on is in a different encoding, it
>>>> will be garbled.  I'm not familiar with OS X's terminal.  Try running python
>>>> and printing sys.stdout.encoding.
>>>>
>>>> Alternatively, wrap your code in a try/except handler and translate the
>>>> exception yourself.
>>>>
>>>>     # coding: utf-8
>>>>     import traceback
>>>>     try:
>>>>         raise Exception(u'??????????????????')
>>>>     except Exception,e:
>>>>         print traceback.format_exc().decode('utf-8')
>>>>
>>>> The last line translates the utf-8 traceback into Unicode.  Printing
>>>> Unicode will encode the output with the terminal's decoding.  If there are
>>>> characters it can't display, you'll still get an error, though.  You can be
>>>> more explicit however:
>>>>
>>>>     print
>>>> traceback.format_exc().decode('utf-8').encode('cp437','replace')
>>>>
>>>> In this case you'll get ? whenever a character can't be represented in
>>>> the selected encoding.  cp437, for example, can't display any russian
>>>> characters, so for me (on Windows) I just get all ???????????.  When I tried
>>>> it with a character string that could be displayed in cp437, it worked fine:
>>>>
>>>>      Traceback (most recent call last):
>>>>       File "<stdin>", line 1, in <module>
>>>>       File "t4.py", line 4, in <module>
>>>>         raise Exception('M???????')
>>>>     Exception: M???????
>>>>
>>>> Another option is to redirect the output to a file and read the file
>>>> with an editor that can display utf-8 (such as Notepad on Windows).
>>>>
>>>>     python testfile.py 2>error.txt          # this redirects stderr to a
>>>> file.
>>>>
>>>> Hope that helps,
>>>> Mark
>>>>
>>>> "Oleg Oltar" <oltarasenko at gmail.com> wrote in message
>>>> news:b4fc2ad80807162050s1de6b6aalc86203c7e1fe3df5 at mail.gmail.com...
>>>>
>>>>> The code
>>>>
>>>>  # -*- coding: utf-8 -*-
>>>> #!/usr/bin/python
>>>>
>>>>
>>>> """
>>>>
>>>> This test case check how system works in the situation, when user tries
>>>> to use already
>>>> used username (domain)
>>>>
>>>> We are creating two accounts with such parameters:
>>>> 1. Sex = Femle
>>>> 2. Name1=Name2 = foobar%S
>>>> 3. Pass1 = Name
>>>> 4. Pass2 = Name
>>>> 5. Email address1 = Email address2 =  Name at meta.ua
>>>>
>>>>
>>>> In the test we use verification point - warning message about incorrect
>>>> input of domain name and the
>>>> sugestion message
>>>>
>>>> """
>>>>
>>>> from selenium import selenium
>>>> import unittest, time, re
>>>> import HTMLTestRunner
>>>> import config
>>>> import Creating_account_basic
>>>>
>>>>
>>>>
>>>>
>>>> class Same_domain_name(unittest.TestCase):
>>>>
>>>>     def setUp(self):
>>>>         self.name = "foobar"
>>>>         self.email = self.name + "@meta.ua"
>>>>         self.verificationErrors = []
>>>>         self.selenium = selenium("localhost", 4444,config.browser,
>>>> config.link)
>>>>         self.selenium.start()
>>>>
>>>>     def test_create_account_to_check(self):
>>>>         """Creating sample account for next test"""
>>>>         sel = self.selenium
>>>>         sel.open("/")
>>>>         sel.click(u"link=???????????")
>>>>         sel.wait_for_page_to_load("70000")
>>>>         sel.click("id_gender_1")
>>>>         sel.type("id_first_name", self.name)
>>>>         sel.type("id_last_name", self.name)
>>>>         sel.type("id_email", self.email)
>>>>         sel.type("id_username",  self.name)
>>>>
>>>> #sel.wait_for_condition(sel.is_element_present("check_username_block"),
>>>> 70000)
>>>>         time.sleep(10)
>>>>         print "!!!", sel.is_element_present("check_username_block")
>>>>         sel.type("id_password",  self.name)
>>>>         print sel.get_text("check_username_block").decode('cp-1252')
>>>>         sel.type("id_password2", self.name)
>>>>         sel.click(u"//input[@value='??????????????????']")
>>>>         sel.wait_for_page_to_load("70000")
>>>>         if config.debugMode is True:
>>>>             time.sleep(5)
>>>>
>>>>
>>>>     def tearDown(self):
>>>>         self.selenium.stop()
>>>>         print self.verificationErrors
>>>>         self.assertEqual([], self.verificationErrors)
>>>>
>>>> if __name__ == "__main__":
>>>>
>>>>     unittest.main()
>>>>     #HTMLTestRunner.main()
>>>>
>>>>
>>>>
>>>> On Thu, Jul 17, 2008 at 6:47 AM, Oleg Oltar <oltarasenko at gmail.com>
>>>> wrote:
>>>>
>>>>> In [1]: import sys
>>>>>
>>>>> In [2]: sys.getdefaultencoding()
>>>>> Out[2]: 'ascii'
>>>>>
>>>>> In [3]: sys.stdout.encoding
>>>>> Out[3]: 'US-ASCII'
>>>>>
>>>>>
>>>>> On Thu, Jul 17, 2008 at 6:29 AM, Oleg Oltar <oltarasenko at gmail.com>
>>>>> wrote:
>>>>>
>>>>>> Seems need help there. Start getting
>>>>>>
>>>>>> Traceback (most recent call last):
>>>>>>   File "./newaccount/Same_domain_name.py", line 56, in
>>>>>> test_create_account_to_check
>>>>>>     print sel.get_text("check_username_block")
>>>>>> UnicodeEncodeError: 'ascii' codec can't encode characters in position
>>>>>> 0-4: ordinal not in range(128)
>>>>>>
>>>>>>
>>>>>> when trying to get the text of one of the elements.
>>>>>>
>>>>>> How to solve it?
>>>>>>
>>>>>>
>>>>>> On Thu, Jul 17, 2008 at 5:11 AM, Oleg Oltar <oltarasenko at gmail.com>
>>>>>> wrote:
>>>>>>
>>>>>>> OK,
>>>>>>>
>>>>>>> I just run the program from terminal. OS: OS X, IDLE = Emacs:).
>>>>>>>
>>>>>>> Yep used the string "# -*- coding: utf-8 -*-" to setup encoding....
>>>>>>>
>>>>>>>
>>>>>>> On Thu, Jul 17, 2008 at 4:14 AM, Kent Johnson <kent37 at tds.net>
>>>>>>> wrote:
>>>>>>>
>>>>>>>> Another possibility - do you have a coding declaration in your
>>>>>>>> source
>>>>>>>> file, something like
>>>>>>>> # -*- coding: <encoding name> -*-
>>>>>>>>
>>>>>>>> If so, does the coding declaration match the actual encoding of the
>>>>>>>> file?
>>>>>>>>
>>>>>>>> Kent
>>>>>>>>
>>>>>>>> On Wed, Jul 16, 2008 at 5:11 PM, Kent Johnson <kent37 at tds.net>
>>>>>>>> wrote:
>>>>>>>> > On Wed, Jul 16, 2008 at 2:40 PM, Oleg Oltar <
>>>>>>>> oltarasenko at gmail.com> wrote:
>>>>>>>> >> Hi I am using unittest framework with selenium.
>>>>>>>> >>
>>>>>>>> >> When I tried this code (my verification point)
>>>>>>>> >>
>>>>>>>> >>         self.assertEqual(True, sel.is_text_present(u"????????
>>>>>>>> ?????? ??
>>>>>>>> >> ?????????"), "System didn't give a correct warning about the
>>>>>>>> password
>>>>>>>> >> misstype")
>>>>>>>> >>
>>>>>>>> >>> Where u"???????? ?????? ?? ?????????" is russian = "Sorry
>>>>>>>> passwords aren't
>>>>>>>> >>> equal", and sel.is_text_present - searches text string on the
>>>>>>>> page
>>>>>>>> >>
>>>>>>>> >> The output I get in case of failure was:
>>>>>>>> >>
>>>>>>>> >>
>>>>>>>> >> Traceback (most recent call last):
>>>>>>>> >>
>>>>>>>> >>   File "./newaccount/Password_matching.py", line 50, in
>>>>>>>> >> test_passwordMatching
>>>>>>>> >>     self.assertEqual(True, sel.is_text_present(u"????????????????
>>>>>>>> >> ???????????? ???? ? ????????????????"), "System didn't give a
>>>>>>>> correct
>>>>>>>> >> warning about the password misstype")
>>>>>>>> >>
>>>>>>>> >> AssertionError: System didn't give a correct warning about the
>>>>>>>> password
>>>>>>>> >> misstype
>>>>>>>> >>
>>>>>>>> >> Is there any way to get normal russian text instead of these
>>>>>>>> strange D chars
>>>>>>>> >> "????????...."
>>>>>>>> >
>>>>>>>> > I don't have the solution but maybe I can give you a useful clue.
>>>>>>>> The
>>>>>>>> > D characters are most likely the utf-8 encoding of the Russian
>>>>>>>> text,
>>>>>>>> > when displayed as if it is latin-1. So something in the system is
>>>>>>>> > converting the text to utf-8 and your console probably has latin-1
>>>>>>>> or
>>>>>>>> > cp1252 encoding.
>>>>>>>> >
>>>>>>>> > Some details might help - how are you running the program -
>>>>>>>> console,
>>>>>>>> > IDLE...? What OS? What are the values of sys.getdefaultencoding()
>>>>>>>> and
>>>>>>>> > sys.stdout.encoding?
>>>>>>>> >
>>>>>>>> > Kent
>>>>>>>> >
>>>>>>>>
>>>>>>>
>>>>>>>
>>>>>>
>>>>>
>>>>  ------------------------------
>>>>
>>>> _______________________________________________
>>>> Tutor maillist  -  Tutor at python.org
>>>> http://mail.python.org/mailman/listinfo/tutor
>>>>
>>>>
>>>> _______________________________________________
>>>> Tutor maillist  -  Tutor at python.org
>>>> http://mail.python.org/mailman/listinfo/tutor
>>>>
>>>>
>>>
>>  ------------------------------
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080717/7af45721/attachment-0001.htm>

From oltarasenko at gmail.com  Thu Jul 17 09:05:08 2008
From: oltarasenko at gmail.com (Oleg Oltar)
Date: Thu, 17 Jul 2008 10:05:08 +0300
Subject: [Tutor] Unittest
In-Reply-To: <b4fc2ad80807170001r3b988e33wa073c90929c9811b@mail.gmail.com>
References: <b4fc2ad80807161140w3d1d0fe5q9d15898969ec3dc7@mail.gmail.com>
	<b4fc2ad80807162029r1bbf3827md3eec2f2eb3f03aa@mail.gmail.com>
	<b4fc2ad80807162047i338faf7ra1253b5dc00c7a1a@mail.gmail.com>
	<b4fc2ad80807162050s1de6b6aalc86203c7e1fe3df5@mail.gmail.com>
	<g5mkd5$ont$1@ger.gmane.org>
	<b4fc2ad80807162330g9b93bfeq1e55af9b3ed97400@mail.gmail.com>
	<b4fc2ad80807162333k6badc3d3of87f402003a3a00a@mail.gmail.com>
	<g5mqcp$6qj$1@ger.gmane.org>
	<b4fc2ad80807162358t576e6fb1x62965c27887b530@mail.gmail.com>
	<b4fc2ad80807170001r3b988e33wa073c90929c9811b@mail.gmail.com>
Message-ID: <b4fc2ad80807170005l3cac91cdk55283a25870c4bb1@mail.gmail.com>

And also:

Getting this in console when trying to generate report via HTMLTestRunner
(it displayed text correctly when tried simple unittest.main)
<td colspan='5' align='center'><a href="javascript:showOutput('pt1.1',
'test_create_account_to_check: Creating sample account for next
test')">pass</a>
<script language="javascript" type="text/javascript">output_list['pt1.1'] =
'!!! True\n?"???????? \'foobar\' ??????????. ? ????????????????????????????
?????????????????? ????????????: ffoobar foobar.foobar foofoo
fofo\n[]\n';</script>
</td>
</tr>



On Thu, Jul 17, 2008 at 10:01 AM, Oleg Oltar <oltarasenko at gmail.com> wrote:

> beryl:~ oleg$ env
> MANPATH=/usr/share/man:/usr/local/share/man:/usr/X11/man
> TERM_PROGRAM=Apple_Terminal
> TERM=xterm-color
> SHELL=/bin/bash
> TMPDIR=/var/folders/PC/PCtFE4gQGiqpQymiAScfnk+++TM/-Tmp-/
> Apple_PubSub_Socket_Render=/tmp/launch-UNXiC6/Render
> TERM_PROGRAM_VERSION=237
> USER=oleg
> COMMAND_MODE=unix2003
> SSH_AUTH_SOCK=/tmp/launch-hfpsIl/Listeners
> __CF_USER_TEXT_ENCODING=0x1F6:0:0
> PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin
> PWD=/Users/oleg
> LANG=ru_RU.UTF-8
> SHLVL=1
> HOME=/Users/oleg
> PYTHONPATH=:/Users/oleg/Documents/wishes_Test
> LOGNAME=oleg
> DISPLAY=/tmp/launch-1kgALC/:0
> SECURITYSESSIONID=a206d0
>
>
>
> On Thu, Jul 17, 2008 at 9:58 AM, Oleg Oltar <oltarasenko at gmail.com> wrote:
>
>> See previous message (sent it few seconds ago)
>>
>>
>> On Thu, Jul 17, 2008 at 9:55 AM, Mark Tolonen <metolone+gmane at gmail.com<metolone%2Bgmane at gmail.com>>
>> wrote:
>>
>>>  OK, your console is set to 'ascii' ('cp437' was my example and is the
>>> Windows console encoding).  'ascii' won't be able to display Russian.
>>> It shouldn't have displayed the "?????????????" characters either.
>>> Are you still running on the same terminal that display those
>>> characters?  Can you change your terminals encoding preference via an
>>> environment variable?
>>> --
>>> Mark
>>>
>>> "Oleg Oltar" <oltarasenko at gmail.com> wrote in message
>>> news:b4fc2ad80807162333k6badc3d3of87f402003a3a00a at mail.gmail.com...
>>>
>>> And in case:
>>> # coding: utf-8
>>>
>>> import traceback
>>> try:
>>>     raise Exception(u'?????????')
>>> except Exception,e:
>>>     print traceback.format_exc().decode('utf-8').encode('cp437',
>>> 'replace')
>>>
>>>
>>> Getting
>>>
>>> beryl:~ oleg$ python ./wish/newaccount/reg.py
>>> Traceback (most recent call last):
>>>   File "./wish/newaccount/reg.py", line 5, in <module>
>>>     raise Exception(u'?????????')
>>> Exception: <unprintable Exception object>
>>>
>>>
>>>
>>> My console settings:
>>>
>>> In [1]: import sys
>>>
>>> In [2]: sys.getdefaultencoding()
>>> Out[2]: 'ascii'
>>>
>>> In [3]: sys.stdout.encoding
>>> Out[3]: 'US-ASCII'
>>>
>>>
>>> On Thu, Jul 17, 2008 at 9:30 AM, Oleg Oltar <oltarasenko at gmail.com>
>>> wrote:
>>>
>>>> OK
>>>> the output:
>>>>
>>>>  # coding: utf-8
>>>>>
>>>>> import traceback
>>>>> try:
>>>>>     raise Exception(u'?????????')
>>>>> except Exception,e:
>>>>>     print traceback.format_exc().decode('utf-8')
>>>>>
>>>>
>>>>
>>>> >>> Traceback (most recent call last):
>>>>   File "/var/folders/PC/PCtFE4gQGiqpQymiAScfnk+++TM/-Tmp-/py46506ECT",
>>>> line 7, in <module>
>>>>     print traceback.format_exc().decode('utf-8')
>>>> UnicodeEncodeError: 'ascii' codec can't encode characters in position
>>>> 148-156: ordinal not in range(128)
>>>>
>>>>
>>>>
>>>>
>>>> On Thu, Jul 17, 2008 at 8:13 AM, Mark Tolonen <metolone+gmane at gmail.com<metolone%2Bgmane at gmail.com>>
>>>> wrote:
>>>>
>>>>>  The Exception is output in the encoding of the source file.  If the
>>>>> terminal you are displaying the exception on is in a different encoding, it
>>>>> will be garbled.  I'm not familiar with OS X's terminal.  Try running python
>>>>> and printing sys.stdout.encoding.
>>>>>
>>>>> Alternatively, wrap your code in a try/except handler and translate the
>>>>> exception yourself.
>>>>>
>>>>>     # coding: utf-8
>>>>>     import traceback
>>>>>     try:
>>>>>         raise Exception(u'??????????????????')
>>>>>     except Exception,e:
>>>>>         print traceback.format_exc().decode('utf-8')
>>>>>
>>>>> The last line translates the utf-8 traceback into Unicode.  Printing
>>>>> Unicode will encode the output with the terminal's decoding.  If there are
>>>>> characters it can't display, you'll still get an error, though.  You can be
>>>>> more explicit however:
>>>>>
>>>>>     print
>>>>> traceback.format_exc().decode('utf-8').encode('cp437','replace')
>>>>>
>>>>> In this case you'll get ? whenever a character can't be represented in
>>>>> the selected encoding.  cp437, for example, can't display any russian
>>>>> characters, so for me (on Windows) I just get all ???????????.  When I tried
>>>>> it with a character string that could be displayed in cp437, it worked fine:
>>>>>
>>>>>      Traceback (most recent call last):
>>>>>       File "<stdin>", line 1, in <module>
>>>>>       File "t4.py", line 4, in <module>
>>>>>         raise Exception('M???????')
>>>>>     Exception: M???????
>>>>>
>>>>> Another option is to redirect the output to a file and read the file
>>>>> with an editor that can display utf-8 (such as Notepad on Windows).
>>>>>
>>>>>     python testfile.py 2>error.txt          # this redirects stderr to
>>>>> a file.
>>>>>
>>>>> Hope that helps,
>>>>> Mark
>>>>>
>>>>> "Oleg Oltar" <oltarasenko at gmail.com> wrote in message
>>>>> news:b4fc2ad80807162050s1de6b6aalc86203c7e1fe3df5 at mail.gmail.com...
>>>>>
>>>>>> The code
>>>>>
>>>>>  # -*- coding: utf-8 -*-
>>>>> #!/usr/bin/python
>>>>>
>>>>>
>>>>> """
>>>>>
>>>>> This test case check how system works in the situation, when user tries
>>>>> to use already
>>>>> used username (domain)
>>>>>
>>>>> We are creating two accounts with such parameters:
>>>>> 1. Sex = Femle
>>>>> 2. Name1=Name2 = foobar%S
>>>>> 3. Pass1 = Name
>>>>> 4. Pass2 = Name
>>>>> 5. Email address1 = Email address2 =  Name at meta.ua
>>>>>
>>>>>
>>>>> In the test we use verification point - warning message about incorrect
>>>>> input of domain name and the
>>>>> sugestion message
>>>>>
>>>>> """
>>>>>
>>>>> from selenium import selenium
>>>>> import unittest, time, re
>>>>> import HTMLTestRunner
>>>>> import config
>>>>> import Creating_account_basic
>>>>>
>>>>>
>>>>>
>>>>>
>>>>> class Same_domain_name(unittest.TestCase):
>>>>>
>>>>>     def setUp(self):
>>>>>         self.name = "foobar"
>>>>>         self.email = self.name + "@meta.ua"
>>>>>         self.verificationErrors = []
>>>>>         self.selenium = selenium("localhost", 4444,config.browser,
>>>>> config.link)
>>>>>         self.selenium.start()
>>>>>
>>>>>     def test_create_account_to_check(self):
>>>>>         """Creating sample account for next test"""
>>>>>         sel = self.selenium
>>>>>         sel.open("/")
>>>>>         sel.click(u"link=???????????")
>>>>>         sel.wait_for_page_to_load("70000")
>>>>>         sel.click("id_gender_1")
>>>>>         sel.type("id_first_name", self.name)
>>>>>         sel.type("id_last_name", self.name)
>>>>>         sel.type("id_email", self.email)
>>>>>         sel.type("id_username",  self.name)
>>>>>
>>>>> #sel.wait_for_condition(sel.is_element_present("check_username_block"),
>>>>> 70000)
>>>>>         time.sleep(10)
>>>>>         print "!!!", sel.is_element_present("check_username_block")
>>>>>         sel.type("id_password",  self.name)
>>>>>         print sel.get_text("check_username_block").decode('cp-1252')
>>>>>         sel.type("id_password2", self.name)
>>>>>         sel.click(u"//input[@value='??????????????????']")
>>>>>         sel.wait_for_page_to_load("70000")
>>>>>         if config.debugMode is True:
>>>>>             time.sleep(5)
>>>>>
>>>>>
>>>>>     def tearDown(self):
>>>>>         self.selenium.stop()
>>>>>         print self.verificationErrors
>>>>>         self.assertEqual([], self.verificationErrors)
>>>>>
>>>>> if __name__ == "__main__":
>>>>>
>>>>>     unittest.main()
>>>>>     #HTMLTestRunner.main()
>>>>>
>>>>>
>>>>>
>>>>> On Thu, Jul 17, 2008 at 6:47 AM, Oleg Oltar <oltarasenko at gmail.com>
>>>>> wrote:
>>>>>
>>>>>> In [1]: import sys
>>>>>>
>>>>>> In [2]: sys.getdefaultencoding()
>>>>>> Out[2]: 'ascii'
>>>>>>
>>>>>> In [3]: sys.stdout.encoding
>>>>>> Out[3]: 'US-ASCII'
>>>>>>
>>>>>>
>>>>>> On Thu, Jul 17, 2008 at 6:29 AM, Oleg Oltar <oltarasenko at gmail.com>
>>>>>> wrote:
>>>>>>
>>>>>>> Seems need help there. Start getting
>>>>>>>
>>>>>>> Traceback (most recent call last):
>>>>>>>   File "./newaccount/Same_domain_name.py", line 56, in
>>>>>>> test_create_account_to_check
>>>>>>>     print sel.get_text("check_username_block")
>>>>>>> UnicodeEncodeError: 'ascii' codec can't encode characters in position
>>>>>>> 0-4: ordinal not in range(128)
>>>>>>>
>>>>>>>
>>>>>>> when trying to get the text of one of the elements.
>>>>>>>
>>>>>>> How to solve it?
>>>>>>>
>>>>>>>
>>>>>>> On Thu, Jul 17, 2008 at 5:11 AM, Oleg Oltar <oltarasenko at gmail.com>
>>>>>>> wrote:
>>>>>>>
>>>>>>>> OK,
>>>>>>>>
>>>>>>>> I just run the program from terminal. OS: OS X, IDLE = Emacs:).
>>>>>>>>
>>>>>>>> Yep used the string "# -*- coding: utf-8 -*-" to setup encoding....
>>>>>>>>
>>>>>>>>
>>>>>>>> On Thu, Jul 17, 2008 at 4:14 AM, Kent Johnson <kent37 at tds.net>
>>>>>>>> wrote:
>>>>>>>>
>>>>>>>>> Another possibility - do you have a coding declaration in your
>>>>>>>>> source
>>>>>>>>> file, something like
>>>>>>>>> # -*- coding: <encoding name> -*-
>>>>>>>>>
>>>>>>>>> If so, does the coding declaration match the actual encoding of the
>>>>>>>>> file?
>>>>>>>>>
>>>>>>>>> Kent
>>>>>>>>>
>>>>>>>>> On Wed, Jul 16, 2008 at 5:11 PM, Kent Johnson <kent37 at tds.net>
>>>>>>>>> wrote:
>>>>>>>>> > On Wed, Jul 16, 2008 at 2:40 PM, Oleg Oltar <
>>>>>>>>> oltarasenko at gmail.com> wrote:
>>>>>>>>> >> Hi I am using unittest framework with selenium.
>>>>>>>>> >>
>>>>>>>>> >> When I tried this code (my verification point)
>>>>>>>>> >>
>>>>>>>>> >>         self.assertEqual(True, sel.is_text_present(u"????????
>>>>>>>>> ?????? ??
>>>>>>>>> >> ?????????"), "System didn't give a correct warning about the
>>>>>>>>> password
>>>>>>>>> >> misstype")
>>>>>>>>> >>
>>>>>>>>> >>> Where u"???????? ?????? ?? ?????????" is russian = "Sorry
>>>>>>>>> passwords aren't
>>>>>>>>> >>> equal", and sel.is_text_present - searches text string on the
>>>>>>>>> page
>>>>>>>>> >>
>>>>>>>>> >> The output I get in case of failure was:
>>>>>>>>> >>
>>>>>>>>> >>
>>>>>>>>> >> Traceback (most recent call last):
>>>>>>>>> >>
>>>>>>>>> >>   File "./newaccount/Password_matching.py", line 50, in
>>>>>>>>> >> test_passwordMatching
>>>>>>>>> >>     self.assertEqual(True,
>>>>>>>>> sel.is_text_present(u"????????????????
>>>>>>>>> >> ???????????? ???? ? ????????????????"), "System didn't give a
>>>>>>>>> correct
>>>>>>>>> >> warning about the password misstype")
>>>>>>>>> >>
>>>>>>>>> >> AssertionError: System didn't give a correct warning about the
>>>>>>>>> password
>>>>>>>>> >> misstype
>>>>>>>>> >>
>>>>>>>>> >> Is there any way to get normal russian text instead of these
>>>>>>>>> strange D chars
>>>>>>>>> >> "????????...."
>>>>>>>>> >
>>>>>>>>> > I don't have the solution but maybe I can give you a useful clue.
>>>>>>>>> The
>>>>>>>>> > D characters are most likely the utf-8 encoding of the Russian
>>>>>>>>> text,
>>>>>>>>> > when displayed as if it is latin-1. So something in the system is
>>>>>>>>> > converting the text to utf-8 and your console probably has
>>>>>>>>> latin-1 or
>>>>>>>>> > cp1252 encoding.
>>>>>>>>> >
>>>>>>>>> > Some details might help - how are you running the program -
>>>>>>>>> console,
>>>>>>>>> > IDLE...? What OS? What are the values of sys.getdefaultencoding()
>>>>>>>>> and
>>>>>>>>> > sys.stdout.encoding?
>>>>>>>>> >
>>>>>>>>> > Kent
>>>>>>>>> >
>>>>>>>>>
>>>>>>>>
>>>>>>>>
>>>>>>>
>>>>>>
>>>>>  ------------------------------
>>>>>
>>>>> _______________________________________________
>>>>> Tutor maillist  -  Tutor at python.org
>>>>> http://mail.python.org/mailman/listinfo/tutor
>>>>>
>>>>>
>>>>> _______________________________________________
>>>>> Tutor maillist  -  Tutor at python.org
>>>>> http://mail.python.org/mailman/listinfo/tutor
>>>>>
>>>>>
>>>>
>>>  ------------------------------
>>>
>>> _______________________________________________
>>> Tutor maillist  -  Tutor at python.org
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>>
>>> _______________________________________________
>>> Tutor maillist  -  Tutor at python.org
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>>
>>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080717/56d5c6a7/attachment-0001.htm>

From monjissvel at googlemail.com  Thu Jul 17 13:46:41 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Thu, 17 Jul 2008 11:46:41 +0000
Subject: [Tutor] Any way of monitoring a python program's memory
	utilization?
In-Reply-To: <Pine.LNX.4.44.0807170112190.30663-100000@violet.rahul.net>
References: <e2f191310807170047m6a7c306s46eaa14049bae62d@mail.gmail.com>
	<Pine.LNX.4.44.0807170112190.30663-100000@violet.rahul.net>
Message-ID: <e2f191310807170446p454b93b7wc5e8496fdeccfc65@mail.gmail.com>

I see no problem, if you open very BIG files then your memory will get
filled up & your system will halt,
can you buy more food than your fridge can handle , and write to a list
asking to invistigate the problem ?

2008/7/17 Terry Carroll <carroll at tjc.com>:

> On Thu, 17 Jul 2008, Monika Jisswel wrote:
>
> > Well, you can check whether your system has reached its limits or not,
> but
> > what for ?
>
> So I can debug the problem.
>
> _______________________________________________
> 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/20080717/7d11da99/attachment.htm>

From josetjr at msn.com  Thu Jul 17 14:07:33 2008
From: josetjr at msn.com (josetjr at msn.com)
Date: Thu, 17 Jul 2008 06:07:33 -0600
Subject: [Tutor] How to populate a dictionary
Message-ID: <BLU119-DS40EFCCE712E3911CA9775BA8E0@phx.gbl>

Hello, I am taking python this summer, and have run into a problem.

The assignment is to create a dictionary from a text file:

"12/07/0526 = St Felix IV begins his reign as Catholic Pope"
"12/07/1109 = Crusaders capture Syria's harbor city of Tripoli"
"12/07/1191 = Richard Coeur de Lion and Crusaders defeat Saracens in Palestine"
"12/07/1290 = Jews are expelled from England by order of King Edward I"
"12/07/1442 = King Alfonso V of Arag?n becomes king of Naples"

"Create a dictionary of dates. Each date you have in there should have a special event. An example would be that the dictionary would contain the following
NOTE: You must have at least 100 different dates. You can get this from lists on the internet if you like, but it must be something real, not just garbage or something just made up.
12/28/1929: My Birthday
1/1/1948: New Years Day 48
9/11: the big one


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

Your program should start by creating an empty dictionary called dates. Then your program will get an array of ALL the keys for that dictionary and then write a loop that will display all the key/value pairs.
BUT: The dictionary setup file should exist OUTSIDE of the program, you should have lines in it that say something like "12/28/1948=Starting Day" or something like that. Your strategy will be to open that file, read it, split it into lines, then for each line, you will split that line by the equals = sign. The left side value is the Key and the Right Hand Side is the value.
You will read this whole files, splitting each key/value pair and store them in a dictionary. Then write the loop which will get all the keys, SORT those keys and print out the key/value pairs. 

here is a sample of my code:

#!python
myDictionary = { }
inputLines = open ("dates.txt") .read() .split ("\n")
for i in range ( len(inputLines) ) :
        if (inputLines [i] != "") :
            leftHandSide = inputLines [i].split ("=")
     rightHandSide = inputLines [i].split ("=")
     myDictionary [leftHandSide] = rightHandSide
theKeys = myDictionary.keys ()
theKeys.sort ()
for i in range (len (theKeys) ):
    print theKeys[i], myDictionary[ theKeys[i] ]

Can anyone help?

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080717/fafded06/attachment.htm>

From raghavendra.gv.vanam at gmail.com  Thu Jul 17 15:13:49 2008
From: raghavendra.gv.vanam at gmail.com (vanam)
Date: Thu, 17 Jul 2008 18:43:49 +0530
Subject: [Tutor] Recursive function
Message-ID: <4499cb6a0807170613q52c01c56v7751d9f9eeeca4b6@mail.gmail.com>

hi all,
i am new to programming, i just started writing scripts in python about
functions.There is a program by name hangman where in i take input three
characters and then concatenate the resultant output is compared to a three
letter string, if it is similar it will display the word as correct if not i
want to execute the same function which evokes to prompt for three
characters as input. The problem is i am not getting a runtime error.
below is the piece of code:
#word Hangman
print "Welcome to the Hangman"
print
print
a = raw_input("enter 1st letter=")
b = raw_input("enter 2nd letter=")
c = raw_input("enter 3rd letter=")
def cmp():
    d = (a+b+c);
    if (d=='PAN'):
        print "word" 'd' "is correct"
    else:
        print "Try Again"
        CALL();
def CALL():
    cmp();
cmp()

-- 
Raghavendra Vanam
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080717/fa6c616e/attachment.htm>

From motoom at xs4all.nl  Thu Jul 17 15:02:22 2008
From: motoom at xs4all.nl (Michiel Overtoom)
Date: Thu, 17 Jul 2008 15:02:22 +0200
Subject: [Tutor] How to populate a dictionary
Message-ID: <2.2.32.20080717130222.012edd88@pop.xs4all.nl>

josetjr wrote...

>Hello, I am taking python this summer, and have run into a problem.


Let me suggest some improvements. You can process all the lines in a
textfile like this:

    for line in open("dates.txt").readlines():
        print line
    
Furthermore, if you have a string in the form of "ABC=DEF", you can split it
like this:

    key,value=s.split("=")

To enumerate the keys of a dictionary in alphabetical order, you can use:

    for k in sorted(d):
        print k
        
So, your little homework program becomes more pythonic like this:

history={}
for line in open("dates.txt").readlines(): 
    line=line.strip("\n\"") # clean the line a bit; strip off the newline
and quotes
    date,event=line.split("=")
    history[date]=event

for k in sorted(history):
    print k,history[k]
    

Have a nice day,



-- 
"The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing." - Vinod Vallopillil
http://www.catb.org/~esr/halloween/halloween4.html


From chester_lab at fltg.net  Thu Jul 17 15:21:14 2008
From: chester_lab at fltg.net (FT)
Date: Thu, 17 Jul 2008 09:21:14 -0400
Subject: [Tutor] How to populate a dictionary
References: <BLU119-DS40EFCCE712E3911CA9775BA8E0@phx.gbl>
Message-ID: <001801c8e810$0c1dcee0$0301a8c0@brucetower>


Dates = {}
def read_Dates (Dates):
    if os.path.exists(FILE_NAME):
        store = open(FILE_NAME,'r')
        for line in store:
            name = line.rstrip()
            entry = store.next().rstrip()
            Dates[name] = entry
        store.close()

def save_Dates (Dates):
    store = open(FILE_NAME, 'w')
    for name,entry in Dates.items():
        store.write(name + '\n')
        store.write(entry + '\n')
    store.close()
    print "%s File Saved and Closed!" % FILE_NAME

----- Original Message ----- 
From: josetjr at msn.com 
To: tutor at python.org 
Sent: Thursday, July 17, 2008 8:07 AM
Subject: [Tutor] How to populate a dictionary


Hello, I am taking python this summer, and have run into a problem.

The assignment is to create a dictionary from a text file:

"12/07/0526 = St Felix IV begins his reign as Catholic Pope"
"12/07/1109 = Crusaders capture Syria's harbor city of Tripoli"
"12/07/1191 = Richard Coeur de Lion and Crusaders defeat Saracens in Palestine"
"12/07/1290 = Jews are expelled from England by order of King Edward I"
"12/07/1442 = King Alfonso V of Arag?n becomes king of Naples"

"Create a dictionary of dates. Each date you have in there should have a special event. An example would be that the dictionary would contain the following
NOTE: You must have at least 100 different dates. You can get this from lists on the internet if you like, but it must be something real, not just garbage or something just made up.
12/28/1929: My Birthday
1/1/1948: New Years Day 48
9/11: the big one


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

Your program should start by creating an empty dictionary called dates. Then your program will get an array of ALL the keys for that dictionary and then write a loop that will display all the key/value pairs.
BUT: The dictionary setup file should exist OUTSIDE of the program, you should have lines in it that say something like "12/28/1948=Starting Day" or something like that. Your strategy will be to open that file, read it, split it into lines, then for each line, you will split that line by the equals = sign. The left side value is the Key and the Right Hand Side is the value.
You will read this whole files, splitting each key/value pair and store them in a dictionary. Then write the loop which will get all the keys, SORT those keys and print out the key/value pairs. 

here is a sample of my code:

#!python
myDictionary = { }
inputLines = open ("dates.txt") .read() .split ("\n")
for i in range ( len(inputLines) ) :
        if (inputLines [i] != "") :
            leftHandSide = inputLines [i].split ("=")
     rightHandSide = inputLines [i].split ("=")
     myDictionary [leftHandSide] = rightHandSide
theKeys = myDictionary.keys ()
theKeys.sort ()
for i in range (len (theKeys) ):
    print theKeys[i], myDictionary[ theKeys[i] ]

Can anyone help?




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


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



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


No virus found in this incoming message.
Checked by AVG. 
Version: 7.5.524 / Virus Database: 270.5.0/1557 - Release Date: 7/17/2008 5:36 AM
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080717/ac68564e/attachment-0001.htm>

From bgailer at gmail.com  Thu Jul 17 15:32:31 2008
From: bgailer at gmail.com (bob gailer)
Date: Thu, 17 Jul 2008 09:32:31 -0400
Subject: [Tutor] How to populate a dictionary
In-Reply-To: <BLU119-DS40EFCCE712E3911CA9775BA8E0@phx.gbl>
References: <BLU119-DS40EFCCE712E3911CA9775BA8E0@phx.gbl>
Message-ID: <487F49EF.9020707@gmail.com>

Several reactions:

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

As I understood it the list policy is:

1) not solve homework problems.
2) request students to tell us exactly what problems they were running into
     e.g. expected output, actual output, exceptions, ...
3) then give specific suggestions

We seem to have violated that policy in this case.

Can we in agreement on the policy?

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

I also prefer list posts to be in plain text rather than various fonts, 
sizes and colors.

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

I think that assignment is very poorly worded!

Why the busywork of coming up with 100 real dates. What does that have 
to do with programming?

-- 
Bob Gailer
919-636-4239 Chapel Hill, NC


From alan.gauld at btinternet.com  Thu Jul 17 16:36:48 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 17 Jul 2008 15:36:48 +0100
Subject: [Tutor] Any way of monitoring a python program's
	memoryutilization?
References: <e2f191310807170047m6a7c306s46eaa14049bae62d@mail.gmail.com><Pine.LNX.4.44.0807170112190.30663-100000@violet.rahul.net>
	<e2f191310807170446p454b93b7wc5e8496fdeccfc65@mail.gmail.com>
Message-ID: <g5nle4$3cs$1@ger.gmane.org>

"Monika Jisswel" <monjissvel at googlemail.com> wrote...
>I see no problem, if you open very BIG files then your memory will 
>get
> filled up & your system will halt,

Only if you were to foolishly read the whole file into memory at once.
Early computers only had memories of a few kilobytes but could
process files much larger than that  - I recall using one with
only 16K RAM and no hard drive( a server not a home computer)
that was able to process data files of several megabytes. And
many PC databases are 10's of GB in size and a database is
no more than a few very big files. Given that many PCs have
a hardware upper memory limit of 2G and 32bit processors
a limit of 4G that would make life very difficult if we were 
restricted
in file size by the RAM available.

You just have to make sure you read the files in small chunks.
and process each chunk in turn. (A technique usually referred to
as paging.) In python the chunk size is usually a line... There is
only a problem if you try saving all of the lines into a collection
of some sort

>> So I can debug the problem.

The problem he is trying to debug is why the files are using up
his memory when he (presumably) was not expecting them to
fill it. To use the fridge analogy, why is the fridge still full after
I've eaten all the food?

Alan G. 



From alan.gauld at btinternet.com  Thu Jul 17 16:53:26 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 17 Jul 2008 15:53:26 +0100
Subject: [Tutor] How to populate a dictionary
References: <BLU119-DS40EFCCE712E3911CA9775BA8E0@phx.gbl>
Message-ID: <g5nmda$7cm$1@ger.gmane.org>

<josetjr at msn.com> wrote

> The assignment is to create a dictionary from a text file:

ok, since it's 'homework' I won't give the whole answer but will try
to point you in the right direction.

> Your program should start by creating an empty dictionary called 
> dates.

> Then your program will get an array of ALL the keys for that 
> dictionary
> and then write a loop that will display all the key/value pairs.

OK, I'm not sure why they want you to build an array, its not really
necessary...

> you should have lines in it that say something like 
> "12/28/1948=Starting Day"

> open that file, read it, split it into lines, then for each line,

Again you don;t need to do all of that, Python has a function
readlines() that does it all for you.

> you will split that line by the equals = sign.
> The left side value is the Key and the Right Hand Side is the value.

> You will read this whole files, splitting each key/value pair and
> store them in a dictionary.

You can do this one line at a time rather than reading the file
then going back over it to split/store the data.

> Then write the loop which will get all the keys,
> SORT those keys and print out the key/value pairs.

OK, Again thats a bit off track as a sequence. I'd get the keys,
sort them then write a loop over the sorted keys to display the 
results.

myDictionary = { }

#AG-You were asked to call it dates!

inputLines = open ("dates.txt") .read() .split ("\n")
for i in range ( len(inputLines) ) :

Could just be:

for line in open("dates.txt"):

        if (inputLines [i] != "") :
            leftHandSide = inputLines [i].split ("=")
     rightHandSide = inputLines [i].split ("=")

These two lines do the same split. You need to store the first split
value in one variable and the second in the other. (Remember split()
returns a list). Try:

lhs, rhs = line.split('=')

     myDictionary [leftHandSide] = rightHandSide

theKeys = myDictionary.keys ()
theKeys.sort ()
for i in range (len (theKeys) ):
    print theKeys[i], myDictionary[ theKeys[i] ]

Rather than indexing via range(len()), a Python for loop is best used
to get the items directly. Thus:

for key in theKeys:
    print key, dates[key]

See how much more readable it is? And how much less typing!


If you have a recent version of Python you can also avoid the
business of extracting the keys and sorting them by using the
sorted() function on the dates directly as part of the for loop.
I'll leave that as an extra research topic! :-)

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 Jul 17 16:58:01 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 17 Jul 2008 15:58:01 +0100
Subject: [Tutor] How to populate a dictionary
References: <2.2.32.20080717130222.012edd88@pop.xs4all.nl>
Message-ID: <g5nmlt$8cn$1@ger.gmane.org>


"Michiel Overtoom" <motoom at xs4all.nl> wrote

> Let me suggest some improvements. You can process all the lines in a
> textfile like this:
>
>    for line in open("dates.txt").readlines():
>        print line

Or just

for line in open("dates.txt"):
    print line.rstrip()

> So, your little homework program becomes more pythonic like this:

Spoilsport, you showed him the answer! :-)

Alan G 



From alan.gauld at btinternet.com  Thu Jul 17 17:02:09 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 17 Jul 2008 16:02:09 +0100
Subject: [Tutor] How to populate a dictionary
References: <BLU119-DS40EFCCE712E3911CA9775BA8E0@phx.gbl>
	<487F49EF.9020707@gmail.com>
Message-ID: <g5nmtk$9eg$1@ger.gmane.org>


"bob gailer" <bgailer at gmail.com> wrote

> As I understood it the list policy is:
>
> 1) not solve homework problems.
> 2) request students to tell us exactly what problems they were 
> running into
>     e.g. expected output, actual output, exceptions, ...
> 3) then give specific suggestions
>
> We seem to have violated that policy in this case.
>
> Can we in agreement on the policy?

So far as I know the policy remains as it always was Bob.

> I also prefer list posts to be in plain text rather than various 
> fonts, sizes and colors.

I haven't had that problem. They are all in plain text whenI get them,
but thats probably my mail/news reader settings

> I think that assignment is very poorly worded!

I agree, the recommended sequence to solve is not great,
but it's better than some homework assignments I've seen
posted here.

> Why the busywork of coming up with 100 real dates. What does that 
> have to do with programming?

Agreed, thats just silly. Unless the course is also trying to teach
research skills!

Alan G. 



From alan.gauld at btinternet.com  Thu Jul 17 17:13:13 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 17 Jul 2008 16:13:13 +0100
Subject: [Tutor] IPython problem: Difficulty in setting editor to TextPad
References: <20080717095442.48F0C1E4003@bag.python.org>
Message-ID: <g5nnid$c54$1@ger.gmane.org>

"Dick Moores" <rdm at rcblue.com> wrote
> In my ipy_user_conf.py I have put this line:
> ipy_editors.install_editor("C:\Program Files\TextPad 5\TextPad.exe")

escape the spaces and backslashes(raw string might work as well)

ipy_editors.install_editor("C:\\Program\ Files\\TextPad 
5\\TextPad.exe")

OR maybe

ipy_editors.install_editor(r"C:\Program Files\TextPad 5\TextPad.exe")

Alan G 



From alan.gauld at btinternet.com  Thu Jul 17 17:10:51 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 17 Jul 2008 16:10:51 +0100
Subject: [Tutor] Recursive function
References: <4499cb6a0807170613q52c01c56v7751d9f9eeeca4b6@mail.gmail.com>
Message-ID: <g5nndv$bhj$1@ger.gmane.org>

"vanam" <raghavendra.gv.vanam at gmail.com> wrote

> i am new to programming, i just started writing scripts in python 
> about
> functions.

You need to check the section of your tutorial/book that
discusses loops. That will make your solution much easier.

> characters as input. The problem is i am not getting a runtime 
> error.

Tell us what you are getting (and what you expected), it makes our
job easier if we don't have to guess.

> below is the piece of code:
> #word Hangman
> print "Welcome to the Hangman"
> print
> print
> a = raw_input("enter 1st letter=")
> b = raw_input("enter 2nd letter=")
> c = raw_input("enter 3rd letter=")
> def cmp():

You shouldn't write functions with the same name as builtin
functions. You will not be able to use the builtin one if you do!
cmp() is the builtin Python function for comparing two things.

>    d = (a+b+c);

You could just have read the three letters at once using
raw_input...

>    if (d=='PAN'):
>        print "word" 'd' "is correct"
>    else:
>        print "Try Again"
>        CALL();
> def CALL():
>    cmp();

You don;t need CALL, you could just have called cmp from
inside cmp - this is known as a recursice call and is allowed
in Python. It can be used to create a loop effect here as you
do but it has a limited number of repetitions and is best not
used for that purpose. Instead use the built in looping
constructs in Python "for" or "while"

In your case you probabnly want something like:

d = ""
while d != "PAN":
    # code inserted here
print "Word", d, "is correct"   # only prints when d == PAN

HTH,

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



From rdm at rcblue.com  Thu Jul 17 17:39:49 2008
From: rdm at rcblue.com (Dick Moores)
Date: Thu, 17 Jul 2008 08:39:49 -0700
Subject: [Tutor] IPython problem: Difficulty in setting editor to TextPad
In-Reply-To: <g5nnid$c54$1@ger.gmane.org>
References: <20080717095442.48F0C1E4003@bag.python.org>
	<g5nnid$c54$1@ger.gmane.org>
Message-ID: <20080717154004.024301E400B@bag.python.org>

At 08:13 AM 7/17/2008, Alan Gauld wrote:
>"Dick Moores" <rdm at rcblue.com> wrote
>>In my ipy_user_conf.py I have put this line:
>>ipy_editors.install_editor("C:\Program Files\TextPad 5\TextPad.exe")
>
>escape the spaces and backslashes(raw string might work as well)

Yeah, I tried that (except for the raw string).

>ipy_editors.install_editor("C:\\Program\ Files\\TextPad 5\\TextPad.exe")
>
>OR maybe
>
>ipy_editors.install_editor(r"C:\Program Files\TextPad 5\TextPad.exe")

I finally got some help from one of the main IPython guys (just now). 
The line that partially works is
ipy_editors.install_editor('"C:\Program Files\TextPad 5\TextPad.exe" 
${file}(${line})')

But using the line number doesn't work, so I skip it and do

In [3]: ed versions.py
Editing... > "C:\Program Files\TextPad 5\TextPad.exe" versions.py(0)

This DOES open versions.py in Textpad, with the caret at line 1.

Thanks for your educated guesses, Alan.

Dick
======================================
Have you seen the video introducing the terrific
and free IDE, Ulipad? Download it from my website.
<http://www.rcblue.com/u3/>



From monjissvel at googlemail.com  Thu Jul 17 21:07:07 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Thu, 17 Jul 2008 19:07:07 +0000
Subject: [Tutor] continuouse loop
Message-ID: <e2f191310807171207g32230df5h63a25f6adfccbf69@mail.gmail.com>

Would a program using a continuouse loop such as in this code take up
resources on the system if left for long period ?

import sys
>
> while 1:
>     self.data = sys.stdin.readline()
>     self.function_1(data)
>

What are my other options is I want to have a running program & other
programs communicate with it & get responses from it ?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080717/d469cfaf/attachment-0001.htm>

From alan.gauld at btinternet.com  Thu Jul 17 21:28:53 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 17 Jul 2008 20:28:53 +0100
Subject: [Tutor] continuouse loop
References: <e2f191310807171207g32230df5h63a25f6adfccbf69@mail.gmail.com>
Message-ID: <g5o6hp$5af$1@ger.gmane.org>


"Monika Jisswel" <monjissvel at googlemail.com> wrote

> Would a program using a continuouse loop such as in this code take 
> up
> resources on the system if left for long period ?

Any running program takes up some resources but whether this
one would increase its resource usage over time, which I assume
is what you want to know, would depend on what it did with self.data
and what happened in self.function_1.

If function_1 did nothing that was resource intensive - like build
a big list in memory or open a new file each time it was called
(and not release it) - then it would be fine. But if function_1 stored
data in a list or opened a new comms port on each call then yes
it will eat up resources.

> import sys
>>
>> while 1:
>>     self.data = sys.stdin.readline()
>>     self.function_1(data)

> What are my other options is I want to have a running program & 
> other
> programs communicate with it & get responses from it ?

The trick to writing long running processes such as Windows services
and Unix daemons is to ensure they are either stateless (the create
use and free the needed resources in each operation) or utilise pools
(pre-allocated sets of resources that are allocated to a function as
needed and released by the function when done - if you run out of
pool you take a decision to enlarge the pool or to stop servicing
requests until resource becomes available - possibly using a
queue if instant response is not critical)

Thee are framweworks around, such as twisted, that help with these
tasks.

HTH,

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



From carroll at tjc.com  Thu Jul 17 23:55:21 2008
From: carroll at tjc.com (Terry Carroll)
Date: Thu, 17 Jul 2008 14:55:21 -0700 (PDT)
Subject: [Tutor] Any way of monitoring a python program's memory
	utilization?
In-Reply-To: <e2f191310807170446p454b93b7wc5e8496fdeccfc65@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0807171429210.426-100000@violet.rahul.net>

On Thu, 17 Jul 2008, Monika Jisswel wrote:

> I see no problem, if you open very BIG files then your memory will get
> filled up & your system will halt,

I'm going to disagree with you on this one.

First, in general, it is not the case that opening a very large file will 
cause memory to be filled up. In general, only the portion of the file 
that is being processed needs to actually be in memory.  A tarfile appears 
to be an exception to that general rule.  The question is, why?  Can that 
exception be avoided and a program that's processing a tar file be as 
well-behaved in terms of resource consumption as a program that processes 
other types of files?

Second, although most resource constraint problems can often be addressed 
by buying more resource, that's not usually a good approach.  Where, as 
here, the resource constraint surfaces only in rare cases (i.e., 
processing a tarfile), the better approach is to find out if something is 
out of whack with respect to that one case.  

Simply adding resources is a poor use of, um, resources, for a couple
reasons.  I'd rather spend my money on a nice dinner than on adding memory
to a computer system that is perfectly adequate in every other way, other
than in processing a single file.  And adding resources, whether memory, 
disk, or CPU, is a band-aid: it gets you over this hump, but not the next.  
If I add enough memory to process a 4-Gb file, great, I can now process a 
4-Gb file.  But if I get a 6-Gb file in a couple months, I have to pull 
out the checkbook again.

But managing the resource utilization is a scalable scheme.

> can you buy more food than your fridge can handle , and write to a list
> asking to invistigate the problem ?

This is such an off-the wall analogy that it's difficult to respond to, 
but what the heck.

First, I'm not writing to the list to ask it to investigate the problem.  
I'm writing to the list to find out what tools are available so that *I*
can investigate the problem.

Second, under this analogy, you're looking at a scenario where food is 
put into a refrigerator in containers, and when consumed, the containers 
are left in the refrigerator.  Now, your solution here might be to keep 
buying more or larger refrigerators.  Mine would be to see if I can get 
rid of all the empty containers that are uselessly occupying space in the 
refrigerator, so I can utilize the space for useful purposes 
(refrigerating food) rather than chilling empty containers for no reason.

Back to the real Python case: now that I can monitor my memory usage, I
can try various strategies to solve the problem, and I can do it with a
subset of data.  Instead of running the program on a 4Gb file and waiting
to see if it blows up or halts my system in 15 minutes after processing a
couple gig, I can run it with a much smaller 60 Mb file, and track its
effects.

For anyone who cares about the real issue: it seems that tarfile.py caches
every member it processes in an internal list.  The list isn't actually
used if accessing the file as an iterator, so by reinitializing it to [],
the memory consumption problem is avoided.  This breaks other methods of
the module, which are used to extract particular desired members, but in
my case, that's okay.  I'm currently experimenting to see if I can come up
with a patch that will either allow both means of accessing the members
(as an iterator and directly), or, as a less desirable alternative, if a
parameter like cache=False is specified, allow access as an iterator and
raise an exception if the other methods are used.

Thanks to a couple tarfile.py experts on comp.lang.python for their 
insight on this.


From monjissvel at googlemail.com  Fri Jul 18 00:45:15 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Thu, 17 Jul 2008 22:45:15 +0000
Subject: [Tutor] Any way of monitoring a python program's memory
	utilization?
In-Reply-To: <Pine.LNX.4.44.0807171429210.426-100000@violet.rahul.net>
References: <e2f191310807170446p454b93b7wc5e8496fdeccfc65@mail.gmail.com>
	<Pine.LNX.4.44.0807171429210.426-100000@violet.rahul.net>
Message-ID: <e2f191310807171545u917fa8frfcbdf976f833cb8a@mail.gmail.com>

I m really sorry if no one of you liked/agreed with the fridge analogy but
that's what my brain could come up with at the time, I have to say it's not
a very scientific argument. but I only meant to say that if you are piping
data into memory & this data is larger than that memory then there is no
problem with the code but with the data, & I think this paragraph actually
confirms some of it :

For anyone who cares about the real issue: it seems that tarfile.py caches
> every member it processes in an internal list.  The list isn't actually
> used if accessing the file as an iterator, so by reinitializing it to [],
> the memory consumption problem is avoided.  This breaks other methods of
> the module, which are used to extract particular desired members, but in
> my case, that's okay.
>

but I have to admit I was completely wrong and a new patch to the tarfile
module will soon see the light to fix this problem for the rest of ur lives
painlessly.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080717/5a6f7ffb/attachment.htm>

From m1tchellnguyen at yahoo.com  Fri Jul 18 00:39:48 2008
From: m1tchellnguyen at yahoo.com (Mitchell Nguyen)
Date: Thu, 17 Jul 2008 15:39:48 -0700 (PDT)
Subject: [Tutor] Question on how to do something.
Message-ID: <912405.29227.qm@web38603.mail.mud.yahoo.com>

Hello. I'm new to Python and I was wondering how to read all the files in a folder. I used this program or command for single files.

import?pprint



pprint.pprint(open(r'c:\text\somefile.txt').readlines())
And if possible, is there a way to make it so that it waits at the end of each file for a confirmation to go onto the next file? Thanks




      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080717/b84dc7ab/attachment.htm>

From mwalsh at groktech.org  Fri Jul 18 03:15:54 2008
From: mwalsh at groktech.org (Martin Walsh)
Date: Thu, 17 Jul 2008 20:15:54 -0500
Subject: [Tutor] continuouse loop
In-Reply-To: <e2f191310807171207g32230df5h63a25f6adfccbf69@mail.gmail.com>
References: <e2f191310807171207g32230df5h63a25f6adfccbf69@mail.gmail.com>
Message-ID: <487FEECA.3020300@groktech.org>

Monika Jisswel wrote:
> Would a program using a continuouse loop such as in this code take up
> resources on the system if left for long period ?
> 
>     import sys
> 
>     while 1:
>         self.data = sys.stdin.readline()
>         self.function_1(data)

Not much, I would think, until something is written to stdin of this
program, and then it would depend on what function_1 does.

> What are my other options is I want to have a running program & other
> programs communicate with it & get responses from it ?

If I understand what you're asking, there are a few options outlined in
the python library reference, here:
http://docs.python.org/lib/ipc.html

I would add named pipes as another option for *nix, windows may have
something similar. And, depending on what you're trying to accomplish
maybe xmlrpclib, soappy, pyro, or perhaps even cgi.

HTH,
Marty


From cspears2002 at yahoo.com  Fri Jul 18 06:09:58 2008
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Thu, 17 Jul 2008 21:09:58 -0700 (PDT)
Subject: [Tutor] creating pop method for stack class
Message-ID: <289059.15816.qm@web51610.mail.re2.yahoo.com>

I am almost done with a stack class that I wrote:

#!/usr/bin/python

class Stack(list):
    def isempty(self):
        length = len(self)
        if length == 0:
	    return True
	else:
	    return False
	    
    def peek(self):
        length = len(self)
	if length == 0:
	    return 0
	else:
	    last_index = length - 1
            return self[last_index]
    
    def stackpop(self):
        length = len(self)
	if length == 0:
	    print "Empty list!"
	else:
	    last_index = length - 1
	    stackpop_val = self[last_index]
	    self = self[:last_index]
	    return stackpop_val
    
    def push(self, value):
        return self.append(value)
	
if __name__ == '__main__':
    x = True
    stack = Stack()
    print "Pick an option to modify stack: "
    while x == True:
	print "1) Peek at the last value"
	print "2) Pop off the last value"
	print "3) Push a value on the stack"
	print "4) Print stack"
	print "5) Quit Program"
	choice_string = raw_input("Make a choice: ")
    
        try:
            choice = int(choice_string)
        except ValueError:
            sys.exit("Not an integer!  Goodbye!")
  
        if choice == 1:
	    if stack.isempty():
	        print "Stack is empty"
	    else:
                peek_val = stack.peek()
	        print peek_val
        elif choice == 2:
	    pop_val = stack.stackpop()
	    print pop_val
        elif choice == 3:
	    push_val = raw_input("Push this value on stack: ")
            stack.push(push_val)
        elif choice == 4:
            print stack
	elif choice == 5:
	    print "Goodbye!"
	    x = False
        else:
	    x = False
            sys.exit("Wrong response Goodbye!")

My main problem seems to be getting this part to work:

def stackpop(self):
        length = len(self)
	if length == 0:
	    print "Empty list!"
	else:
	    last_index = length - 1
	    stackpop_val = self[last_index]
	    self = self[:last_index]
	    return stackpop_val

The easiest solution would be to use the pop method from list, but I decided I wanted to take a crack at writing my own pop method.  Unfortunately, this always happens when I run the program:

1) Peek at the last value
2) Pop off the last value
3) Push a value on the stack
4) Print stack
5) Quit Program
Make a choice: 3
Push this value on stack: 1
1) Peek at the last value
2) Pop off the last value
3) Push a value on the stack
4) Print stack
5) Quit Program
Make a choice: 3
Push this value on stack: blah
1) Peek at the last value
2) Pop off the last value
3) Push a value on the stack
4) Print stack
5) Quit Program
Make a choice: 3
Push this value on stack: blah blah
1) Peek at the last value
2) Pop off the last value
3) Push a value on the stack
4) Print stack
5) Quit Program
Make a choice: 2
blah blah
1) Peek at the last value
2) Pop off the last value
3) Push a value on the stack
4) Print stack
5) Quit Program
Make a choice: 4
['1', 'blah', 'blah blah']

How come the stack doesn't shrink when I pop off the last value?  I tested the code in the interpreter:

>>> lista = [1,2,3,4]
>>> lista[:len(lista)-1]
[1, 2, 3]
>>> lista = lista[:len(lista)-1]
>>> lista
[1, 2, 3]

Any hints?


      

From john at fouhy.net  Fri Jul 18 06:26:14 2008
From: john at fouhy.net (John Fouhy)
Date: Fri, 18 Jul 2008 16:26:14 +1200
Subject: [Tutor] creating pop method for stack class
In-Reply-To: <289059.15816.qm@web51610.mail.re2.yahoo.com>
References: <289059.15816.qm@web51610.mail.re2.yahoo.com>
Message-ID: <5e58f2e40807172126o409808a8j66f3f2d022759270@mail.gmail.com>

On 18/07/2008, Christopher Spears <cspears2002 at yahoo.com> wrote:
>  How come the stack doesn't shrink when I pop off the last value?  I tested the code in the interpreter:
>
>  >>> lista = [1,2,3,4]
>  >>> lista[:len(lista)-1]
>  [1, 2, 3]
>  >>> lista = lista[:len(lista)-1]
>  >>> lista
>  [1, 2, 3]

First, a tip:

Instead of lista[:len(lista)-1], you can (and should) just write lista[:-1].

Now, what if we wrap that in a function:

>>> def shorten(lst):
...   lst = lst[:-1]  # identical to: lst = lst[:len(lst)-1]
...

Then test it:

>>> lista = [1, 2, 3, 4]
>>> shorten(lista)

What do you think will be the result of:

>>> print lista

?

PS.  You wrote:

>     def stackpop(self):
>         length = len(self)
>         if length == 0:
>             print "Empty list!"

If you're trying to pop from an empty stack, this is an error
condition.  Rather than printing a message, the correct way to handle
errors in python is by raising exceptions.  e.g.

def stackpop(self):
    if len(self) == 0:
        raise IndexError    # or you could define your own exception...

>     def peek(self):
>         length = len(self)
>         if length == 0:
>             return 0

The same applies here -- peeking at an empty stack should be an error
too.  Otherwise, how can you tell the difference between an empty
stack and a stack where the top item happens to be a 0?

-- 
John.

From nibudh at gmail.com  Fri Jul 18 06:56:24 2008
From: nibudh at gmail.com (nibudh)
Date: Fri, 18 Jul 2008 14:56:24 +1000
Subject: [Tutor] parsing sendmail logs
In-Reply-To: <487CA578.7060300@groktech.org>
References: <77f8f7c30807140029w4c2d003cg8c49b8c08e140dd8@mail.gmail.com>
	<1c2a2c590807140347m31569475iae4b1dfcb35241ec@mail.gmail.com>
	<e2f191310807141110n985be8fwace998044c06c15c@mail.gmail.com>
	<77f8f7c30807141725m51c0ef14t31f23a8381c5633@mail.gmail.com>
	<e2f191310807150415m516fefddxcd1922dc6b1de3ee@mail.gmail.com>
	<487CA578.7060300@groktech.org>
Message-ID: <77f8f7c30807172156t1bbf21basd9a9c8a52cffa6f@mail.gmail.com>

2008/7/15 Martin Walsh <mwalsh at groktech.org>:

>  >     Any pragmatic advice on building or working with a framework to get
> >     to the point where i can do analysis on my logs would be cool.
> >
>
>
> As an exercise, I think it would be a reasonable approach to write
> python derivatives of the shell commands being used, perhaps tailored to
> the data set, to get a feel for working with text data in python. Then
> ask questions here if you get stuck, or need optimization advice. I
> think you'll find you can accomplish this with just a few lines of
> python code for each (sort -u, grep, awk '{print $n}', etc), given your
> use of the commands in the examples provided. Write each as a function,
> and you'll end up with code you can reuse for other log analysis
> projects. Bonus!
>
> HTH,
> Marty
>
>
Hi Marty,

Thanks for the input. I like the idea of writing tailored versions of the
standard unix tools. I think what has held me back from writing more than a
few scripts based on someone elses code is a lack of clarity about what i'm
wanting to write.

I've done a bit of web programming in ASP,PHP and Perl mostly in the
presentation layer, but the shift in domain to sysadmin tasks has for some
reason has been difficult.

To essentially re-write "sort -u" in python has the advantage for me that i
use sort _alot_ so i'm familiar with the concept and it's  a small enough
tasks to feel doable. :-)

Your suggestion also provides an insight into how to program that i find
easy to forget. which is to break things down into smaller pieces.

Cheers,

nibuh.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080718/594aab06/attachment.htm>

From nibudh at gmail.com  Fri Jul 18 06:59:42 2008
From: nibudh at gmail.com (nibudh)
Date: Fri, 18 Jul 2008 14:59:42 +1000
Subject: [Tutor] parsing sendmail logs
In-Reply-To: <C5816C01-7216-4C15-A498-F4558FFE0734@drinktomi.com>
References: <77f8f7c30807140029w4c2d003cg8c49b8c08e140dd8@mail.gmail.com>
	<C5816C01-7216-4C15-A498-F4558FFE0734@drinktomi.com>
Message-ID: <77f8f7c30807172159n2f009cc4j814ea3efcab4b90a@mail.gmail.com>

2008/7/16 Jeff Younker <jeff at drinktomi.com>:

> Parsers as referenced in your link are intended for heavy-duty lifting
> such as parsing programming languages.
>
> Sendmail logs are very simple, so those parsers are vast overkill.   Split
> on whitespace combined with regular expressions should be up to the job.
>
> -jeff
>
>
Jeff,

Thanks for the clarification, I was looking at these parsers thinking they
were overkill.

split and regex for version 0.0.0.1 of my script looks like the order of the
day :-)

Cheers,

ram,
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080718/9fcd76db/attachment.htm>

From steve.poe at gmail.com  Fri Jul 18 07:29:27 2008
From: steve.poe at gmail.com (Steve Poe)
Date: Thu, 17 Jul 2008 22:29:27 -0700
Subject: [Tutor] Guidance on jump-starting to learn Python
Message-ID: <721b21dc0807172229y59e1d6f2kbef45cad9a84eff5@mail.gmail.com>

I have the challenge / opportunity to learn Python quickly. I
am technically-minded, but I am not a programmer. When I have
tried / used Python before (I've written 5-6 python programs/utilities),
it has been solving a particular issue but not learning the proper
structure/procedures
to learn Python (nor any other programming language).
I humbly admit I have cut corners, so I have bad habits. I have been advised
to start with
the basics but at an accelerated pace.

Any recommended "homework" assignments?

I have two books as well:
Core Python Programming from Wesley Chun , Second Edition.
Python Programming for the Absolute Beginner, Second Edition.

Thanks so much for your advice/help in advance.

Steve
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080717/3c87357a/attachment.htm>

From cspears2002 at yahoo.com  Fri Jul 18 07:32:54 2008
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Thu, 17 Jul 2008 22:32:54 -0700 (PDT)
Subject: [Tutor] creating pop method for stack class
In-Reply-To: <5e58f2e40807172126o409808a8j66f3f2d022759270@mail.gmail.com>
Message-ID: <171538.59587.qm@web51612.mail.re2.yahoo.com>


> 
> First, a tip:
> 
> Instead of lista[:len(lista)-1], you can (and should) just
> write lista[:-1].
> 
> Now, what if we wrap that in a function:
> 
> >>> def shorten(lst):
> ...   lst = lst[:-1]  # identical to: lst =
> lst[:len(lst)-1]
> ...
> 
> Then test it:
> 
> >>> lista = [1, 2, 3, 4]
> >>> shorten(lista)
> 
> What do you think will be the result of:
> 
> >>> print lista
> 
> ?
> 

I see what you mean.  I have tested it, and I have gotten a weird result:
>>> def shorten(lst):
...     lst = lst[:-1]
...
>>> lista = [1,2,3,4]
>>> shorten(lista)
>>> print lista
[1, 2, 3, 4]
>>> lista = [1,2,3,4]
>>> lista = lista[:-1]
>>> print lista
[1, 2, 3]
>>>

Strange...why does it work outside of the function but not in it?  Let me try something else:

>>> def shorten(lst):
...     lst = lst[:-1]
...     return lst
...
>>> lista = [1,2,3,4]
>>> shorten(lista)
[1, 2, 3]
>>> print lista
[1, 2, 3, 4]
>>> lista = shorten(lista)
>>> print lista
[1, 2, 3]
>>>

Huh, how do you explain that?



      

From alan.gauld at btinternet.com  Fri Jul 18 08:16:53 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 18 Jul 2008 07:16:53 +0100
Subject: [Tutor] Question on how to do something.
References: <912405.29227.qm@web38603.mail.mud.yahoo.com>
Message-ID: <g5pcgp$4q7$1@ger.gmane.org>


"Mitchell Nguyen" <m1tchellnguyen at yahoo.com> wrote in message 
news:912405.29227.qm at web38603.mail.mud.yahoo.com...
Hello. I'm new to Python and I was wondering how to read all the files 
in a folder.

Take a look at the fileinput module, I think it will do what you want.

Alan G 



From alan.gauld at btinternet.com  Fri Jul 18 08:25:58 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 18 Jul 2008 07:25:58 +0100
Subject: [Tutor] creating pop method for stack class
References: <289059.15816.qm@web51610.mail.re2.yahoo.com>
Message-ID: <g5pd1q$647$1@ger.gmane.org>


"Christopher Spears" <cspears2002 at yahoo.com> wrote 


>I am almost done with a stack class that I wrote:

Some comments...

> class Stack(list):
>    def isempty(self):
>        length = len(self)
>        if length == 0:
>     return True
> else:
>     return False

This can just be 
     return bool(len(self))

>    def peek(self):
>        length = len(self)
> if length == 0:
>     return 0

How do you know whether zero was the last item or an error?
Better to raise an IndexError or a ValueError or define your 
own StackEmptyError.

> else:
>     last_index = length - 1
>            return self[last_index]

You don't need the last_index thing, just use -1
-1 is always the last item.

>    def stackpop(self):
>        length = len(self)
> if length == 0:
>     print "Empty list!"

And this is inconsistent with the previous method.
Keep your error jhandling style the same or confuse your users. 
In general putting  print statements inside class methods is a 
bad idea. Raise an exception instead.

> else:
>     last_index = length - 1
>     stackpop_val = self[last_index]
>     self = self[:last_index]
>     return stackpop_val

I don't think reassigning self is a good idea. 
I'd go with deleting the last member using del(self[-1])

> My main problem seems to be getting this part to work:
> 
> def stackpop(self):
...
>     self = self[:last_index]
>     return stackpop_val

see comment above.

HTH,


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


From john at fouhy.net  Fri Jul 18 09:04:21 2008
From: john at fouhy.net (John Fouhy)
Date: Fri, 18 Jul 2008 19:04:21 +1200
Subject: [Tutor] creating pop method for stack class
In-Reply-To: <171538.59587.qm@web51612.mail.re2.yahoo.com>
References: <5e58f2e40807172126o409808a8j66f3f2d022759270@mail.gmail.com>
	<171538.59587.qm@web51612.mail.re2.yahoo.com>
Message-ID: <5e58f2e40807180004y72dfa2b5w5f67a5fcc4ff0f9b@mail.gmail.com>

On 18/07/2008, Christopher Spears <cspears2002 at yahoo.com> wrote:
> I see what you mean.  I have tested it, and I have gotten a weird result:
>
> >>> def shorten(lst):
>  ...     lst = lst[:-1]
>
> ...
>
> >>> lista = [1,2,3,4]
>  >>> shorten(lista)
> >>> print lista
> [1, 2, 3, 4]
[...]
>  Strange...why does it work outside of the function but not in it?
[...]
>  Huh, how do you explain that?

Have a look at Alan's tutorial; in particular, the section on
namespaces: http://www.freenetpages.co.uk/hp/alan.gauld/tutname.htm

Or you might find this helpful also:
http://www.greenteapress.com/thinkpython/html/book004.html#toc31
(sections 3.8 and 3.9)

Also, try this, in a new interpreter session:

Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04)
[GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def setXTo3():
...     x = 3
...
>>> setXTo3()
>>> print x

Is that the result you expect?  If not, can you explain it after
reading the web pages above?  If it is what you expect, can you apply
the same idea to the shorten(lst) function above?

-- 
John.

From eric at ericabrahamsen.net  Fri Jul 18 12:10:40 2008
From: eric at ericabrahamsen.net (Eric Abrahamsen)
Date: Fri, 18 Jul 2008 18:10:40 +0800
Subject: [Tutor] python environment
Message-ID: <DDDC9FEB-8BFE-4606-9DC1-17F01B6187E4@ericabrahamsen.net>

I've been looking around for a good tutorial or background info on how  
the Python runtime environment works, and haven't quite found what I'm  
looking for. I started fooling with having different versions of  
modules available to difference processes on a single server, which  
led me to virtualenv, and then I realized I'm way in over my head. I'm  
sure I can make virtualenv work, but I won't understand what's  
happening.

Can anyone recommend any resources along these lines? Chapter 26 in  
the library reference is on Python Runtime Services ? these are the  
models I want to understand, but I feel like what I need is one level  
_under_ these modules: I guess, how the python interpreter works as an  
os process, and how its environment differs from... the other  
environment?. The command line interpreter also has options like  
'ignore environment variables' and 'don't imply "import site" on  
initialization' ? I just don't quite get it.

Thanks in advance for any and all enlightenment.

Eric

From mwalsh at groktech.org  Fri Jul 18 15:32:04 2008
From: mwalsh at groktech.org (Martin Walsh)
Date: Fri, 18 Jul 2008 08:32:04 -0500
Subject: [Tutor] creating pop method for stack class
In-Reply-To: <171538.59587.qm@web51612.mail.re2.yahoo.com>
References: <171538.59587.qm@web51612.mail.re2.yahoo.com>
Message-ID: <48809B54.1070402@groktech.org>

Christopher Spears wrote:
> I see what you mean.  I have tested it, and I have gotten a weird result:
>>>> def shorten(lst):
> ...     lst = lst[:-1]
> ...
>>>> lista = [1,2,3,4]
>>>> shorten(lista)
>>>> print lista
> [1, 2, 3, 4]
>>>> lista = [1,2,3,4]
>>>> lista = lista[:-1]
>>>> print lista
> [1, 2, 3]
> 
> Strange...why does it work outside of the function but not in it?  Let me try something else:
> 
>>>> def shorten(lst):
> ...     lst = lst[:-1]

Perhaps it would be helpful to consider the following...

def shorten1(lst):
     lst[:] = lst[:-1]

... or ...

def shorten2(lst):
     lst.pop()

Why might these exhibit different behavior?

HTH,
Marty



From motoom at xs4all.nl  Fri Jul 18 16:09:48 2008
From: motoom at xs4all.nl (Michiel Overtoom)
Date: Fri, 18 Jul 2008 16:09:48 +0200
Subject: [Tutor] Guidance on jump-starting to learn Python
Message-ID: <2.2.32.20080718140948.0115423c@pop.xs4all.nl>

Setve wrote...

> I have the challenge / opportunity to learn Python quickly. I
> am technically-minded, but I am not a programmer.

You have seen the page http://wiki.python.org/moin/BeginnersGuide, and more
specific, http://wiki.python.org/moin/BeginnersGuide/NonProgrammers ?

Ans of course, you can always ask the mailinglist if you feel that you're
hitting a wall ;-)

Greetings,

-- 
"The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing." - Vinod Vallopillil
http://www.catb.org/~esr/halloween/halloween4.html


From malaclypse2 at gmail.com  Fri Jul 18 17:10:54 2008
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Fri, 18 Jul 2008 11:10:54 -0400
Subject: [Tutor] Question on how to do something.
In-Reply-To: <912405.29227.qm@web38603.mail.mud.yahoo.com>
References: <912405.29227.qm@web38603.mail.mud.yahoo.com>
Message-ID: <16651e80807180810s5b30ecb9s7d022880aa703224@mail.gmail.com>

On Thu, Jul 17, 2008 at 6:39 PM, Mitchell Nguyen
<m1tchellnguyen at yahoo.com> wrote:
> Hello. I'm new to Python and I was wondering how to read all the files in a
> folder. I used this program or command for single files.
>
> And if possible, is there a way to make it so that it waits at the end of
> each file for a confirmation to go onto the next file? Thanks

Try something like this:

import glob
for filename in glob.glob('*.txt'):
    print filename
    response = raw_input("Press ENTER to continue.")

Instead of the print statement, you can process your file any way you
like.  If you want to give the user the ability to abort the program,
or take some other action, you can look at the response variable and
decide what to do with the user's input.

-- 
Jerry

From rdm at rcblue.com  Fri Jul 18 17:32:19 2008
From: rdm at rcblue.com (Dick Moores)
Date: Fri, 18 Jul 2008 08:32:19 -0700
Subject: [Tutor] Advice for my function, isPrime(n), please
Message-ID: <20080718153308.9A12F1E4007@bag.python.org>

I'm rather please with the speed of isPrime(). Any credit, of course, 
goes to Alex Martelli, who wrote gmpy.
from gmpy import is_prime
def isPrime(n):
     """
     Return True if n is prime, False if not prime.
     If n not an int or a long, return None.
     """
     if not isinstance(n, (int, long)):
         return None
     x = is_prime(n,100)
     if x == 0:
         return False
     else:
         return True

Take a large integer I believe to be prime:
n = 88888888888888888888888888888888888888888888888888888888888888943

In [15]: isPrime(n)
Out[15]: True

In [16]: timeit isPrime(n)
100 loops, best of 3: 20.1 ms per loop

It couldn't be used for cryptography, I suppose, because it's 
probability of being accurate is not 1, but 1 - 1/(2**100), or 1 - 
7.8886090522101181e-031 .

My question is about whether to test for integerhood. Without that 
test,  isPrime(3.7) returns true, and isPrime('44') returns False. 
I've gone with testing for integerhood, and with returning None when 
n fails the test. Thus,

In [3]: print isPrime(3.7)
None

In [4]: print isPrime('44')
None

Advice?

Thanks,

Dick Moores



From kent37 at tds.net  Fri Jul 18 19:03:59 2008
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 18 Jul 2008 13:03:59 -0400
Subject: [Tutor] Advice for my function, isPrime(n), please
In-Reply-To: <20080718153308.9A12F1E4007@bag.python.org>
References: <20080718153308.9A12F1E4007@bag.python.org>
Message-ID: <1c2a2c590807181003w2b29cdd2ld37be1d90a1582a@mail.gmail.com>

On Fri, Jul 18, 2008 at 11:32 AM, Dick Moores <rdm at rcblue.com> wrote:
>    if x == 0:
>        return False
>    else:
>        return True

Could be just
  return x!=0
or
  return not x

> My question is about whether to test for integerhood. Without that test,
>  isPrime(3.7) returns true, and isPrime('44') returns False. I've gone with
> testing for integerhood, and with returning None when n fails the test.

Better to raise TypeError.

Kent

From jeff at drinktomi.com  Fri Jul 18 19:52:35 2008
From: jeff at drinktomi.com (Jeff Younker)
Date: Fri, 18 Jul 2008 10:52:35 -0700
Subject: [Tutor] parsing sendmail logs
In-Reply-To: <g5ivhe$i0r$1@ger.gmane.org>
References: <77f8f7c30807140029w4c2d003cg8c49b8c08e140dd8@mail.gmail.com><1c2a2c590807140347m31569475iae4b1dfcb35241ec@mail.gmail.com><e2f191310807141110n985be8fwace998044c06c15c@mail.gmail.com><77f8f7c30807141725m51c0ef14t31f23a8381c5633@mail.gmail.com>
	<e2f191310807150415m516fefddxcd1922dc6b1de3ee@mail.gmail.com>
	<g5ivhe$i0r$1@ger.gmane.org>
Message-ID: <DD921845-4C3D-4C68-B957-3C6949DF116E@drinktomi.com>

> If you run a pipeline chain from within subprocess every part of the
> chain will be a separate process, thats a lot of overhead. Thats why
> admins tend to prefer writing utilities in Perl rather than bash  
> these days.
> ...

Nobody I know uses perl for systems administration because it doesn't
have the cost of forking a process.  They use it because you have real
data structures, functions, access to system calls, etc. with one  
*cough*
consistent syntax.   One of perl's big selling points for system
administration is that it is *so* easy to fork off a shell and read  
its output.

The argument that processes are too expensive might have had some
truth back in '92 or '93 when machines had 8M or 16M of memory, had
500M hard drives, and ran at a fraction of the speed they do now, but
that was a long time ago.

-jeff

From rdm at rcblue.com  Fri Jul 18 20:25:56 2008
From: rdm at rcblue.com (Dick Moores)
Date: Fri, 18 Jul 2008 11:25:56 -0700
Subject: [Tutor] Advice for my function, isPrime(n), please
In-Reply-To: <1c2a2c590807181003w2b29cdd2ld37be1d90a1582a@mail.gmail.com
 >
References: <20080718153308.9A12F1E4007@bag.python.org>
	<1c2a2c590807181003w2b29cdd2ld37be1d90a1582a@mail.gmail.com>
Message-ID: <20080718182609.756A81E400D@bag.python.org>

At 10:03 AM 7/18/2008, Kent Johnson wrote:
>On Fri, Jul 18, 2008 at 11:32 AM, Dick Moores <rdm at rcblue.com> wrote:
> >    if x == 0:
> >        return False
> >    else:
> >        return True
>
>Could be just
>   return x!=0

I see this works, but it's Greek to me. HOW does it work? And why is 
it better than what I had? Is it faster? Or what?

>or
>   return not x
>
> > My question is about whether to test for integerhood. Without that test,
> >  isPrime(3.7) returns true, and isPrime('44') returns False. I've gone with
> > testing for integerhood, and with returning None when n fails the test.
>
>Better to raise TypeError.

Like this?
if not isinstance(n, (int, long)):
         raise TypeError, "n must be an int or a long"

Thanks,

Dick



From kent37 at tds.net  Fri Jul 18 21:38:19 2008
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 18 Jul 2008 15:38:19 -0400
Subject: [Tutor] Advice for my function, isPrime(n), please
In-Reply-To: <20080718182609.756A81E400D@bag.python.org>
References: <20080718153308.9A12F1E4007@bag.python.org>
	<1c2a2c590807181003w2b29cdd2ld37be1d90a1582a@mail.gmail.com>
	<20080718182609.756A81E400D@bag.python.org>
Message-ID: <1c2a2c590807181238j46c391d8gb4843d68d6348549@mail.gmail.com>

On Fri, Jul 18, 2008 at 2:25 PM, Dick Moores <rdm at rcblue.com> wrote:
> At 10:03 AM 7/18/2008, Kent Johnson wrote:
>>
>> On Fri, Jul 18, 2008 at 11:32 AM, Dick Moores <rdm at rcblue.com> wrote:
>> >    if x == 0:
>> >        return False
>> >    else:
>> >        return True
>>
>> Could be just
>>  return x!=0
>
> I see this works, but it's Greek to me. HOW does it work? And why is it
> better than what I had? Is it faster? Or what?

x != 0 is an expression. The value of that expression is either True
or False and is returned as the function result. It is better because
it is concise and idiomatic and has exactly the same result as yours.

>> > My question is about whether to test for integerhood. Without that test,
>> >  isPrime(3.7) returns true, and isPrime('44') returns False. I've gone
>> > with
>> > testing for integerhood, and with returning None when n fails the test.
>>
>> Better to raise TypeError.
>
> Like this?
> if not isinstance(n, (int, long)):
>        raise TypeError, "n must be an int or a long"

Yes, though "The argument to isPrime() must be an int or a long" might
be more expressive.

Kent

From mishu_yim at yahoo.com  Fri Jul 18 22:31:40 2008
From: mishu_yim at yahoo.com (asdg asdg)
Date: Fri, 18 Jul 2008 13:31:40 -0700 (PDT)
Subject: [Tutor] confusing HTTP error while using urlopen
In-Reply-To: <1c2a2c590807181238j46c391d8gb4843d68d6348549@mail.gmail.com>
Message-ID: <305015.70497.qm@web46108.mail.sp1.yahoo.com>

I'll skip the introduction and go right to the question cause it's as simple as it's confusing for me.

Why does urllib2.urlopen("http://www.anuntul.ro") return HTTPError: HTTP Error 400: Bad Request, while the site opens with no problems in any regular browser.

Thank you in advance for answering :)



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080718/e1a6b251/attachment-0001.htm>

From rdm at rcblue.com  Fri Jul 18 22:45:07 2008
From: rdm at rcblue.com (Dick Moores)
Date: Fri, 18 Jul 2008 13:45:07 -0700
Subject: [Tutor] Advice for my function, isPrime(n), please
In-Reply-To: <1c2a2c590807181238j46c391d8gb4843d68d6348549@mail.gmail.co
 m>
References: <20080718153308.9A12F1E4007@bag.python.org>
	<1c2a2c590807181003w2b29cdd2ld37be1d90a1582a@mail.gmail.com>
	<20080718182609.756A81E400D@bag.python.org>
	<1c2a2c590807181238j46c391d8gb4843d68d6348549@mail.gmail.com>
Message-ID: <20080718204525.ABC341E400A@bag.python.org>

At 12:38 PM 7/18/2008, Kent Johnson wrote:
>On Fri, Jul 18, 2008 at 2:25 PM, Dick Moores <rdm at rcblue.com> wrote:
> > At 10:03 AM 7/18/2008, Kent Johnson wrote:
> >>
> >> On Fri, Jul 18, 2008 at 11:32 AM, Dick Moores <rdm at rcblue.com> wrote:
> >> >    if x == 0:
> >> >        return False
> >> >    else:
> >> >        return True
> >>
> >> Could be just
> >>  return x!=0
> >
> > I see this works, but it's Greek to me. HOW does it work? And why is it
> > better than what I had? Is it faster? Or what?
>
>x != 0 is an expression. The value of that expression is either True
>or False and is returned as the function result.

Huh. Brand new to me. Thanks.

>  It is better because
>it is concise and idiomatic and has exactly the same result as yours.

Is it time to quote this again?

In [15]: import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.  <--
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.  <--
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!


> >> > My question is about whether to test for integerhood. Without that test,
> >> >  isPrime(3.7) returns true, and isPrime('44') returns False. I've gone
> >> > with
> >> > testing for integerhood, and with returning None when n fails the test.
> >>
> >> Better to raise TypeError.
> >
> > Like this?
> > if not isinstance(n, (int, long)):
> >        raise TypeError, "n must be an int or a long"
>
>Yes, though "The argument to isPrime() must be an int or a long" might
>be more expressive.

OK, I'll use it.

Thanks,

Dick
=====================================
Have you seen the video introducing the terrific
and free IDE, Ulipad? Download it from my website.
<http://www.rcblue.com/u3/>


From flaxeater at gmail.com  Fri Jul 18 23:38:49 2008
From: flaxeater at gmail.com (Chad Crabtree)
Date: Fri, 18 Jul 2008 17:38:49 -0400
Subject: [Tutor] confusing HTTP error while using urlopen
In-Reply-To: <305015.70497.qm@web46108.mail.sp1.yahoo.com>
References: <1c2a2c590807181238j46c391d8gb4843d68d6348549@mail.gmail.com>
	<305015.70497.qm@web46108.mail.sp1.yahoo.com>
Message-ID: <584940990807181438q65afeeacqfa77c5d06bc64928@mail.gmail.com>

Well I can confirm this behavior.  I tried changing the user-agent
thinking there might be some filtering based on that but no go. Still
HTTP 400 error.  WGET works just fine though

On Fri, Jul 18, 2008 at 4:31 PM, asdg asdg <mishu_yim at yahoo.com> wrote:
> I'll skip the introduction and go right to the question cause it's as simple
> as it's confusing for me.
>
> Why does urllib2.urlopen("http://www.anuntul.ro") return HTTPError: HTTP
> Error 400: Bad Request, while the site opens with no problems in any regular
> browser.
>
> Thank you in advance for answering :)
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>

From arsyed at gmail.com  Sat Jul 19 00:30:58 2008
From: arsyed at gmail.com (arsyed)
Date: Fri, 18 Jul 2008 18:30:58 -0400
Subject: [Tutor] confusing HTTP error while using urlopen
In-Reply-To: <584940990807181438q65afeeacqfa77c5d06bc64928@mail.gmail.com>
References: <1c2a2c590807181238j46c391d8gb4843d68d6348549@mail.gmail.com>
	<305015.70497.qm@web46108.mail.sp1.yahoo.com>
	<584940990807181438q65afeeacqfa77c5d06bc64928@mail.gmail.com>
Message-ID: <9a2cc7a70807181530y6c3be51cya63849aeb9d14ad4@mail.gmail.com>

It looks like the site wants an Accept header. The following works:

import urllib2
url = 'http://www.anuntul.ro/'
headers = {'Accept': 'text/html'}
req = urllib2.Request(url=url, headers=headers)
rsp = urllib2.urlopen(req)
page = rsp.read()
print page





On Fri, Jul 18, 2008 at 5:38 PM, Chad Crabtree <flaxeater at gmail.com> wrote:

> Well I can confirm this behavior.  I tried changing the user-agent
> thinking there might be some filtering based on that but no go. Still
> HTTP 400 error.  WGET works just fine though
>
> On Fri, Jul 18, 2008 at 4:31 PM, asdg asdg <mishu_yim at yahoo.com> wrote:
> > I'll skip the introduction and go right to the question cause it's as
> simple
> > as it's confusing for me.
> >
> > Why does urllib2.urlopen("http://www.anuntul.ro") return HTTPError: HTTP
> > Error 400: Bad Request, while the site opens with no problems in any
> regular
> > browser.
> >
> > Thank you in advance for answering :)
> >
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080718/d5b1d727/attachment.htm>

From arsyed at gmail.com  Sat Jul 19 00:41:53 2008
From: arsyed at gmail.com (arsyed)
Date: Fri, 18 Jul 2008 18:41:53 -0400
Subject: [Tutor] IPython problem: Difficulty in setting editor to TextPad
In-Reply-To: <20080717154004.024301E400B@bag.python.org>
References: <20080717095442.48F0C1E4003@bag.python.org>
	<g5nnid$c54$1@ger.gmane.org>
	<20080717154004.024301E400B@bag.python.org>
Message-ID: <9a2cc7a70807181541h7846b68dsec33e71e1132c062@mail.gmail.com>

I just set the EDITOR environment variable under windows to textpad and %ed
works fine from ipython. It also gets used by subversion and other programs
for commit messages, etc.

>echo %EDITOR%
"C:\Program Files\TextPad 5\TextPad.exe"





On Thu, Jul 17, 2008 at 11:39 AM, Dick Moores <rdm at rcblue.com> wrote:

> At 08:13 AM 7/17/2008, Alan Gauld wrote:
>
>> "Dick Moores" <rdm at rcblue.com> wrote
>>
>>> In my ipy_user_conf.py I have put this line:
>>> ipy_editors.install_editor("C:\Program Files\TextPad 5\TextPad.exe")
>>>
>>
>> escape the spaces and backslashes(raw string might work as well)
>>
>
> Yeah, I tried that (except for the raw string).
>
>  ipy_editors.install_editor("C:\\Program\ Files\\TextPad 5\\TextPad.exe")
>>
>> OR maybe
>>
>> ipy_editors.install_editor(r"C:\Program Files\TextPad 5\TextPad.exe")
>>
>
> I finally got some help from one of the main IPython guys (just now). The
> line that partially works is
> ipy_editors.install_editor('"C:\Program Files\TextPad 5\TextPad.exe"
> ${file}(${line})')
>
> But using the line number doesn't work, so I skip it and do
>
> In [3]: ed versions.py
> Editing... > "C:\Program Files\TextPad 5\TextPad.exe" versions.py(0)
>
> This DOES open versions.py in Textpad, with the caret at line 1.
>
> Thanks for your educated guesses, Alan.
>
> Dick
> ======================================
> Have you seen the video introducing the terrific
> and free IDE, Ulipad? Download it from my website.
> <http://www.rcblue.com/u3/>
>
>
> _______________________________________________
> 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/20080718/dbd763ac/attachment.htm>

From rdm at rcblue.com  Sat Jul 19 02:49:01 2008
From: rdm at rcblue.com (Dick Moores)
Date: Fri, 18 Jul 2008 17:49:01 -0700
Subject: [Tutor] IPython problem: Difficulty in setting editor to TextPad
In-Reply-To: <9a2cc7a70807181541h7846b68dsec33e71e1132c062@mail.gmail.co
 m>
References: <20080717095442.48F0C1E4003@bag.python.org>
	<g5nnid$c54$1@ger.gmane.org>
	<20080717154004.024301E400B@bag.python.org>
	<9a2cc7a70807181541h7846b68dsec33e71e1132c062@mail.gmail.com>
Message-ID: <20080719004914.8C3A71E400A@bag.python.org>

At 03:41 PM 7/18/2008, arsyed wrote:

>I just set the EDITOR environment variable under windows to textpad 
>and %ed works fine from ipython. It also gets used by subversion and 
>other programs for commit messages, etc.
>
> >echo %EDITOR%
>"C:\Program Files\TextPad 5\TextPad.exe"

I'd already done that. However up to now I'd had an editor set for 
IPython in either IPythonrc.ini or in ipy_user_conf.py. Upon reading 
your reply I commented out the current line setting the editor in 
ipy_user_conf.py,

ipy_editors.install_editor('"C:\Program Files\TextPad 5\TextPad.exe" 
${file}(${line})')

and found that you're right!

However, I've also learned a bit more about how to use said line:

ed -n m versions.py

will open filename.py in TextPad at line m, which can be handy when 
the file is big.

Dick
======================================
Have you seen the video introducing the terrific
and free IDE, Ulipad? Download it from my website.
<http://www.rcblue.com/u3/>


From kent37 at tds.net  Sat Jul 19 05:40:40 2008
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 18 Jul 2008 23:40:40 -0400
Subject: [Tutor] Advice for my function, isPrime(n), please
In-Reply-To: <20080718204525.ABC341E400A@bag.python.org>
References: <20080718153308.9A12F1E4007@bag.python.org>
	<1c2a2c590807181003w2b29cdd2ld37be1d90a1582a@mail.gmail.com>
	<20080718182609.756A81E400D@bag.python.org>
	<1c2a2c590807181238j46c391d8gb4843d68d6348549@mail.gmail.com>
	<20080718204525.ABC341E400A@bag.python.org>
Message-ID: <1c2a2c590807182040r16042a08t6098546c61711a09@mail.gmail.com>

On Fri, Jul 18, 2008 at 4:45 PM, Dick Moores <rdm at rcblue.com> wrote:
> At 12:38 PM 7/18/2008, Kent Johnson wrote:
>>
>> On Fri, Jul 18, 2008 at 2:25 PM, Dick Moores <rdm at rcblue.com> wrote:
>> > At 10:03 AM 7/18/2008, Kent Johnson wrote:
>> >>
>> >> On Fri, Jul 18, 2008 at 11:32 AM, Dick Moores <rdm at rcblue.com> wrote:
>> >> >    if x == 0:
>> >> >        return False
>> >> >    else:
>> >> >        return True
>> >>
>> >> Could be just
>> >>  return x!=0
>> >
>> > I see this works, but it's Greek to me. HOW does it work? And why is it
>> > better than what I had? Is it faster? Or what?
>>
>> x != 0 is an expression. The value of that expression is either True
>> or False and is returned as the function result.
>
> Huh. Brand new to me. Thanks.
>
>>  It is better because
>> it is concise and idiomatic and has exactly the same result as yours.
>
> Is it time to quote this again?

No :-)

> In [15]: import this
> The Zen of Python, by Tim Peters
>
> Explicit is better than implicit.  <--

My way is explicit. It creates a value, either true or false, and
returns it. Nothing is hidden.

> Readability counts.  <--

Personally I think my way is more readable. It says what it means
without any fluff. IMO it is explicit, readable, concise and to the
point.

Maybe this will help you understand, it does the same thing:
  value = x != 0
  return value

Kent

From rdm at rcblue.com  Sat Jul 19 11:03:16 2008
From: rdm at rcblue.com (Dick Moores)
Date: Sat, 19 Jul 2008 02:03:16 -0700
Subject: [Tutor] Advice for my function, isPrime(n), please
In-Reply-To: <1c2a2c590807182040r16042a08t6098546c61711a09@mail.gmail.co
 m>
References: <20080718153308.9A12F1E4007@bag.python.org>
	<1c2a2c590807181003w2b29cdd2ld37be1d90a1582a@mail.gmail.com>
	<20080718182609.756A81E400D@bag.python.org>
	<1c2a2c590807181238j46c391d8gb4843d68d6348549@mail.gmail.com>
	<20080718204525.ABC341E400A@bag.python.org>
	<1c2a2c590807182040r16042a08t6098546c61711a09@mail.gmail.com>
Message-ID: <20080719090414.ABF511E400A@bag.python.org>

At 08:40 PM 7/18/2008, Kent Johnson wrote:
>On Fri, Jul 18, 2008 at 4:45 PM, Dick Moores <rdm at rcblue.com> wrote:
> > At 12:38 PM 7/18/2008, Kent Johnson wrote:
> >>
> >> On Fri, Jul 18, 2008 at 2:25 PM, Dick Moores <rdm at rcblue.com> wrote:
> >> > At 10:03 AM 7/18/2008, Kent Johnson wrote:
> >> >>
> >> >> On Fri, Jul 18, 2008 at 11:32 AM, Dick Moores <rdm at rcblue.com> wrote:
> >> >> >    if x == 0:
> >> >> >        return False
> >> >> >    else:
> >> >> >        return True
> >> >>
> >> >> Could be just
> >> >>  return x!=0
> >> >
> >> > I see this works, but it's Greek to me. HOW does it work? And why is it
> >> > better than what I had? Is it faster? Or what?
> >>
> >> x != 0 is an expression. The value of that expression is either True
> >> or False and is returned as the function result.
> >
> > Huh. Brand new to me. Thanks.
> >
> >>  It is better because
> >> it is concise and idiomatic and has exactly the same result as yours.
> >
> > Is it time to quote this again?
>
>No :-)

Aw, isn't it good to read it every so often? And I'll bet there are 
Tutorees out there who have never seen it.

> > In [15]: import this
> > The Zen of Python, by Tim Peters
> >
> > Explicit is better than implicit.  <--
>
>My way is explicit. It creates a value, either true or false, and
>returns it. Nothing is hidden.

OK, I'll give you that.

> > Readability counts.  <--
>
>Personally I think my way is more readable. It says what it means
>without any fluff. IMO it is explicit, readable, concise and to the
>point.

Well, readability is in the eye of the reader. Also, because I lived 
in Japan 30 years, I could throw a concise, explicit, and 
to-the-point Japanese sentence at you that you wouldn't understand at all.

>Maybe this will help you understand, it does the same thing:
>   value = x != 0
>   return value

I understand now, and will probably start using such things 
as    return  x != 0, if grumpily at first -- then I'll begin to 
think they're cool.

value = (x != 0)
return value

is clearer, IMO.

Thanks for your guidance, Kent.

Dick



From kent37 at tds.net  Sat Jul 19 13:44:07 2008
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 19 Jul 2008 07:44:07 -0400
Subject: [Tutor] Advice for my function, isPrime(n), please
In-Reply-To: <20080719090414.ABF511E400A@bag.python.org>
References: <20080718153308.9A12F1E4007@bag.python.org>
	<1c2a2c590807181003w2b29cdd2ld37be1d90a1582a@mail.gmail.com>
	<20080718182609.756A81E400D@bag.python.org>
	<1c2a2c590807181238j46c391d8gb4843d68d6348549@mail.gmail.com>
	<20080718204525.ABC341E400A@bag.python.org>
	<1c2a2c590807182040r16042a08t6098546c61711a09@mail.gmail.com>
	<20080719090414.ABF511E400A@bag.python.org>
Message-ID: <1c2a2c590807190444o6cb13939gd15eec9246a61129@mail.gmail.com>

On Sat, Jul 19, 2008 at 5:03 AM, Dick Moores <rdm at rcblue.com> wrote:

>> > Readability counts.  <--
>>
>> Personally I think my way is more readable. It says what it means
>> without any fluff. IMO it is explicit, readable, concise and to the
>> point.
>
> Well, readability is in the eye of the reader. Also, because I lived in
> Japan 30 years, I could throw a concise, explicit, and to-the-point Japanese
> sentence at you that you wouldn't understand at all.

Yes, and then if I complained that the sentence was not readable you
would rightly conclude that the problem was with the reader, not the
sentence.

> value = (x != 0)
> return value
>
> is clearer, IMO.

Yes.

Kent

From rdm at rcblue.com  Sat Jul 19 14:23:16 2008
From: rdm at rcblue.com (Dick Moores)
Date: Sat, 19 Jul 2008 05:23:16 -0700
Subject: [Tutor] Advice for my function, isPrime(n), please
In-Reply-To: <1c2a2c590807190444o6cb13939gd15eec9246a61129@mail.gmail.co
 m>
References: <20080718153308.9A12F1E4007@bag.python.org>
	<1c2a2c590807181003w2b29cdd2ld37be1d90a1582a@mail.gmail.com>
	<20080718182609.756A81E400D@bag.python.org>
	<1c2a2c590807181238j46c391d8gb4843d68d6348549@mail.gmail.com>
	<20080718204525.ABC341E400A@bag.python.org>
	<1c2a2c590807182040r16042a08t6098546c61711a09@mail.gmail.com>
	<20080719090414.ABF511E400A@bag.python.org>
	<1c2a2c590807190444o6cb13939gd15eec9246a61129@mail.gmail.com>
Message-ID: <20080719122329.08ED91E400A@bag.python.org>

At 04:44 AM 7/19/2008, Kent Johnson wrote:
>On Sat, Jul 19, 2008 at 5:03 AM, Dick Moores <rdm at rcblue.com> wrote:
>
> >> > Readability counts.  <--
> >>
> >> Personally I think my way is more readable. It says what it means
> >> without any fluff. IMO it is explicit, readable, concise and to the
> >> point.
> >
> > Well, readability is in the eye of the reader. Also, because I lived in
> > Japan 30 years, I could throw a concise, explicit, and 
> to-the-point Japanese
> > sentence at you that you wouldn't understand at all.
>
>Yes, and then if I complained that the sentence was not readable you
>would rightly conclude that the problem was with the reader, not the
>sentence.

Maybe we're running my analogy into the failure it deserves.

Your basic point is that  return x != 0  is standard, idiomatic 
Pythonese and I'm wrong to complain. I should suck it up and study 
harder. Point taken. I welcome this addition to my Python vocabulary.

Dick



From lowelltackett at yahoo.com  Sat Jul 19 15:28:25 2008
From: lowelltackett at yahoo.com (Lowell Tackett)
Date: Sat, 19 Jul 2008 06:28:25 -0700 (PDT)
Subject: [Tutor] Advice for my function, isPrime(n), please
In-Reply-To: <20080719122329.08ED91E400A@bag.python.org>
Message-ID: <859310.58822.qm@web110105.mail.gq1.yahoo.com>



>From the virtual desk of Lowell Tackett  



--- On Sat, 7/19/08, Dick Moores <rdm at rcblue.com> wrote:

> From: Dick Moores <rdm at rcblue.com>
> Subject: Re: [Tutor] Advice for my function, isPrime(n), please
> To: "Python Tutor List" <tutor at python.org>
> Date: Saturday, July 19, 2008, 8:23 AM
> At 04:44 AM 7/19/2008, Kent Johnson wrote:
> >On Sat, Jul 19, 2008 at 5:03 AM, Dick Moores
> <rdm at rcblue.com> wrote:
> >
> > >> > Readability counts.  <--
> > >>
> > >> Personally I think my way is more readable.
> It says what it means
> > >> without any fluff. IMO it is explicit,
> readable, concise and to the
> > >> point.
> > >
> > > Well, readability is in the eye of the reader.
> Also, because I lived in
> > > Japan 30 years, I could throw a concise,
> explicit, and 
> > to-the-point Japanese
> > > sentence at you that you wouldn't understand
> at all.
> >
> >Yes, and then if I complained that the sentence was not
> readable you
> >would rightly conclude that the problem was with the
> reader, not the
> >sentence.
> 
> Maybe we're running my analogy into the failure it
> deserves.
> 
> Your basic point is that  return x != 0  is standard,
> idiomatic 
> Pythonese and I'm wrong to complain. I should suck it
> up and study 
> harder. Point taken. I welcome this addition to my Python
> vocabulary.
> 
> Dick
> 
> Just a comment from the sidelines...this ongoing discourse, and its' humorous diversions, has been a fun read-and made some good pedagogial points-in its' own right.  Always a good thing to never take ones' self too seriously, isn't it?!

Thanks for the <intelligent> wandering from strict tutorial protocol!
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


      


From steve.poe at gmail.com  Sat Jul 19 20:41:47 2008
From: steve.poe at gmail.com (Steve Poe)
Date: Sat, 19 Jul 2008 11:41:47 -0700
Subject: [Tutor] Online class/education for Python?
Message-ID: <721b21dc0807191141q3704c8f9jcc3790f838c87f60@mail.gmail.com>

Anyone taken or know of any online classes
teaching Python? I know O'Reilly Press
teaches online technical courses, through the University of
Illinois, but no Python
.

Thanks.

Steve
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080719/1bf551e6/attachment.htm>

From monjissvel at googlemail.com  Sat Jul 19 20:43:13 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Sat, 19 Jul 2008 18:43:13 +0000
Subject: [Tutor] continuouse loop
In-Reply-To: <487FEECA.3020300@groktech.org>
References: <e2f191310807171207g32230df5h63a25f6adfccbf69@mail.gmail.com>
	<487FEECA.3020300@groktech.org>
Message-ID: <e2f191310807191143l295f346chab2b9b82eab3f53a@mail.gmail.com>

Thanks or your replies, in fact I need my server to recieve queries from
some 40 clients, process the recieved text (some calculations) & send a
response back to them, in my previouse application I used a database, (they
entered thier queries into the db & my calculating script looks at new
records in db every 2 minutes & inserts  the answers  into the db too so
that the users could see them on thier interface. but now I need to move to
a server/client design because at the time i had created this program I
didn't have much time & I had to put it into production.

Right now I am working on some code using the SOCKET module as it was the
only module that allows inter-process communication & was simple enough for
me  to understand how it works.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080719/2f8e9acf/attachment.htm>

From electroblog at gmail.com  Sat Jul 19 21:31:57 2008
From: electroblog at gmail.com (Joe Veldhuis)
Date: Sat, 19 Jul 2008 15:31:57 -0400
Subject: [Tutor] Generating audio tones?
Message-ID: <20080719153157.9e23e138.electroblog@gmail.com>

Hello list. I'm trying to put together an AFSK modem in Python, and I have most of the code worked out. The last remaining issue will be generating the actual audio signal. Unfortunately, I have never written any kind of audio code before in any language, so I don't really know what I am doing.

I did find some code that generated a single or DTMF tone, but it only worked if you let it fill the whole buffer with samples, less than that and it would get distorted at the end. That, and it didn't allow the frequency to be changed mid-run. I will need to generate sinusoidal tones of arbitrary length, shifting frequency as often as once every 8 milliseconds.

The function should be something like this:

def makesamples(frequency,length,phase):
	samples=[]
	for t in range(length):
		# ???
	return samples

Then, calling it:

# ...
for sample in makesamples(1200,40,phase):
	soundcard.write(chr(sample & 0x00FF) + chr(sample & 0xFF00 >> 8))
# ...

The code calling the function would probably have to figure out the phase for the next call based on the length of the output.

For what it's worth, this will be running on an x86-64 Linux machine, using the ossaudiodev module to access the soundcard. Anyone think they can help?

-Joe

From mwalsh at groktech.org  Sat Jul 19 22:22:51 2008
From: mwalsh at groktech.org (Martin Walsh)
Date: Sat, 19 Jul 2008 15:22:51 -0500
Subject: [Tutor] continuouse loop
In-Reply-To: <e2f191310807191143l295f346chab2b9b82eab3f53a@mail.gmail.com>
References: <e2f191310807171207g32230df5h63a25f6adfccbf69@mail.gmail.com>	<487FEECA.3020300@groktech.org>
	<e2f191310807191143l295f346chab2b9b82eab3f53a@mail.gmail.com>
Message-ID: <48824D1B.7020204@groktech.org>

Monika Jisswel wrote:
> Thanks or your replies, in fact I need my server to recieve queries from
> some 40 clients, process the recieved text (some calculations) & send a
> response back to them, in my previouse application I used a database,
> (they entered thier queries into the db & my calculating script looks at
> new records in db every 2 minutes & inserts  the answers  into the db
> too so that the users could see them on thier interface. but now I need
> to move to a server/client design because at the time i had created this
> program I didn't have much time & I had to put it into production.

Assuming your 40 clients represent real human users, and not automated
processes, I almost always approach this kind of problem with a web
application, usually a cgi script or simple mod_python handler. That way
I can spend more time solving the problem at hand, and less on
client/server design details or client installation/upgrade scheduling.
But then browsers and web servers are very common in our environment.

> Right now I am working on some code using the SOCKET module as it was
> the only module that allows inter-process communication & was simple
> enough for me  to understand how it works.

In that case, you might want to have a look at the SocketServer module
also. http://www.python.org/doc/lib/module-SocketServer.html

HTH,
Marty

From david at abbottdavid.com  Sat Jul 19 23:45:22 2008
From: david at abbottdavid.com (David)
Date: Sat, 19 Jul 2008 17:45:22 -0400
Subject: [Tutor] Online class/education for Python?
In-Reply-To: <721b21dc0807191141q3704c8f9jcc3790f838c87f60@mail.gmail.com>
References: <721b21dc0807191141q3704c8f9jcc3790f838c87f60@mail.gmail.com>
Message-ID: <48826072.1050009@abbottdavid.com>

Steve Poe wrote:
> Anyone taken or know of any online classes
> teaching Python? I know O'Reilly Press
> teaches online technical courses, through the University of
> Illinois, but no Python
> .
>
> Thanks.
>
> Steve
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   
I  am new to Python so this one was pretty good for me;
http://www.ed2go.com/cgi-bin/ed2go/newcrsdes.cgi?course=ipy&title=Introduction^to^Python^2.5^Programming&departmentnum=WP&path=1

-- 
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com


From rdm at rcblue.com  Sun Jul 20 08:08:04 2008
From: rdm at rcblue.com (Dick Moores)
Date: Sat, 19 Jul 2008 23:08:04 -0700
Subject: [Tutor] Online class/education for Python?
In-Reply-To: <48826072.1050009@abbottdavid.com>
References: <721b21dc0807191141q3704c8f9jcc3790f838c87f60@mail.gmail.com>
	<48826072.1050009@abbottdavid.com>
Message-ID: <20080720060817.B4B1C1E400A@bag.python.org>

At 02:45 PM 7/19/2008, David wrote:
>Steve Poe wrote:
>>Anyone taken or know of any online classes
>>teaching Python? I know O'Reilly Press
>>teaches online technical courses, through the University of
>>Illinois, but no Python
>>.
>>
>>Thanks.
>>
>>Steve
>>------------------------------------------------------------------------
>>
>>_______________________________________________
>>Tutor maillist  -  Tutor at python.org
>>http://mail.python.org/mailman/listinfo/tutor
>>
>I  am new to Python so this one was pretty good for me;
>http://www.ed2go.com/cgi-bin/ed2go/newcrsdes.cgi?course=ipy&title=Introduction^to^Python^2.5^Programming&departmentnum=WP&path=1

This does look good. I'm thinking about the $129.

1. Is there a problem set for each lesson? Are they corrected or commented on?
2. How do you ask for help from the instructor? By email? In a forum? 
Was he helpful?

Thanks,

Dick Moores
===========================================================================
Have you seen Kelie Feng's video introducing the terrific and free 
IDE, Ulipad? Download it from my website.
<http://www.rcblue.com/u3/> Get Ulipad 3.9 from 
<http://code.google.com/p/ulipad/downloads/list>
Use svn for the latest revision <http://ulipad.googlecode.com/svn/trunk/>
Mailing list for Ulipad: <http://groups-beta.google.com/group/ulipad> 


From amit.pureenergy at gmail.com  Sun Jul 20 08:16:11 2008
From: amit.pureenergy at gmail.com (amit sethi)
Date: Sun, 20 Jul 2008 11:46:11 +0530
Subject: [Tutor] (no subject)
Message-ID: <da81a0a80807192316g11b88089i9ab3cedf7565fb46@mail.gmail.com>

Hi list ,
Can someone give me an idea about the audio libraries in python . I tried
using pymedia . What are the options available .
-- 
A-M-I-T S|S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080720/a9842112/attachment.htm>

From noufal at nibrahim.net.in  Sun Jul 20 09:59:06 2008
From: noufal at nibrahim.net.in (Noufal Ibrahim)
Date: Sun, 20 Jul 2008 13:29:06 +0530
Subject: [Tutor] (no subject)
In-Reply-To: <da81a0a80807192316g11b88089i9ab3cedf7565fb46@mail.gmail.com>
References: <da81a0a80807192316g11b88089i9ab3cedf7565fb46@mail.gmail.com>
Message-ID: <4882F04A.1090800@nibrahim.net.in>

amit sethi wrote:
> 
> Hi list ,
> Can someone give me an idea about the audio libraries in python . I 
> tried using pymedia . What are the options available .

These may be a little heavy duty for you but they do audio.

0. Pyglet (Full windowing and multimedia library) - http://pyglet.org/
1. Gstreamer python bindings - 
http://gstreamer.freedesktop.org/modules/gst-python.html

If you just want to play some sounds, pygame has a sound module which 
might suit your purposes.


-- 
~noufal
http://nibrahim.net.in/

From arsyed at gmail.com  Sun Jul 20 10:23:08 2008
From: arsyed at gmail.com (arsyed)
Date: Sun, 20 Jul 2008 04:23:08 -0400
Subject: [Tutor] (no subject)
In-Reply-To: <da81a0a80807192316g11b88089i9ab3cedf7565fb46@mail.gmail.com>
References: <da81a0a80807192316g11b88089i9ab3cedf7565fb46@mail.gmail.com>
Message-ID: <9a2cc7a70807200123h45b50b1id05b63bba49f9b5b@mail.gmail.com>

The python wiki has some options that might be worth checking out under
"Playing and Creating Sounds":

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



On Sun, Jul 20, 2008 at 2:16 AM, amit sethi <amit.pureenergy at gmail.com>
wrote:

>
> Hi list ,
> Can someone give me an idea about the audio libraries in python . I tried
> using pymedia . What are the options available .
> --
> A-M-I-T S|S
>
> _______________________________________________
> 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/20080720/89c86ac3/attachment.htm>

From wescpy at gmail.com  Sun Jul 20 10:41:55 2008
From: wescpy at gmail.com (wesley chun)
Date: Sun, 20 Jul 2008 01:41:55 -0700
Subject: [Tutor] Guidance on jump-starting to learn Python
In-Reply-To: <721b21dc0807172229y59e1d6f2kbef45cad9a84eff5@mail.gmail.com>
References: <721b21dc0807172229y59e1d6f2kbef45cad9a84eff5@mail.gmail.com>
Message-ID: <78b3a9580807200141w784db476wa19de694ec403956@mail.gmail.com>

> Any recommended "homework" assignments?
>
> I have two books as well:
> Core Python Programming from Wesley Chun , Second Edition.


here are some exercises suggestions on "homework" based on the lab
assignments i give in my courses based on that book.  the legend is
"CHAP#: EXERCISE #s" and apply to the exercises found at the end of
every chapter of the book.

the problems are broken up into 2 groups: "Review" and "Coding". the
review exercises can be completed in your head or on a piece of paper
after reading the appropriate chapters. the coding exercises are to
hammer home the concepts that you just read about.

Homework 1
Review: 1: 2, 4; 2: 3; 3: 1, 3; 4:1
Coding: 1: 5, 6; 2: 4a

Homework 2
Review: 2: 1; 5: 9
Coding: 2: 4b, 5; 5: 2, 4 (only divisible by 4 for now)

Homework 3
Review: 7:1; 8:1, 3a-b
Coding: 2:7; 5: 4 (full definition); 6: 3, 5a; 8: 2

good luck, and let me know if you need any more!
-- 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 bhaaluu at gmail.com  Sun Jul 20 15:06:46 2008
From: bhaaluu at gmail.com (bhaaluu)
Date: Sun, 20 Jul 2008 09:06:46 -0400
Subject: [Tutor] Guidance on jump-starting to learn Python
In-Reply-To: <721b21dc0807172229y59e1d6f2kbef45cad9a84eff5@mail.gmail.com>
References: <721b21dc0807172229y59e1d6f2kbef45cad9a84eff5@mail.gmail.com>
Message-ID: <ea979d70807200606q65508716y68ce6389bbd92565@mail.gmail.com>

On Fri, Jul 18, 2008 at 1:29 AM, Steve Poe <steve.poe at gmail.com> wrote:
>
> Any recommended "homework" assignments?
>
> I have two books as well:
> Core Python Programming from Wesley Chun , Second Edition.
> Python Programming for the Absolute Beginner, Second Edition.
>
> Thanks so much for your advice/help in advance.
>
> Steve

Since you don't have a programming background, the "fast track"
probably insn't a good idea. The "fast track" is usually for people
who are already programmers, and want to learn the specifics of
the Python language.

Python Programming for the Absolute Beginner, 2E is an excellent
Python tutorial. If you'll read it from cover to cover, you'll learn Python.
PPftAB2E uses games to teach Python, so it is fun to work through.
Personally, I learn better when something is fun.

Each chapter has exercises at the end. If you can do the exercises,
then you understand the chapter. If you can't do the exercises, then
you probably didn't understand something.... go back and re-read
that chapter, and try doing the exercises again.

You can always ask questions on this mailing list.

Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m
Kid on Bus: What are you gonna do today, Napoleon?
Napoleon Dynamite: Whatever I feel like I wanna do. Gosh!

From lucychili at gmail.com  Sun Jul 20 15:17:41 2008
From: lucychili at gmail.com (Janet Hawtin)
Date: Sun, 20 Jul 2008 22:47:41 +0930
Subject: [Tutor] Guidance on jump-starting to learn Python
In-Reply-To: <ea979d70807200606q65508716y68ce6389bbd92565@mail.gmail.com>
References: <721b21dc0807172229y59e1d6f2kbef45cad9a84eff5@mail.gmail.com>
	<ea979d70807200606q65508716y68ce6389bbd92565@mail.gmail.com>
Message-ID: <c9d7bc330807200617s11c07e6fvc58a947137007c4d@mail.gmail.com>

Hi folks

I am using twitter and there is an account on that which posts
links from a del.icio.us account which is collecting programming references
Quite a few of the links posted are for python programming.

http://twitter.com/delicious_prog

Janet

From neven.gorsic at gmail.com  Sun Jul 20 16:33:04 2008
From: neven.gorsic at gmail.com (=?ISO-8859-2?Q?Neven_Gor=B9i=E6?=)
Date: Sun, 20 Jul 2008 16:33:04 +0200
Subject: [Tutor] Raw string
Message-ID: <8acd28da0807200733m5a9ed2eerbfb2dc31fa8c37a7@mail.gmail.com>

Hi!

In every manual and book I read only one way to make a raw string:
r"e:\mm tests\1. exp files\5.MOC-1012.exp".
I don't know how to make a string raw string if it is already
contained in a variable.
s.raw() or something like that ...



Thank you very much

PS. It seems like a very basic question but I can not find the answer
in few books.

From steve at alchemy.com  Sun Jul 20 17:48:30 2008
From: steve at alchemy.com (Steve Willoughby)
Date: Sun, 20 Jul 2008 08:48:30 -0700
Subject: [Tutor] Raw string
In-Reply-To: <8acd28da0807200733m5a9ed2eerbfb2dc31fa8c37a7@mail.gmail.com>
References: <8acd28da0807200733m5a9ed2eerbfb2dc31fa8c37a7@mail.gmail.com>
Message-ID: <48835E4E.3040900@alchemy.com>

Neven Gor?i? wrote:
> Hi!
> 
> In every manual and book I read only one way to make a raw string:
> r"e:\mm tests\1. exp files\5.MOC-1012.exp".
> I don't know how to make a string raw string if it is already
> contained in a variable.
> s.raw() or something like that ...

Actually, there's no such thing as a "raw string" once it's constructed 
and sitting as an object in the runtime environment, or "contained in a 
string" as you stated.  It's just a string.  Raw strings simply refer to 
how the string constant value is assembled by the Python interpreter as 
the string object is being constructed.  In other words, it simply 
affects how the source code itself is understood to represent the string 
value.

r"e:\mm tests\1. exp files\5.MOC-1012.exp" will create a string object 
with the characters "e:\mm tests\1. exp files\5.MOC-1012.exp".  But now 
that's just a string value.  From here on out, those are simply a 
collection of those individual character values and won't be interpreted 
further.

"e:\mm tests\1. exp files\5.MOC-1012.exp" will create a string object 
with the characters "e:\mm tests^A. exp files^E.MOC-1012.exp".  But now 
that's just a string value with those characters.  There's no concept of 
"making it a raw string" after that point at all.
> 
> 
> 
> Thank you very much
> 
> PS. It seems like a very basic question but I can not find the answer
> in few books.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


From bgailer at gmail.com  Sun Jul 20 18:21:33 2008
From: bgailer at gmail.com (bob gailer)
Date: Sun, 20 Jul 2008 12:21:33 -0400
Subject: [Tutor] Raw string
In-Reply-To: <8acd28da0807200733m5a9ed2eerbfb2dc31fa8c37a7@mail.gmail.com>
References: <8acd28da0807200733m5a9ed2eerbfb2dc31fa8c37a7@mail.gmail.com>
Message-ID: <4883660D.2070903@gmail.com>

Neven Gor?i? wrote:
> Hi!
>
> In every manual and book I read only one way to make a raw string:
> r"e:\mm tests\1. exp files\5.MOC-1012.exp".
> I don't know how to make a string raw string if it is already
> contained in a variable.
> s.raw() or something like that ...
>   

Looking up raw string in the docs yields:
"String literals may optionally be prefixed with a letter "r" or "R"; 
such strings are called /raw strings/ and use different rules for 
interpreting backslash escape sequences."

Note that "raw string" is a form of string literal. The concept does not 
apply to other forms of strings.

 >>> x = r"\t"
 >>> x
'\\t'

I'm guessing you want

 >>> x.raw() # to display
r"\t"

Is that true. That's the only way I can interpret your question.

There is no such function that I'm aware of. One could easily write one.

-- 
Bob Gailer
919-636-4239 Chapel Hill, NC


From steve at alchemy.com  Sun Jul 20 18:26:17 2008
From: steve at alchemy.com (Steve Willoughby)
Date: Sun, 20 Jul 2008 09:26:17 -0700
Subject: [Tutor] Raw string
In-Reply-To: <4883660D.2070903@gmail.com>
References: <8acd28da0807200733m5a9ed2eerbfb2dc31fa8c37a7@mail.gmail.com>
	<4883660D.2070903@gmail.com>
Message-ID: <48836729.6050702@alchemy.com>

bob gailer wrote:
> I'm guessing you want
> 
>  >>> x.raw() # to display
> r"\t"
> 
> Is that true. That's the only way I can interpret your question.

Hm... or did you (speaking to the OP) intend for your script to 
interpret strings you're reading from another source, like user input or 
a text file, and letting those input sources use the string building syntax?

I guess it would be better to step back and tell us what you're actually 
trying to accomplish and maybe we can suggest an alternative approach. 
You've asked a pretty narrowly focused question here and it's hard for 
us to see it in context.

From oltarasenko at gmail.com  Sun Jul 20 18:46:37 2008
From: oltarasenko at gmail.com (Oleg Oltar)
Date: Sun, 20 Jul 2008 19:46:37 +0300
Subject: [Tutor] Import modeuls
Message-ID: <b4fc2ad80807200946s56954709h27432cf0163535c5@mail.gmail.com>

Hi
I need to import several modules from many folders which has subfolders

~/folder/tests/sampletest.py
~/folder/suites/samplesuit.py

a suit uses tests from tests folder. I need to import them somehow from
tests folder. I added ~/folder to PYTHONPATH in my test_runner:


import sys
import os

sys.path.insert(0, "~/folder")
os.popen("python2.5 %s" %sys.argv[1])

But when trying to import module in the samplesuite file:

from tests.sampletest.EmailWithoutA import EmailWithoutA
>

But I getting ImportError: No module named ....

Please help
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080720/bfeb7ef7/attachment.htm>

From arsyed at gmail.com  Sun Jul 20 23:28:48 2008
From: arsyed at gmail.com (arsyed)
Date: Sun, 20 Jul 2008 17:28:48 -0400
Subject: [Tutor] Import modeuls
In-Reply-To: <b4fc2ad80807200946s56954709h27432cf0163535c5@mail.gmail.com>
References: <b4fc2ad80807200946s56954709h27432cf0163535c5@mail.gmail.com>
Message-ID: <9a2cc7a70807201428n29802dd1g97dfb6707e78e420@mail.gmail.com>

On Sun, Jul 20, 2008 at 12:46 PM, Oleg Oltar <oltarasenko at gmail.com> wrote:

> Hi
> I need to import several modules from many folders which has subfolders
>
> ~/folder/tests/sampletest.py
> ~/folder/suites/samplesuit.py
>
> a suit uses tests from tests folder. I need to import them somehow from
> tests folder. I added ~/folder to PYTHONPATH in my test_runner:
>
>
> import sys
> import os
>
> sys.path.insert(0, "~/folder")
> os.popen("python2.5 %s" %sys.argv[1])
>
> But when trying to import module in the samplesuite file:
>
> from tests.sampletest.EmailWithoutA import EmailWithoutA
>>
>
> But I getting ImportError: No module named ....
>
> Please help
>
>

Do you have an __init__.py file in the tests and suites directories?

More on that here:

http://docs.python.org/tut/node8.html

"The __init__.py files are required to make Python treat the directories as
containing packages; this is done to prevent directories with a common name,
such as "string", from unintentionally hiding valid modules that occur later
on the module search path. In the simplest case, __init__.py can just be an
empty file, but it can also execute initialization code for the package or
set the __all__ variable, described later."
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080720/a3fb5108/attachment.htm>

From neven.gorsic at gmail.com  Mon Jul 21 00:14:13 2008
From: neven.gorsic at gmail.com (=?ISO-8859-2?Q?Neven_Gor=B9i=E6?=)
Date: Mon, 21 Jul 2008 00:14:13 +0200
Subject: [Tutor] Raw string
In-Reply-To: <48835E4E.3040900@alchemy.com>
References: <8acd28da0807200733m5a9ed2eerbfb2dc31fa8c37a7@mail.gmail.com>
	<48835E4E.3040900@alchemy.com>
Message-ID: <8acd28da0807201514h419398b4u5598f464c6fc189e@mail.gmail.com>

On Sun, Jul 20, 2008 at 5:48 PM, Steve Willoughby <steve at alchemy.com> wrote:
> Neven Gor?i? wrote:
>>
>> Hi!
>>
>> In every manual and book I read only one way to make a raw string:
>> r"e:\mm tests\1. exp files\5.MOC-1012.exp".
>> I don't know how to make a string raw string if it is already
>> contained in a variable.
>> s.raw() or something like that ...
>
> Actually, there's no such thing as a "raw string" once it's constructed and
> sitting as an object in the runtime environment, or "contained in a string"
> as you stated.  It's just a string.  Raw strings simply refer to how the
> string constant value is assembled by the Python interpreter as the string
> object is being constructed.  In other words, it simply affects how the
> source code itself is understood to represent the string value.
>
> r"e:\mm tests\1. exp files\5.MOC-1012.exp" will create a string object with
> the characters "e:\mm tests\1. exp files\5.MOC-1012.exp".  But now that's
> just a string value.  From here on out, those are simply a collection of
> those individual character values and won't be interpreted further.
>
> "e:\mm tests\1. exp files\5.MOC-1012.exp" will create a string object with
> the characters "e:\mm tests^A. exp files^E.MOC-1012.exp".  But now that's
> just a string value with those characters.  There's no concept of "making it
> a raw string" after that point at all.
>>
>>
>>
>> Thank you very much
>>
>> PS. It seems like a very basic question but I can not find the answer
>> in few books.
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>
------------------------------------------------------------

Thank You for your explanation. It seems that I have to explain in detail:


I read from one file plenty of parameters and among them one file name
of other file.
That file name is 'e:\mm tests\1. exp files\5.MOC-1012.exp' and I hold
it in variable s.

In program I need to know it's relative name and it's path.
When I try to get it with following commands I get wrong answers:

>>> s='e:\mm tests\1. exp files\5.MOC-1012.exp'
>>> os.path.split(s)
('e:\\', 'mm tests\x01. exp files\x05.MOC-1012.exp')
>>> os.path.dirname(s)
'e:\\'
>>> os.path.basename(s)
'mm tests\x01. exp files\x05.MOC-1012.exp'

instead of: 'e:\mm tests\1. exp files'   and   '5.MOC-1012.exp'.

The problem is that \1 and \5 is wrongly understood. I know that
everything works fine if I put raw string prefix r in front of string
which I put between "":

>>> os.path.split(r'e:\mm tests\1. exp files\5.MOC-1012.exp')
('e:\\mm tests\\1. exp files', '5.MOC-1012.exp')

but I can not do it that because I have already read path string
and it is now stored in variable s.

Maybe you wanted to suggest me to read from a file immediately
in a raw 'mode' but I don't know how to do that. Please tell me!

I solved that problem with 'workaround' witch works, but I am not
too happy with it:

def split_path(f_abs):
    """ Extract path and relative file name from abs. path """
    os.mkdir(f_abs+'_{}[]{}7x')  # create any subdirectory
    os.chdir(f_abs+'_{}[]{}7x')   # go in
    os.chdir('..')                      # go back
    os.rmdir(f_abs+'_{}[]{}7x')   # delete it (restore previous conditions)
    f_path=os.getcwd()           # get current dir
    f_rel=f_abs[1+len(f_path):] # 1 space because of '\'
    return f_path, f_rel

Thanks for your consideration
Regards,

Neven Gorsic

From john at fouhy.net  Mon Jul 21 00:34:20 2008
From: john at fouhy.net (John Fouhy)
Date: Mon, 21 Jul 2008 10:34:20 +1200
Subject: [Tutor] Raw string
In-Reply-To: <8acd28da0807201514h419398b4u5598f464c6fc189e@mail.gmail.com>
References: <8acd28da0807200733m5a9ed2eerbfb2dc31fa8c37a7@mail.gmail.com>
	<48835E4E.3040900@alchemy.com>
	<8acd28da0807201514h419398b4u5598f464c6fc189e@mail.gmail.com>
Message-ID: <5e58f2e40807201534k73c40046pb0a22211d352785e@mail.gmail.com>

On 21/07/2008, Neven Gor?i? <neven.gorsic at gmail.com> wrote:
>  >>> s='e:\mm tests\1. exp files\5.MOC-1012.exp'
>  >>> os.path.split(s)
>  ('e:\\', 'mm tests\x01. exp files\x05.MOC-1012.exp')
[...]
>  The problem is that \1 and \5 is wrongly understood.

Yup, that's not surprising.

> I know that
>  everything works fine if I put raw string prefix r in front of string
>  which I put between "":
[...]
>  but I can not do it that because I have already read path string
>  and it is now stored in variable s.

Are you sure?

If I create a file tmp which contains just that string:

### tmp ### this line not part of file ###
e:\mm tests\1. exp files\5.MOC-1012.exp
### end tmp ###

and I read it in:

>>> f = open('tmp')
>>> s = f.read()

Then I get:

>>> s
'e:\\mm tests\\1. exp files\\5.MOC-1012.exp\n'

which, apart from the newline on the end, looks like exactly what you
want.  If this isn't working for you, can you show what is going
wrong?

-- 
John.

From jammer10000 at gmail.com  Mon Jul 21 00:51:01 2008
From: jammer10000 at gmail.com (Joe Bennett)
Date: Sun, 20 Jul 2008 17:51:01 -0500
Subject: [Tutor] Online class/education for Python?
In-Reply-To: <20080720060817.B4B1C1E400A@bag.python.org>
References: <721b21dc0807191141q3704c8f9jcc3790f838c87f60@mail.gmail.com>
	<48826072.1050009@abbottdavid.com>
	<20080720060817.B4B1C1E400A@bag.python.org>
Message-ID: <dfd7bbde0807201551j68e0f1b8v845d07934f99fd88@mail.gmail.com>

What time where the classes? Web site seems to be missing that info...


-Joe



On Sun, Jul 20, 2008 at 1:08 AM, Dick Moores <rdm at rcblue.com> wrote:
> At 02:45 PM 7/19/2008, David wrote:
>>
>> Steve Poe wrote:
>>>
>>> Anyone taken or know of any online classes
>>> teaching Python? I know O'Reilly Press
>>> teaches online technical courses, through the University of
>>> Illinois, but no Python
>>> .
>>>
>>> Thanks.
>>>
>>> Steve
>>> ------------------------------------------------------------------------
>>>
>>> _______________________________________________
>>> Tutor maillist  -  Tutor at python.org
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>> I  am new to Python so this one was pretty good for me;
>>
>> http://www.ed2go.com/cgi-bin/ed2go/newcrsdes.cgi?course=ipy&title=Introduction^to^Python^2.5^Programming&departmentnum=WP&path=1
>
> This does look good. I'm thinking about the $129.
>
> 1. Is there a problem set for each lesson? Are they corrected or commented
> on?
> 2. How do you ask for help from the instructor? By email? In a forum? Was he
> helpful?
>
> Thanks,
>
> Dick Moores
> ===========================================================================
> Have you seen Kelie Feng's video introducing the terrific and free IDE,
> Ulipad? Download it from my website.
> <http://www.rcblue.com/u3/> Get Ulipad 3.9 from
> <http://code.google.com/p/ulipad/downloads/list>
> Use svn for the latest revision <http://ulipad.googlecode.com/svn/trunk/>
> Mailing list for Ulipad: <http://groups-beta.google.com/group/ulipad>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From steve.poe at gmail.com  Mon Jul 21 01:19:48 2008
From: steve.poe at gmail.com (Steve Poe)
Date: Sun, 20 Jul 2008 16:19:48 -0700
Subject: [Tutor] Online class/education for Python?
In-Reply-To: <dfd7bbde0807201551j68e0f1b8v845d07934f99fd88@mail.gmail.com>
References: <721b21dc0807191141q3704c8f9jcc3790f838c87f60@mail.gmail.com>
	<48826072.1050009@abbottdavid.com>
	<20080720060817.B4B1C1E400A@bag.python.org>
	<dfd7bbde0807201551j68e0f1b8v845d07934f99fd88@mail.gmail.com>
Message-ID: <721b21dc0807201619h66ca352aq110d3425ee563d85@mail.gmail.com>

Joe,

It's an online class without a specific time. The class runs for six weeks
with two assignments
per week.

Steve

On Sun, Jul 20, 2008 at 3:51 PM, Joe Bennett <jammer10000 at gmail.com> wrote:

> What time where the classes? Web site seems to be missing that info...
>
>
> -Joe
>
>
>
> On Sun, Jul 20, 2008 at 1:08 AM, Dick Moores <rdm at rcblue.com> wrote:
> > At 02:45 PM 7/19/2008, David wrote:
> >>
> >> Steve Poe wrote:
> >>>
> >>> Anyone taken or know of any online classes
> >>> teaching Python? I know O'Reilly Press
> >>> teaches online technical courses, through the University of
> >>> Illinois, but no Python
> >>> .
> >>>
> >>> Thanks.
> >>>
> >>> Steve
> >>>
> ------------------------------------------------------------------------
> >>>
> >>> _______________________________________________
> >>> Tutor maillist  -  Tutor at python.org
> >>> http://mail.python.org/mailman/listinfo/tutor
> >>>
> >> I  am new to Python so this one was pretty good for me;
> >>
> >>
> http://www.ed2go.com/cgi-bin/ed2go/newcrsdes.cgi?course=ipy&title=Introduction
> ^to^Python^2.5^Programming&departmentnum=WP&path=1
> >
> > This does look good. I'm thinking about the $129.
> >
> > 1. Is there a problem set for each lesson? Are they corrected or
> commented
> > on?
> > 2. How do you ask for help from the instructor? By email? In a forum? Was
> he
> > helpful?
> >
> > Thanks,
> >
> > Dick Moores
> >
> ===========================================================================
> > Have you seen Kelie Feng's video introducing the terrific and free IDE,
> > Ulipad? Download it from my website.
> > <http://www.rcblue.com/u3/> Get Ulipad 3.9 from
> > <http://code.google.com/p/ulipad/downloads/list>
> > Use svn for the latest revision <http://ulipad.googlecode.com/svn/trunk/
> >
> > Mailing list for Ulipad: <http://groups-beta.google.com/group/ulipad>
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080720/70dcf215/attachment.htm>

From cspears2002 at yahoo.com  Mon Jul 21 01:48:33 2008
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Sun, 20 Jul 2008 16:48:33 -0700 (PDT)
Subject: [Tutor] adding a watermark to a sequence of images
Message-ID: <307808.5381.qm@web51612.mail.re2.yahoo.com>

Has anyone used Python to watermark of sequence of images?

Thanks.


      

From motoom at xs4all.nl  Mon Jul 21 03:09:45 2008
From: motoom at xs4all.nl (Michiel Overtoom)
Date: Mon, 21 Jul 2008 03:09:45 +0200
Subject: [Tutor] adding a watermark to a sequence of images
Message-ID: <2.2.32.20080721010945.01255d58@pop.xs4all.nl>

Christopher wrote...

> Has anyone used Python to watermark of sequence of images?

No, but I have used PIL (Python Image Library) to do other things to batches
of images, like resizing or printing statistics on it.
Maybe you can get some ideas from these; maybe you can combine them with a
watermarking library.

------------------------------- ShowImageDimensions.py

import os,sys,Image

# See http://www.pythonware.com/library/pil/handbook/introduction.htm

def showdimension(filename):
    im=Image.open(filename)
    print filename,im.size
    
for infile in os.listdir('.'):
    f, e = os.path.splitext(infile)
    if (e=='.tga' or e=='.jpg' or e=='.gif' or e=='.bmp'):
        showdimension(infile)



------------------------------- WoWScreenshotConverter.py

# this converts all TGA's in the current ditectory to JPG's, full-, half-
and small size versions.
# I wrote this in the time when World of Warcraft could not save screenshots
in JPG format.


import os,sys,Image

# See http://www.pythonware.com/library/pil/handbook/introduction.htm
            
def convert(basename):
    print 'Converting',basename
    im=Image.open(basename+'.tga')
    im.save(basename+'-full.jpg')
    # halfsize=tuple(map(lambda x: x/2,im.size))
    halfsize=tuple([x/2 for x in im.size])
    im.thumbnail(halfsize,Image.ANTIALIAS)
    im.save(basename+'-half.jpg')
    thumbsize=128,128
    im.thumbnail(thumbsize,Image.ANTIALIAS)
    im.save(basename+'-small.jpg')
    

# convert('WoWScrnShot_123005_091926.tga')
for infile in os.listdir('.'):
    f, e = os.path.splitext(infile)
    if (e=='.tga'):
        convert(f)

-- 
"The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing." - Vinod Vallopillil
http://www.catb.org/~esr/halloween/halloween4.html


From bhaaluu at gmail.com  Mon Jul 21 03:17:51 2008
From: bhaaluu at gmail.com (bhaaluu)
Date: Sun, 20 Jul 2008 21:17:51 -0400
Subject: [Tutor] Online class/education for Python?
In-Reply-To: <721b21dc0807191141q3704c8f9jcc3790f838c87f60@mail.gmail.com>
References: <721b21dc0807191141q3704c8f9jcc3790f838c87f60@mail.gmail.com>
Message-ID: <ea979d70807201817x362d038cic86f492a7c7aa850@mail.gmail.com>

Hiyas Steve,

If you're disciplined enough to shell out $$$ for an online class
and do the work, why not just do it on your own? The tuition for
a class will buy you several very nice Python books:

Learning Python. Lutz.
Programming Python. Lutz
Core Python. Wesley Chun.
Python Programming for the Absolute Beginner 2E (if you're new to programming).

Read the book you buy, do the exercises, and if you run into
a problem, ask on this list. You'll end up learning Python, and
have a Python book to refer to as well. The structure of the class
is up to you, depending on what you want to use Python for,
and how the book you choose is written. You take your time,
or do 3-4-5 assignments per week. It's up to you!

If you've never done any programming before, I suggest
Dawson's book (PPftAB2E).

If you've done 'some' programming in another language and
want to learn Python, try Learning Python, followed by Programming
Python, both by Lutz.

If you're an experienced programmer, and want to get up to
speed with Python, try Chun's book. He's also a Tutor on this list.

Otherwise, take a look at all the wonderful free Python books and
tutorials on the Net, and make up your mind to start learning
Python, then DO it. Read some, program some. Ask questions here.

When you ask a question here, try to be as explicit as possible.
Tell the Tutors which platform you're working on (Linux, Mac, MS, other),
which version of Python you're using (ex: 2.4, 2.5, etc.). what you're
trying to do, what the errors are, and if at all possible, show them your
code! This is a beginner's list, so don't be ashamed to show your
beginner code! That is how you will learn! The Tutors won't do your
homework for you, but you'll get plenty of help otherwise!

Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m
Kid on Bus: What are you gonna do today, Napoleon?
Napoleon Dynamite: Whatever I feel like I wanna do. Gosh!

On Sat, Jul 19, 2008 at 2:41 PM, Steve Poe <steve.poe at gmail.com> wrote:
> Anyone taken or know of any online classes
> teaching Python? I know O'Reilly Press
> teaches online technical courses, through the University of
> Illinois, but no Python
> .
>
> Thanks.
>
> Steve
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>

From monjissvel at googlemail.com  Mon Jul 21 09:44:12 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Mon, 21 Jul 2008 07:44:12 +0000
Subject: [Tutor] Raw string
In-Reply-To: <e2f191310807210043q7b0d5841jd1b884dcaeb2c2ce@mail.gmail.com>
References: <8acd28da0807200733m5a9ed2eerbfb2dc31fa8c37a7@mail.gmail.com>
	<48835E4E.3040900@alchemy.com>
	<8acd28da0807201514h419398b4u5598f464c6fc189e@mail.gmail.com>
	<5e58f2e40807201534k73c40046pb0a22211d352785e@mail.gmail.com>
	<e2f191310807210043q7b0d5841jd1b884dcaeb2c2ce@mail.gmail.com>
Message-ID: <e2f191310807210044k1f10e7efv5afe0c8ad364d823@mail.gmail.com>

instead  of s='e:\mm tests\1. exp files\5.MOC-1012.exp'
try to use : s = r'e:\mm tests\1. exp files\5.MOC-1012.exp'.replace('\\',
'\\\\')
for me here is what it gives:

>>> s = r'e:\mm tests\1. exp files\5.MOC-1012.exp'.replace('\\', '\\\\')
>>> print s
e:\\mm tests\\1. exp files\\5.MOC-1012.exp
>>> s.split('\\\\')
['e:', 'mm tests', '1. exp files', '5.MOC-1012.exp']


why \\  i you only have one \ ? : you need to escape it because its a
special character to the python interpreter.


the r character is important in the expression  s = r'e:\mm tests\1. exp
files\5.MOC-1012.exp'.replace('\\', '\\\\') because it tells the interpreter
to take the string as RAW and thus leave it unchanged even if it contains
special characters that should actually be treated special.

now to use the r or not to use it ? when to use it ? how to use it ? I
always use it ! & always had the result I expected, so I would suggest you
use it always too specialy with the re module, ofcourse unless the result is
not satisaying you,

so this code (using r this time works too) :

>>> s = r'e:\mm tests\1. exp files\5.MOC-1012.exp'.replace(r'\\', r'\\\\')
>>> print s
e:\\mm tests\\1. exp files\\5.MOC-1012.exp
>>> s.split('\\\\')
['e:', 'mm tests', '1. exp files', '5.MOC-1012.exp']
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080721/840a4392/attachment-0001.htm>

From oltarasenko at gmail.com  Mon Jul 21 09:46:56 2008
From: oltarasenko at gmail.com (Oleg Oltar)
Date: Mon, 21 Jul 2008 11:46:56 +0400
Subject: [Tutor] Import modeuls
In-Reply-To: <9a2cc7a70807201428n29802dd1g97dfb6707e78e420@mail.gmail.com>
References: <b4fc2ad80807200946s56954709h27432cf0163535c5@mail.gmail.com>
	<9a2cc7a70807201428n29802dd1g97dfb6707e78e420@mail.gmail.com>
Message-ID: <b4fc2ad80807210046o3f0698d5q39c1744b1b1f72dc@mail.gmail.com>

If I am adding, __init__.py it still doesn't import anything.
Do I have add the import (from sampletest import EmailWithoutA) in my init
file?


On Mon, Jul 21, 2008 at 1:28 AM, arsyed <arsyed at gmail.com> wrote:

> On Sun, Jul 20, 2008 at 12:46 PM, Oleg Oltar <oltarasenko at gmail.com>
> wrote:
>
>> Hi
>> I need to import several modules from many folders which has subfolders
>>
>> ~/folder/tests/sampletest.py
>> ~/folder/suites/samplesuit.py
>>
>> a suit uses tests from tests folder. I need to import them somehow from
>> tests folder. I added ~/folder to PYTHONPATH in my test_runner:
>>
>>
>> import sys
>> import os
>>
>> sys.path.insert(0, "~/folder")
>> os.popen("python2.5 %s" %sys.argv[1])
>>
>> But when trying to import module in the samplesuite file:
>>
>> from tests.sampletest.EmailWithoutA import EmailWithoutA
>>>
>>
>> But I getting ImportError: No module named ....
>>
>> Please help
>>
>>
>
> Do you have an __init__.py file in the tests and suites directories?
>
> More on that here:
>
> http://docs.python.org/tut/node8.html
>
> "The __init__.py files are required to make Python treat the directories
> as containing packages; this is done to prevent directories with a common
> name, such as "string", from unintentionally hiding valid modules that
> occur later on the module search path. In the simplest case, __init__.pycan just be an empty file, but it can also execute initialization code for
> the package or set the __all__ variable, described later."
>
>
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080721/37539ec3/attachment.htm>

From arsyed at gmail.com  Mon Jul 21 10:06:21 2008
From: arsyed at gmail.com (arsyed)
Date: Mon, 21 Jul 2008 04:06:21 -0400
Subject: [Tutor] Import modeuls
In-Reply-To: <b4fc2ad80807210046o3f0698d5q39c1744b1b1f72dc@mail.gmail.com>
References: <b4fc2ad80807200946s56954709h27432cf0163535c5@mail.gmail.com>
	<9a2cc7a70807201428n29802dd1g97dfb6707e78e420@mail.gmail.com>
	<b4fc2ad80807210046o3f0698d5q39c1744b1b1f72dc@mail.gmail.com>
Message-ID: <9a2cc7a70807210106m4f2ab4f1u5c15637df100f3fd@mail.gmail.com>

On Mon, Jul 21, 2008 at 3:46 AM, Oleg Oltar <oltarasenko at gmail.com> wrote:

> If I am adding, __init__.py it still doesn't import anything.
> Do I have add the import (from sampletest import EmailWithoutA) in my init
> file?
>
>

I didn't notice this before, but I don't think python does tilde expansion
in sys.path. Try using an absolute path, for example:

sys.path.insert(0, "~/folder")

to

sys.path.insert(0, "/home/user/folder')
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080721/de81d856/attachment.htm>

From neven.gorsic at gmail.com  Mon Jul 21 10:42:35 2008
From: neven.gorsic at gmail.com (=?ISO-8859-2?Q?Neven_Gor=B9i=E6?=)
Date: Mon, 21 Jul 2008 10:42:35 +0200
Subject: [Tutor] Raw string
In-Reply-To: <e2f191310807210044k1f10e7efv5afe0c8ad364d823@mail.gmail.com>
References: <8acd28da0807200733m5a9ed2eerbfb2dc31fa8c37a7@mail.gmail.com>
	<48835E4E.3040900@alchemy.com>
	<8acd28da0807201514h419398b4u5598f464c6fc189e@mail.gmail.com>
	<5e58f2e40807201534k73c40046pb0a22211d352785e@mail.gmail.com>
	<e2f191310807210043q7b0d5841jd1b884dcaeb2c2ce@mail.gmail.com>
	<e2f191310807210044k1f10e7efv5afe0c8ad364d823@mail.gmail.com>
Message-ID: <8acd28da0807210142j5c599a41waf3b9ae10d3cf91c@mail.gmail.com>

On Mon, Jul 21, 2008 at 9:44 AM, Monika Jisswel
<monjissvel at googlemail.com> wrote:
> instead  of s='e:\mm tests\1. exp files\5.MOC-1012.exp'
> try to use : s = r'e:\mm tests\1. exp files\5.MOC-1012.exp'.replace(
> '\\', '\\\\')
> for me here is what it gives:
>
>>>> s = r'e:\mm tests\1. exp files\5.MOC-1012.exp'.replace('\\', '\\\\')
>>>> print s
> e:\\mm tests\\1. exp files\\5.MOC-1012.exp
>>>> s.split('\\\\')
> ['e:', 'mm tests', '1. exp files', '5.MOC-1012.exp']
>
>
> why \\  i you only have one \ ? : you need to escape it because its a
> special character to the python interpreter.
>
>
> the r character is important in the expression  s = r'e:\mm tests\1. exp
> files\5.MOC-1012.exp'.replace('\\', '\\\\') because it tells the interpreter
> to take the string as RAW and thus leave it unchanged even if it contains
> special characters that should actually be treated special.
>
> now to use the r or not to use it ? when to use it ? how to use it ? I
> always use it ! & always had the result I expected, so I would suggest you
> use it always too specialy with the re module, ofcourse unless the result is
> not satisaying you,
>
> so this code (using r this time works too) :
>
>>>> s = r'e:\mm tests\1. exp files\5.MOC-1012.exp'.replace(r'\\', r'\\\\')
>>>> print s
> e:\\mm tests\\1. exp files\\5.MOC-1012.exp
>>>> s.split('\\\\')
> ['e:', 'mm tests', '1. exp files', '5.MOC-1012.exp']
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
--------------------

Thanks,
I am aware of goodies that raw string offers, but my question was how to
use it with variable that already contains string.  :)

From oltarasenko at gmail.com  Mon Jul 21 11:15:53 2008
From: oltarasenko at gmail.com (Oleg Oltar)
Date: Mon, 21 Jul 2008 12:15:53 +0300
Subject: [Tutor] Import modeuls
In-Reply-To: <9a2cc7a70807210211i635d2b0s5eac8d54feff40e6@mail.gmail.com>
References: <b4fc2ad80807200946s56954709h27432cf0163535c5@mail.gmail.com>
	<9a2cc7a70807201428n29802dd1g97dfb6707e78e420@mail.gmail.com>
	<b4fc2ad80807210046o3f0698d5q39c1744b1b1f72dc@mail.gmail.com>
	<9a2cc7a70807210106m4f2ab4f1u5c15637df100f3fd@mail.gmail.com>
	<b4fc2ad80807210146p17a005cfwada2bf7e08937567@mail.gmail.com>
	<9a2cc7a70807210211i635d2b0s5eac8d54feff40e6@mail.gmail.com>
Message-ID: <b4fc2ad80807210215w50674159r3bdea6efd5203a8f@mail.gmail.com>

They want me to do one test runner which runs any test... And ideally it
should work on any platform....

When I added something to $PYTHONPATH, they told me to remove it...



On Mon, Jul 21, 2008 at 12:11 PM, arsyed <arsyed at gmail.com> wrote:

> On Mon, Jul 21, 2008 at 4:46 AM, Oleg Oltar <oltarasenko at gmail.com> wrote:
>
>> Anyway. another related question. I run tests using the runner.py
>>
>> It has following syntax
>> sys.path.insert(path)
>> os.popen("python module to run")
>>
>> Will the python runned from the file see new path?
>>
>>
>>
> I'm not sure but I don't think so. Try and see what happens.
>
> I think to get that behavior, you want to set the PYTHONPATH environment
> variable instead. Then, I believe the child process will inherit the parent
> process's environment variable. If that doesn't work, look into the
> subprocess module which takes an explicit env parameter for the Popen class
> in order to accomplish this.
>
> It's probably easier just to set PYTHONPATH in your shell and then run your
> scripts so all programs will have access to it.
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080721/33af5f11/attachment.htm>

From arsyed at gmail.com  Mon Jul 21 11:36:42 2008
From: arsyed at gmail.com (arsyed)
Date: Mon, 21 Jul 2008 05:36:42 -0400
Subject: [Tutor] Import modeuls
In-Reply-To: <b4fc2ad80807210215w50674159r3bdea6efd5203a8f@mail.gmail.com>
References: <b4fc2ad80807200946s56954709h27432cf0163535c5@mail.gmail.com>
	<9a2cc7a70807201428n29802dd1g97dfb6707e78e420@mail.gmail.com>
	<b4fc2ad80807210046o3f0698d5q39c1744b1b1f72dc@mail.gmail.com>
	<9a2cc7a70807210106m4f2ab4f1u5c15637df100f3fd@mail.gmail.com>
	<b4fc2ad80807210146p17a005cfwada2bf7e08937567@mail.gmail.com>
	<9a2cc7a70807210211i635d2b0s5eac8d54feff40e6@mail.gmail.com>
	<b4fc2ad80807210215w50674159r3bdea6efd5203a8f@mail.gmail.com>
Message-ID: <9a2cc7a70807210236s1f0eb3f6hd997d39dd2300a2d@mail.gmail.com>

On Mon, Jul 21, 2008 at 5:15 AM, Oleg Oltar <oltarasenko at gmail.com> wrote:

> They want me to do one test runner which runs any test... And ideally it
> should work on any platform....
>
> When I added something to $PYTHONPATH, they told me to remove it...
>
>
You can set environment variables within python, e.g.:

os.environ['PYTHONPATH'] = '/some/path:' + old_path

What I don't know is if child processes invoked through os.popen inherit
that variable on all platforms. However, the subprocess.Popen object takes
an explicit "env" variable for that purpose:

http://docs.python.org/lib/node528.html
http://docs.python.org/lib/module-subprocess.html

So you should be able to use that for the same effect.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080721/7c6a6048/attachment.htm>

From monjissvel at googlemail.com  Mon Jul 21 12:23:01 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Mon, 21 Jul 2008 10:23:01 +0000
Subject: [Tutor] Raw string
In-Reply-To: <8acd28da0807210142j5c599a41waf3b9ae10d3cf91c@mail.gmail.com>
References: <8acd28da0807200733m5a9ed2eerbfb2dc31fa8c37a7@mail.gmail.com>
	<48835E4E.3040900@alchemy.com>
	<8acd28da0807201514h419398b4u5598f464c6fc189e@mail.gmail.com>
	<5e58f2e40807201534k73c40046pb0a22211d352785e@mail.gmail.com>
	<e2f191310807210043q7b0d5841jd1b884dcaeb2c2ce@mail.gmail.com>
	<e2f191310807210044k1f10e7efv5afe0c8ad364d823@mail.gmail.com>
	<8acd28da0807210142j5c599a41waf3b9ae10d3cf91c@mail.gmail.com>
Message-ID: <e2f191310807210323t4a496610tb5756c2bc2c4c54@mail.gmail.com>

>
> Thanks,
> I am aware of goodies that raw string offers, but my question was how to
> use it with variable that already contains string.  :)
>


if you are reading the value from a file :

import re
for line in myfile:
    if re.search(r'e:\mm tests\1. exp files\5.MOC-1012.exp', line):
        line = r'e:\mm tests\1. exp files\5.MOC-1012.exp'.replace('\\',
'\\\\')
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080721/de9c681c/attachment.htm>

From kent37 at tds.net  Mon Jul 21 13:34:24 2008
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 21 Jul 2008 07:34:24 -0400
Subject: [Tutor] Import modeuls
In-Reply-To: <b4fc2ad80807210215w50674159r3bdea6efd5203a8f@mail.gmail.com>
References: <b4fc2ad80807200946s56954709h27432cf0163535c5@mail.gmail.com>
	<9a2cc7a70807201428n29802dd1g97dfb6707e78e420@mail.gmail.com>
	<b4fc2ad80807210046o3f0698d5q39c1744b1b1f72dc@mail.gmail.com>
	<9a2cc7a70807210106m4f2ab4f1u5c15637df100f3fd@mail.gmail.com>
	<b4fc2ad80807210146p17a005cfwada2bf7e08937567@mail.gmail.com>
	<9a2cc7a70807210211i635d2b0s5eac8d54feff40e6@mail.gmail.com>
	<b4fc2ad80807210215w50674159r3bdea6efd5203a8f@mail.gmail.com>
Message-ID: <1c2a2c590807210434x29819b87taccdfc6cce552612@mail.gmail.com>

On Mon, Jul 21, 2008 at 5:15 AM, Oleg Oltar <oltarasenko at gmail.com> wrote:
> They want me to do one test runner which runs any test... And ideally it
> should work on any platform....

You might want to look at nose or py.test, they both have test
runners. I think you can give nose a directory and it will find and
run the tests in the directory.
http://www.somethingaboutorange.com/mrl/projects/nose/

Kent

From ebrosh at nana10.co.il  Mon Jul 21 14:07:20 2008
From: ebrosh at nana10.co.il (Eli Brosh)
Date: Mon, 21 Jul 2008 15:07:20 +0300
Subject: [Tutor] List installed python modules
References: <001701c8ddff$eda93ef0$0501a8c0@brucetower>
Message-ID: <957526FB6E347743AAB42B212AB54FDA95BB4A@NANAMAILBACK1.nanamail.co.il>

Hello,

Is there a way to get a list of installed python modules and their versions ?
i.e. I would like to know if matplotlib is installed on my computer and what version is it.
And so with other modules.

Thanks
Eli
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080721/efa7e61d/attachment.htm>

From mwalsh at groktech.org  Mon Jul 21 14:18:18 2008
From: mwalsh at groktech.org (Martin Walsh)
Date: Mon, 21 Jul 2008 07:18:18 -0500
Subject: [Tutor] Raw string
In-Reply-To: <8acd28da0807201514h419398b4u5598f464c6fc189e@mail.gmail.com>
References: <8acd28da0807200733m5a9ed2eerbfb2dc31fa8c37a7@mail.gmail.com>	<48835E4E.3040900@alchemy.com>
	<8acd28da0807201514h419398b4u5598f464c6fc189e@mail.gmail.com>
Message-ID: <48847E8A.1060505@groktech.org>

Neven Gor?i? wrote:
> I read from one file plenty of parameters and among them one file name
> of other file.
> That file name is 'e:\mm tests\1. exp files\5.MOC-1012.exp' and I hold
> it in variable s.

As John pointed out, if you're really reading this string from a file
(with something like file.read or ConfigParser) it should already be
escaped properly, and you'd get back something like 'e:\\mm tests\\1.
exp files\\5.MOC-1012.exp' instead. Which would probably work for your
purposes.

Can you show us an example of the approach you're using to 'read'
parameters from a file, including the variable assignment?

Marty




From monjissvel at googlemail.com  Mon Jul 21 14:18:54 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Mon, 21 Jul 2008 12:18:54 +0000
Subject: [Tutor] Raw string
In-Reply-To: <8acd28da0807210500kd0c4870k9cec260595211e0c@mail.gmail.com>
References: <8acd28da0807200733m5a9ed2eerbfb2dc31fa8c37a7@mail.gmail.com>
	<48835E4E.3040900@alchemy.com>
	<8acd28da0807201514h419398b4u5598f464c6fc189e@mail.gmail.com>
	<5e58f2e40807201534k73c40046pb0a22211d352785e@mail.gmail.com>
	<e2f191310807210043q7b0d5841jd1b884dcaeb2c2ce@mail.gmail.com>
	<e2f191310807210044k1f10e7efv5afe0c8ad364d823@mail.gmail.com>
	<8acd28da0807210142j5c599a41waf3b9ae10d3cf91c@mail.gmail.com>
	<e2f191310807210323t4a496610tb5756c2bc2c4c54@mail.gmail.com>
	<8acd28da0807210500kd0c4870k9cec260595211e0c@mail.gmail.com>
Message-ID: <e2f191310807210518m620f3e7dmb3ba36ad87241b82@mail.gmail.com>

>
> I don't know in advance what the file name will be...


import re
for line in myfile:
    if re.search(r'\', line):
        line = line.replace('\\', '\\\\')

if you have lines that contain a \ in them that you don't want to substitute
then you need another if statement.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080721/2204fe5e/attachment.htm>

From mail at timgolden.me.uk  Mon Jul 21 14:37:15 2008
From: mail at timgolden.me.uk (Tim Golden)
Date: Mon, 21 Jul 2008 13:37:15 +0100
Subject: [Tutor] List installed python modules
In-Reply-To: <957526FB6E347743AAB42B212AB54FDA95BB4A@NANAMAILBACK1.nanamail.co.il>
References: <001701c8ddff$eda93ef0$0501a8c0@brucetower>
	<957526FB6E347743AAB42B212AB54FDA95BB4A@NANAMAILBACK1.nanamail.co.il>
Message-ID: <488482FB.1060508@timgolden.me.uk>

Eli Brosh wrote:
> Hello,
> 
> Is there a way to get a list of installed python modules and their 
> versions ?
> i.e. I would like to know if matplotlib is installed on my computer and 
> what version is it.
> And so with other modules.

You've got two slightly different requirements there:

1) List all modules installed

and

2) Is *this* module installed?

The second is easy:

<code>
try:
 import ModuleX
except ImportError:
 print "ModuleX is not installed"
else:
 print "ModuleX is installed"
 print "with version", getattr (ModuleX, __VERSION__, "unknown")
 
</code>

There's no prescribed attribute for version, so you
might have to check a few like that if you didn't
know what to look for.

The first is harder, and in effect impossible in general.
Given a well-known and controlled setup, you could do
various things like interrogate the system's package
database or scan sys.path looking for modules & packages,
but it's all a bit hazy and wouldn't take into account,
say, a library module local to a particular application
which differs from a centrally-installed one for version
reasons.

TJG


From neven.gorsic at gmail.com  Mon Jul 21 14:55:13 2008
From: neven.gorsic at gmail.com (=?ISO-8859-2?Q?Neven_Gor=B9i=E6?=)
Date: Mon, 21 Jul 2008 14:55:13 +0200
Subject: [Tutor] Raw string
In-Reply-To: <48847E8A.1060505@groktech.org>
References: <8acd28da0807200733m5a9ed2eerbfb2dc31fa8c37a7@mail.gmail.com>
	<48835E4E.3040900@alchemy.com>
	<8acd28da0807201514h419398b4u5598f464c6fc189e@mail.gmail.com>
	<48847E8A.1060505@groktech.org>
Message-ID: <8acd28da0807210555j4e1644cjf8d368935a67414b@mail.gmail.com>

2008/7/21 Martin Walsh <mwalsh at groktech.org>:
> Neven Gor?i? wrote:
>> I read from one file plenty of parameters and among them one file name
>> of other file.
>> That file name is 'e:\mm tests\1. exp files\5.MOC-1012.exp' and I hold
>> it in variable s.
>
> As John pointed out, if you're really reading this string from a file
> (with something like file.read or ConfigParser) it should already be
> escaped properly, and you'd get back something like 'e:\\mm tests\\1.
> exp files\\5.MOC-1012.exp' instead. Which would probably work for your
> purposes.
>
> Can you show us an example of the approach you're using to 'read'
> parameters from a file, including the variable assignment?
>
> Marty
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
------------------------------------------------------------------------------------------------------------

I reconfigured file my parameter file. I left only one parameter in that line
(path) and write path without ''. Then f.readline() get correct raw string
and I can get path and file name properly by means of os.path.split(line).

Thank you for your good will

Neven Gorsic

From deliberatus at verizon.net  Mon Jul 21 15:38:29 2008
From: deliberatus at verizon.net (Kirk Bailey)
Date: Mon, 21 Jul 2008 09:38:29 -0400
Subject: [Tutor] seaxtradusa site
Message-ID: <48849155.2070104@verizon.net>

ok, here is the link;
http://www.seaxtradusa.org/
In the footer of all webppages (not in the wiki or in the 
forum), is a link so i can edit pages on the site without 
bothering to use a shell account or upload pages or 
anything. I just wrote this, and it is password protected.
This is a handy little feature and it is kinda useful.

The link uses a server side include in a universal footer, 
and yes, this WILL point the script to the right page:

<a href="/cgi-bin/EditMyPage.py?
<!--#echo var="DOCUMENT_NAME" -->">Edit This Page</a>

NOTE the page name is inserted into the structure with a 
simple SSI echo command.

Place this link in the universal footer of your site, it 
will work. All pages so edit must be in the root directory 
for THIS edition, but who knows what the future holds.

-- 


Cheers!
           -Kirk D Bailey

               THINK
              +-----+
   .*.        | BOX |
   ..*        +-----+
   ***         THINK

From d.conca at gmail.com  Mon Jul 21 16:08:45 2008
From: d.conca at gmail.com (Daniele)
Date: Mon, 21 Jul 2008 16:08:45 +0200
Subject: [Tutor] Configuration File Pattern
Message-ID: <537341c70807210708x52faac7dy44cb850d4a7c4bc6@mail.gmail.com>

Hi list,
I've recently developed a basic python program which needs to store
some data in a file (e.g. a directory path).
What the program needs is a dictionary containing the data, so I used
the pickle module to store the dictionary in a file and read it back
when the program is launched.
I wanted to know which is the common pattern in python programming in
this case, because the way I've choosen only lets the user configure
the data via a GUI (the file is somehow "compiled"). Is it better to
store the data in a text file and then parse it and construct a
dictionary? Or is there e third way?

Thanks, Daniele

From deliberatus at verizon.net  Mon Jul 21 16:10:15 2008
From: deliberatus at verizon.net (Kirk Bailey)
Date: Mon, 21 Jul 2008 10:10:15 -0400
Subject: [Tutor] seaxtradusa site
In-Reply-To: <48849155.2070104@verizon.net>
References: <48849155.2070104@verizon.net>
Message-ID: <488498C7.8080409@verizon.net>

BTW, wordwrap issue, all that is on ONE LINE.

Kirk Bailey wrote:
> ok, here is the link;
> http://www.seaxtradusa.org/
> In the footer of all webppages (not in the wiki or in the forum), is a 
> link so i can edit pages on the site without bothering to use a shell 
> account or upload pages or anything. I just wrote this, and it is 
> password protected.
> This is a handy little feature and it is kinda useful.
> 
> The link uses a server side include in a universal footer, and yes, this 
> WILL point the script to the right page:
> 
> <a href="/cgi-bin/EditMyPage.py?
> <!--#echo var="DOCUMENT_NAME" -->">Edit This Page</a>
> 
> NOTE the page name is inserted into the structure with a simple SSI echo 
> command.
> 
> Place this link in the universal footer of your site, it will work. All 
> pages so edit must be in the root directory for THIS edition, but who 
> knows what the future holds.
> 

-- 


Cheers!
           -Kirk D Bailey

               THINK
              +-----+
   .*.        | BOX |
   ..*        +-----+
   ***         THINK

From flaxeater at gmail.com  Mon Jul 21 18:14:42 2008
From: flaxeater at gmail.com (Chad Crabtree)
Date: Mon, 21 Jul 2008 12:14:42 -0400
Subject: [Tutor] Configuration File Pattern
In-Reply-To: <537341c70807210708x52faac7dy44cb850d4a7c4bc6@mail.gmail.com>
References: <537341c70807210708x52faac7dy44cb850d4a7c4bc6@mail.gmail.com>
Message-ID: <584940990807210914o457de5bs80a84028ed93ddb0@mail.gmail.com>

What I use in this situation is the INI config file parser in the
standard lib.  It's easy to use

##CONFIG FILE####
[paths]
images=/home/user/Images


##CODE###
import ConfigParser
config=ConfigParser.ConfigParser()
config.readfp(open(conf,'r'))
print config


http://docs.python.org/lib/module-ConfigParser.html

On Mon, Jul 21, 2008 at 10:08 AM, Daniele <d.conca at gmail.com> wrote:
> Hi list,
> I've recently developed a basic python program which needs to store
> some data in a file (e.g. a directory path).
> What the program needs is a dictionary containing the data, so I used
> the pickle module to store the dictionary in a file and read it back
> when the program is launched.
> I wanted to know which is the common pattern in python programming in
> this case, because the way I've choosen only lets the user configure
> the data via a GUI (the file is somehow "compiled"). Is it better to
> store the data in a text file and then parse it and construct a
> dictionary? Or is there e third way?
>
> Thanks, Daniele
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From dsarmientos at gmail.com  Mon Jul 21 19:20:59 2008
From: dsarmientos at gmail.com (Daniel Sarmiento)
Date: Mon, 21 Jul 2008 12:20:59 -0500
Subject: [Tutor] Advice for my function, isPrime(n), please
Message-ID: <d356a5240807211020v245fc7a3i4be1c2708d95c144@mail.gmail.com>

What about the following function?

if x == 0:
    return False
return True


I am a beginner, but I think it is more clear (at least to me) what
the function does. And it is only one line longer than

value = (x != 0)
return value

From marc.tompkins at gmail.com  Mon Jul 21 19:29:53 2008
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Mon, 21 Jul 2008 10:29:53 -0700
Subject: [Tutor] Advice for my function, isPrime(n), please
In-Reply-To: <d356a5240807211020v245fc7a3i4be1c2708d95c144@mail.gmail.com>
References: <d356a5240807211020v245fc7a3i4be1c2708d95c144@mail.gmail.com>
Message-ID: <40af687b0807211029t586376ebl91cf5574d8c0dff2@mail.gmail.com>

On Mon, Jul 21, 2008 at 10:20 AM, Daniel Sarmiento <dsarmientos at gmail.com>
wrote:

> What about the following function?
>
> if x == 0:
>    return False
> return True
>
>
> I am a beginner, but I think it is more clear (at least to me) what
> the function does. And it is only one line longer than
>
> value = (x != 0)
> return value
>

How about

> return (x!=0)
>
?

Short and cryptic!


-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080721/91beb024/attachment.htm>

From marc.tompkins at gmail.com  Mon Jul 21 19:32:39 2008
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Mon, 21 Jul 2008 10:32:39 -0700
Subject: [Tutor] Advice for my function, isPrime(n), please
In-Reply-To: <40af687b0807211029t586376ebl91cf5574d8c0dff2@mail.gmail.com>
References: <d356a5240807211020v245fc7a3i4be1c2708d95c144@mail.gmail.com>
	<40af687b0807211029t586376ebl91cf5574d8c0dff2@mail.gmail.com>
Message-ID: <40af687b0807211032p7e99370by8946e05ecaa440f3@mail.gmail.com>

On Mon, Jul 21, 2008 at 10:29 AM, Marc Tompkins <marc.tompkins at gmail.com>
wrote:

>
> How about
>
>> return (x!=0)
>>
> ?
>
> Short and cryptic!
>

Sorry - I had deleted all the old messages in the thread, and only responded
to the latest.  My bad - I see now that I've joined in beating a dead horse.


-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080721/2d2c705e/attachment.htm>

From ruivaldo at gmail.com  Mon Jul 21 19:59:36 2008
From: ruivaldo at gmail.com (Ruivaldo Neto)
Date: Mon, 21 Jul 2008 14:59:36 -0300
Subject: [Tutor] Tkinter Help
Message-ID: <d4a50f170807211059q713f9110g4d98001d1f0bdb8a@mail.gmail.com>

Hi,

I have a Python app that runs as a Windows Service. Inside this
application, there is a Thread that starts a webservice.
When this webservice is called, this thread displays a simple Tkinter
window with some entry?s for input.

But the mainloop simple stays running without presenting any popup or error.
The app is running as SYSTEM on Windows. As other user, the code works great.

Any advice to make this work ?

Thanks in advance.


Ruivaldo Neto

From lie.1296 at gmail.com  Mon Jul 21 20:13:32 2008
From: lie.1296 at gmail.com (Lie Ryan)
Date: Tue, 22 Jul 2008 01:13:32 +0700
Subject: [Tutor] Raw string
In-Reply-To: <mailman.51.1216634425.10910.tutor@python.org>
References: <mailman.51.1216634425.10910.tutor@python.org>
Message-ID: <1216664012.6381.12.camel@lieryan-laptop>

> ?Thanks,
> I am aware of goodies that raw string offers, but my question was 
?> how to use it with variable that already contains string.  :)

If you really have to, you may use something like this:

# Untested
def kludge(s):
    s = 'r"""%s"""' % repr(s)
    return eval(s)

Most people would frown at the use of eval (in fact I do too), because
it is possible to leak dangerous code from this function, given certain
string sequences.

But, that's enough of a kludge and don't ask for more kludges. THE
correct way to fix the problem is not here, but in the input function
(the function that assigns the variable)...

If you're reading from a file, and you get this problem, most probably
the program that generates the file is the problem. Check the file's
real content...

If you're reading from standard input, make sure you use raw_input(),
instead of input(), as text in input() is eval()ed first, not something
we would want... 


From lie.1296 at gmail.com  Mon Jul 21 20:23:07 2008
From: lie.1296 at gmail.com (Lie Ryan)
Date: Tue, 22 Jul 2008 01:23:07 +0700
Subject: [Tutor] Configuration File Pattern
In-Reply-To: <mailman.4113.1216649337.920.tutor@python.org>
References: <mailman.4113.1216649337.920.tutor@python.org>
Message-ID: <1216664587.6381.23.camel@lieryan-laptop>

> Message: 9
> Date: Mon, 21 Jul 2008 16:08:45 +0200
> From: Daniele <d.conca at gmail.com>
> Subject: [Tutor] Configuration File Pattern
> To: tutor at python.org
> Message-ID:
>         <537341c70807210708x52faac7dy44cb850d4a7c4bc6 at mail.gmail.com>
> Content-Type: text/plain; charset=UTF-8
> 
> Hi list,
> I've recently developed a basic python program which needs to store
> some data in a file (e.g. a directory path).
> What the program needs is a dictionary containing the data, so I used
> the pickle module to store the dictionary in a file and read it back
> when the program is launched.
> I wanted to know which is the common pattern in python programming in
> this case, because the way I've choosen only lets the user configure
> the data via a GUI (the file is somehow "compiled"). Is it better to
> store the data in a text file and then parse it and construct a
> dictionary? Or is there e third way?

Following the Unix philosophy (?"Store data in flat text file"), it is
much better to dump the dictionary into a plain text file, but pickling
is so damn easy. If you have the time and space to do it, you should
make a dumper and parser, if not, there is no real problem with using
pickled format as far as I'm aware (especially if you strictly don't
want someone to manually modify the file). 

The only potential problem, I could think of, is whether pickled data is
cross-version compatible.


From dkuhlman at rexx.com  Mon Jul 21 20:39:12 2008
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Mon, 21 Jul 2008 11:39:12 -0700
Subject: [Tutor] Online class/education for Python?
In-Reply-To: <ea979d70807201817x362d038cic86f492a7c7aa850@mail.gmail.com>
References: <721b21dc0807191141q3704c8f9jcc3790f838c87f60@mail.gmail.com>
	<ea979d70807201817x362d038cic86f492a7c7aa850@mail.gmail.com>
Message-ID: <20080721183912.GA46263@cutter.rexx.com>

On Sun, Jul 20, 2008 at 09:17:51PM -0400, bhaaluu wrote:
> 
> If you're disciplined enough to shell out $$$ for an online class
> and do the work, why not just do it on your own? The tuition for
> a class will buy you several very nice Python books:
> 
> Learning Python. Lutz.
> Programming Python. Lutz
> Core Python. Wesley Chun.
> Python Programming for the Absolute Beginner 2E (if you're new to programming).

bhaaluu is right.  There is lots of help on line.

But, some prefer help and others prefer working on their own.

If you do want to do it on your own, also take a look at:

    http://wiki.python.org/moin/BeginnersGuide
    http://wiki.python.org/moin/BeginnersGuide/NonProgrammers
    http://wiki.python.org/moin/BeginnersGuide/Programmers

- Dave


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

From ladynikon at gmail.com  Mon Jul 21 22:20:31 2008
From: ladynikon at gmail.com (Danyelle Gragsone)
Date: Mon, 21 Jul 2008 16:20:31 -0400
Subject: [Tutor] Online class/education for Python?
In-Reply-To: <ea979d70807201817x362d038cic86f492a7c7aa850@mail.gmail.com>
References: <721b21dc0807191141q3704c8f9jcc3790f838c87f60@mail.gmail.com>
	<ea979d70807201817x362d038cic86f492a7c7aa850@mail.gmail.com>
Message-ID: <59f9c5160807211320x4087cbf8kc89e2ad7404cc526@mail.gmail.com>

Hi,

I have the first edition of Python Programming for the Absolute Beginner.
Will this work instead of the 2nd edition?

thanks,
Danyelle
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080721/edb39f87/attachment.htm>

From carroll at tjc.com  Mon Jul 21 22:30:56 2008
From: carroll at tjc.com (Terry Carroll)
Date: Mon, 21 Jul 2008 13:30:56 -0700 (PDT)
Subject: [Tutor] adding a watermark to a sequence of images
In-Reply-To: <307808.5381.qm@web51612.mail.re2.yahoo.com>
Message-ID: <Pine.LNX.4.44.0807211326480.14276-100000@violet.rahul.net>

On Sun, 20 Jul 2008, Christopher Spears wrote:

> Has anyone used Python to watermark of sequence of images?

There's a recipe for watermarking using PIL here:

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

I have a half-baked program that goes through a directory of images and 
time-stamps them with information from the EXIF data, which I'd be happy 
to share with you.  I started writing it because my wife likes to have our 
photos timestamped, and I don't, so this was our compromise; but she later 
came around to my point of view so I never really cleaned it up.  It 
works, but needs some polish.  It would be easy to adapt to a fixed 
watermark.


From carroll at tjc.com  Mon Jul 21 22:42:39 2008
From: carroll at tjc.com (Terry Carroll)
Date: Mon, 21 Jul 2008 13:42:39 -0700 (PDT)
Subject: [Tutor] Advice for my function, isPrime(n), please
In-Reply-To: <d356a5240807211020v245fc7a3i4be1c2708d95c144@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0807211334260.14276-100000@violet.rahul.net>

On Mon, 21 Jul 2008, Daniel Sarmiento wrote:

> What about the following function?
> 
> if x == 0:
>     return False
> return True

I don't like it, myself.  You have multiple points of exit, and, yes, you 
can see that the fallthough is only executed if the condition is not met, 
but it makes you do a double-take when reading it.

If you insist on having the conditional, this is clearer:

if x == 0:
    return False
else:
    return True

I'd rather have the condition test for truth, though:

if x != 0:
    return True
else:
    return False

But that leads to what you don't like anyway, which I think is your best 
solution:

return x != 0



From arsyed at gmail.com  Mon Jul 21 22:58:52 2008
From: arsyed at gmail.com (arsyed)
Date: Mon, 21 Jul 2008 16:58:52 -0400
Subject: [Tutor] Tkinter Help
In-Reply-To: <d4a50f170807211059q713f9110g4d98001d1f0bdb8a@mail.gmail.com>
References: <d4a50f170807211059q713f9110g4d98001d1f0bdb8a@mail.gmail.com>
Message-ID: <9a2cc7a70807211358p417390b7l75c1deeedb081309@mail.gmail.com>

On Mon, Jul 21, 2008 at 1:59 PM, Ruivaldo Neto <ruivaldo at gmail.com> wrote:

> Hi,
>
> I have a Python app that runs as a Windows Service. Inside this
> application, there is a Thread that starts a webservice.
> When this webservice is called, this thread displays a simple Tkinter
> window with some entry?s for input.
>
> But the mainloop simple stays running without presenting any popup or
> error.
> The app is running as SYSTEM on Windows. As other user, the code works
> great.
>
> Any advice to make this work ?
>
> Thanks in advance.
>
>

I think this is because you need to have the service marked as
"Interactive".  This page has some information:

http://msdn.microsoft.com/en-us/library/ms683502(VS.85).aspx

It might be worth asking the question in the py-win32 group or some windows
related forum.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080721/efe784ab/attachment.htm>

From d.conca at gmail.com  Mon Jul 21 23:15:15 2008
From: d.conca at gmail.com (Daniele)
Date: Mon, 21 Jul 2008 23:15:15 +0200
Subject: [Tutor] Configuration File Pattern
In-Reply-To: <584940990807210914o457de5bs80a84028ed93ddb0@mail.gmail.com>
References: <537341c70807210708x52faac7dy44cb850d4a7c4bc6@mail.gmail.com>
	<584940990807210914o457de5bs80a84028ed93ddb0@mail.gmail.com>
Message-ID: <537341c70807211415w3e327b01s3fb031ddc34e132c@mail.gmail.com>

> What I use in this situation is the INI config file parser in the
> standard lib.  It's easy to use
>
> http://docs.python.org/lib/module-ConfigParser.html
>

Awesome!
Really easy and intuitive.
Thanks a lot

From cspears2002 at yahoo.com  Tue Jul 22 00:10:14 2008
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Mon, 21 Jul 2008 15:10:14 -0700 (PDT)
Subject: [Tutor] adding a watermark to a sequence of images
In-Reply-To: <Pine.LNX.4.44.0807211326480.14276-100000@violet.rahul.net>
Message-ID: <310154.62167.qm@web51605.mail.re2.yahoo.com>

By all means, share your script!  Even if I don't use it, I can learn something from it!

Thanks!

--- On Mon, 7/21/08, Terry Carroll <carroll at tjc.com> wrote:

> From: Terry Carroll <carroll at tjc.com>
> Subject: Re: [Tutor] adding a watermark to a sequence of images
> To: cspears2002 at yahoo.com, tutor at python.org
> Date: Monday, July 21, 2008, 1:30 PM
> On Sun, 20 Jul 2008, Christopher Spears wrote:
> 
> > Has anyone used Python to watermark of sequence of
> images?
> 
> There's a recipe for watermarking using PIL here:
> 
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362879
> 
> I have a half-baked program that goes through a directory
> of images and 
> time-stamps them with information from the EXIF data, which
> I'd be happy 
> to share with you.  I started writing it because my wife
> likes to have our 
> photos timestamped, and I don't, so this was our
> compromise; but she later 
> came around to my point of view so I never really cleaned
> it up.  It 
> works, but needs some polish.  It would be easy to adapt to
> a fixed 
> watermark.


      

From alan.gauld at btinternet.com  Tue Jul 22 00:54:48 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 21 Jul 2008 23:54:48 +0100
Subject: [Tutor] Tkinter Help
References: <d4a50f170807211059q713f9110g4d98001d1f0bdb8a@mail.gmail.com>
Message-ID: <g6343p$p62$1@ger.gmane.org>

"Ruivaldo Neto" <ruivaldo at gmail.com> wrote

> I have a Python app that runs as a Windows Service. Inside this
> application, there is a Thread that starts a webservice.
> When this webservice is called, this thread displays a simple 
> Tkinter
> window with some entry?s for input.

Thats usually a very bad idea. Presenting services  with GUIs
can lead to lockups and other bad things under Windows so
you should only do it if absolutely essential. Are you sure there
is no other way to run your app? Maybe with the GUI part as
a separate program that communicates with the service?

> But the mainloop simple stays running without presenting
> any popup or error. The app is running as SYSTEM on
> Windows. As other user, the code works great.

I think the requirements of a service mean there are some
extra flags that need to be set. MSDN is probably your best
bet for info. It will also explain why services and GUIs don't
usually mix.

> Any advice to make this work ?

Don't do it. Find another way.

Alan G. 



From alan.gauld at btinternet.com  Tue Jul 22 00:58:07 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 21 Jul 2008 23:58:07 +0100
Subject: [Tutor] Online class/education for Python?
References: <721b21dc0807191141q3704c8f9jcc3790f838c87f60@mail.gmail.com><ea979d70807201817x362d038cic86f492a7c7aa850@mail.gmail.com>
	<59f9c5160807211320x4087cbf8kc89e2ad7404cc526@mail.gmail.com>
Message-ID: <g634a0$pm8$1@ger.gmane.org>


"Danyelle Gragsone" <ladynikon at gmail.com> wrote

> I have the first edition of Python Programming for the Absolute 
> Beginner.
> Will this work instead of the 2nd edition?

Python changes little and slowly between versions so the
answer is almost certainly yes. New features are by definition
major and fast but the existing features tend to only move a
little over time.

Alan G. 



From rdm at rcblue.com  Tue Jul 22 01:02:14 2008
From: rdm at rcblue.com (Dick Moores)
Date: Mon, 21 Jul 2008 16:02:14 -0700
Subject: [Tutor] Advice for my function, isPrime(n), please
In-Reply-To: <Pine.LNX.4.44.0807211334260.14276-100000@violet.rahul.net>
References: <d356a5240807211020v245fc7a3i4be1c2708d95c144@mail.gmail.com>
	<Pine.LNX.4.44.0807211334260.14276-100000@violet.rahul.net>
Message-ID: <20080721230226.693101E4010@bag.python.org>

At 01:42 PM 7/21/2008, Terry Carroll wrote:
>On Mon, 21 Jul 2008, Daniel Sarmiento wrote:
>
> > What about the following function?
> >
> > if x == 0:
> >     return False
> > return True
>
>I don't like it, myself.  You have multiple points of exit, and, yes, you
>can see that the fallthough is only executed if the condition is not met,
>but it makes you do a double-take when reading it.
>
>If you insist on having the conditional, this is clearer:
>
>if x == 0:
>     return False
>else:
>     return True
>
>I'd rather have the condition test for truth, though:
>
>if x != 0:
>     return True
>else:
>     return False
>
>But that leads to what you don't like anyway, which I think is your best
>solution:
>
>return x != 0

Actually, and as I predicted, I'm beginning to like it. :-)

Dick



From metolone+gmane at gmail.com  Tue Jul 22 04:41:03 2008
From: metolone+gmane at gmail.com (Mark Tolonen)
Date: Mon, 21 Jul 2008 19:41:03 -0700
Subject: [Tutor] Raw string
References: <8acd28da0807200733m5a9ed2eerbfb2dc31fa8c37a7@mail.gmail.com><48835E4E.3040900@alchemy.com><8acd28da0807201514h419398b4u5598f464c6fc189e@mail.gmail.com><5e58f2e40807201534k73c40046pb0a22211d352785e@mail.gmail.com><e2f191310807210043q7b0d5841jd1b884dcaeb2c2ce@mail.gmail.com><e2f191310807210044k1f10e7efv5afe0c8ad364d823@mail.gmail.com>
	<8acd28da0807210142j5c599a41waf3b9ae10d3cf91c@mail.gmail.com>
Message-ID: <g63hbt$nfd$1@ger.gmane.org>


"Neven Gorsic" <neven.gorsic at gmail.com> wrote in message 
news:8acd28da0807210142j5c599a41waf3b9ae10d3cf91c at mail.gmail.com...
> On Mon, Jul 21, 2008 at 9:44 AM, Monika Jisswel
> <monjissvel at googlemail.com> wrote:
>> instead  of s='e:\mm tests\1. exp files\5.MOC-1012.exp'
>> try to use : s = r'e:\mm tests\1. exp files\5.MOC-1012.exp'.replace(
>> '\\', '\\\\')
>> for me here is what it gives:
>>
>>>>> s = r'e:\mm tests\1. exp files\5.MOC-1012.exp'.replace('\\', '\\\\')
>>>>> print s
>> e:\\mm tests\\1. exp files\\5.MOC-1012.exp
>>>>> s.split('\\\\')
>> ['e:', 'mm tests', '1. exp files', '5.MOC-1012.exp']
>>
>>
>> why \\  i you only have one \ ? : you need to escape it because its a
>> special character to the python interpreter.
>>
>>
>> the r character is important in the expression  s = r'e:\mm tests\1. exp
>> files\5.MOC-1012.exp'.replace('\\', '\\\\') because it tells the 
>> interpreter
>> to take the string as RAW and thus leave it unchanged even if it contains
>> special characters that should actually be treated special.
>>
>> now to use the r or not to use it ? when to use it ? how to use it ? I
>> always use it ! & always had the result I expected, so I would suggest 
>> you
>> use it always too specialy with the re module, ofcourse unless the result 
>> is
>> not satisaying you,
>>
>> so this code (using r this time works too) :
>>
>>>>> s = r'e:\mm tests\1. exp files\5.MOC-1012.exp'.replace(r'\\', r'\\\\')
>>>>> print s
>> e:\\mm tests\\1. exp files\\5.MOC-1012.exp
>>>>> s.split('\\\\')
>> ['e:', 'mm tests', '1. exp files', '5.MOC-1012.exp']
>>
>
> Thanks,
> I am aware of goodies that raw string offers, but my question was how to
> use it with variable that already contains string.  :)

What it seems you don't understand is that raw strings just a method to 
create a string.  If you already have a string read from a file, it is 
already created.  Maybe you are confused between the "representation" of a 
string and the "value" of the string.

    >>> s = 'c:\\abc\\123.txt'
    >>> t = r'c:\abc\123.txt'
    >>> s==t
    True

Two ways to *create* the *same* string.

Note there are two ways to *display* a string as well.  print displays the 
actual value.  If you don't use print, you get a representation of the 
string in a way that can be used to create the string in code.

    >>> print s
    c:\abc\123.txt
    >>> print t
    c:\abc\123.txt
    >>> s
    'c:\\abc\\123.txt'
    >>> t
    'c:\\abc\\123.txt'

Note what happens if you use single backslashes without a raw to create the 
string:

    >>> s = 'c:\abc\123.txt'
    >>> s
    'c:\x07bcS.txt'
    >>> print s
    c:bcS.txt

Because it wasn't a 'raw' string, the \a was interpreted as the 
non-printable BEL control character.  \123 was interpreted as an octal 
constant, which turned out to be capital-S.  The representation of the 
string contained a \x07 for the BEL control character.  Since it is 
unprintable, the representation displayed it as a hexadecimal escape code.

When you read a string from a file, the actual characters in the file end up 
in the string.  No backslash interpretation is performed.  So in your 
example, just read in the file and perform your operations:

sample.txt contains:

    c:\abc\123.txt

Code:

    >>> import os
    >>> pathname = open('sample.txt').read()
    >>> pathname
    'c:\\abc\\123.txt'
    >>> print pathname
    c:\abc\123.txt
    >>> print os.path.dirname(pathname)
    c:\abc
    >>> print os.path.basename(pathname)
    123.txt
    >>> os.path.dirname(pathname)
    'c:\\abc'
    >>> os.path.basename(pathname)
    '123.txt'

Does that clear up the confusion?

--Mark



From Romaine.Rupp at arrisi.com  Mon Jul 21 19:25:10 2008
From: Romaine.Rupp at arrisi.com (Rupp, Romaine)
Date: Mon, 21 Jul 2008 10:25:10 -0700
Subject: [Tutor] question about socket status
Message-ID: <4F68D1DF3745984280EDAE91602C54D2722192F2@beoexch1.NTSCD.C-COR.com>

Hello,
I am new to programming with python and sockets.
I would like to determine the status of a socket as it  is returned when you do 'netstat -a | grep <port#>'.  I would like  to know if the socket state is ESTABLISHED, LISTEN , CLOSE_WAIT, etc.
Is there a way to get this information through a socket call?
I've tried using socket.getperrname() function, but that only tells if there is a connection.
Is there a way to get more information on the state of the socket connection?
Thanks,
rrupp
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080721/fb438b3b/attachment.htm>

From carroll at tjc.com  Tue Jul 22 07:56:33 2008
From: carroll at tjc.com (Terry Carroll)
Date: Mon, 21 Jul 2008 22:56:33 -0700 (PDT)
Subject: [Tutor] adding a watermark to a sequence of images
In-Reply-To: <310154.62167.qm@web51605.mail.re2.yahoo.com>
Message-ID: <Pine.LNX.4.44.0807212246580.20120-100000@violet.rahul.net>

On Mon, 21 Jul 2008, Christopher Spears wrote:

> By all means, share your script!  Even if I don't use it, I can learn
> something from it!

Well, maybe.  If nothing else, perhaps you'll learn some new bad habits.

The timestamp on this file shows that I dropped this project in June 2005, 
and you can see it's unfinished.  It still has a few raw edges (including 
a prompt for a "preserve EXIF" feature that never got written; and lots of 
debugging print statements), but it's not bad as a proof-of-concept.

The code imports and depends on Gene Cash's EXIF.py module; it now 
apparently lives at http://sourceforge.net/projects/exif-py/ rather than 
the URL in the code.  But still, if the EXIF module doesn't exist, it just 
uses the file's timestamp as the date -- not exactly the safest way of 
figuring the date the photo was taken.

At the time I wrote this, I was unaware that PIL had some 
then-undocumented EXIF support; I probably would have used that to avoid 
importing a non-standard module.

Use this code however you wish, if you find it helpful.  Ignore the 
copyright statement; BaishuSoft was just a little joke between my wife and 
me.


------snip-------
import Tkinter as Tk
import tkFileDialog
import os, sys, time
import Image, ImageDraw, ImageFont, ImageTk


class MyApp:
    """Begin a Tkinter-based application"""
    
    def __init__(self, root):
        """initializer for Tkinter-based application"""
        self.root=root
        self.root.title("Picture TimeStamper")
        NoticeFrame = Tk.Frame(self.root)
        NoticeFrame.pack()
        headertext = u"""
        Baishusoft Picture TimeStamper
        \U000000A9 2005 Baishusoft LLP
        """
        Tk.Label(NoticeFrame,text=headertext).pack()
        ButtonFrame = Tk.Frame(self.root)
        ButtonFrame.pack()       
        SelButton = Tk.Button(ButtonFrame, 
            text="Select Directory", command=self.select)
        SelButton.pack(side="left")
        QuitButton = Tk.Button(ButtonFrame, text="Quit", 
            command=self.quit)
        QuitButton.pack(side="left")

        OptionsFrame = Tk.Frame(self.root)
        OptionsFrame.pack()
        self.EXIFvar = Tk.IntVar()
        self.EXIFCheckbox = Tk.Checkbutton(
            OptionsFrame,
            text="Preserve EXIF (requires JHead)",
            variable = self.EXIFvar)
        self.EXIFCheckbox.pack(side="top")
        self.Progressvar = Tk.IntVar()
        self.ProgressCheckbox = Tk.Checkbutton(
            OptionsFrame,
            text="Show progress",
            variable = self.Progressvar)
        self.ProgressCheckbox.pack(side="left")
               
        self.StatusFrame = Tk.Frame(self.root)
        self.StatusFrame.pack()
        self.ImageLabel = Tk.Label(self.StatusFrame)
        self.ImageLabel.pack()
        self.FilenameLabel = Tk.Label(self.StatusFrame)
        self.FilenameLabel.pack()

    def select(self):
        dirname = tkFileDialog.askdirectory()
        if dirname != '':
            os.path.walk(dirname, self.process_files, None)
            print "PROCESSING COMPLETED.  SELECT MORE FILES OR QUIT."
        else:
            print "NO DIRECTORY SELECTED."
        return
    
    def quit(self):
        print "EXITING."
        sys.exit()

    def process_files(self, junk, dirpath, namelist):
        for filename in namelist:
            stamped_filename = self.getstampedfilename(filename)
            if stamped_filename is not None:
                if os.path.isfile(os.path.join(dirpath,stamped_filename)):
                    print "FILE EXISTS, SKIPPING:", stamped_filename
                else:
                    self.updatestatus(dirpath, filename)
                    datetext = self.timestamp(dirpath, filename, 
                        stamped_filename)
                    print "FILE IMPRINTED:", stamped_filename, datetext
                    
    def updatestatus(self,dirpath,filename):
        im=Image.open(os.path.join(dirpath, filename))
        print time.asctime(), "thumbnailing...", filename, im.mode, im.size
        im.thumbnail((100,75))
        print time.asctime(), "showing...", filename, im.mode, im.size
        #im.show()
        self.Tkimage = ImageTk.PhotoImage(im)
        print "created"
        self.ImageLabel.config(image=self.Tkimage)
        self.ImageLabel.pack()
        self.FilenameLabel.config(text=filename)
        self.FilenameLabel.pack()
        self.StatusFrame.pack()
        self.root.update()

    
    def getstampedfilename(self, filename):
        fn, ft = os.path.splitext(filename)
        if ft.upper() in [".JPG", ".JPEG"] and \
               not (fn.upper().endswith("-DATED")):
            return fn + "-dated" + ft
        else:
            return None

    def timestamp(self, dirpath, original_filename, new_filename):
        full_original_filename = os.path.join(dirpath, original_filename)
        full_new_filename = os.path.join(dirpath, new_filename)
        font=ImageFont.truetype("Arial.ttf", 40)
        datetext = GetFileDate(full_original_filename)
        im = Image.open(full_original_filename)
        im0 = Imprint(im, datetext, font=font, opacity=0.6, 
             color=(255,255,255))
        im0.save(full_new_filename, "JPEG")
        return datetext

def GetFileDate(file):
    """
    Returns the date associated with a file.
    For JPEG files, it will use the EXIF data, if available
    """
    try:
        import EXIF
        # EXIF.py from http://home.cfl.rr.com/genecash/digital_camera.html
        f = open(file, "rb")
        tags = EXIF.process_file(f)
        f.close()
        return str(tags['Image DateTime'])
    except (KeyError, ImportError):
        # EXIF not installed or no EXIF date available
        import os.path, time
        return time.ctime(os.path.getmtime(file))

def ReduceOpacity(im, opacity):
    """
    Returns an image with reduced opacity.
    Taken from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362879
    """

    import ImageEnhance
    assert opacity >= 0 and opacity <= 1
    if im.mode != 'RGBA':
        im = im.convert('RGBA')
    else:
        im = im.copy()
    alpha = im.split()[3]
    alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
    im.putalpha(alpha)
    return im

def Imprint(im, inputtext, font=None, color=None, opacity=.6, margin=(30,30)):
    """
    imprints a PIL image with the indicated text in lower-right corner
    """
    if im.mode != "RGBA":
        im = im.convert("RGBA")
    textlayer = Image.new("RGBA", im.size, (0,0,0,0))
    textdraw = ImageDraw.Draw(textlayer)
    textsize = textdraw.textsize(inputtext, font=font)
    textpos = [im.size[i]-textsize[i]-margin[i] for i in [0,1]]
    textdraw.text(textpos, inputtext, font=font, fill=color)
    if opacity != 1:
        textlayer = ReduceOpacity(textlayer,opacity)
    return Image.composite(textlayer, im, textlayer)
        
            
root = Tk.Tk()
myapp = MyApp(root)
root.mainloop()



From bryan.fodness at gmail.com  Tue Jul 22 17:40:39 2008
From: bryan.fodness at gmail.com (Bryan Fodness)
Date: Tue, 22 Jul 2008 11:40:39 -0400
Subject: [Tutor] checking if data files are good, readable, and exist
Message-ID: <fbf64d2b0807220840t3b1fb966qf5f8cf3ada7c2708@mail.gmail.com>

I would like to check to see if the data files are good, readable, and
exist.  I have checked to see if they exist, but their is a possibility that
the data file might be binary, and I would like to have a sys.exit for that
as well.

if not os.path.isfile(A_data) or not os.path.isfile(B_data)\
   or not os.path.isfile(C_data) or not os.path.isfile(D_data):
    sys.exit(14)




-- 
"The game of science can accurately be described as a never-ending insult to
human intelligence." - Jo?o Magueijo
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080722/6e4e18e9/attachment.htm>

From mail at timgolden.me.uk  Tue Jul 22 18:05:56 2008
From: mail at timgolden.me.uk (Tim Golden)
Date: Tue, 22 Jul 2008 17:05:56 +0100
Subject: [Tutor] checking if data files are good, readable, and exist
In-Reply-To: <fbf64d2b0807220840t3b1fb966qf5f8cf3ada7c2708@mail.gmail.com>
References: <fbf64d2b0807220840t3b1fb966qf5f8cf3ada7c2708@mail.gmail.com>
Message-ID: <48860564.7090502@timgolden.me.uk>

Bryan Fodness wrote:
> I would like to check to see if the data files are good, readable, and 
> exist.  I have checked to see if they exist, but their is a possibility 
> that the data file might be binary, and I would like to have a sys.exit 
> for that as well.

You're going to be asked a lot of questions along the lines
of "What do you mean by binary?". I'm going to assume you
mean: has things other than ordinary letters, numbers
and punctuation in it. In today's internationalised and
Unicoded world that's a highly dodgy assumption, but I'm 
going to go with it.

To compound the crudeness of my approach, I'm going to
assume that anything > 126 is "binary" (thus dodging
the more complicated issue of the 0-31 control chars).

<code>
def is_binary (filename):
  return any (ord (c) > 126 for c in open (filename).read ())

print is_binary ("file1.txt")

</code>

Obviously, if you know any of the files is going to be
massive, you'll want to do something a bit smarter than
this.

TJG

From srilyk at gmail.com  Tue Jul 22 18:09:19 2008
From: srilyk at gmail.com (W W)
Date: Tue, 22 Jul 2008 11:09:19 -0500
Subject: [Tutor] checking if data files are good, readable, and exist
In-Reply-To: <fbf64d2b0807220840t3b1fb966qf5f8cf3ada7c2708@mail.gmail.com>
References: <fbf64d2b0807220840t3b1fb966qf5f8cf3ada7c2708@mail.gmail.com>
Message-ID: <333efb450807220909h36cee42aubdd742aea9b9f36e@mail.gmail.com>

On Tue, Jul 22, 2008 at 10:40 AM, Bryan Fodness <bryan.fodness at gmail.com>
wrote:

> I would like to check to see if the data files are good, readable, and
> exist.  I have checked to see if they exist, but their is a possibility that
> the data file might be binary, and I would like to have a sys.exit for that
> as well.
>
> if not os.path.isfile(A_data) or not os.path.isfile(B_data)\
>    or not os.path.isfile(C_data) or not os.path.isfile(D_data):
>     sys.exit(14)
>

Am I wrong in thinking that /all/ files are stored as binary? And then when
python opens them, it automagically opens them in a more readable format,
unless you open them in binary with "rb" or similar command?

-Wayne

-- 
To be considered stupid and to be told so is more painful than being called
gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness,
every vice, has found its defenders, its rhetoric, its ennoblement and
exaltation, but stupidity hasn't. - Primo Levi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080722/e9823176/attachment.htm>

From dextrous85 at gmail.com  Tue Jul 22 20:37:02 2008
From: dextrous85 at gmail.com (vishwajeet singh)
Date: Wed, 23 Jul 2008 00:07:02 +0530
Subject: [Tutor] %(value1, value2) what does this returns
Message-ID: <5487b3060807221137r371800ddx2712c1fc02c35076@mail.gmail.com>

Hi List,

def __request(symbol, stat):
    url = 'http://finance.yahoo.com/d/quotes.csv?s=%s&f=%s' % (symbol, stat)
     return urllib.urlopen(url)

I want to know in this % (symbol, stat) returns

thanks for help

Regards,
Vishwajeet
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080723/8d4f9122/attachment.htm>

From motoom at xs4all.nl  Tue Jul 22 20:48:47 2008
From: motoom at xs4all.nl (Michiel Overtoom)
Date: Tue, 22 Jul 2008 20:48:47 +0200
Subject: [Tutor] %(value1, value2) what does this returns
Message-ID: <2.2.32.20080722184847.011b9d98@pop.xs4all.nl>

Vishwajeet wrote...

> I want to know in this % (symbol, stat) returns

In itself it returns nothing.  The '%' is used as the 'string interpolation
operator' here.

http://docs.python.org/lib/typesseq-strings.html

>>> print "%d kilos of %s for %f euro" % (2,"mangos",3.75)
2 kilos of mangos for 3.750000 euro

Greetings,

-- 
"The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing." - Vinod Vallopillil
http://www.catb.org/~esr/halloween/halloween4.html


From bgailer at gmail.com  Tue Jul 22 20:55:51 2008
From: bgailer at gmail.com (bob gailer)
Date: Tue, 22 Jul 2008 14:55:51 -0400
Subject: [Tutor] %(value1, value2) what does this returns
In-Reply-To: <5487b3060807221137r371800ddx2712c1fc02c35076@mail.gmail.com>
References: <5487b3060807221137r371800ddx2712c1fc02c35076@mail.gmail.com>
Message-ID: <48862D37.5030300@gmail.com>

vishwajeet singh wrote:
> Hi List,
>
> def __request(symbol, stat):
>     url = 'http://finance.yahoo.com/d/quotes.csv?s=%s&f=%s 
> <http://finance.yahoo.com/d/quotes.csv?s=%s&f=%s>' % (symbol, stat)
>      return urllib.urlopen(url)
>
> I want to know in this % (symbol, stat) returns

Assume symbol = "foo" and stat = "bar".
Then url = 'http://finance.yahoo.com/d/quotes.csv?s=foo&f=bar 
<http://finance.yahoo.com/d/quotes.csv?s=%s&f=%s>

-- 
Bob Gailer
919-636-4239 Chapel Hill, NC


From dextrous85 at gmail.com  Tue Jul 22 20:56:30 2008
From: dextrous85 at gmail.com (vishwajeet singh)
Date: Wed, 23 Jul 2008 00:26:30 +0530
Subject: [Tutor] %(value1, value2) what does this returns
In-Reply-To: <2.2.32.20080722184847.011b9d98@pop.xs4all.nl>
References: <2.2.32.20080722184847.011b9d98@pop.xs4all.nl>
Message-ID: <5487b3060807221156r77fe254fu9b6fd461628342e6@mail.gmail.com>

thanks to all of you for your responses;

On Wed, Jul 23, 2008 at 12:18 AM, Michiel Overtoom <motoom at xs4all.nl> wrote:

> Vishwajeet wrote...
>
> > I want to know in this % (symbol, stat) returns
>
> In itself it returns nothing.  The '%' is used as the 'string interpolation
> operator' here.
>
> http://docs.python.org/lib/typesseq-strings.html
>
> >>> print "%d kilos of %s for %f euro" % (2,"mangos",3.75)
> 2 kilos of mangos for 3.750000 euro
>
> Greetings,
>
> --
> "The ability of the OSS process to collect and harness
> the collective IQ of thousands of individuals across
> the Internet is simply amazing." - Vinod Vallopillil
> http://www.catb.org/~esr/halloween/halloween4.html<http://www.catb.org/%7Eesr/halloween/halloween4.html>
>
> _______________________________________________
> 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/20080723/6543ee71/attachment.htm>

From alan.gauld at btinternet.com  Tue Jul 22 23:01:30 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 22 Jul 2008 22:01:30 +0100
Subject: [Tutor] checking if data files are good, readable, and exist
References: <fbf64d2b0807220840t3b1fb966qf5f8cf3ada7c2708@mail.gmail.com>
	<333efb450807220909h36cee42aubdd742aea9b9f36e@mail.gmail.com>
Message-ID: <g65hrb$84q$1@ger.gmane.org>

"W W" <srilyk at gmail.com> wrote

> Am I wrong in thinking that /all/ files are stored as binary?

No, thats quite right.

> python opens them, it automagically opens them in a
> more readable format,

But that isn't. Python just reads the data and interprets it
as text if you specify a text file - the default - or as raw data
if you use rb.

Python doesn't alter the data in any way it simply assumes
that its text and interprets the bytes according to the current
alphabet. Thus it reads the value 65 and interprets it as 'A'
(assuming ASCII) in text mode or just as the bit pattern
01000001 in binary. The application must then interpret the
bits in whatever way it considers appropriate - ass an integer,
a bitmask, part of a graphic image etc.

The important point is that there is no distinction between
binary data or text data in the file itself its just how it is
interpreted that distinguishes them. (This is not completely
true on some OS where text files always have an EOF marker,
but it is itself just a binary value!)

None of which helps the OP other than to highlight the difficulty
of determining if a file in binary or not. We can sometimes
tell if a file is not text - if it uses ASCII - by looking at the 
range
of byte values, but thats sloooooowww... but we can never be
sure that a file is non text. (We can also check for common
file headers such as postscript, GIF, MP3, JPEG, MIDI, etc
etc but even they can be misleading if they just coincidentally
look valid)

HTH,

Alan G. 



From bgailer at gmail.com  Wed Jul 23 01:47:30 2008
From: bgailer at gmail.com (bob gailer)
Date: Tue, 22 Jul 2008 19:47:30 -0400
Subject: [Tutor] checking if data files are good, readable, and exist
In-Reply-To: <g65hrb$84q$1@ger.gmane.org>
References: <fbf64d2b0807220840t3b1fb966qf5f8cf3ada7c2708@mail.gmail.com>	<333efb450807220909h36cee42aubdd742aea9b9f36e@mail.gmail.com>
	<g65hrb$84q$1@ger.gmane.org>
Message-ID: <48867192.3070107@gmail.com>

Alan Gauld wrote:
> But that isn't. Python just reads the data and interprets it
> as text if you specify a text file - the default - or as raw data
> if you use rb.

But it DOES handle line-ends in an OS independent manner. Windows uses 
CR-LF as a line end, whereas Unix, Linux, Mac use (just CR or is it LF?).

Python presents line-ends uniformly as \n when you open the file in text 
mode.

Witness: (on Windows)

 >>> f = open('c:/foo.txt', 'r')
 >>> f.read()
'this line contains as\nbut this has as\n'
 >>> f = open('c:/foo.txt', 'rb')
 >>> f.read()
'this line contains as\r\nbut this has as\r\n'

[snip]

-- 
Bob Gailer
919-636-4239 Chapel Hill, NC


From jfabiani at yolo.com  Wed Jul 23 01:17:14 2008
From: jfabiani at yolo.com (johnf)
Date: Tue, 22 Jul 2008 16:17:14 -0700
Subject: [Tutor] OT looking for help creating a thumbnail
Message-ID: <200807221617.14651.jfabiani@yolo.com>

Hi,
I'm sorry this is OT but you guys are very knowledgeable with the world of 
python.  I already tried the python list. - no response.

I need a py tool that will provide a thumbnail (bmp?) from a video (avi,
wmv) that will be cross platform (linux, windows). ?Research has provided
pymedia for Linux but I haven't found anything for windows. ?Hopefully,
someone has had to do this in the past and knows what has to be done.

Thanks in Advance,
Johnf


From alan.gauld at btinternet.com  Wed Jul 23 02:34:17 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 23 Jul 2008 01:34:17 +0100
Subject: [Tutor] checking if data files are good, readable, and exist
References: <fbf64d2b0807220840t3b1fb966qf5f8cf3ada7c2708@mail.gmail.com>	<333efb450807220909h36cee42aubdd742aea9b9f36e@mail.gmail.com><g65hrb$84q$1@ger.gmane.org>
	<48867192.3070107@gmail.com>
Message-ID: <g65uaa$bnj$1@ger.gmane.org>

"bob gailer" <bgailer at gmail.com> wrote 

>> But that isn't. Python just reads the data and interprets it
>> as text if you specify a text file - the default - or as raw data
>> if you use rb.

> But it DOES handle line-ends in an OS independent manner. 

OK, I'll grant you that small piece of data manipulation. :-)

(Although it could be argued that even that is just translating 
two bytes into one character in the set.)

Alan G.



From arsyed at gmail.com  Wed Jul 23 03:31:47 2008
From: arsyed at gmail.com (arsyed)
Date: Tue, 22 Jul 2008 21:31:47 -0400
Subject: [Tutor] question about socket status
In-Reply-To: <4F68D1DF3745984280EDAE91602C54D2722192F2@beoexch1.NTSCD.C-COR.com>
References: <4F68D1DF3745984280EDAE91602C54D2722192F2@beoexch1.NTSCD.C-COR.com>
Message-ID: <9a2cc7a70807221831i7766daccue28b36748ed99ca2@mail.gmail.com>

On Mon, Jul 21, 2008 at 1:25 PM, Rupp, Romaine <Romaine.Rupp at arrisi.com> wrote:
> Hello,
>
> I am new to programming with python and sockets.
>
> I would like to determine the status of a socket as it  is returned when you
> do 'netstat ?a | grep <port#>'.  I would like  to know if the socket state
> is ESTABLISHED, LISTEN , CLOSE_WAIT, etc.
>
> Is there a way to get this information through a socket call?
>
> I've tried using socket.getperrname() function, but that only tells if there
> is a connection.
>
> Is there a way to get more information on the state of the socket
> connection?
>


If you're on linux, you could try poking around /proc/net. See, for example:

http://www.linuxdevcenter.com/pub/a/linux/2000/11/16/LinuxAdmin.html

But I think invoking netstat and parsing the output from python might
work well enough.

From ladynikon at gmail.com  Wed Jul 23 05:38:48 2008
From: ladynikon at gmail.com (Danyelle Gragsone)
Date: Tue, 22 Jul 2008 23:38:48 -0400
Subject: [Tutor] Online class/education for Python?
In-Reply-To: <ea979d70807220427t3fdc99bfh4948f3287eb57867@mail.gmail.com>
References: <721b21dc0807191141q3704c8f9jcc3790f838c87f60@mail.gmail.com>
	<ea979d70807201817x362d038cic86f492a7c7aa850@mail.gmail.com>
	<59f9c5160807211320x4087cbf8kc89e2ad7404cc526@mail.gmail.com>
	<ea979d70807220427t3fdc99bfh4948f3287eb57867@mail.gmail.com>
Message-ID: <59f9c5160807222038v1a8e7ff6wa7c2f2043c61d7e@mail.gmail.com>

> <http://mail.python.org/mailman/listinfo/tutor>
>
> Hi,
>
> I have the Second Edition of PPftAB, and it was published in 2006.
> The version of Python used in PPftAB2E is Python 2.3.5.
> I'm running Python 2.4.4 on Debian GNU/Linux. So far, no problems.
>
> The only problems I can see you having is if the examples in your book
> use a feature that is no longer used in Python. Otherwise, I don't think
> you'll have any problems. The core principles of Python Programming
> remain the same.
>
> Just out of curiosity, when was the First Edition published? Which version
> of Python is used in the book?
>
>
It was done in 2003.  The version of python the book uses is 2.2.3.
However, it does talk about using the latest versions of python.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080722/76af9ce9/attachment.htm>

From dextrous85 at gmail.com  Wed Jul 23 08:30:07 2008
From: dextrous85 at gmail.com (vishwajeet singh)
Date: Wed, 23 Jul 2008 12:00:07 +0530
Subject: [Tutor] Element tree: Not giving processing instruction
Message-ID: <5487b3060807222330n4ef49375r8b68b1c8d09bc5e6@mail.gmail.com>

Hi List,

I am trying to use element tree for processing xml and xml has applied xsl
on top of it but when I read this file using element tree how I can get the
xsl instruction as element tree gives values from root that is first node.


Regards,
Vishwajeet
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080723/f994c409/attachment.htm>

From =?UTF-8?Q?=D8=B2=D9=8A=D8=A7=D8=AF_=D8=A8=D9=86_?=  Wed Jul 23 11:37:53 2008
From: =?UTF-8?Q?=D8=B2=D9=8A=D8=A7=D8=AF_=D8=A8=D9=86_?= (=?UTF-8?Q?=D8=B2=D9=8A=D8=A7=D8=AF_=D8=A8=D9=86_?=)
Date: Wed, 23 Jul 2008 12:37:53 +0300
Subject: [Tutor] OT looking for help creating a thumbnail
In-Reply-To: <200807221617.14651.jfabiani@yolo.com>
References: <200807221617.14651.jfabiani@yolo.com>
Message-ID: <1216805873.13359.2.camel@gobuntu.zamb.pc>


On Tue, 2008-07-22 at 16:17 -0700, johnf wrote:
> Hi,
> I'm sorry this is OT but you guys are very knowledgeable with the world of 
> python.  I already tried the python list. - no response.
> 
> I need a py tool that will provide a thumbnail (bmp?) from a video (avi,
> wmv) that will be cross platform (linux, windows).  Research has provided
> pymedia for Linux but I haven't found anything for windows.  Hopefully,
> someone has had to do this in the past and knows what has to be done.
> 
> Thanks in Advance,
> Johnf
> 
http://code.google.com/p/pyffmpeg/
Licence: LGPL.

There's a nice sample code.

Hope this is what you're looking for.
Ziyad.


From technorapture at gmail.com  Wed Jul 23 12:04:58 2008
From: technorapture at gmail.com (Shrutarshi Basu)
Date: Wed, 23 Jul 2008 06:04:58 -0400
Subject: [Tutor] Alter print action for objects
Message-ID: <376fbdcf0807230304v2809d88ao246eb79851f2a319@mail.gmail.com>

I'm working on a graph class to become more familiar with graphs in
general. I'd like to be able to do something like 'print gr'  and get
something intelligible like a list of vertices. But using print on a
Graph class instance simply returns <Graph instance at some_hex_addr>
Is there someway I can change what print prints?

-- 
The ByteBaker :
http://www.bytebaker.com

From jordangreenberg at gmail.com  Wed Jul 23 13:22:00 2008
From: jordangreenberg at gmail.com (Jordan Greenberg)
Date: Wed, 23 Jul 2008 07:22:00 -0400
Subject: [Tutor] Alter print action for objects
In-Reply-To: <376fbdcf0807230304v2809d88ao246eb79851f2a319@mail.gmail.com>
References: <376fbdcf0807230304v2809d88ao246eb79851f2a319@mail.gmail.com>
Message-ID: <48871458.4010401@gmail.com>

Shrutarshi Basu wrote:
> I'm working on a graph class to become more familiar with graphs in
> general. I'd like to be able to do something like 'print gr'  and get
> something intelligible like a list of vertices. But using print on a
> Graph class instance simply returns <Graph instance at some_hex_addr>
> Is there someway I can change what print prints?
> 

print will print the string returned by an object's __str__ method.
Try something like this:

In [1]: class Example(object):
    ...:     def __init__(self, x):
    ...:         self.x=x
    ...:     def __str__(self):
    ...:         return "x is: %s"%(self.x)
    ...:

In [3]: ex=Example(5)

In [4]: print ex
x is: 5

The "basic customization" page in the Python Reference Manual may be of 
use as well: http://docs.python.org/ref/customization.html

HTH,
JordanG

From the_sam_smart at yahoo.com  Wed Jul 23 19:29:06 2008
From: the_sam_smart at yahoo.com (Sam Last Name)
Date: Wed, 23 Jul 2008 10:29:06 -0700 (PDT)
Subject: [Tutor] Newbie
Message-ID: <562071.37071.qm@web59516.mail.ac4.yahoo.com>

Hey guys, I'm wanting to learn Python and eventually how to program with it. I'm 16 and very eager to learn. I already have a question.

Heres my script:
print "Hello World!"
print "Here are the ten numbers from 0 to 9"
for i in range(10) :
    print i,
    print "Goodbye World!"

Result of my script : 
Hello World!
Here are the ten numbers from 0 to 9
0 Goodbye World!
1 Goodbye World!
2 Goodbye World!
3 Goodbye World!
4 Goodbye World!
5 Goodbye World!
6 Goodbye World!
7 Goodbye World!
8 Goodbye World!
9 Goodbye World!


I don't Understand. I have an idea it something like Goodbye world is threading together with the numbers? Feedback is Thanked :)



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080723/cd561256/attachment.htm>

From sruiz at canterburyschool.org  Wed Jul 23 20:14:41 2008
From: sruiz at canterburyschool.org (=?ISO-8859-1?Q?=22Sim=F3n_A=2E_Ruiz=22?=)
Date: Wed, 23 Jul 2008 14:14:41 -0400
Subject: [Tutor] Newbie
In-Reply-To: <562071.37071.qm@web59516.mail.ac4.yahoo.com>
References: <562071.37071.qm@web59516.mail.ac4.yahoo.com>
Message-ID: <48877511.6020805@canterburyschool.org>



Sam Last Name wrote:
> Hey guys, I'm wanting to learn Python and eventually how to program with 
> it. I'm 16 and very eager to learn. I already have a question.
> 
> Heres my script:
> print "Hello World!"
> print "Here are the ten numbers from 0 to 9"
> for i in range(10) :
>     print i,
>     print "Goodbye World!"
> 
> Result of my script :
> Hello World!
> Here are the ten numbers from 0 to 9
> 0 Goodbye World!
> 1 Goodbye World!
> 2 Goodbye World!
> 3 Goodbye World!
> 4 Goodbye World!
> 5 Goodbye World!
> 6 Goodbye World!
> 7 Goodbye World!
> 8 Goodbye World!
> 9 Goodbye World!
> 
> 
> I don't Understand. I have an idea it something like Goodbye world is 
> threading together with the numbers? Feedback is Thanked :)

It would help if you explain what it was you *expected* as an output.

Otherwise we have to guess. :-)

If what you expected was something like:

Hello World!
Here are ten numbers from 0 to 9
0 1 2 3 4 5 6 7 8 9 Goodbye World!

Then you want that final print statement to not be included in your for 
loop block; i.e., unindent it:

for i in range(10):
     print i,
print "Goodbye World!"

Hope this helps!

Sim?n

From wim at dehul.com  Wed Jul 23 19:58:34 2008
From: wim at dehul.com (Wim De Hul)
Date: Wed, 23 Jul 2008 19:58:34 +0200
Subject: [Tutor] Newbie
In-Reply-To: <562071.37071.qm@web59516.mail.ac4.yahoo.com>
References: <562071.37071.qm@web59516.mail.ac4.yahoo.com>
Message-ID: <3EBB5A0D-D165-446C-94B4-B75372A82105@dehul.com>

Hey Sam,

The way your output is formatted is because you use a comma after  
print i and you use an indent too much. The indent is used to group  
everything that has to be in the for loop (for your example).

Your program should run fine if you do it like this

> print "Hello World!"
> print "Here are the ten numbers from 0 to 9"
> for i in range(10) :
>     print i
> print "Goodbye World!"



Cheers & happy programming!

Wim

On 23 Jul 2008, at 19:29, Sam Last Name wrote:

> Hey guys, I'm wanting to learn Python and eventually how to program  
> with it. I'm 16 and very eager to learn. I already have a question.
>
> Heres my script:
> print "Hello World!"
> print "Here are the ten numbers from 0 to 9"
> for i in range(10) :
>     print i,
>     print "Goodbye World!"
>
> Result of my script :
> Hello World!
> Here are the ten numbers from 0 to 9
> 0 Goodbye World!
> 1 Goodbye World!
> 2 Goodbye World!
> 3 Goodbye World!
> 4 Goodbye World!
> 5 Goodbye World!
> 6 Goodbye World!
> 7 Goodbye World!
> 8 Goodbye World!
> 9 Goodbye World!
>
>
> I don't Understand. I have an idea it something like Goodbye world  
> is threading together with the numbers? Feedback is Thanked :)
>
> _______________________________________________
> 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/20080723/937de087/attachment.htm>

From alan.gauld at btinternet.com  Wed Jul 23 22:04:57 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 23 Jul 2008 21:04:57 +0100
Subject: [Tutor] Newbie
References: <562071.37071.qm@web59516.mail.ac4.yahoo.com>
	<48877511.6020805@canterburyschool.org>
Message-ID: <g682tb$1j2$1@ger.gmane.org>


""Sim?n A. Ruiz"" <sruiz at canterburyschool.org> wrote
> If what you expected was something like:
>
> Hello World!
> Here are ten numbers from 0 to 9
> 0 1 2 3 4 5 6 7 8 9 Goodbye World!
>
> Then you want that final print statement to not be included in your 
> for loop block; i.e., unindent it:

And if you wanted the Goodbye on a separate line add a
newline character('\n') in front of the text:

for i in range(10):
     print i,
print "\nGoodbye World!"

You now have at least 3 options to pick from :-)

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



From monjissvel at googlemail.com  Thu Jul 24 09:51:32 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Thu, 24 Jul 2008 07:51:32 +0000
Subject: [Tutor] question about socket status
In-Reply-To: <9a2cc7a70807221831i7766daccue28b36748ed99ca2@mail.gmail.com>
References: <4F68D1DF3745984280EDAE91602C54D2722192F2@beoexch1.NTSCD.C-COR.com>
	<9a2cc7a70807221831i7766daccue28b36748ed99ca2@mail.gmail.com>
Message-ID: <e2f191310807240051w260a1c18t4fcfe2db612d18db@mail.gmail.com>

if networking code is inside of the kernel then its from the kernel that you
can get network information & nowhere else.
(http://www.linuxdevcenter.com/pub/a/linux/2000/11/16/LinuxAdmin.html)
<http://www.linuxdevcenter.com/pub/a/linux/2000/11/16/LinuxAdmin.html>
I would just add that to see what netstat does simply use "strace netstat"
it will probably tell you the interesting files it reads when run.


2008/7/23 arsyed <arsyed at gmail.com>:

> On Mon, Jul 21, 2008 at 1:25 PM, Rupp, Romaine <Romaine.Rupp at arrisi.com>
> wrote:
> > Hello,
> >
> > I am new to programming with python and sockets.
> >
> > I would like to determine the status of a socket as it  is returned when
> you
> > do 'netstat ?a | grep <port#>'.  I would like  to know if the socket
> state
> > is ESTABLISHED, LISTEN , CLOSE_WAIT, etc.
> >
> > Is there a way to get this information through a socket call?
> >
> > I've tried using socket.getperrname() function, but that only tells if
> there
> > is a connection.
> >
> > Is there a way to get more information on the state of the socket
> > connection?
> >
>
>
> If you're on linux, you could try poking around /proc/net. See, for
> example:
>
> http://www.linuxdevcenter.com/pub/a/linux/2000/11/16/LinuxAdmin.html
>
> But I think invoking netstat and parsing the output from python might
> work well enough.
> _______________________________________________
> 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/20080724/138fc3c9/attachment-0001.htm>

From andreas at kostyrka.org  Thu Jul 24 12:48:07 2008
From: andreas at kostyrka.org (Andreas Kostyrka)
Date: Thu, 24 Jul 2008 12:48:07 +0200
Subject: [Tutor] Newbie
In-Reply-To: <g682tb$1j2$1@ger.gmane.org>
References: <562071.37071.qm@web59516.mail.ac4.yahoo.com>
	<48877511.6020805@canterburyschool.org>
	<g682tb$1j2$1@ger.gmane.org>
Message-ID: <200807241248.12614.andreas@kostyrka.org>

On Wednesday 23 July 2008 22:04:57 Alan Gauld wrote:
> ""Sim?n A. Ruiz"" <sruiz at canterburyschool.org> wrote
>
> > If what you expected was something like:
> >
> > Hello World!
> > Here are ten numbers from 0 to 9
> > 0 1 2 3 4 5 6 7 8 9 Goodbye World!
> >
> > Then you want that final print statement to not be included in your
> > for loop block; i.e., unindent it:
>
> And if you wanted the Goodbye on a separate line add a
> newline character('\n') in front of the text:
>
> for i in range(10):
>      print i,
> print "\nGoodbye World!"
>
> You now have at least 3 options to pick from :-)

One another *g*

print " ".join(str(x) for x in range(10))
print "Goodbye World!"

Which has the "benefit" of not printing a space after the 9.

explanations:

str(x) converts the integers to strings.
str(x) for x in range(10) is basically a generator that 
generates "0", "1", ..., "9"

" ".join(expr) joins the strings given by expr by " ".

It's basically a very useful idiom when you need to generate
seperators without outputing the seperator at the end.

In other languages, you often have a loop like this:

for elem in list:
    print elem
    if is_not_last_element:
        print seperator

That is most often best solved in Python by using the " ".join(values) idiom.

Andreas
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: This is a digitally signed message part.
URL: <http://mail.python.org/pipermail/tutor/attachments/20080724/a56ced14/attachment.pgp>

From ladynikon at gmail.com  Thu Jul 24 13:30:14 2008
From: ladynikon at gmail.com (Danyelle Gragsone)
Date: Thu, 24 Jul 2008 07:30:14 -0400
Subject: [Tutor] Online class/education for Python?
In-Reply-To: <ea979d70807231544o37fb3e00w9d27f3eb190cc058@mail.gmail.com>
References: <721b21dc0807191141q3704c8f9jcc3790f838c87f60@mail.gmail.com>
	<ea979d70807201817x362d038cic86f492a7c7aa850@mail.gmail.com>
	<59f9c5160807211320x4087cbf8kc89e2ad7404cc526@mail.gmail.com>
	<ea979d70807220427t3fdc99bfh4948f3287eb57867@mail.gmail.com>
	<59f9c5160807222038v1a8e7ff6wa7c2f2043c61d7e@mail.gmail.com>
	<ea979d70807231544o37fb3e00w9d27f3eb190cc058@mail.gmail.com>
Message-ID: <59f9c5160807240430h64863d6eg5a8245b9d47bc8fd@mail.gmail.com>

>
>
> You should be able to use the 1st edition of PPftAB to learn Python.
> Pre-2.2 might have caused some minor problems, but 2.2 is okay.
>
> If you run into any problems, just post your problem code to the list,
> with your platform info (GNU/Linux, Mac OS X, MS-Windows...) and
> the version of Python you are using.
>
> One thing I found that might be useful to you when you get close to
> the end of the book: the version of LiveWires Dawson uses has been
> customized, and needs to be installed for the Pizza Panic game, and
> the Asteroid games to work properly. I already had LiveWires installed,
> and didn't think I needed to re-install his version. However, I couldn't
> get those games to work until I installed the version of LiveWires that
> he includes on the CD in the back of the book.
>
> Hopefully helpful?
>
>
Yes very much so!.  I will keep that in mind when i get to the end.
*hopefully* I get to the end.  I am  also going for my A+  so my schedule
with work and my volunteering  at the fire house is tight!

Thanks!
Danyelle
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080724/11211a9e/attachment.htm>

From timovwb at gmail.com  Thu Jul 24 16:14:40 2008
From: timovwb at gmail.com (Timo)
Date: Thu, 24 Jul 2008 16:14:40 +0200
Subject: [Tutor] Check for file in different dirs
Message-ID: <48888e46.0422300a.1b03.184a@mx.google.com>

I want to check for a file in 3 directories. If the file is found in 1 
of the dirs then do something, if the file was found in 2 or 3 dirs, 
then do something else. I know the paths and filename. How can this be done?

From bgailer at gmail.com  Thu Jul 24 20:36:50 2008
From: bgailer at gmail.com (bob gailer)
Date: Thu, 24 Jul 2008 14:36:50 -0400
Subject: [Tutor] Check for file in different dirs
In-Reply-To: <48888e46.0422300a.1b03.184a@mx.google.com>
References: <48888e46.0422300a.1b03.184a@mx.google.com>
Message-ID: <4888CBC2.6010209@gmail.com>

Timo wrote:
> I want to check for a file in 3 directories. If the file is found in 1 
> of the dirs then do something, if the file was found in 2 or 3 dirs, 
> then do something else. I know the paths and filename. How can this be 
> done?

We like to give a hand and prefer not to write programs.

So I suggest you write as much of the program as you can, then show it 
to us and tell us where you are stuck. I assume you have enough Python 
knowledge to get a start. If you are new to Python then at least present 
a program design.

Take a look at the os.path module and its exists function. That is what 
you use to see if a file exists.

-- 
Bob Gailer
919-636-4239 Chapel Hill, NC


From alan.gauld at btinternet.com  Thu Jul 24 20:43:35 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 24 Jul 2008 19:43:35 +0100
Subject: [Tutor] Check for file in different dirs
References: <48888e46.0422300a.1b03.184a@mx.google.com>
Message-ID: <g6aigq$hs0$1@ger.gmane.org>

"Timo" <timovwb at gmail.com> wrote

>I want to check for a file in 3 directories. If the file is found in 
>1 of the dirs then do something, if the file was found in 2 or 3 
>dirs, then do something else. I know the paths and filename. How can 
>this be done?

Lots of ways but one is to write a predicate function that checks if
a file is in a directory:

def inDirectory(fname, dirname):
     # your code here returns 1 = True/0 = False

count = inDirectory(fname, dir1) + inDirectory(fname,dir2) + 
inDirectory(fname,dir3)
if count == 1:  # do something
elif 2 <= count <= 3: # do another
else: # file not found

HTH,

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



From yla116 at sfu.ca  Thu Jul 24 18:54:13 2008
From: yla116 at sfu.ca (yla116 at sfu.ca)
Date: Thu, 24 Jul 2008 09:54:13 -0700
Subject: [Tutor]  Python Assistance!
Message-ID: <200807241654.m6OGsDPt014125@rm-rstar.sfu.ca>

An embedded and charset-unspecified text was scrubbed...
Name: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20080724/72a9c743/attachment.txt>

From dyoo at cs.wpi.edu  Fri Jul 25 01:14:25 2008
From: dyoo at cs.wpi.edu (Danny Yoo)
Date: Thu, 24 Jul 2008 19:14:25 -0400
Subject: [Tutor] Python Assistance!
In-Reply-To: <200807241654.m6OGsDPt014125@rm-rstar.sfu.ca>
References: <200807241654.m6OGsDPt014125@rm-rstar.sfu.ca>
Message-ID: <d06401780807241614m1f3fe826u1504666e9f029ff6@mail.gmail.com>

On Thu, Jul 24, 2008 at 12:54 PM,  <yla116 at sfu.ca> wrote:
> Hi, this is my first time come to this website to ask about python question.
> I'm totally don't know how to do my last assignment.It is distance education
> class, and my taxt book DOES NOT show exactly information for me to do this
> assignment.

[assignment cut]

This is out of bounds of the the academic honesty policy of your institution.

    http://www.sfu.ca/policies/teaching/t10-02.htm

From alan.gauld at btinternet.com  Fri Jul 25 01:37:34 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 25 Jul 2008 00:37:34 +0100
Subject: [Tutor] Python Assistance!
References: <200807241654.m6OGsDPt014125@rm-rstar.sfu.ca>
Message-ID: <g6b3o2$bnt$1@ger.gmane.org>

<yla116 at sfu.ca> wrote

> I'm totally don't know how to do my last assignment.It is distance 
> education

We don't do homeworks but we can offer suggestions and advice.
However you will need to solve the problem yourself.

> There is my assignment,
> http://cmpt165.cs.sfu.ca/~ggbaker/examples/chequebook.html

I'm not sure how that's supposed to work. The data I got didn't seem
to add up correctly!

> I feel so helpless when I doing this assignment
> Could you teach how to start and end this assignmet?
>
> I try to write something about password but I still don't have any 
> idea.

So what did you write about the password?
I don't see any of it below. What happened? What did you
expect to happen?

Also how are you running these programs? Are you using a web
server or a command line console? Do you have to produce web
page output or can you use the command window (which is much
easier)

> Here is some codes which I try to write

The code implies that you are using a web environment but you
do not import the cgi module which is normally required to process
HTML forms.

Can you describe what you think you are being asked to do?
And ideally how you were planning on going about it?
Also how much background do you have in programming?
In Python? And which OS etc are you using?

Lots of questions but we need to know that stuff before we
can give you sensible answers.

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



From the_sam_smart at yahoo.com  Fri Jul 25 03:47:32 2008
From: the_sam_smart at yahoo.com (Sam Last Name)
Date: Thu, 24 Jul 2008 18:47:32 -0700 (PDT)
Subject: [Tutor]  Newbie
Message-ID: <370291.77091.qm@web59515.mail.ac4.yahoo.com>

mmmkay its me again
Iv'e been learning alot and have found so much joy in making programs that solve equations using the input function.
I need Help on this though.
Im trying to make a program where it solves the quadratic formula when you put in the variables. 
Here wats i got so far. :) and also, is there a function for square root? 

a  =  input("What is the variable a?")
b  =  input("What is the variable b?")
c  =  input("What is the variable c?")
# this is where i need help :(
print -b + /sqrt (b*b - 4*a*c)/(2*a) 
# this of course doesn't work i believe because i don't have the square root function and don know how to make one

Feedback appreciated :)


      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080724/b02787c9/attachment-0001.htm>

From john at fouhy.net  Fri Jul 25 03:53:40 2008
From: john at fouhy.net (John Fouhy)
Date: Fri, 25 Jul 2008 13:53:40 +1200
Subject: [Tutor] Newbie
In-Reply-To: <370291.77091.qm@web59515.mail.ac4.yahoo.com>
References: <370291.77091.qm@web59515.mail.ac4.yahoo.com>
Message-ID: <5e58f2e40807241853r59e539a8m5f0695cac5190a1f@mail.gmail.com>

On 25/07/2008, Sam Last Name <the_sam_smart at yahoo.com> wrote:
> Here wats i got so far. :) and also, is there a function for square root?

Have a look at the math module.

(you can also do fractional exponentiation.. remember, sqrt(x) is the
same as x**0.5)

-- 
John.

From john at fouhy.net  Fri Jul 25 04:17:33 2008
From: john at fouhy.net (John Fouhy)
Date: Fri, 25 Jul 2008 14:17:33 +1200
Subject: [Tutor] Newbie
In-Reply-To: <215491.1184.qm@web59512.mail.ac4.yahoo.com>
References: <215491.1184.qm@web59512.mail.ac4.yahoo.com>
Message-ID: <5e58f2e40807241917l27cc2746k56a03a0ce8e04a59@mail.gmail.com>

On 25/07/2008, Sam Last Name <the_sam_smart at yahoo.com> wrote:
>
> Okay thanks still didnt get it working but one step closer. Take a look at
> this
>
>
> a = input("What is the variable a?")
> b = input("What is the variable b?")
> c = input("What is the variable c?")
> print -b + [((b*b - 4*a*c)**0.5)/(2*a)]
> # my new equation thanks to you :)
>
>
> i run the script and here is error message there are 2 messages. i will post
> both.
>
> What is the variable a?2
> What is the variable b?2
> What is the variable c?2
>
> Traceback (most recent call last):
>   File "C:\Python\Script2.py", line 4, in <module>
>     print -b + [((b*b - 4*a*c)**0.5)/(2*a)]
> ValueError: negative number cannot be raised to a fractional power

This is normal; if you want to handle complex numbers you will need to
do a lot more work..

> # i changed the numbers so it would be postive number when squarerooting and
> it worked but then this error popped up :(
>
>
> What is the variable a?2
> What is the variable b?14
> What is the variable c?5
>
> Traceback (most recent call last):
>   File "C:\Python\Script2.py", line 4, in <module>
>     print -b + [((b*b - 4*a*c)**0.5)/(2*a)]
> TypeError: unsupported operand type(s) for +: 'int' and 'list'
>
> # I"m bewildered to what that means. ty for feed back :) this is so i can do
> alegbra2 easily haha.

Different types of brackets mean different things in python.  You
can't just use square brackets instead of round brackets to make it
easier to read :-)  In this case, square brackets indicates a list and
python is complaining that it doesn't know how to add an integer (-b)
to a list ([..]).  I recommend reading through the tutorial on
python.org.

PS.  Please use the reply-all when using this mailing list so other
people can follow the conversation if they wish to.

-- 
John.

From the_sam_smart at yahoo.com  Fri Jul 25 04:41:36 2008
From: the_sam_smart at yahoo.com (Sam Last Name)
Date: Thu, 24 Jul 2008 19:41:36 -0700 (PDT)
Subject: [Tutor] Tutor Newbie
Message-ID: <138002.84298.qm@web59507.mail.ac4.yahoo.com>

Hey guys, need some info on "programs" :) 


Heres a Very simple Script that works with basically any numbers.


width = input("What is the Width?")
length = input("What is the Length?")
area = width*length
print area
 # my question is what would it take (programs, extra stuff in script, ect..) to make this a nice looking usable desktop program?



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080724/459af3e1/attachment.htm>

From jar_head at fuse.net  Fri Jul 25 06:13:13 2008
From: jar_head at fuse.net (jar_head at fuse.net)
Date: Fri, 25 Jul 2008 0:13:13 -0400
Subject: [Tutor] Newbie
Message-ID: <13115980.1216959193506.JavaMail.root@wmvirt8>


> ------------------------------
> 
> Message: 9
> Date: Thu, 24 Jul 2008 18:47:32 -0700 (PDT)
> From: Sam Last Name <the_sam_smart at yahoo.com>
> Subject: [Tutor]  Newbie
> To: tutor at python.org
> Message-ID: <370291.77091.qm at web59515.mail.ac4.yahoo.com>
> Content-Type: text/plain; charset="us-ascii"
> 
> mmmkay its me again
> Iv'e been learning alot and have found so much joy in making programs that solve equations using the input function.
> I need Help on this though.
> Im trying to make a program where it solves the quadratic formula when you put in the variables. 
> Here wats i got so far. :) and also, is there a function for square root? 
> 
> a  =  input("What is the variable a?")
> b  =  input("What is the variable b?")
> c  =  input("What is the variable c?")
> # this is where i need help :(
> print -b + /sqrt (b*b - 4*a*c)/(2*a) 
> # this of course doesn't work i believe because i don't have the square root function and don know how to make one
> 
> Feedback appreciated :)
> 

You're going to need to use your parenthesis differently.  You might have a problem with the grouping if you leave it as it is.  It'd be better written as this:

print (-b + /sqrt ((b*b) - (4*a*c))/(2*a))

I don't know the function for square root either, but I'm sure one of the others will answer that for you.

-Jay

> 
>       
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL: <http://mail.python.org/pipermail/tutor/attachments/20080724/b02787c9/attachment.htm>
> 
> ------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> End of Tutor Digest, Vol 53, Issue 87
> *************************************


From steve at alchemy.com  Fri Jul 25 06:32:19 2008
From: steve at alchemy.com (Steve Willoughby)
Date: Thu, 24 Jul 2008 21:32:19 -0700
Subject: [Tutor] Newbie
In-Reply-To: <13115980.1216959193506.JavaMail.root@wmvirt8>
References: <13115980.1216959193506.JavaMail.root@wmvirt8>
Message-ID: <48895753.3070302@alchemy.com>

To answer the specific question about square roots below, Python's 
square root function is in the math module.  You can either include this 
module and invoke it like this:

import math
.
.
.
y = math.sqrt(x)

-or- if you want the sqrt() function brought into your main namespace, 
you can do it like this:

from math import sqrt
.
.
.
y = sqrt(x)

Either way, y will now have the value of the square root of x.

HTH
HAND


jar_head at fuse.net wrote:
>> ------------------------------
>>
>> Message: 9
>> Date: Thu, 24 Jul 2008 18:47:32 -0700 (PDT)
>> From: Sam Last Name <the_sam_smart at yahoo.com>
>> Subject: [Tutor]  Newbie
>> To: tutor at python.org
>> Message-ID: <370291.77091.qm at web59515.mail.ac4.yahoo.com>
>> Content-Type: text/plain; charset="us-ascii"
>>
>> mmmkay its me again
>> Iv'e been learning alot and have found so much joy in making programs that solve equations using the input function.
>> I need Help on this though.
>> Im trying to make a program where it solves the quadratic formula when you put in the variables. 
>> Here wats i got so far. :) and also, is there a function for square root? 
>>
>> a  =  input("What is the variable a?")
>> b  =  input("What is the variable b?")
>> c  =  input("What is the variable c?")
>> # this is where i need help :(
>> print -b + /sqrt (b*b - 4*a*c)/(2*a) 
>> # this of course doesn't work i believe because i don't have the square root function and don know how to make one
>>
>> Feedback appreciated :)
>>
> 
> You're going to need to use your parenthesis differently.  You might have a problem with the grouping if you leave it as it is.  It'd be better written as this:
> 
> print (-b + /sqrt ((b*b) - (4*a*c))/(2*a))
> 
> I don't know the function for square root either, but I'm sure one of the others will answer that for you.
> 
> -Jay
> 
>>       
>> -------------- next part --------------
>> An HTML attachment was scrubbed...
>> URL: <http://mail.python.org/pipermail/tutor/attachments/20080724/b02787c9/attachment.htm>
>>
>> ------------------------------
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>> End of Tutor Digest, Vol 53, Issue 87
>> *************************************
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


From kent37 at tds.net  Fri Jul 25 08:14:43 2008
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 25 Jul 2008 02:14:43 -0400
Subject: [Tutor] Newbie
In-Reply-To: <5e58f2e40807241917l27cc2746k56a03a0ce8e04a59@mail.gmail.com>
References: <215491.1184.qm@web59512.mail.ac4.yahoo.com>
	<5e58f2e40807241917l27cc2746k56a03a0ce8e04a59@mail.gmail.com>
Message-ID: <1c2a2c590807242314t786c3e38y39298eee6febef39@mail.gmail.com>

On Thu, Jul 24, 2008 at 10:17 PM, John Fouhy <john at fouhy.net> wrote:
> On 25/07/2008, Sam Last Name <the_sam_smart at yahoo.com> wrote:
>>
>> Traceback (most recent call last):
>>   File "C:\Python\Script2.py", line 4, in <module>
>>     print -b + [((b*b - 4*a*c)**0.5)/(2*a)]
>> ValueError: negative number cannot be raised to a fractional power
>
> This is normal; if you want to handle complex numbers you will need to
> do a lot more work..

The sqrt() function in the cmath module will compute complex square roots.

Kent

From muchanek at gmail.com  Fri Jul 25 09:13:53 2008
From: muchanek at gmail.com (kinuthiA muchanE)
Date: Fri, 25 Jul 2008 10:13:53 +0300
Subject: [Tutor] Newbie
In-Reply-To: <mailman.6161.1216950462.920.tutor@python.org>
References: <mailman.6161.1216950462.920.tutor@python.org>
Message-ID: <1216970034.6213.10.camel@www.kinuthia.com>


On Fri, 2008-07-25 at 03:47 +0200, tutor-request at python.org wrote:
> Message: 9
> Date: Thu, 24 Jul 2008 18:47:32 -0700 (PDT)
> From: Sam Last Name <the_sam_smart at yahoo.com>
> Subject: [Tutor]  Newbie
> To: tutor at python.org
> Message-ID: <370291.77091.qm at web59515.mail.ac4.yahoo.com>
> Content-Type: text/plain; charset="us-ascii"
> 
> mmmkay its me again
> Iv'e been learning alot and have found so much joy in making programs
> that solve equations using the input function.
> I need Help on this though.
> Im trying to make a program where it solves the quadratic formula when
> you put in the variables. 
> Here wats i got so far. :) and also, is there a function for square
> root? 
> 
> a  =  input("What is the variable a?")
> b  =  input("What is the variable b?")
> c  =  input("What is the variable c?")
> # this is where i need help :(
> print -b + /sqrt (b*b - 4*a*c)/(2*a) 
> # this of course doesn't work i believe because i don't have the
> square root function and don know how to make one
>>> import math
>>> print math.sqrt(6)
2.44948974278
>>> print math.sqrt(8)
2.82842712475
>>> 
math is a module which contains most of  the mathematical functions that
you need most of the time. Here we used just one of them, sqrt, to find
the square root of an integer. The Python Library Reference lists all of
them and their usage.
Does this help?
Kinuthia...




> 
> Feedback appreciated :)


From alan.gauld at btinternet.com  Fri Jul 25 10:01:20 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 25 Jul 2008 09:01:20 +0100
Subject: [Tutor] Tutor Newbie
References: <138002.84298.qm@web59507.mail.ac4.yahoo.com>
Message-ID: <g6c18l$dr7$1@ger.gmane.org>


"Sam Last Name" <the_sam_smart at yahoo.com> wrote

> Hey guys, need some info on "programs" :)

A program has two meanings in programming!
To the programmer a program is just a piece of
sofftware that he has written, usually one that
is runnable. It may be an entire *application* or
just a part of a bigger software suite.

To end users a program is another name for
an application - a full set of software tools that
togerher fulfil some function - a word processor
say. Most modern applications consist of several
programs (in the programmers sense)

I'll assume that you are here askling about how
to create an application?

> Heres a Very simple Script that works with basically any numbers.
> # my question is what would it take (programs, extra stuff in 
> script,
> ect..) to make this a nice looking usable desktop program?

By nice looking I'll assume you mean that it has a GUI?

What that normally means is logically dividing your design
into two parts, the presentation(GUI) and the logic(the algorithms
etc). You create the logic section as a set of functions.
You then create a GUI using a GUI Toolkit (in Python
you have the choice of several toolkits, the most popular
being wxPython and Tkinter which ships with Python).
The GUI controls (buttons, menu items etc) are then hooked
up to the functions in your logic section.

So as a beginner you need to learn how to:
1) write Python functions
2) write a GUI using a toolkit

In practice you may need to create some kind of installation
program too if you plan on giving the application to any other
users.

For now I'd forget about GUIs and concentrate on getting
the basic Python functions under your belt. You can usually
add a GUI to your programs retrospecively without too much
pain.

You will find information on all of the above in my tutorial.

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



From monjissvel at googlemail.com  Fri Jul 25 10:25:22 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Fri, 25 Jul 2008 08:25:22 +0000
Subject: [Tutor] Check for file in different dirs
In-Reply-To: <g6aigq$hs0$1@ger.gmane.org>
References: <48888e46.0422300a.1b03.184a@mx.google.com>
	<g6aigq$hs0$1@ger.gmane.org>
Message-ID: <e2f191310807250125o70666a07s925525938b50c3f3@mail.gmail.com>

>
> for f in file1 file2 file3 file4 file5:
>     a = os.path.exists('/home/dir1/file.txt')
>     b = os.path.exists('/home/dir2/file.txt')
>     c = os.path.exists('/home/dir3/file.txt')
>     if a and b and c:
>          do ...
>     elif a and b :
>          do ...
>     elif a :
>           do ...
>     elif b :
>           do ...
>     elif c :
>            do ...
>     else:
>            #file doesn't exist
>            do ...
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080725/b339f43d/attachment.htm>

From bhaaluu at gmail.com  Fri Jul 25 12:17:41 2008
From: bhaaluu at gmail.com (bhaaluu)
Date: Fri, 25 Jul 2008 06:17:41 -0400
Subject: [Tutor] Tutor Newbie
In-Reply-To: <138002.84298.qm@web59507.mail.ac4.yahoo.com>
References: <138002.84298.qm@web59507.mail.ac4.yahoo.com>
Message-ID: <ea979d70807250317u37cc2091mddf3fab74ef7ef7d@mail.gmail.com>

On Thu, Jul 24, 2008 at 10:41 PM, Sam Last Name <the_sam_smart at yahoo.com> wrote:
> Hey guys, need some info on "programs" :)
>
> Heres a Very simple Script that works with basically any numbers.
>
> width = input("What is the Width?")
> length = input("What is the Length?")
> area = width*length
> print area
>  # my question is what would it take (programs, extra stuff in script,
> ect..) to make this a nice looking usable desktop program?
>

A usable desktop program probably implies a program that has a
Graphical User Interface (GUI) that can be invoked by clicking on an
Icon that resides on the Desktop. GUI programs might have drop
down menus which in turn might have sub-menus, dialogue boxes,
radio buttons, slider bars, and so forth. The GUI toolkit that usually
ships with Python is Tkinter. Other GUI toolkits that work with Python
include: wxPython, PyQT, PyGTK, PythonCard, AnyGui, and others.

I prefer CLI (Command Line Interface) programs myself, where options
are entered on the command line to do a job. Each program is small and
does one thing very well. Usually the output from one program can be
piped to another program, or input can be piped from another program,
to do the job. The program is usually started from an XTerm, Terminal,
or Konsole, or even from a non-GUI console. These programs usually
are small and fast. Your hands never have to leave the keyboard to
click a mouse button, or whatever.

Anyway, here is a simple Tkinter example from Programming Python 3rd Edition
(which has over 300 pages of Tkinter tutorial in it, plus several
full-feature GUI
programs):

import sys
from Tkinter import *
widget = Button(None, text='Hello widget world', command=sys.exit)
widget.pack( )
widget.mainloop( )

Key in the above code into your favorite text editor, save it as gui2.py,
then run it however you're running Python scripts
I do it like this:
python gui2.py

Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m
Kid on Bus: What are you gonna do today, Napoleon?
Napoleon Dynamite: Whatever I feel like I wanna do. Gosh!

From rdm at rcblue.com  Fri Jul 25 14:14:32 2008
From: rdm at rcblue.com (Dick Moores)
Date: Fri, 25 Jul 2008 05:14:32 -0700
Subject: [Tutor] Is there a better way to get a current mid-rate Yen quote
 with Python?
Message-ID: <20080725121444.818C41E4007@bag.python.org>

Better than this? <http://py77.python.pastebin.com/fc7553a4>

I've heard about BeautifulSoup. 
<http://www.crummy.com/software/BeautifulSoup/>. Is it worth 
learning? Is it crummy? ;-)

So 2 questions.

Thanks,

Dick Moores


From rick at niof.net  Fri Jul 25 16:04:35 2008
From: rick at niof.net (Rick Pasotto)
Date: Fri, 25 Jul 2008 10:04:35 -0400
Subject: [Tutor] where to report a bug?
Message-ID: <20080725140435.GI31862@niof.net>

I have a script that works fine on my linux machine but bombs out when
run under windows using the exact same data files. The script downloads
a file then unzips it and then scans the resulting file for certain
records. Under Windows it gets a memory error in the unzip routine.

Where should I send the error report?

-- 
"With the first link, the chain is forged.  The first speech censured,
 the first thought forbidden, the first freedom denied chains us all
 irrevocably." -- Judge Aaron Satie (As quoted by J.L. Picard)
    Rick Pasotto    rick at niof.net    http://www.niof.net

From seed19841985 at hotmail.com  Fri Jul 25 17:06:35 2008
From: seed19841985 at hotmail.com (lee lucia)
Date: Fri, 25 Jul 2008 15:06:35 +0000
Subject: [Tutor] Tutor Digest, Vol 53, Issue 89
In-Reply-To: <mailman.49.1216980062.1270.tutor@python.org>
References: <mailman.49.1216980062.1270.tutor@python.org>
Message-ID: <BAY116-W390A83B227029F1F357CA1D9860@phx.gbl>


> From: tutor-request at python.org> Subject: Tutor Digest, Vol 53, Issue 89> To: tutor at python.org> Date: Fri, 25 Jul 2008 12:01:02 +0200> > Send Tutor mailing list submissions to> tutor at python.org> > To subscribe or unsubscribe via the World Wide Web, visit> http://mail.python.org/mailman/listinfo/tutor> or, via email, send a message with subject or body 'help' to> tutor-request at python.org> > You can reach the person managing the list at> tutor-owner at python.org> > When replying, please edit your Subject line so it is more specific> than "Re: Contents of Tutor digest..."> > > Today's Topics:> > 1. Re: Check for file in different dirs (Monika Jisswel)> > > ----------------------------------------------------------------------> > Message: 1> Date: Fri, 25 Jul 2008 08:25:22 +0000> From: "Monika Jisswel" <monjissvel at googlemail.com>> Subject: Re: [Tutor] Check for file in different dirs> To: tutor at python.org> Message-ID:> <e2f191310807250125o70666a07s925525938b50c3f3 at mail.gmail.com>> Content-Type: text/plain; charset="iso-8859-1"> > >> > for f in file1 file2 file3 file4 file5:> > a = os.path.exists('/home/dir1/file.txt')> > b = os.path.exists('/home/dir2/file.txt')> > c = os.path.exists('/home/dir3/file.txt')> > if a and b and c:> > do ...> > elif a and b :> > do ...> > elif a :> > do ...> > elif b :> > do ...> > elif c :> > do ...> > else:> > #file doesn't exist> > do ...> >> -------------- next part --------------> An HTML attachment was scrubbed...> URL: <http://mail.python.org/pipermail/tutor/attachments/20080725/b339f43d/attachment-0001.htm>> > ------------------------------> > _______________________________________________> Tutor maillist - Tutor at python.org> http://mail.python.org/mailman/listinfo/tutor> > > End of Tutor Digest, Vol 53, Issue 89> *************************************
_________________________________________________________________
??? Windows Live Messenger ? Hotmail????????????? ? Windows Live for Mobile 
http://www.msn.com.tw/msnmobile/ 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080725/40769967/attachment.htm>

From rdm at rcblue.com  Fri Jul 25 17:16:54 2008
From: rdm at rcblue.com (Dick Moores)
Date: Fri, 25 Jul 2008 08:16:54 -0700
Subject: [Tutor] Is there a better way to get a current mid-rate Yen
 quote with Python?
Message-ID: <20080725151800.7AC851E4012@bag.python.org>

An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080725/6241fe25/attachment.htm>

From malaclypse2 at gmail.com  Fri Jul 25 17:22:25 2008
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Fri, 25 Jul 2008 11:22:25 -0400
Subject: [Tutor] where to report a bug?
In-Reply-To: <20080725140435.GI31862@niof.net>
References: <20080725140435.GI31862@niof.net>
Message-ID: <16651e80807250822m48f7b301v493a0b59d1aa5667@mail.gmail.com>

On Fri, Jul 25, 2008 at 10:04 AM, Rick Pasotto <rick at niof.net> wrote:
> I have a script that works fine on my linux machine but bombs out when
> run under windows using the exact same data files. The script downloads
> a file then unzips it and then scans the resulting file for certain
> records. Under Windows it gets a memory error in the unzip routine.
>
> Where should I send the error report?

In general, http://bugs.python.org/ is the place to report python bugs.

Before you do that though, you should probably put together a bit of
sample code to show the bug, and post it to comp.lang.python (or the
main python mailing list - they mirror each other).  That will help
make sure there isn't a bug in your code rather than in the zipfile
module.

-- 
Jerry

From cfuller084 at thinkingplanet.net  Fri Jul 25 17:29:48 2008
From: cfuller084 at thinkingplanet.net (Chris Fuller)
Date: Fri, 25 Jul 2008 10:29:48 -0500
Subject: [Tutor] where to report a bug?
In-Reply-To: <20080725140435.GI31862@niof.net>
References: <20080725140435.GI31862@niof.net>
Message-ID: <200807251029.48669.cfuller084@thinkingplanet.net>

On Friday 25 July 2008 09:04, Rick Pasotto wrote:
> I have a script that works fine on my linux machine but bombs out when
> run under windows using the exact same data files. The script downloads
> a file then unzips it and then scans the resulting file for certain
> records. Under Windows it gets a memory error in the unzip routine.
>
> Where should I send the error report?

Quoth
http://www.python.org/dev/faq/#where-can-i-submit-view-bugs-for-python

6.1   Where can I submit/view bugs for Python?
The Python project uses Roundup for bug tracking. Go to 
http://bugs.python.org/ for all bug management needs. You will need to create 
a Roundup account for yourself before submitting the first bug report; 
anonymous reports have been disabled since it was too difficult to get in 
contact with submitters. If you previously had used SourceForge to report 
Python bugs, you can use Roundup's "Lost your login?" link to obtain your 
Roundup password.

Make sure you are using the latest version, at least for that series (2.4.x, 
2.5.x, 2.6.x), and make some attempt to search the database to see if its a 
known bug.

You might also make sure that your linux and windows systems have the same 
version of Python installed.  For instance, If they are sharing files created 
by the Pickle module, this can fail if the Pickle format was updated with the 
newer version.

Do include some example code in your bug report.  Share with this list if you 
are uncertain about anything.

Which reminds me, I have a glitch that bombs with the cStringIO module but 
works with StringIO.  Thanks!

Thanks for your support in making Python better!


From alan.gauld at btinternet.com  Fri Jul 25 18:41:25 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 25 Jul 2008 17:41:25 +0100
Subject: [Tutor] where to report a bug?
References: <20080725140435.GI31862@niof.net>
Message-ID: <g6cvnq$kvs$1@ger.gmane.org>


"Rick Pasotto" <rick at niof.net> wrote 

> records. Under Windows it gets a memory error in the unzip routine.

I asssume you have tried the obvious and manually unzipped it
to check that the file is not corrupted?

Alan G




From alan.gauld at btinternet.com  Fri Jul 25 18:47:25 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 25 Jul 2008 17:47:25 +0100
Subject: [Tutor] Is there a better way to get a current mid-rate Yen
	quote with Python?
References: <20080725151800.7AC851E4012@bag.python.org>
Message-ID: <g6d031$m5a$1@ger.gmane.org>

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

> Here's one opinion, an answer to my second question.
> 
> Dick

And to answer your first: It depends on how you define better.

Certainly Beautiful Soup will not be muh longer and a lot more 
elegant and probably more resilient.

But to extract a single piece of text in a well defined location 
then your approach although somewhat crude will work just fine.

Alan G


From yla116 at sfu.ca  Fri Jul 25 18:20:53 2008
From: yla116 at sfu.ca (yla116 at sfu.ca)
Date: Fri, 25 Jul 2008 09:20:53 -0700
Subject: [Tutor]  Python Assistance!
Message-ID: <200807251620.m6PGKrLY014888@rm-rstar.sfu.ca>

An embedded and charset-unspecified text was scrubbed...
Name: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20080725/19242962/attachment.txt>

From rdm at rcblue.com  Fri Jul 25 19:15:17 2008
From: rdm at rcblue.com (Dick Moores)
Date: Fri, 25 Jul 2008 10:15:17 -0700
Subject: [Tutor] Is there a better way to get a current mid-rate Yen
 quote with Python?
In-Reply-To: <g6d031$m5a$1@ger.gmane.org>
References: <20080725151800.7AC851E4012@bag.python.org>
	<g6d031$m5a$1@ger.gmane.org>
Message-ID: <20080725171530.5F94A1E4011@bag.python.org>

At 09:47 AM 7/25/2008, Alan Gauld wrote:
>"Dick Moores" <rdm at rcblue.com> wrote
>>Here's one opinion, an answer to my second question.
>>Dick
>
>And to answer your first: It depends on how you define better.
>
>Certainly Beautiful Soup will not be muh longer and a lot more 
>elegant and probably more resilient.

Alan, expand a bit, please. Longer? Resilient?


>But to extract a single piece of text in a well defined location 
>then your approach although somewhat crude will work just fine.

Crude? What's crude about my code? I want to improve, so please tell 
me. <http://py77.python.pastebin.com/fc7553a4>

Thanks,

Dick
===================================================
Have you seen Kelie Feng's video introducing the terrific and free
IDE, Ulipad? <http://www.rcblue.com/u3/>
Get Ulipad 3.9 from <http://code.google.com/p/ulipad/downloads/list>
svn for the latest revision <http://ulipad.googlecode.com/svn/trunk/>
Mailing list for Ulipad: <http://groups-beta.google.com/group/ulipad>


From mikem at blazenetme.net  Sat Jul 26 00:05:07 2008
From: mikem at blazenetme.net (Mike Meisner)
Date: Fri, 25 Jul 2008 18:05:07 -0400
Subject: [Tutor] List indexing problem
Message-ID: <000901c8eea2$7fd57f70$08a305cf@Parents>

I need to do some statistical analysis by binning values into an array.

Being new to Python, I tried to use a list of lists.  I've extracted just the minimum code that I'm having trouble with:

def testanalysis():
    IP = []
    temp = [[0, 0, 0],[0, 0, 0],[0, 0, 0]]
    # initialize to zero
    for i in range(20):
        IP.append(temp)
    # increment each of the first five elements by 1
    for index in range(5):
        for type in range(3):
            for phase in range(3):
                IP[index][type][phase] += 1

    print IP 

The output is:

[[[5, 5, 5], [5, 5, 5], [5, 5, 5]], [[5, 5, 5], [5, 5, 5], [5, 5, 5]], [[5, 5, 5], [5, 5, 5], [5, 5, 5]], [[5, 5, 5], [5, 5, 5], [5, 5, 5]], [[5, 5, 5], [5, 5, 5], [5, 5, 5]], [[5, 5, 5], [5, 5, 5], [5, 5, 5]], [[5, 5, 5], [5, 5, 5], [5, 5, 5]], [[5, 5, 5], [5, 5, 5], [5, 5, 5]], [[5, 5, 5], [5, 5, 5], [5, 5, 5]], [[5, 5, 5], [5, 5, 5], [5, 5, 5]], [[5, 5, 5], [5, 5, 5], [5, 5, 5]], [[5, 5, 5], [5, 5, 5], [5, 5, 5]], [[5, 5, 5], [5, 5, 5], [5, 5, 5]], [[5, 5, 5], [5, 5, 5], [5, 5, 5]], [[5, 5, 5], [5, 5, 5], [5, 5, 5]], [[5, 5, 5], [5, 5, 5], [5, 5, 5]], [[5, 5, 5], [5, 5, 5], [5, 5, 5]], [[5, 5, 5], [5, 5, 5], [5, 5, 5]], [[5, 5, 5], [5, 5, 5], [5, 5, 5]], [[5, 5, 5], [5, 5, 5], [5, 5, 5]]]

What I wanted, of course, is to increment only the first 5 sub-lists to a value of 1 (not 5).

I'm obviously misunderstanding something fundamental about lists, list indexing, or both.

Is this enough information for someone to point out what I'm doing wrong?

Mike
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080725/86d7d736/attachment.htm>

From dkuhlman at rexx.com  Sat Jul 26 00:11:57 2008
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Fri, 25 Jul 2008 15:11:57 -0700
Subject: [Tutor] where to report a bug?
In-Reply-To: <20080725140435.GI31862@niof.net>
References: <20080725140435.GI31862@niof.net>
Message-ID: <20080725221157.GA67528@cutter.rexx.com>

On Fri, Jul 25, 2008 at 10:04:35AM -0400, Rick Pasotto wrote:
> I have a script that works fine on my linux machine but bombs out when
> run under windows using the exact same data files. The script downloads
> a file then unzips it and then scans the resulting file for certain
> records. Under Windows it gets a memory error in the unzip routine.
> 
> Where should I send the error report?

You might want to post your code here.  Someone might be able to
suggest a fix (to your code) or at least a work-around.

One question -- Are you downloading the file and unzipping it with
the zipfile module?  Or, are you downloading the file and then
writing the file to disk.

If you are writing the file to disk, make sure that you open the
file in binary mode, since a zipped file is binary data.  If you
fail to do so, your code will work on Linux/UNIX, but not on
Windows.  I've written code with that bug myself.

- Dave


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

From steve at alchemy.com  Sat Jul 26 01:03:58 2008
From: steve at alchemy.com (Steve Willoughby)
Date: Fri, 25 Jul 2008 16:03:58 -0700
Subject: [Tutor] List indexing problem
In-Reply-To: <000901c8eea2$7fd57f70$08a305cf@Parents>
References: <000901c8eea2$7fd57f70$08a305cf@Parents>
Message-ID: <488A5BDE.9080505@alchemy.com>

Mike Meisner wrote:
> I need to do some statistical analysis by binning values into an array.
>  
> Being new to Python, I tried to use a list of lists.  I've extracted 
> just the minimum code that I'm having trouble with:

What you need to remember is that Python works with *objects*, and 
variables are simply *references* to those objects.  So if I say
a = [1,2,3]
b = a

b and a both refer to the *SAME* list object (not two lists which happen 
to have the same elements).

>     temp = [[0, 0, 0],[0, 0, 0],[0, 0, 0]]

temp now refers to a list object containing 3 lists, each containing 3 
integers.

>     # initialize to zero
>     for i in range(20):
>         IP.append(temp)

Now IP contains 20 copies of references to the *same* list object.
So you were modifying the underlying list object which happens to be 
referenced many times in IP.

From alan.gauld at btinternet.com  Sat Jul 26 01:11:50 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 26 Jul 2008 00:11:50 +0100
Subject: [Tutor] Is there a better way to get a current mid-rate Yen
	quote with Python?
References: <20080725151800.7AC851E4012@bag.python.org><g6d031$m5a$1@ger.gmane.org>
	<20080725171530.5F94A1E4011@bag.python.org>
Message-ID: <g6dmjr$sbj$1@ger.gmane.org>

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

>>Certainly Beautiful Soup will not be muh longer and a lot more 
>>elegant and probably more resilient.
> 
> Alan, expand a bit, please. Longer? Resilient?

Longer as in lines of code. BS is good for extracting several 
different parts from the soup, but just to pull out one very 
specific item the setup and so on may mean that the 
framework actually works out the same or longer than 
your code.

Resilient as in able to handle unexpected changes in 
the HTML used by the site or slight changes in formatting 
of the results etc.

>>But to extract a single piece of text in a well defined location 
>>then your approach although somewhat crude will work just fine.
> 
> Crude? What's crude about my code? 

Its just a little bit too hard coded for my liking, all that 
splitting and searching means theres a lot of work going on
to extract a small piece of data. You iterate over the whole 
page to do the first spliot, then you iterate over the whole 
thing again to find the line you want. Consider thios line:

if 'JPY' in x and '>USDJPY=X<' in x:

Sincy JPY is in both strings the first check is effectively 
redundant but still requires a string search over the line.
A well crafted regex would probably be faster than the 
double in test and provide better checking by including
allowances for extra spaces or case changes etc.

Then having found the string once with 'in' you them have 
to find it again with split(). You could just have done 
a find the first time and stored the index as a basis for 
the slicing later.

You also use lots of very specific slicing values to extract the 
data - thats where you lose resilience compared to a parser 
approach like BS. Again I suspect a regex might work better 
in extracting the value. And hard coding the url in the function 
also adds to its fragility.

Stylistically all those single character variable names hurts 
readability and maintainability too. 

> I want to improve, so please tell 

It will work as is, but it could be tidied up a bit is all.

Alan G.


From alan.gauld at btinternet.com  Sat Jul 26 01:15:12 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 26 Jul 2008 00:15:12 +0100
Subject: [Tutor] List indexing problem
References: <000901c8eea2$7fd57f70$08a305cf@Parents>
Message-ID: <g6dmq4$sq6$1@ger.gmane.org>


"Mike Meisner" <mikem at blazenetme.net> wrote

def testanalysis():
    IP = []
    temp = [[0, 0, 0],[0, 0, 0],[0, 0, 0]]
    # initialize to zero
    for i in range(20):
        IP.append(temp)

this appends the same list (temp)  20 times. So when you 
change the list it is reflected 20 times. Lists hold references 
to their data (even if the data is anotyher list). You need to 
make copies before appending.

Don't worry, this is one of the most common gotchas in 
Python...

HTH,

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


From mikem at blazenetme.net  Sat Jul 26 01:35:54 2008
From: mikem at blazenetme.net (Mike Meisner)
Date: Fri, 25 Jul 2008 19:35:54 -0400
Subject: [Tutor] List indexing problem
References: <000901c8eea2$7fd57f70$08a305cf@Parents>
	<488A5BDE.9080505@alchemy.com>
Message-ID: <000501c8eeaf$2e822df0$08a305cf@Parents>

Thanks Steve.

It's obvious now that you've pointed it out.

Do you happen to know if there is an efficient way to initialize a  list 
like this without explicitly writing out each element?

Mike
----- Original Message ----- 
From: "Steve Willoughby" <steve at alchemy.com>
To: "Mike Meisner" <mikem at blazenetme.net>
Cc: <tutor at python.org>
Sent: Friday, July 25, 2008 7:03 PM
Subject: Re: [Tutor] List indexing problem


> Mike Meisner wrote:
>> I need to do some statistical analysis by binning values into an array.
>>  Being new to Python, I tried to use a list of lists.  I've extracted 
>> just the minimum code that I'm having trouble with:
>
> What you need to remember is that Python works with *objects*, and 
> variables are simply *references* to those objects.  So if I say
> a = [1,2,3]
> b = a
>
> b and a both refer to the *SAME* list object (not two lists which happen 
> to have the same elements).
>
>>     temp = [[0, 0, 0],[0, 0, 0],[0, 0, 0]]
>
> temp now refers to a list object containing 3 lists, each containing 3 
> integers.
>
>>     # initialize to zero
>>     for i in range(20):
>>         IP.append(temp)
>
> Now IP contains 20 copies of references to the *same* list object.
> So you were modifying the underlying list object which happens to be 
> referenced many times in IP.
>
> 



From motoom at xs4all.nl  Sat Jul 26 02:20:09 2008
From: motoom at xs4all.nl (Michiel Overtoom)
Date: Sat, 26 Jul 2008 02:20:09 +0200
Subject: [Tutor] List indexing problem
Message-ID: <2.2.32.20080726002009.01207c14@pop.xs4all.nl>

Mike wrote...

>Do you happen to know if there is an efficient way to initialize a  list 
>like this without explicitly writing out each element?

>>> temp = [[0, 0, 0],[0, 0, 0],[0, 0, 0]]
>>> print temp
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

>>> print [[0]*3]*3
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]


-- 
"The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing." - Vinod Vallopillil
http://www.catb.org/~esr/halloween/halloween4.html


From rdm at rcblue.com  Sat Jul 26 02:53:38 2008
From: rdm at rcblue.com (Dick Moores)
Date: Fri, 25 Jul 2008 17:53:38 -0700
Subject: [Tutor] Is there a better way to get a current mid-rate Yen
 quote with Python?
In-Reply-To: <g6dmjr$sbj$1@ger.gmane.org>
References: <20080725151800.7AC851E4012@bag.python.org>
	<g6d031$m5a$1@ger.gmane.org>
	<20080725171530.5F94A1E4011@bag.python.org>
	<g6dmjr$sbj$1@ger.gmane.org>
Message-ID: <20080726005352.2A2921E400C@bag.python.org>

At 04:11 PM 7/25/2008, Alan Gauld wrote:
>"Dick Moores" <rdm at rcblue.com> wrote
>>>Certainly Beautiful Soup will not be muh longer and a lot more 
>>>elegant and probably more resilient.
>>Alan, expand a bit, please. Longer? Resilient?
>
>Longer as in lines of code. BS is good for extracting several 
>different parts from the soup, but just to pull out one very 
>specific item the setup and so on may mean that the framework 
>actually works out the same or longer than your code.
>
>Resilient as in able to handle unexpected changes in the HTML used 
>by the site or slight changes in formatting of the results etc.
>
>>>But to extract a single piece of text in a well defined location 
>>>then your approach although somewhat crude will work just fine.
>>Crude? What's crude about my code?
>
>Its just a little bit too hard coded for my liking, all that 
>splitting and searching means theres a lot of work going on
>to extract a small piece of data. You iterate over the whole page to 
>do the first spliot,

Ah. I had the idea that it would be better to split it into its 
natural lines, by line 7.  But I could have just started with the 
first relevant split.

>  then you iterate over the whole thing again to find the line you 
> want. Consider thios line:
>
>if 'JPY' in x and '>USDJPY=X<' in x:
>
>Sincy JPY is in both strings the first check is effectively 
>redundant but still requires a string search over the line.
>A well crafted regex would probably be faster than the double in 
>test and provide better checking by including
>allowances for extra spaces or case changes etc.

I'll try to do that.

>Then having found the string once with 'in' you then have to find it 
>again with split().

Do you mean string x? After c = x (line 10), the next split is on c. 
I'm not finding it again, am I?

>  You could just have done a find the first time and stored the 
> index as a basis for the slicing later.
>
>You also use lots of very specific slicing values to extract the 
>data - thats where you lose resilience compared to a parser approach like BS.

Since I posted I found that I could add some resilience by extending 
the end of the slice and then cutting back with an rstrip().

I haven't the slightest idea what a parser is. But I'll find out 
while learning BS.

>  Again I suspect a regex might work better in extracting the value. 
> And hard coding the url in the function also adds to its fragility.

I can't imagine what else is possible?

>Stylistically all those single character variable names hurts 
>readability and maintainability too.

I was at a loss as to what variable names to use, so I figured I'd 
use a, b, c, .. in order, because I thought it was obvious that I was 
narrowing the search for the yen rate. Could you give me an idea of 
what names I could use?

>>I want to improve, so please tell
>
>It will work as is, but it could be tidied up a bit is all.

Thanks Alan, for your tough look at the code. I appreciate it.

Dick
===================================================
Have you seen Kelie Feng's video introducing the terrific and free
IDE, Ulipad? <http://www.rcblue.com/u3/>
Get Ulipad 3.9 from <http://code.google.com/p/ulipad/downloads/list>
svn for the latest revision <http://ulipad.googlecode.com/svn/trunk/>
Mailing list for Ulipad: <http://groups-beta.google.com/group/ulipad>


From lie.1296 at gmail.com  Sat Jul 26 02:44:39 2008
From: lie.1296 at gmail.com (Lie Ryan)
Date: Sat, 26 Jul 2008 07:44:39 +0700
Subject: [Tutor] Is there a better way to get a current mid-rate Yen
In-Reply-To: <mailman.6462.1217004473.920.tutor@python.org>
References: <mailman.6462.1217004473.920.tutor@python.org>
Message-ID: <1217033079.6444.2.camel@lieryan-laptop>

> Date: Fri, 25 Jul 2008 05:14:32 -0700
> From: Dick Moores <rdm at rcblue.com>
> Subject: [Tutor] Is there a better way to get a current mid-rate Yen
>         quote with Python?
> To: Python Tutor List <tutor at python.org>
> Message-ID: <20080725121444.818C41E4007 at bag.python.org>
> Content-Type: text/plain; charset="us-ascii"; format=flowed
> 
> Better than this? <http://py77.python.pastebin.com/fc7553a4>
> 
> I've heard about BeautifulSoup. 
> <http://www.crummy.com/software/BeautifulSoup/>. Is it worth 
> learning? Is it crummy? ;-)
> 
> So 2 questions.
> 
> Thanks,
> 
> Dick Moores

Slightly better would be to use the re (regular expression) module.
It'd be more flexible than coding and easier than Beautiful Soup (which,
IMHO, is an overkill for simple data extraction like this).


From lie.1296 at gmail.com  Sat Jul 26 03:25:42 2008
From: lie.1296 at gmail.com (Lie Ryan)
Date: Sat, 26 Jul 2008 08:25:42 +0700
Subject: [Tutor] List indexing problem
In-Reply-To: <mailman.6588.1217031611.920.tutor@python.org>
References: <mailman.6588.1217031611.920.tutor@python.org>
Message-ID: <1217035542.6444.30.camel@lieryan-laptop>

On Sat, 2008-07-26 at 02:20 +0200, tutor-request at python.org wrote:
> Message: 8
> Date: Fri, 25 Jul 2008 19:35:54 -0400
> From: "Mike Meisner" <mikem at blazenetme.net>
> Subject: Re: [Tutor] List indexing problem
> To: "Steve Willoughby" <steve at alchemy.com>
> Cc: tutor at python.org
> Message-ID: <000501c8eeaf$2e822df0$08a305cf at Parents>
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
>         reply-type=response
> 
> Thanks Steve.
> 
> It's obvious now that you've pointed it out.
> 
> Do you happen to know if there is an efficient way to initialize a
> list 
> like this without explicitly writing out each element?
> 
> Mike

A bit fragile, since it uses eval: 

lst = eval(repr([[[0]*3]*3]*10))

but in this particular case, eval won't leak harmful code (as far as I
can see) since all it process is literals, not user-inputted data.

The alternative is this:
lst = [[[0 for _ in range(3)] for _ in range(3)] for _ in range(10)]


From kent37 at tds.net  Sat Jul 26 09:08:45 2008
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 26 Jul 2008 03:08:45 -0400
Subject: [Tutor] List indexing problem
In-Reply-To: <000501c8eeaf$2e822df0$08a305cf@Parents>
References: <000901c8eea2$7fd57f70$08a305cf@Parents>
	<488A5BDE.9080505@alchemy.com>
	<000501c8eeaf$2e822df0$08a305cf@Parents>
Message-ID: <1c2a2c590807260008k637b7fa7j8835d58d8c90748f@mail.gmail.com>

On Fri, Jul 25, 2008 at 7:35 PM, Mike Meisner <mikem at blazenetme.net> wrote:
> Do you happen to know if there is an efficient way to initialize a  list
> like this without explicitly writing out each element?

You can make a copy of the inner list each time through the loop:
    IP = []
    temp = [[0, 0, 0],[0, 0, 0],[0, 0, 0]]
    # initialize to zero
    for i in range(20):
        IP.append(list(temp))

Kent

From kent37 at tds.net  Sat Jul 26 09:15:59 2008
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 26 Jul 2008 03:15:59 -0400
Subject: [Tutor] List indexing problem
In-Reply-To: <2.2.32.20080726002009.01207c14@pop.xs4all.nl>
References: <2.2.32.20080726002009.01207c14@pop.xs4all.nl>
Message-ID: <1c2a2c590807260015xe078946qc612cbca6902a265@mail.gmail.com>

On Fri, Jul 25, 2008 at 8:20 PM, Michiel Overtoom <motoom at xs4all.nl> wrote:
> Mike wrote...
>
>>Do you happen to know if there is an efficient way to initialize a  list
>>like this without explicitly writing out each element?
>
>>>> temp = [[0, 0, 0],[0, 0, 0],[0, 0, 0]]
>>>> print temp
> [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>
>>>> print [[0]*3]*3
> [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

This has the same aliasing problem as the original:
>>> x=[[0]*3]*3
>>> x
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> x[0][0]=1
>>> x
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]

BTW this is a FAQ:
http://effbot.org/pyfaq/how-do-i-create-a-multidimensional-list.htm

Kent

From wescpy at gmail.com  Sat Jul 26 10:43:35 2008
From: wescpy at gmail.com (wesley chun)
Date: Sat, 26 Jul 2008 01:43:35 -0700
Subject: [Tutor] Online class/education for Python?
In-Reply-To: <59f9c5160807240430h64863d6eg5a8245b9d47bc8fd@mail.gmail.com>
References: <721b21dc0807191141q3704c8f9jcc3790f838c87f60@mail.gmail.com>
	<ea979d70807201817x362d038cic86f492a7c7aa850@mail.gmail.com>
	<59f9c5160807211320x4087cbf8kc89e2ad7404cc526@mail.gmail.com>
	<ea979d70807220427t3fdc99bfh4948f3287eb57867@mail.gmail.com>
	<59f9c5160807222038v1a8e7ff6wa7c2f2043c61d7e@mail.gmail.com>
	<ea979d70807231544o37fb3e00w9d27f3eb190cc058@mail.gmail.com>
	<59f9c5160807240430h64863d6eg5a8245b9d47bc8fd@mail.gmail.com>
Message-ID: <78b3a9580807260143qed85701lc1ba4c6e398d48c@mail.gmail.com>

> I have the first edition of Python Programming for the Absolute Beginner.
> Will this work instead of the 2nd edition?


i just found out from bookpool today that the 2nd edition is now also
out-of-print. does anyone know if a 3rd edition is being worked on?

-- 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 amit.pureenergy at gmail.com  Sat Jul 26 14:51:22 2008
From: amit.pureenergy at gmail.com (amit sethi)
Date: Sat, 26 Jul 2008 18:21:22 +0530
Subject: [Tutor] (no subject)
Message-ID: <da81a0a80807260551n4cdddbaft54a25c17d8c86bee@mail.gmail.com>

hi,
Can somebody tell me about tools to  convert stereo mp3 signal to mono wave
signal . I tried using pymedia but i am not able to understand how to
convert stereo signal to a mono signal .

-- 
A-M-I-T S|S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080726/3f346856/attachment.htm>

From rdm at rcblue.com  Sat Jul 26 16:11:56 2008
From: rdm at rcblue.com (Dick Moores)
Date: Sat, 26 Jul 2008 07:11:56 -0700
Subject: [Tutor] Online class/education for Python?
In-Reply-To: <78b3a9580807260143qed85701lc1ba4c6e398d48c@mail.gmail.com>
References: <721b21dc0807191141q3704c8f9jcc3790f838c87f60@mail.gmail.com>
	<ea979d70807201817x362d038cic86f492a7c7aa850@mail.gmail.com>
	<59f9c5160807211320x4087cbf8kc89e2ad7404cc526@mail.gmail.com>
	<ea979d70807220427t3fdc99bfh4948f3287eb57867@mail.gmail.com>
	<59f9c5160807222038v1a8e7ff6wa7c2f2043c61d7e@mail.gmail.com>
	<ea979d70807231544o37fb3e00w9d27f3eb190cc058@mail.gmail.com>
	<59f9c5160807240430h64863d6eg5a8245b9d47bc8fd@mail.gmail.com>
	<78b3a9580807260143qed85701lc1ba4c6e398d48c@mail.gmail.com>
Message-ID: <20080726141208.A1AF31E4013@bag.python.org>

At 01:43 AM 7/26/2008, wesley chun wrote:
> > I have the first edition of Python Programming for the Absolute Beginner.
> > Will this work instead of the 2nd edition?
>
>
>i just found out from bookpool today that the 2nd edition is now also
>out-of-print.

But:
<http://search.barnesandnoble.com/booksearch/isbnInquiry.asp?ISBN=9781598631128&>
<http://www.amazon.com/Python-Programming-Absolute-Beginner-Second/dp/1598631128/ref=sr_11_1?ie=UTF8&qid=1217080779&sr=11-1>
And at the Publisher:
<http://www.courseptr.com/ptr_detail.cfm?group=Programming&subcat=Other&isbn=978%2D1%2D59863%2D112%2D8>


>  does anyone know if a 3rd edition is being worked on?

publisher contact info:
<http://www.courseptr.com/ptr_customerService.cfm>

I used to have the author's email, but I've lost it.

Dick Moores

===================================================
Have you seen Kelie Feng's video introducing the terrific and free
IDE, Ulipad? <http://www.rcblue.com/u3/>
Get Ulipad 3.9 from <http://code.google.com/p/ulipad/downloads/list>
svn for the latest revision <http://ulipad.googlecode.com/svn/trunk/>
Mailing list for Ulipad: <http://groups-beta.google.com/group/ulipad> 


From corbettt at dcn.davis.ca.us  Sat Jul 26 08:27:26 2008
From: corbettt at dcn.davis.ca.us (Thomas Corbett)
Date: Fri, 25 Jul 2008 23:27:26 -0700
Subject: [Tutor] Unable to Reconfigure IDLE
Message-ID: <EDB49B2F-EB91-4309-803D-17FFD8C87FDE@dcn.davis.ca.us>

Running IDLE 1.2.2 under MacPython 2.5 on Mac OS X 5.1.

Configured shell window to wrong size, now can't seem to find the menu  
(Options > Configure) to resize the shell.

Tried going to username > Library > Preferences  and removing  
org.python* files, but that did not work.

Thanks!

From alan.gauld at btinternet.com  Sat Jul 26 18:02:22 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 26 Jul 2008 17:02:22 +0100
Subject: [Tutor] Unable to Reconfigure IDLE
References: <EDB49B2F-EB91-4309-803D-17FFD8C87FDE@dcn.davis.ca.us>
Message-ID: <g6fhqk$tke$1@ger.gmane.org>


"Thomas Corbett" <corbettt at dcn.davis.ca.us> wrote

> Configured shell window to wrong size, now can't seem to find the 
> menu  (Options > Configure) to resize the shell.

Don't you just resize it then close it and the next time it opens
it uses the new size?

Thats how I thought it was supposed to work!

Alan G 



From rick at niof.net  Sat Jul 26 19:00:05 2008
From: rick at niof.net (Rick Pasotto)
Date: Sat, 26 Jul 2008 13:00:05 -0400
Subject: [Tutor] where to report a bug?
In-Reply-To: <20080725221157.GA67528@cutter.rexx.com>
References: <20080725140435.GI31862@niof.net>
	<20080725221157.GA67528@cutter.rexx.com>
Message-ID: <20080726170005.GN31862@niof.net>

On Fri, Jul 25, 2008 at 03:11:57PM -0700, Dave Kuhlman wrote:
> On Fri, Jul 25, 2008 at 10:04:35AM -0400, Rick Pasotto wrote:
> > I have a script that works fine on my linux machine but bombs out when
> > run under windows using the exact same data files. The script downloads
> > a file then unzips it and then scans the resulting file for certain
> > records. Under Windows it gets a memory error in the unzip routine.
> > 
> > Where should I send the error report?
> 
> You might want to post your code here.  Someone might be able to
> suggest a fix (to your code) or at least a work-around.
> 
> One question -- Are you downloading the file and unzipping it with
> the zipfile module?  Or, are you downloading the file and then
> writing the file to disk.
> 
> If you are writing the file to disk, make sure that you open the
> file in binary mode, since a zipped file is binary data.  If you
> fail to do so, your code will work on Linux/UNIX, but not on
> Windows.  I've written code with that bug myself.

That was a good thought but when I double checked the code I found that
I was already opening the write file in 'wb' mode.

Here's where things stand now.

I searched comp.lang.python for 'zipfile' and found several messages
that talked about this error. It seems that Windows doesn't handle
memory allocation very well on large files (surprise, surprise). The
module was written to deal with small files and so that was not a
consideration in writing the module.

One of the messages included a workaround that replaced the 'write'
method with an 'explode' funtion that opperated on 8k chunks instead of
the whole file. This had the added advantage of my being able to tap
into the function to display a progress indicator.

Again, it worked fine on my linux machine but failed on Windows, but
this time with a different error. This error really surprises me.

The new explode function uses the zipfile.ZipInfo.file_offset attribute.
Windows reports that there is no such attribute. Turns out that while it
exists in 2.4, which is what I am still running, it does *not* exist in
2.5, which is what the python.org Windows installer uses. I have 2.5 on
my linux machine and when I run python2.5 there, ZipInfo.file_offset is
not in the dir(zipfile.ZipInfo) list. All the other attributes match.

Where did it go? And why? Was it intentionally removed? If so, why and
how do I get its functionality? I haven't spotted any reference to the
change in the changelists I've seen but maybe I haven't looked in the
right places.

What should be my next step?

-- 
"You are the only one who can use your ability. It is an awesome
 responsibility." -- Zig Zigler
    Rick Pasotto    rick at niof.net    http://www.niof.net

From wescpy at gmail.com  Sat Jul 26 19:14:57 2008
From: wescpy at gmail.com (wesley chun)
Date: Sat, 26 Jul 2008 10:14:57 -0700
Subject: [Tutor] Online class/education for Python?
In-Reply-To: <20080726141208.A1AF31E4013@bag.python.org>
References: <721b21dc0807191141q3704c8f9jcc3790f838c87f60@mail.gmail.com>
	<ea979d70807201817x362d038cic86f492a7c7aa850@mail.gmail.com>
	<59f9c5160807211320x4087cbf8kc89e2ad7404cc526@mail.gmail.com>
	<ea979d70807220427t3fdc99bfh4948f3287eb57867@mail.gmail.com>
	<59f9c5160807222038v1a8e7ff6wa7c2f2043c61d7e@mail.gmail.com>
	<ea979d70807231544o37fb3e00w9d27f3eb190cc058@mail.gmail.com>
	<59f9c5160807240430h64863d6eg5a8245b9d47bc8fd@mail.gmail.com>
	<78b3a9580807260143qed85701lc1ba4c6e398d48c@mail.gmail.com>
	<20080726141208.A1AF31E4013@bag.python.org>
Message-ID: <78b3a9580807261014o3d2a2ef6s46f4efc75c9f74@mail.gmail.com>

On Sat, Jul 26, 2008 at 7:11 AM, Dick Moores <rdm at rcblue.com> wrote:
> At 01:43 AM 7/26/2008, wesley chun wrote:
>>
>> > I have the first edition of Python Programming for the Absolute
>> > Beginner.
>> > Will this work instead of the 2nd edition?
>>
>>
>> i just found out from bookpool today that the 2nd edition is now also
>> out-of-print.
>
> But:
> <http://search.barnesandnoble.com/booksearch/isbnInquiry.asp?ISBN=9781598631128&>
> <http://www.amazon.com/Python-Programming-Absolute-Beginner-Second/dp/1598631128/ref=sr_11_1?ie=UTF8&qid=1217080779&sr=11-1>
> And at the Publisher:
> <http://www.courseptr.com/ptr_detail.cfm?group=Programming&subcat=Other&isbn=978%2D1%2D59863%2D112%2D8>
>
>
>>  does anyone know if a 3rd edition is being worked on?
>
> publisher contact info:
> <http://www.courseptr.com/ptr_customerService.cfm>
>
> I used to have the author's email, but I've lost it.
>
> Dick Moores


hey, don't shoot the messenger!  here's what bookpool said yesterday:

> This book is now out of print, and we have removed it from our website.
> A new edition has not been released.

it's probly only still available at general retailers because they
have such massive stock.  of course the publisher has all remaining
inventory. i'm only letting folks here know in case they want this
book, it may disappear soon.

that's why i was also asking about a 3rd edition. also, as you can see
from the 2nd review for this author's "other" Python book, it could be
some nefarious actions from the publisher itself... no wonder it's
"out-of-print!"

http://amazon.com/dp/1423901126

caveat emptor!
-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 motoom at xs4all.nl  Sat Jul 26 21:42:40 2008
From: motoom at xs4all.nl (Michiel Overtoom)
Date: Sat, 26 Jul 2008 21:42:40 +0200
Subject: [Tutor] Unable to Reconfigure IDLE
Message-ID: <2.2.32.20080726194240.0120303c@pop.xs4all.nl>

Thomas wrote...

>Running IDLE 1.2.2 under MacPython 2.5 on Mac OS X 5.1.
>
>Configured shell window to wrong size, now can't seem to find the menu  
>(Options > Configure) to resize the shell.
>
>Tried going to username > Library > Preferences  and removing  
>org.python* files, but that did not work.

IDLE keeps it preferences in a hidden directory '.idlerc' in your home
directory. 

Greetings,

-- 
"The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing." - Vinod Vallopillil
http://www.catb.org/~esr/halloween/halloween4.html


From dkuhlman at rexx.com  Sat Jul 26 22:28:24 2008
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Sat, 26 Jul 2008 13:28:24 -0700
Subject: [Tutor] List indexing problem
In-Reply-To: <1c2a2c590807260008k637b7fa7j8835d58d8c90748f@mail.gmail.com>
References: <000901c8eea2$7fd57f70$08a305cf@Parents>
	<488A5BDE.9080505@alchemy.com>
	<000501c8eeaf$2e822df0$08a305cf@Parents>
	<1c2a2c590807260008k637b7fa7j8835d58d8c90748f@mail.gmail.com>
Message-ID: <20080726202824.GA80870@cutter.rexx.com>

On Sat, Jul 26, 2008 at 03:08:45AM -0400, Kent Johnson wrote:
> On Fri, Jul 25, 2008 at 7:35 PM, Mike Meisner <mikem at blazenetme.net> wrote:
> > Do you happen to know if there is an efficient way to initialize a  list
> > like this without explicitly writing out each element?
> 
> You can make a copy of the inner list each time through the loop:
>     IP = []
>     temp = [[0, 0, 0],[0, 0, 0],[0, 0, 0]]
>     # initialize to zero
>     for i in range(20):
>         IP.append(list(temp))

How about::

    In [26]: IP = [[0, 0, 0] for x in range(5)]
    In [27]: IP
    Out[27]: [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
    In [28]: id(IP[0])
    Out[28]: 13122016
    In [29]: id(IP[1])
    Out[29]: 13121152
    In [30]: id(IP[2])
    Out[30]: 13121800

- Dave


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

From alan.gauld at btinternet.com  Sun Jul 27 02:03:02 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 27 Jul 2008 01:03:02 +0100
Subject: [Tutor] Online class/education for Python?
References: <721b21dc0807191141q3704c8f9jcc3790f838c87f60@mail.gmail.com><ea979d70807201817x362d038cic86f492a7c7aa850@mail.gmail.com><59f9c5160807211320x4087cbf8kc89e2ad7404cc526@mail.gmail.com><ea979d70807220427t3fdc99bfh4948f3287eb57867@mail.gmail.com><59f9c5160807222038v1a8e7ff6wa7c2f2043c61d7e@mail.gmail.com><ea979d70807231544o37fb3e00w9d27f3eb190cc058@mail.gmail.com><59f9c5160807240430h64863d6eg5a8245b9d47bc8fd@mail.gmail.com><78b3a9580807260143qed85701lc1ba4c6e398d48c@mail.gmail.com><20080726141208.A1AF31E4013@bag.python.org>
	<78b3a9580807261014o3d2a2ef6s46f4efc75c9f74@mail.gmail.com>
Message-ID: <g6gdvs$4ai$1@ger.gmane.org>


"wesley chun" <wescpy at gmail.com> wrote

> from the 2nd review for this author's "other" Python book, it could 
> be
> some nefarious actions from the publisher itself... no wonder it's
> "out-of-print!"
>
> http://amazon.com/dp/1423901126

At $88 for 500 pages it had better be good or he will be stuxck
with academic-only sales!

Alan G 



From d.conca at gmail.com  Sun Jul 27 02:31:10 2008
From: d.conca at gmail.com (Daniele)
Date: Sun, 27 Jul 2008 02:31:10 +0200
Subject: [Tutor] urllib2 and php authentication
Message-ID: <537341c70807261731k2c5a06dp91fe114586133ce7@mail.gmail.com>

Hi,
I'm trying to connect to a site that requires a php login. I used the
urllib2 module in the following way:

>>> import urllib2
>>> user='xxx'
>>> password='yyy'
>>> hp = urllib2.HTTPPasswordMgr()
>>> uri = 'http://s2.ikariam.it/index.php?action=loginAvatar&function=login'
>>> hp.add_password(None, uri, user, password)
>>> opener = urllib2.build_opener(urllib2.HTTPBasicAuthHandler( hp))
>>> req = urllib2.Request(uri)
>>> opener.open(req).readlines()

Needless to say, it doesn't work. I get an html page back from the
opener saying username and/or password are invalid.
Can anyone point me in the right direction?

thanks a lot,
Daniele

From srilyk at gmail.com  Sun Jul 27 03:58:34 2008
From: srilyk at gmail.com (W W)
Date: Sat, 26 Jul 2008 20:58:34 -0500
Subject: [Tutor] urllib2 and php authentication
In-Reply-To: <537341c70807261731k2c5a06dp91fe114586133ce7@mail.gmail.com>
References: <537341c70807261731k2c5a06dp91fe114586133ce7@mail.gmail.com>
Message-ID: <333efb450807261858s6bcc9290v122be6cb38938665@mail.gmail.com>

On Sat, Jul 26, 2008 at 7:31 PM, Daniele <d.conca at gmail.com> wrote:

> Hi,
> I'm trying to connect to a site that requires a php login. I used the
> urllib2 module in the following way:
>

It requires a php login, or php handles the login?

>>> import urllib2
> >>> user='xxx'
> >>> password='yyy'
> >>> hp = urllib2.HTTPPasswordMgr()
> >>> uri = '
> http://s2.ikariam.it/index.php?action=loginAvatar&function=login'
> >>> hp.add_password(None, uri, user, password)
> >>> opener = urllib2.build_opener(urllib2.HTTPBasicAuthHandler( hp))
> >>> req = urllib2.Request(uri)
> >>> opener.open(req).readlines()
>
> Needless to say, it doesn't work. I get an html page back from the
> opener saying username and/or password are invalid.
> Can anyone point me in the right direction?
>

If php is handling the login, my guess is that it's receiving the info via
either POST or GET.

And if you don't have access to the script, and you're not sure what the
names of the values are, that might require some trial and error.

HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080726/f5e7efc5/attachment.htm>

From corbettt at dcn.davis.ca.us  Sat Jul 26 19:18:20 2008
From: corbettt at dcn.davis.ca.us (Thomas Corbett)
Date: Sat, 26 Jul 2008 10:18:20 -0700
Subject: [Tutor] Unable to Reconfigure IDLE
In-Reply-To: <g6fhqk$tke$1@ger.gmane.org>
References: <EDB49B2F-EB91-4309-803D-17FFD8C87FDE@dcn.davis.ca.us>
	<g6fhqk$tke$1@ger.gmane.org>
Message-ID: <C18A9DD3-1B8A-4F47-854B-EF5503C6FD4F@dcn.davis.ca.us>


On Jul 26, 2008, at 9:02 AM, Alan Gauld wrote:

>
> "Thomas Corbett" <corbettt at dcn.davis.ca.us> wrote
>
>> Configured shell window to wrong size, now can't seem to find the  
>> menu  (Options > Configure) to resize the shell.
>
> Don't you just resize it then close it and the next time it opens
> it uses the new size?
>
> Thats how I thought it was supposed to work!
>
> Alan G
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


The window is too large to resize.

-Tom


From wescpy at gmail.com  Sun Jul 27 09:33:24 2008
From: wescpy at gmail.com (wesley chun)
Date: Sun, 27 Jul 2008 00:33:24 -0700
Subject: [Tutor] Online class/education for Python?
In-Reply-To: <g6gdvs$4ai$1@ger.gmane.org>
References: <721b21dc0807191141q3704c8f9jcc3790f838c87f60@mail.gmail.com>
	<59f9c5160807211320x4087cbf8kc89e2ad7404cc526@mail.gmail.com>
	<ea979d70807220427t3fdc99bfh4948f3287eb57867@mail.gmail.com>
	<59f9c5160807222038v1a8e7ff6wa7c2f2043c61d7e@mail.gmail.com>
	<ea979d70807231544o37fb3e00w9d27f3eb190cc058@mail.gmail.com>
	<59f9c5160807240430h64863d6eg5a8245b9d47bc8fd@mail.gmail.com>
	<78b3a9580807260143qed85701lc1ba4c6e398d48c@mail.gmail.com>
	<20080726141208.A1AF31E4013@bag.python.org>
	<78b3a9580807261014o3d2a2ef6s46f4efc75c9f74@mail.gmail.com>
	<g6gdvs$4ai$1@ger.gmane.org>
Message-ID: <78b3a9580807270033r37f28819v31687367aaf7754c@mail.gmail.com>

> At $88 for 500 pages it had better be good or he will be stuxck
> with academic-only sales!


well, the other thing is that the 2nd review will really make ppl go
back to the original title since it's $18 vs. $88 for the (apparently)
same material, both academic and general sales. i can't imagine why
anyone would get the latter, hence what i think will drive sales all
to the former. it's fortunate that there are currently a lot of copies
out there, but again, this behavior is rarely the work of the author,
who has much less control over their material than one would
ordinarily believe.

another alternative that many have already recommended is How to Think
Like a Computer Scientist.  the 1st edition is available both in-print
and online, but the 2nd edition is only available online (for now).

1st: http://www.greenteapress.com/thinkpython/thinkCSpy/
2nd: http://openbookproject.net/thinkCSpy

oh, if there were only some other alternative for complete newbies to
programmers... say, um, a 2nd edition of Learn to Program?!? (yeah, i
keep teasing about this but i am kinda serious in some ways too [altho
i'm aware of the work involved in such an endeavor].) :)

on a tangential note, i may be asked to teach a private course to
individuals who have never formally learned to program before, and i'm
participating in this thread for a number of reasons, including the
fact that i'm trying to come up with a supplemental textbook to use in
addition to my course notes. i had envisioned the dawson book, but if
it's going OoP, i will have to come up with alternatives.

cheers,
-wesley

From rdm at rcblue.com  Sun Jul 27 07:46:07 2008
From: rdm at rcblue.com (Dick Moores)
Date: Sat, 26 Jul 2008 22:46:07 -0700
Subject: [Tutor] Online class/education for Python?
In-Reply-To: <g6gdvs$4ai$1@ger.gmane.org>
References: <721b21dc0807191141q3704c8f9jcc3790f838c87f60@mail.gmail.com>
	<ea979d70807201817x362d038cic86f492a7c7aa850@mail.gmail.com>
	<59f9c5160807211320x4087cbf8kc89e2ad7404cc526@mail.gmail.com>
	<ea979d70807220427t3fdc99bfh4948f3287eb57867@mail.gmail.com>
	<59f9c5160807222038v1a8e7ff6wa7c2f2043c61d7e@mail.gmail.com>
	<ea979d70807231544o37fb3e00w9d27f3eb190cc058@mail.gmail.com>
	<59f9c5160807240430h64863d6eg5a8245b9d47bc8fd@mail.gmail.com>
	<78b3a9580807260143qed85701lc1ba4c6e398d48c@mail.gmail.com>
	<20080726141208.A1AF31E4013@bag.python.org>
	<78b3a9580807261014o3d2a2ef6s46f4efc75c9f74@mail.gmail.com>
	<g6gdvs$4ai$1@ger.gmane.org>
Message-ID: <20080727082141.6E00A1E401B@bag.python.org>

At 05:03 PM 7/26/2008, Alan Gauld wrote:

>"wesley chun" <wescpy at gmail.com> wrote
>
>>from the 2nd review for this author's "other" Python book, it could be
>>some nefarious actions from the publisher itself... no wonder it's
>>"out-of-print!"
>>
>>http://amazon.com/dp/1423901126
>
>At $88 for 500 pages it had better be good or he will be stuxck
>with academic-only sales!

It's exactly as good as the 2nd edition! See the 2nd review at that link:

=================================================
Careful buying this., May 17, 2008

While I won't deny this is the best book out there to teach someone 
Python, it is pretty much Word for Word the same book as Python for 
the Absolute Beginner (which is by the same author). This version is 
packaged as an academic book, and costs 4 times as much!
I love the author for this book, but the publisher should be shot.
Go pick up the absolute beginner version and saves yourself $60.

If it hadn't been the same book, I would happily given it 5 stars.
=================================================

I can confirm this. I eagerly snatched it up when it came out, only 
to find that it was just a slick repackaging of what I already owned. 
Returned it the next day.

Dick



From rschroev_nospam_ml at fastmail.fm  Sun Jul 27 10:50:53 2008
From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven)
Date: Sun, 27 Jul 2008 10:50:53 +0200
Subject: [Tutor] urllib2 and php authentication
In-Reply-To: <333efb450807261858s6bcc9290v122be6cb38938665@mail.gmail.com>
References: <537341c70807261731k2c5a06dp91fe114586133ce7@mail.gmail.com>
	<333efb450807261858s6bcc9290v122be6cb38938665@mail.gmail.com>
Message-ID: <g6hctd$t0o$1@ger.gmane.org>

W W schreef:
> On Sat, Jul 26, 2008 at 7:31 PM, Daniele <d.conca at gmail.com 
> <mailto:d.conca at gmail.com>> wrote:
> 
>     Hi,
>     I'm trying to connect to a site that requires a php login. I used the
>     urllib2 module in the following way:
> 
> 
> It requires a php login, or php handles the login?
> 
>      >>> import urllib2
>      >>> user='xxx'
>      >>> password='yyy'
>      >>> hp = urllib2.HTTPPasswordMgr()
>      >>> uri =
>     'http://s2.ikariam.it/index.php?action=loginAvatar&function=login
>     <http://s2.ikariam.it/index.php?action=loginAvatar&function=login>'
>      >>> hp.add_password(None, uri, user, password)
>      >>> opener = urllib2.build_opener(urllib2.HTTPBasicAuthHandler( hp))
>      >>> req = urllib2.Request(uri)
>      >>> opener.open(req).readlines()
> 
>     Needless to say, it doesn't work. I get an html page back from the
>     opener saying username and/or password are invalid.
>     Can anyone point me in the right direction?
> 
> 
> If php is handling the login, my guess is that it's receiving the info 
> via either POST or GET.
> 
> And if you don't have access to the script, and you're not sure what the 
> names of the values are, that might require some trial and error.

I suggest you use something like the Live HTTP Headers plugin in Firefox 
to see exactly what happens when you log in manually. That should give 
you enough information to do the same thing from your program.

-- 
The saddest aspect of life right now is that science gathers knowledge
faster than society gathers wisdom.
   -- Isaac Asimov

Roel Schroeven


From ladynikon at gmail.com  Sun Jul 27 13:09:34 2008
From: ladynikon at gmail.com (Danyelle Gragsone)
Date: Sun, 27 Jul 2008 07:09:34 -0400
Subject: [Tutor] Online class/education for Python?
In-Reply-To: <20080727082141.6E00A1E401B@bag.python.org>
References: <721b21dc0807191141q3704c8f9jcc3790f838c87f60@mail.gmail.com>
	<ea979d70807220427t3fdc99bfh4948f3287eb57867@mail.gmail.com>
	<59f9c5160807222038v1a8e7ff6wa7c2f2043c61d7e@mail.gmail.com>
	<ea979d70807231544o37fb3e00w9d27f3eb190cc058@mail.gmail.com>
	<59f9c5160807240430h64863d6eg5a8245b9d47bc8fd@mail.gmail.com>
	<78b3a9580807260143qed85701lc1ba4c6e398d48c@mail.gmail.com>
	<20080726141208.A1AF31E4013@bag.python.org>
	<78b3a9580807261014o3d2a2ef6s46f4efc75c9f74@mail.gmail.com>
	<g6gdvs$4ai$1@ger.gmane.org>
	<20080727082141.6E00A1E401B@bag.python.org>
Message-ID: <59f9c5160807270409v1920fa6bx85703a364631397d@mail.gmail.com>

On Sun, Jul 27, 2008 at 1:46 AM, Dick Moores <rdm at rcblue.com> wrote:

> At 05:03 PM 7/26/2008, Alan Gauld wrote:
>
>  "wesley chun" <wescpy at gmail.com> wrote
>>
>>  from the 2nd review for this author's "other" Python book, it could be
>>> some nefarious actions from the publisher itself... no wonder it's
>>> "out-of-print!"
>>>
>>> http://amazon.com/dp/1423901126
>>>
>>
>> At $88 for 500 pages it had better be good or he will be stuxck
>> with academic-only sales!
>>
>
> It's exactly as good as the 2nd edition! See the 2nd review at that link:
>
> =================================================
> Careful buying this., May 17, 2008
>
> While I won't deny this is the best book out there to teach someone Python,
> it is pretty much Word for Word the same book as Python for the Absolute
> Beginner (which is by the same author). This version is packaged as an
> academic book, and costs 4 times as much!
> I love the author for this book, but the publisher should be shot.
> Go pick up the absolute beginner version and saves yourself $60.
>
> If it hadn't been the same book, I would happily given it 5 stars.
> =================================================
>
> I can confirm this. I eagerly snatched it up when it came out, only to find
> that it was just a slick repackaging of what I already owned. Returned it
> the next day.
>
> Dick
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

Aren't those different books? than PPftAB?

LN
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080727/9fc8544f/attachment.htm>

From ppetto at apk.net  Sun Jul 27 14:40:16 2008
From: ppetto at apk.net (Peter Petto)
Date: Sun, 27 Jul 2008 08:40:16 -0400
Subject: [Tutor] newbie graphing question
Message-ID: <p06240801c4b21b28f90e@[192.168.1.124]>

I'm about to try some Python programming for drawing simple geometric 
pictures (for math classes I teach) and was hoping to get some advice 
that will send me off in the best direction.

I want to write programs that can draw figures with commands akin to 
point(x,y) to draw a point at coordinates (x,y), or segment 
(x1,y1,x2, y2) to draw a segment between points (x1, y1) and (x2, y2)?

I'd appreciate recommendations as to the best facility or library to 
use to this end. I primarily use a Mac, but my students primarily use 
Windows.

I'd love to hear any and all pointers or comments. Thanks!


-- 
===

Peter Petto <ppetto at apk.net>
Bay Village, OH   tel: 440.249.4289

From alan.gauld at btinternet.com  Sun Jul 27 15:55:49 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 27 Jul 2008 14:55:49 +0100
Subject: [Tutor] newbie graphing question
References: <p06240801c4b21b28f90e@[192.168.1.124]>
Message-ID: <g6hupc$9t6$1@ger.gmane.org>

"Peter Petto" <ppetto at apk.net> wrote

> I want to write programs that can draw figures with commands akin to 
> point(x,y) to draw a point at coordinates (x,y), or segment 
> (x1,y1,x2, y2) to draw a segment between points (x1, y1) and (x2, 
> y2)?

Most GUI toolkits will have a Canvas widget or similar that allows
drawing at that level. Also the standard turtle module might be
helpful with supoport for turtle graphics. Finally there are Python
plotting libraries that can be used for graphing and charts

However the GUI toolkits have the big disadvantage that you have to
build a GUII and all the controls before you can use the Canvas. That
migt not be what you want. Or you may want to build a basic framework
that your students can start from.

> I'd appreciate recommendations as to the best facility or library to 
> use to this end. I primarily use a Mac, but my students primarily 
> use Windows.

Standard Tkinter or wxPython both work on the Mac.

It depends on whether you want to teach graphics programming or
just graphics for data presentation. If the latter you are probably 
better
off with a standard spreadsheet like Excel.

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 Jul 27 16:01:36 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 27 Jul 2008 15:01:36 +0100
Subject: [Tutor] Online class/education for Python?
References: <721b21dc0807191141q3704c8f9jcc3790f838c87f60@mail.gmail.com><59f9c5160807211320x4087cbf8kc89e2ad7404cc526@mail.gmail.com><ea979d70807220427t3fdc99bfh4948f3287eb57867@mail.gmail.com><59f9c5160807222038v1a8e7ff6wa7c2f2043c61d7e@mail.gmail.com><ea979d70807231544o37fb3e00w9d27f3eb190cc058@mail.gmail.com><59f9c5160807240430h64863d6eg5a8245b9d47bc8fd@mail.gmail.com><78b3a9580807260143qed85701lc1ba4c6e398d48c@mail.gmail.com><20080726141208.A1AF31E4013@bag.python.org><78b3a9580807261014o3d2a2ef6s46f4efc75c9f74@mail.gmail.com><g6gdvs$4ai$1@ger.gmane.org>
	<78b3a9580807270033r37f28819v31687367aaf7754c@mail.gmail.com>
Message-ID: <g6hv46$av0$1@ger.gmane.org>

"wesley chun" <wescpy at gmail.com> wrote

> oh, if there were only some other alternative for complete newbies 
> to
> programmers... say, um, a 2nd edition of Learn to Program?!? (yeah, 
> i
> keep teasing about this but i am kinda serious in some ways too 
> [altho
> i'm aware of the work involved in such an endeavor].) :)

I might be able to contemplate such a task in the near future.
I'm not sure whether the publisher would be keen though, sales
are steady but hardly best-seller - an inherent risk when you
publish a web version too! In fact my biggest sales are currently
in Japan (where I assume there is a more limited range of Python
books available!).

If I did do a 2nd edition I'd probably aim it at Python 3.0 - which
would give me the motivation to start looking at V3 more closely.

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



From mail at timgolden.me.uk  Sun Jul 27 16:16:42 2008
From: mail at timgolden.me.uk (Tim Golden)
Date: Sun, 27 Jul 2008 15:16:42 +0100
Subject: [Tutor] Unable to Reconfigure IDLE
In-Reply-To: <C18A9DD3-1B8A-4F47-854B-EF5503C6FD4F@dcn.davis.ca.us>
References: <EDB49B2F-EB91-4309-803D-17FFD8C87FDE@dcn.davis.ca.us>	<g6fhqk$tke$1@ger.gmane.org>
	<C18A9DD3-1B8A-4F47-854B-EF5503C6FD4F@dcn.davis.ca.us>
Message-ID: <488C834A.20805@timgolden.me.uk>

Thomas Corbett wrote:
> 
> On Jul 26, 2008, at 9:02 AM, Alan Gauld wrote:
> 
>>
>> "Thomas Corbett" <corbettt at dcn.davis.ca.us> wrote
>>
>>> Configured shell window to wrong size, now can't seem to find the 
>>> menu  (Options > Configure) to resize the shell.
>>
>> Don't you just resize it then close it and the next time it opens
>> it uses the new size?
>>
>> Thats how I thought it was supposed to work!
>>
>> Alan G
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> The window is too large to resize.

I missed the beginning of this thread, but I assume that you
mean its edges are off the visible screen so you can't use
the mouse to grab the frame and resize it? If so, and if
you're on Windows, you can resize with the keyboard:
Alt-Space S will put you in Sizing mode; then use the
cursor keys to move the edges in and out. Alternatively,
Alt -Space M will put the window in Moving mode and, again,
the cursor keys can be used to bring a corner into view
and into range of the mouse.

TJG

From bhaaluu at gmail.com  Sun Jul 27 16:18:14 2008
From: bhaaluu at gmail.com (bhaaluu)
Date: Sun, 27 Jul 2008 10:18:14 -0400
Subject: [Tutor] Online class/education for Python?
In-Reply-To: <78b3a9580807270033r37f28819v31687367aaf7754c@mail.gmail.com>
References: <721b21dc0807191141q3704c8f9jcc3790f838c87f60@mail.gmail.com>
	<ea979d70807220427t3fdc99bfh4948f3287eb57867@mail.gmail.com>
	<59f9c5160807222038v1a8e7ff6wa7c2f2043c61d7e@mail.gmail.com>
	<ea979d70807231544o37fb3e00w9d27f3eb190cc058@mail.gmail.com>
	<59f9c5160807240430h64863d6eg5a8245b9d47bc8fd@mail.gmail.com>
	<78b3a9580807260143qed85701lc1ba4c6e398d48c@mail.gmail.com>
	<20080726141208.A1AF31E4013@bag.python.org>
	<78b3a9580807261014o3d2a2ef6s46f4efc75c9f74@mail.gmail.com>
	<g6gdvs$4ai$1@ger.gmane.org>
	<78b3a9580807270033r37f28819v31687367aaf7754c@mail.gmail.com>
Message-ID: <ea979d70807270718l46a03fbx34e23fa7208fbfd1@mail.gmail.com>

On Sun, Jul 27, 2008 at 3:33 AM, wesley chun <wescpy at gmail.com> wrote:
>
> on a tangential note, i may be asked to teach a private course to
> individuals who have never formally learned to program before, and i'm
> participating in this thread for a number of reasons, including the
> fact that i'm trying to come up with a supplemental textbook to use in
> addition to my course notes. i had envisioned the dawson book, but if
> it's going OoP, i will have to come up with alternatives.
>
> cheers,
> -wesley
>

While Python wasn't my first computer programming language, I found
the Dawson book (PPftAB2E) to be very approachable, and would highly recommend
it to anyone interested in learning Python. PPftAB2E is just a lot of
FUN to work
through, even if the student isn't planning on becoming a "game programmer."
It seems to cover all the Python basics.

I liked the fact that most of the 'games' used as example programs were text-
based games. The introduction to Python OOP was gentle, yet covered most
of the aspects of OOP without being overwhelming. Each chapter in the book
built on the previous chapter's examples.

I learned more about programming, reading/doing PPftAB2E, than from any other
programming book I've read/done. I'd like to repeat that the FUN factor was an
important aspect. Personally, I learn better and faster when I'm
having fun, than
when I have to learn something that is tedious from the very beginning.

Even though PPftAB2E uses games to teach Python, it never really gets
into PyGame.
Instead, it uses a customized version of a PyGame wrapper, called LiveWires.
LiveWires was developed to teach programming to kids in Great Britain. So if
a student goes through PPftAB2E, and wants to continue programming games,
I'd recommend "Game Programming" by Andy Harris [ISBN-13: 978-0-470-06822-9].
Game Programming is a fairly complete PyGame tutorial.

>From the Preface:

<quote>
Let's face it: Games are fun. Games are what brought me into computer
programming
so long ago, and they're a big part of why I'm still in it. There's
something irresistible
about immersing yourself in an imaginary world. Books and movies are a great way
to experience a form of "alternative reality," but an interactive
computer game is
something more. You don't simple watch a game. You 'participate.'

If you think games are fun to play, you should try 'creating' them.
There's nothing
more fun than building your own gaming environment, and when you actually make
something that's exciting for others to play, you'll feel a rare sense
of accomplishment.
If playing games is more immersive than watching movies, writing games is even
more immersive than playing them. After all, the players are really
playing with a
universe constructed by you. In a sense they're playing with you.
</quote>

PyGame is a Python wrapper around the extraordinary SDL library, which allows
beginning programmers to do some really incredible things, using the Python
language. The bottom line is: PPftAB2E is a fantastic book to use to
teach people
who have never programmed a computer before; and Game Programming is a
great follow-up book for those from the beginning class who want to continue
learning game programming with Python/PyGame. The PyGame crowd even have
their own website and mailing list: http://www.pygame.org/news.html

There are quite a few Python/PyGame examples on the PyGame website, so an
advanced Python class from the intermediate class would have lots of stuff to
take apart, modify, and put back together. Or, the class could team-build a game
for one of the Python/PyGame game competitions.

So there is a complete curriculum for you. I'm sure that students who
learned how
to program Python by learning to program games, would be well equipped to learn
how to program anything, from networked business apps, to Enterprise apps, or
anything else. They would be well-grounded Problem Solvers who have learned
how to learn. They probably had a lot of FUN learning how to learn, so it sticks
with them better, and longer, I'm so sure. 8^D

Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m
Kid on Bus: What are you gonna do today, Napoleon?
Napoleon Dynamite: Whatever I feel like I wanna do. Gosh!

From bhaaluu at gmail.com  Sun Jul 27 16:32:02 2008
From: bhaaluu at gmail.com (bhaaluu)
Date: Sun, 27 Jul 2008 10:32:02 -0400
Subject: [Tutor] newbie graphing question
In-Reply-To: <p06240801c4b21b28f90e@192.168.1.124>
References: <p06240801c4b21b28f90e@192.168.1.124>
Message-ID: <ea979d70807270732k5b381d19tc53e1f93ff88e03c@mail.gmail.com>

On Sun, Jul 27, 2008 at 8:40 AM, Peter Petto <ppetto at apk.net> wrote:
> I'm about to try some Python programming for drawing simple geometric
> pictures (for math classes I teach) and was hoping to get some advice that
> will send me off in the best direction.
>
> I want to write programs that can draw figures with commands akin to
> point(x,y) to draw a point at coordinates (x,y), or segment (x1,y1,x2, y2)
> to draw a segment between points (x1, y1) and (x2, y2)?
>
> I'd appreciate recommendations as to the best facility or library to use to
> this end. I primarily use a Mac, but my students primarily use Windows.
>
> I'd love to hear any and all pointers or comments. Thanks!
> --
> ===
> Peter Petto <ppetto at apk.net>
> Bay Village, OH   tel: 440.249.4289
>

Hello Mr. Petto,

I'd recommend the PyGame library. PyGame is a Python wrapper around the
extraordinary SDL library. For an example program of what you might be looking
for, take a look at:

http://www.cs.iupui.edu/~aharris/pygame/ch05/paint.py

The whole site has a lot of Python/PyGame examples:
http://www.cs.iupui.edu/~aharris/pygame/

Andy Harris is a CS professor at Indiana University-Perdue University
Indianapolis,
and is the author of several books, including Game Programming
[ISBN-13: 978-0-470-06822-9], which is a fairly complete introduction
and tutorial
for PyGame.

Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m
Kid on Bus: What are you gonna do today, Napoleon?
Napoleon Dynamite: Whatever I feel like I wanna do. Gosh!

From rdm at rcblue.com  Sun Jul 27 13:54:53 2008
From: rdm at rcblue.com (Dick Moores)
Date: Sun, 27 Jul 2008 04:54:53 -0700
Subject: [Tutor] Online class/education for Python?
In-Reply-To: <59f9c5160807270409v1920fa6bx85703a364631397d@mail.gmail.co
 m>
References: <721b21dc0807191141q3704c8f9jcc3790f838c87f60@mail.gmail.com>
	<ea979d70807220427t3fdc99bfh4948f3287eb57867@mail.gmail.com>
	<59f9c5160807222038v1a8e7ff6wa7c2f2043c61d7e@mail.gmail.com>
	<ea979d70807231544o37fb3e00w9d27f3eb190cc058@mail.gmail.com>
	<59f9c5160807240430h64863d6eg5a8245b9d47bc8fd@mail.gmail.com>
	<78b3a9580807260143qed85701lc1ba4c6e398d48c@mail.gmail.com>
	<20080726141208.A1AF31E4013@bag.python.org>
	<78b3a9580807261014o3d2a2ef6s46f4efc75c9f74@mail.gmail.com>
	<g6gdvs$4ai$1@ger.gmane.org>
	<20080727082141.6E00A1E401B@bag.python.org>
	<59f9c5160807270409v1920fa6bx85703a364631397d@mail.gmail.com>
Message-ID: <20080727162050.D53B51E400B@bag.python.org>

At 04:09 AM 7/27/2008, Danyelle Gragsone wrote:

>Aren't those different books? than PPftAB?

Your acronym has lost me, but _Programming Python for the Absolute 
Beginner_, 2nd ed. is essentially the same book as the much more 
expensive _Guide to Programming with Python_.

Dick
===================================================
Have you seen Kelie Feng's video introducing the terrific and free
IDE, Ulipad? <http://www.rcblue.com/u3/>
Get Ulipad 3.9 from <http://code.google.com/p/ulipad/downloads/list>
svn for the latest revision <http://ulipad.googlecode.com/svn/trunk/>
Mailing list for Ulipad: <http://groups-beta.google.com/group/ulipad>


From ladynikon at gmail.com  Sun Jul 27 20:16:47 2008
From: ladynikon at gmail.com (Danyelle Gragsone)
Date: Sun, 27 Jul 2008 14:16:47 -0400
Subject: [Tutor] Online class/education for Python?
In-Reply-To: <20080727162050.D53B51E400B@bag.python.org>
References: <721b21dc0807191141q3704c8f9jcc3790f838c87f60@mail.gmail.com>
	<ea979d70807231544o37fb3e00w9d27f3eb190cc058@mail.gmail.com>
	<59f9c5160807240430h64863d6eg5a8245b9d47bc8fd@mail.gmail.com>
	<78b3a9580807260143qed85701lc1ba4c6e398d48c@mail.gmail.com>
	<20080726141208.A1AF31E4013@bag.python.org>
	<78b3a9580807261014o3d2a2ef6s46f4efc75c9f74@mail.gmail.com>
	<g6gdvs$4ai$1@ger.gmane.org>
	<20080727082141.6E00A1E401B@bag.python.org>
	<59f9c5160807270409v1920fa6bx85703a364631397d@mail.gmail.com>
	<20080727162050.D53B51E400B@bag.python.org>
Message-ID: <59f9c5160807271116r1463159ocb834c3c74092cac@mail.gmail.com>

On Sun, Jul 27, 2008 at 7:54 AM, Dick Moores <rdm at rcblue.com> wrote:

> At 04:09 AM 7/27/2008, Danyelle Gragsone wrote:
>
>  Aren't those different books? than PPftAB?
>>
>
> Your acronym has lost me, but _Programming Python for the Absolute
> Beginner_, 2nd ed. is essentially the same book as the much more expensive
> _Guide to Programming with Python_.
>
> Dick


That acronym has been used throughout this thread to mean the same book you
are talking about _Programming Python for the Absolute Beginner_, 2nd.
essentially and the same isnt the exact same thing ;).

:)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080727/b020b6fa/attachment.htm>

From arsyed at gmail.com  Sun Jul 27 21:17:26 2008
From: arsyed at gmail.com (arsyed)
Date: Sun, 27 Jul 2008 15:17:26 -0400
Subject: [Tutor] newbie graphing question
In-Reply-To: <p06240801c4b21b28f90e@192.168.1.124>
References: <p06240801c4b21b28f90e@192.168.1.124>
Message-ID: <9a2cc7a70807271217m67a7c7d3i6b28bbec5df2caa9@mail.gmail.com>

On Sun, Jul 27, 2008 at 8:40 AM, Peter Petto <ppetto at apk.net> wrote:
> I'm about to try some Python programming for drawing simple geometric
> pictures (for math classes I teach) and was hoping to get some advice that
> will send me off in the best direction.
>
> I want to write programs that can draw figures with commands akin to
> point(x,y) to draw a point at coordinates (x,y), or segment (x1,y1,x2, y2)
> to draw a segment between points (x1, y1) and (x2, y2)?
>
> I'd appreciate recommendations as to the best facility or library to use to
> this end. I primarily use a Mac, but my students primarily use Windows.
>
> I'd love to hear any and all pointers or comments. Thanks!
>


Take a look at PiScript:

http://www.math.ubc.ca/~cass/piscript/docs/piscript.html

From jamesmithen at googlemail.com  Sun Jul 27 18:30:29 2008
From: jamesmithen at googlemail.com (James Mithen)
Date: Sun, 27 Jul 2008 17:30:29 +0100
Subject: [Tutor] plotting graphs
Message-ID: <9281a4a60807270930u36356ec9r8060ce11642f3040@mail.gmail.com>

I'd personally recommend the matplotlib plotting library.  It has a
matlab style plotting interface.  The only work required by you would
be to write a few one line functions that wrap the
matpotlib.pylab.plot() function call.  Your students on windows could
use idle as a back end (you have to have idle in interactive plotting
mode for it to work, but that is fine unless you are doing some pretty
heavy graphing).

James M


> On Sun, Jul 27, 2008 at 8:40 AM, Peter Petto <ppetto at apk.net> wrote:
>> I'm about to try some Python programming for drawing simple geometric
>> pictures (for math classes I teach) and was hoping to get some advice that
>> will send me off in the best direction.
>>
>> I want to write programs that can draw figures with commands akin to
>> point(x,y) to draw a point at coordinates (x,y), or segment (x1,y1,x2, y2)
>> to draw a segment between points (x1, y1) and (x2, y2)?
>>
>> I'd appreciate recommendations as to the best facility or library to use to
>> this end. I primarily use a Mac, but my students primarily use Windows.
>>
>> I'd love to hear any and all pointers or comments. Thanks!
>> --
>> ===
>> Peter Petto <ppetto at apk.net>
>> Bay Village, OH   tel: 440.249.4289
>>
>
> Hello Mr. Petto,
>
> I'd recommend the PyGame library. PyGame is a Python wrapper around the
> extraordinary SDL library. For an example program of what you might be looking
> for, take a look at:
>
> http://www.cs.iupui.edu/~aharris/pygame/ch05/paint.py
>
> The whole site has a lot of Python/PyGame examples:
> http://www.cs.iupui.edu/~aharris/pygame/
>
> Andy Harris is a CS professor at Indiana University-Perdue University
> Indianapolis,
> and is the author of several books, including Game Programming
> [ISBN-13: 978-0-470-06822-9], which is a fairly complete introduction
> and tutorial
> for PyGame.
>
> Happy Programming!
> --
> b h a a l u u at g m a i l dot c o m
> Kid on Bus: What are you gonna do today, Napoleon?
> Napoleon Dynamite: Whatever I feel like I wanna do. Gosh!
>
>
> ------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
> End of Tutor Digest, Vol 53, Issue 95
> *************************************
>

From rdm at rcblue.com  Sun Jul 27 18:13:48 2008
From: rdm at rcblue.com (Dick Moores)
Date: Sun, 27 Jul 2008 09:13:48 -0700
Subject: [Tutor] Online class/education for Python?
In-Reply-To: <ea979d70807270718l46a03fbx34e23fa7208fbfd1@mail.gmail.com>
References: <721b21dc0807191141q3704c8f9jcc3790f838c87f60@mail.gmail.com>
	<ea979d70807220427t3fdc99bfh4948f3287eb57867@mail.gmail.com>
	<59f9c5160807222038v1a8e7ff6wa7c2f2043c61d7e@mail.gmail.com>
	<ea979d70807231544o37fb3e00w9d27f3eb190cc058@mail.gmail.com>
	<59f9c5160807240430h64863d6eg5a8245b9d47bc8fd@mail.gmail.com>
	<78b3a9580807260143qed85701lc1ba4c6e398d48c@mail.gmail.com>
	<20080726141208.A1AF31E4013@bag.python.org>
	<78b3a9580807261014o3d2a2ef6s46f4efc75c9f74@mail.gmail.com>
	<g6gdvs$4ai$1@ger.gmane.org>
	<78b3a9580807270033r37f28819v31687367aaf7754c@mail.gmail.com>
	<ea979d70807270718l46a03fbx34e23fa7208fbfd1@mail.gmail.com>
Message-ID: <20080727231300.E15681E4013@bag.python.org>

At 07:18 AM 7/27/2008, bhaaluu wrote:

>So if
>a student goes through PPftAB2E, and wants to continue programming games,
>I'd recommend "Game Programming" by Andy Harris [ISBN-13: 978-0-470-06822-9].
>Game Programming is a fairly complete PyGame tutorial.

What do you think of _Beginning Game Development with Python and 
Pygame_, Apress, 2007?

Dick Moores
===================================================
Have you seen Kelie Feng's video introducing the terrific and free
IDE, Ulipad? <http://www.rcblue.com/u3/>
Get Ulipad 3.9 from <http://code.google.com/p/ulipad/downloads/list>
svn for the latest revision <http://ulipad.googlecode.com/svn/trunk/>
Mailing list for Ulipad: <http://groups-beta.google.com/group/ulipad>


From rdm at rcblue.com  Sun Jul 27 20:35:40 2008
From: rdm at rcblue.com (Dick Moores)
Date: Sun, 27 Jul 2008 11:35:40 -0700
Subject: [Tutor] Online class/education for Python?
In-Reply-To: <59f9c5160807271116r1463159ocb834c3c74092cac@mail.gmail.com
 >
References: <721b21dc0807191141q3704c8f9jcc3790f838c87f60@mail.gmail.com>
	<ea979d70807231544o37fb3e00w9d27f3eb190cc058@mail.gmail.com>
	<59f9c5160807240430h64863d6eg5a8245b9d47bc8fd@mail.gmail.com>
	<78b3a9580807260143qed85701lc1ba4c6e398d48c@mail.gmail.com>
	<20080726141208.A1AF31E4013@bag.python.org>
	<78b3a9580807261014o3d2a2ef6s46f4efc75c9f74@mail.gmail.com>
	<g6gdvs$4ai$1@ger.gmane.org>
	<20080727082141.6E00A1E401B@bag.python.org>
	<59f9c5160807270409v1920fa6bx85703a364631397d@mail.gmail.com>
	<20080727162050.D53B51E400B@bag.python.org>
	<59f9c5160807271116r1463159ocb834c3c74092cac@mail.gmail.com>
Message-ID: <20080728010429.81A411E4009@bag.python.org>

An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080727/f8ed558e/attachment.htm>

From pierre.dagenais at ncf.ca  Mon Jul 28 04:20:46 2008
From: pierre.dagenais at ncf.ca (Pierre Dagenais)
Date: Sun, 27 Jul 2008 22:20:46 -0400
Subject: [Tutor] newbie graphing question
In-Reply-To: <p06240801c4b21b28f90e@[192.168.1.124]>
References: <p06240801c4b21b28f90e@[192.168.1.124]>
Message-ID: <488D2CFE.60503@ncf.ca>

Peter Petto wrote:
> I'm about to try some Python programming for drawing simple geometric 
> pictures (for math classes I teach) and was hoping to get some advice 
> that will send me off in the best direction.
> 
> I want to write programs that can draw figures with commands akin to 
> point(x,y) to draw a point at coordinates (x,y), or segment (x1,y1,x2, 
> y2) to draw a segment between points (x1, y1) and (x2, y2)?
> 
> I'd appreciate recommendations as to the best facility or library to use 
> to this end. I primarily use a Mac, but my students primarily use Windows.
> 
> I'd love to hear any and all pointers or comments. Thanks!
> 
> 
Hi Peter,
I'm just trying to do the same, draw points and lines without having to 
spend the next six months learning a GUI environment and then finding 
I've been learning the wrong one all this time. Then I stumbled on these 
pages at py4fun, it's a quick and dirty introduction to the basics of 
Tkinter, just a few commands and you're in business. Hope that is what 
you're looking for,
> http://ibiblio.org/obp/py4fun/gui/tkPhone.html
> http://ibiblio.org/obp/py4fun/wave/wave.html




From wesbrooks at gmail.com  Mon Jul 28 11:16:47 2008
From: wesbrooks at gmail.com (Wesley Brooks)
Date: Mon, 28 Jul 2008 10:16:47 +0100
Subject: [Tutor] Creating a unicode string from bytes and % opperator
Message-ID: <eec9f8ee0807280216g67c4047dv6fe6f04ad4520263@mail.gmail.com>

Dear Users,

I'm trying to create a unicode character from two bytes. Unfortunatly
I'm getting a "UnicodeDecodeError". Can some one please suggest an
alternative way of doing what's bellow? In the example bellow the two
bytes have been converted into a string hex value, but they could just
as easily be an integer or binary value if either is easier to deal
with.

Python 2.4.3 - Enthought Edition 1.0.0 (#69, Aug  2 2006, 12:09:59) [MSC v.1310
32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> a = u"\u%s%s" %('0d', 'fe')
UnicodeDecodeError: 'unicodeescape' codec can't decode bytes in position 0-2: tr
uncated \uXXXX escape
>>>

Cheers,

Wesley Brooks.

From mail at timgolden.me.uk  Mon Jul 28 11:22:58 2008
From: mail at timgolden.me.uk (Tim Golden)
Date: Mon, 28 Jul 2008 10:22:58 +0100
Subject: [Tutor] Creating a unicode string from bytes and % opperator
In-Reply-To: <eec9f8ee0807280216g67c4047dv6fe6f04ad4520263@mail.gmail.com>
References: <eec9f8ee0807280216g67c4047dv6fe6f04ad4520263@mail.gmail.com>
Message-ID: <488D8FF2.9010702@timgolden.me.uk>

Wesley Brooks wrote:
> I'm trying to create a unicode character from two bytes. Unfortunatly
> I'm getting a "UnicodeDecodeError". Can some one please suggest an
> alternative way of doing what's bellow? In the example bellow the two
> bytes have been converted into a string hex value, but they could just
> as easily be an integer or binary value if either is easier to deal
> with.
> 
> Python 2.4.3 - Enthought Edition 1.0.0 (#69, Aug  2 2006, 12:09:59) [MSC v.1310
> 32 bit (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
>>>> a = u"\u%s%s" %('0d', 'fe')
> UnicodeDecodeError: 'unicodeescape' codec can't decode bytes in position 0-2: tr
> uncated \uXXXX escape

Nice try :)

Unfortunately, if you think about what's happening here, the
"string interpreter" bit of Python is getting to that
unicode-escape before the "%-processing" bit of Python.
So Python's trying --and failing-- to interpret \u%s%s as some sort of
bizarre unicode escape.

Can you not just use the unichr function?

TJG

From wesbrooks at gmail.com  Mon Jul 28 11:30:01 2008
From: wesbrooks at gmail.com (Wesley Brooks)
Date: Mon, 28 Jul 2008 10:30:01 +0100
Subject: [Tutor] Creating a unicode string from bytes and % opperator
In-Reply-To: <488D8FF2.9010702@timgolden.me.uk>
References: <eec9f8ee0807280216g67c4047dv6fe6f04ad4520263@mail.gmail.com>
	<488D8FF2.9010702@timgolden.me.uk>
Message-ID: <eec9f8ee0807280230j7e73a355s1d9701b9f652b595@mail.gmail.com>

Thanks Tim Golden,

That'll do the trick! Thought there must have been something simple for it!

Cheers,

Wesley Brooks

2008/7/28 Tim Golden <mail at timgolden.me.uk>:
> Wesley Brooks wrote:
>>
>> I'm trying to create a unicode character from two bytes. Unfortunatly
>> I'm getting a "UnicodeDecodeError". Can some one please suggest an
>> alternative way of doing what's bellow? In the example bellow the two
>> bytes have been converted into a string hex value, but they could just
>> as easily be an integer or binary value if either is easier to deal
>> with.
>>
>> Python 2.4.3 - Enthought Edition 1.0.0 (#69, Aug  2 2006, 12:09:59) [MSC
>> v.1310
>> 32 bit (Intel)] on win32
>> Type "help", "copyright", "credits" or "license" for more information.
>>>>>
>>>>> a = u"\u%s%s" %('0d', 'fe')
>>
>> UnicodeDecodeError: 'unicodeescape' codec can't decode bytes in position
>> 0-2: tr
>> uncated \uXXXX escape
>
> Nice try :)
>
> Unfortunately, if you think about what's happening here, the
> "string interpreter" bit of Python is getting to that
> unicode-escape before the "%-processing" bit of Python.
> So Python's trying --and failing-- to interpret \u%s%s as some sort of
> bizarre unicode escape.
>
> Can you not just use the unichr function?
>
> TJG
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From mail at timgolden.me.uk  Mon Jul 28 11:33:10 2008
From: mail at timgolden.me.uk (Tim Golden)
Date: Mon, 28 Jul 2008 10:33:10 +0100
Subject: [Tutor] Creating a unicode string from bytes and % opperator
In-Reply-To: <eec9f8ee0807280230j7e73a355s1d9701b9f652b595@mail.gmail.com>
References: <eec9f8ee0807280216g67c4047dv6fe6f04ad4520263@mail.gmail.com>	<488D8FF2.9010702@timgolden.me.uk>
	<eec9f8ee0807280230j7e73a355s1d9701b9f652b595@mail.gmail.com>
Message-ID: <488D9256.6050203@timgolden.me.uk>

Wesley Brooks wrote:
> Thanks Tim Golden,
> 
> That'll do the trick! Thought there must have been something simple for it!

To be perverse, you *could* have done it like this:

eval ("u'\u" + "%s%s'" % ("0d", "fe"))

But please don't :)

TJG

From bhaaluu at gmail.com  Mon Jul 28 15:49:06 2008
From: bhaaluu at gmail.com (bhaaluu)
Date: Mon, 28 Jul 2008 09:49:06 -0400
Subject: [Tutor] Online class/education for Python?
In-Reply-To: <20080727231300.E15681E4013@bag.python.org>
References: <721b21dc0807191141q3704c8f9jcc3790f838c87f60@mail.gmail.com>
	<ea979d70807231544o37fb3e00w9d27f3eb190cc058@mail.gmail.com>
	<59f9c5160807240430h64863d6eg5a8245b9d47bc8fd@mail.gmail.com>
	<78b3a9580807260143qed85701lc1ba4c6e398d48c@mail.gmail.com>
	<20080726141208.A1AF31E4013@bag.python.org>
	<78b3a9580807261014o3d2a2ef6s46f4efc75c9f74@mail.gmail.com>
	<g6gdvs$4ai$1@ger.gmane.org>
	<78b3a9580807270033r37f28819v31687367aaf7754c@mail.gmail.com>
	<ea979d70807270718l46a03fbx34e23fa7208fbfd1@mail.gmail.com>
	<20080727231300.E15681E4013@bag.python.org>
Message-ID: <ea979d70807280649r2ad52eb1h553818fb252768fc@mail.gmail.com>

On Sun, Jul 27, 2008 at 12:13 PM, Dick Moores <rdm at rcblue.com> wrote:
> At 07:18 AM 7/27/2008, bhaaluu wrote:
>
>> So if
>> a student goes through PPftAB2E, and wants to continue programming games,
>> I'd recommend "Game Programming" by Andy Harris [ISBN-13:
>> 978-0-470-06822-9].
>> Game Programming is a fairly complete PyGame tutorial.
>
> What do you think of _Beginning Game Development with Python and Pygame_,
> Apress, 2007?
>
> Dick Moores

The main difference between GAME PROGRAMMING and BEGINNING GAME DEVELOPMENT
is that the former deals with 2D scrolling arcade type games, using
PyGame; and the
latter gets into 3D games using PyGame and openGL (I think). I don't
have the McGugan
book, so I don't know for sure. You can take a look at a sample
chapter at Will's site:
http://www.willmcgugan.com/2007/10/04/free-chapter-of-beginning-game-development-with-python-and-pygame/
The publisher also has the source code from the book available.

Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m
Kid on Bus: What are you gonna do today, Napoleon?
Napoleon Dynamite: Whatever I feel like I wanna do. Gosh!

From rs.karthick at gmail.com  Mon Jul 28 17:56:41 2008
From: rs.karthick at gmail.com (Karthik)
Date: Mon, 28 Jul 2008 21:26:41 +0530
Subject: [Tutor] Memory error - how to manage large data sets?
Message-ID: <488dec4a.02066e0a.7632.fffff2c4@mx.google.com>

Hi,

 

I am new to Python programming, I was trying to work out a few problems in
order to grasp the knowledge gained after going through the basic chapters
on Python programming. I got stuck with a memory error.

 

Following is what I did,

 

1.     I need to find the sum of all numbers at even positions in the
Fibonacci series upto 2 million.

2.     I have used lists to achieve this.

3.     My program works good with smaller ranges. Say till 10,000 or even
100,000. However when I compute the sum for bigger ranges it gives me the
memory error.

4.     Also could someone tell me how to get the result in the form of an
exponent. For instance, I would prefer 10^5 rather  100000.

 

Thanks in advance,

Karthik

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080728/da6963ab/attachment.htm>

From alan.gauld at btinternet.com  Mon Jul 28 18:46:27 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 28 Jul 2008 17:46:27 +0100
Subject: [Tutor] Memory error - how to manage large data sets?
References: <488dec4a.02066e0a.7632.fffff2c4@mx.google.com>
Message-ID: <g6kt38$isa$1@ger.gmane.org>


"Karthik" <rs.karthick at gmail.com> wrote


> I am new to Python programming, I was trying to work out a few 
> problems in
> order to grasp the knowledge gained after going through the basic 
> chapters
> on Python programming. I got stuck with a memory error.

Always show us the full error text, it contains a lot of useful data.

It is usually helpful to show us the code too if not too long.
Alternatively post in on a web site such as pastebin.

> Following is what I did,
> 1.     I need to find the sum of all numbers at even positions in 
> the
> Fibonacci series upto 2 million.

Shouldn't be a problem.

> 2.     I have used lists to achieve this.

One list should suffice. (and you could do it without any lists...)

> 3.     My program works good with smaller ranges. Say till 10,000 or 
> even
> 100,000. However when I compute the sum for bigger ranges it gives 
> me the
> memory error.
>
> 4.     Also could someone tell me how to get the result in the form 
> of an
> exponent. For instance, I would prefer 10^5 rather  100000.

You can use string formatting using the %e or %g markers.
See my tutorial topic Simple Sequences for more info on format strings
or search the documentation.

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



From rs.karthick at gmail.com  Mon Jul 28 19:14:08 2008
From: rs.karthick at gmail.com (Karthik)
Date: Mon, 28 Jul 2008 22:44:08 +0530
Subject: [Tutor] Memory error - how to manage large data sets?
Message-ID: <488dfe6a.04506e0a.40cd.23a1@mx.google.com>

Forgot to include the following information,

 

Platform - win32

Version - 2.5.1

 

Error message:

 

Traceback (most recent call last):

  File "C:\Python25\programs\fibo.py", line 10, in <module>

    if i % 2 == 0:

MemoryError

 

Code:

 

fib = []

even = []

def fibonacci(x,y):

    return x+y

for i in range (0,1000000):

    if i < 2:

        fib.append(i)

    else:

        i = fib[i-1] + fib[i-2]

        if i % 2 == 0:

            fib.append(i)

            even.append(i)

        else:

            fib.append(i)

total = reduce(fibonacci,even)

print total

 

Any pointers would be of great help to me.

 

Regards,

Karthik

 

From: Karthik [mailto:rs.karthick at gmail.com] 
Sent: Monday, July 28, 2008 9:27 PM
To: 'tutor at python.org'
Subject: Memory error - how to manage large data sets?

 

Hi,

 

I am new to Python programming, I was trying to work out a few problems in
order to grasp the knowledge gained after going through the basic chapters
on Python programming. I got stuck with a memory error.

 

Following is what I did,

 

1.     I need to find the sum of all numbers at even positions in the
Fibonacci series upto 2 million.

2.     I have used lists to achieve this.

3.     My program works good with smaller ranges. Say till 10,000 or even
100,000. However when I compute the sum for bigger ranges it gives me the
memory error.

4.     Also could someone tell me how to get the result in the form of an
exponent. For instance, I would prefer 10^5 rather  100000.

 

Thanks in advance,

Karthik

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080728/ff9e0107/attachment-0001.htm>

From cfuller084 at thinkingplanet.net  Mon Jul 28 19:27:58 2008
From: cfuller084 at thinkingplanet.net (Chris Fuller)
Date: Mon, 28 Jul 2008 12:27:58 -0500
Subject: [Tutor] Memory error - how to manage large data sets?
In-Reply-To: <488dec4a.02066e0a.7632.fffff2c4@mx.google.com>
References: <488dec4a.02066e0a.7632.fffff2c4@mx.google.com>
Message-ID: <200807281227.58842.cfuller084@thinkingplanet.net>

On Monday 28 July 2008 10:56, Karthik wrote:
> Hi,
>
>
>
> I am new to Python programming, I was trying to work out a few problems in
> order to grasp the knowledge gained after going through the basic chapters
> on Python programming. I got stuck with a memory error.
>
>
>
> Following is what I did,
>
>
>
> 1.     I need to find the sum of all numbers at even positions in the
> Fibonacci series upto 2 million.
>
> 2.     I have used lists to achieve this.
>
> 3.     My program works good with smaller ranges. Say till 10,000 or even
> 100,000. However when I compute the sum for bigger ranges it gives me the
> memory error.
>
> 4.     Also could someone tell me how to get the result in the form of an
> exponent. For instance, I would prefer 10^5 rather  100000.
>
>
>
> Thanks in advance,
>
> Karthik

It sounds like you are storing all the fibonacci numbers as you generate them.  
Why?  You only need the previous two to find the next in the sequence.  The 
sum is a single number that you can add every other element in the sequence 
to.  You only need to store three numbers in memory.  Storing millions is 
wasteful, and doesn't scale very well.

To find an exponent, use the "**" operator.  For instance, 2**3 is 8, and 3**2 
is 9.

Cheers

From dyoo at cs.wpi.edu  Mon Jul 28 20:23:36 2008
From: dyoo at cs.wpi.edu (Danny Yoo)
Date: Mon, 28 Jul 2008 14:23:36 -0400
Subject: [Tutor] Memory error - how to manage large data sets?
In-Reply-To: <488dfe6a.04506e0a.40cd.23a1@mx.google.com>
References: <488dfe6a.04506e0a.40cd.23a1@mx.google.com>
Message-ID: <d06401780807281123o63347d9elaac1a9a48a921cb4@mail.gmail.com>

> 1.     I need to find the sum of all numbers at even positions in the
> Fibonacci series upto 2 million.
>
> 2.     I have used lists to achieve this.

I see.  You may want to produce a "sequence" or "iterator" of
fibonacci numbers rather than an explicit list.  As it is, your
machine does not have enough physical memory to hold the whole
sequence at once.

Python has a "generator" language feature that supports a style of
programming on infinite sequences.  You can find an introduction to
Python generators here:

    http://linuxgazette.net/100/pramode.html

From dsarmientos at gmail.com  Mon Jul 28 20:26:13 2008
From: dsarmientos at gmail.com (Daniel Sarmiento)
Date: Mon, 28 Jul 2008 13:26:13 -0500
Subject: [Tutor] Memory error - how to manage large data sets?
Message-ID: <d356a5240807281126t6bd27dc5y6ef411305a9f5f5a@mail.gmail.com>

Hi

I tried to run your code and checked (with top) the memory ussage and
it uses more than 2 Gb of memory.

I tried to modify the code a little bit to use less memory and came up
with this:

fib = {0:0,1:1}
even = []

def fibonacci(x,y):
   return x+y

for j in xrange (2,1000000):
    i = fib[j-1] + fib[j-2]
    if i % 2 == 0:
        even.append(i)
    fib = {j-1:fib[j-1], j:i}

total = reduce(fibonacci,even)
print total

First, I replaced range with xrange.
I figured that you only need the last two values in the fibonnaci
series to calculate the next value, so I replaced the fib list with a
dictionary to only store the last two values instead of the whole
series.

It looks like the progam still hangs and I did not notice any memory
imrovements when running it with 1 000 000

Am I wrong thinking that the modifications I made help use less memory?

> Date: Mon, 28 Jul 2008 22:44:08 +0530
> From: "Karthik" <rs.karthick at gmail.com>
> Subject: Re: [Tutor] Memory error - how to manage large data sets?
> To: <tutor at python.org>
> Message-ID: <488dfe6a.04506e0a.40cd.23a1 at mx.google.com>
> Content-Type: text/plain; charset="us-ascii"
>
> Forgot to include the following information,
>
>
>
> Platform - win32
>
> Version - 2.5.1
>
>
>
> Error message:
>
>
>
> Traceback (most recent call last):
>
>  File "C:\Python25\programs\fibo.py", line 10, in <module>
>
>    if i % 2 == 0:
>
> MemoryError
>
>
>
> Code:
>
>
>
> fib = []
>
> even = []
>
> def fibonacci(x,y):
>
>    return x+y
>
> for i in range (0,1000000):
>
>    if i < 2:
>
>        fib.append(i)
>
>    else:
>
>        i = fib[i-1] + fib[i-2]
>
>        if i % 2 == 0:
>
>            fib.append(i)
>
>            even.append(i)
>
>        else:
>
>            fib.append(i)
>
> total = reduce(fibonacci,even)
>
> print total
>
>
>
> Any pointers would be of great help to me.
>
>
>
> Regards,
>
> Karthik

From rdm at rcblue.com  Mon Jul 28 22:44:08 2008
From: rdm at rcblue.com (Dick Moores)
Date: Mon, 28 Jul 2008 13:44:08 -0700
Subject: [Tutor] Turtle problem: how to exit the .exe?
Message-ID: <20080728204423.A7BCB1E400C@bag.python.org>

Win XP, Python 2.51

The script is at <http://py77.python.pastebin.com/f414c8ce4>  It 
calls the Windows console to show the printed data.

I've successfully used PyInstaller to make an .exe for this.  For 
informed users, exiting the program before it finishes is easily and 
cleanly done by a Ctrl+Q on the console window.

But I'd like to make a version of the script that doesn't report any 
data. How can I write it so that the .exe can be easily exited by the 
user? If Tkinter instead of Turtle were involved, I could have an 
Exit button connected to command=root.quit .

Thanks,

Dick Moores


From jfabiani at yolo.com  Mon Jul 28 23:55:46 2008
From: jfabiani at yolo.com (johnf)
Date: Mon, 28 Jul 2008 14:55:46 -0700
Subject: [Tutor] login using PAM
Message-ID: <200807281455.46377.jfabiani@yolo.com>

I have been attempting to research the web on how python-pam works.  Does 
anyone have example code?
-- 
John Fabiani

From corbettt at dcn.davis.ca.us  Mon Jul 28 23:25:02 2008
From: corbettt at dcn.davis.ca.us (Thomas Corbett)
Date: Mon, 28 Jul 2008 14:25:02 -0700
Subject: [Tutor] Unable to Reconfigure IDLE
In-Reply-To: <488C834A.20805@timgolden.me.uk>
References: <EDB49B2F-EB91-4309-803D-17FFD8C87FDE@dcn.davis.ca.us>	<g6fhqk$tke$1@ger.gmane.org>
	<C18A9DD3-1B8A-4F47-854B-EF5503C6FD4F@dcn.davis.ca.us>
	<488C834A.20805@timgolden.me.uk>
Message-ID: <ACB137A5-A9EA-4ECC-9A6A-7165FF622C99@dcn.davis.ca.us>


On Jul 27, 2008, at 7:16 AM, Tim Golden wrote:

> Thomas Corbett wrote:
>> On Jul 26, 2008, at 9:02 AM, Alan Gauld wrote:
>>>
>>> "Thomas Corbett" <corbettt at dcn.davis.ca.us> wrote
>>>
>>>> Configured shell window to wrong size, now can't seem to find the  
>>>> menu  (Options > Configure) to resize the shell.
>>>
>>> Don't you just resize it then close it and the next time it opens
>>> it uses the new size?
>>>
>>> Thats how I thought it was supposed to work!
>>>
>>> Alan G
>>>
>>> _______________________________________________
>>> Tutor maillist  -  Tutor at python.org
>>> http://mail.python.org/mailman/listinfo/tutor
>> The window is too large to resize.
>
> I missed the beginning of this thread, but I assume that you
> mean its edges are off the visible screen so you can't use
> the mouse to grab the frame and resize it? If so, and if
> you're on Windows, you can resize with the keyboard:
> Alt-Space S will put you in Sizing mode; then use the
> cursor keys to move the edges in and out. Alternatively,
> Alt -Space M will put the window in Moving mode and, again,
> the cursor keys can be used to bring a corner into view
> and into range of the mouse.
>
> TJG
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

Running IDLE 1.2.2 under MacPython 2.5 on Mac OS X 5.1. Not aware of a  
similar option on Mac.


From alan.gauld at btinternet.com  Tue Jul 29 00:32:26 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 28 Jul 2008 23:32:26 +0100
Subject: [Tutor] Turtle problem: how to exit the .exe?
References: <20080728204423.A7BCB1E400C@bag.python.org>
Message-ID: <g6lhac$tn9$1@ger.gmane.org>


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

> But I'd like to make a version of the script that doesn't report any 
> data. How can I write it so that the .exe can be easily exited by 
> the user? If Tkinter instead of Turtle were involved, I could have 
> an Exit button connected to command=root.quit .

Tkinter is involved, turtle usesw Tkinter.

But to exit I would expect the standard Windows exit key
combination (Alt F4) to work fine?

Alan G 



From alan.gauld at btinternet.com  Tue Jul 29 01:09:30 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 29 Jul 2008 00:09:30 +0100
Subject: [Tutor] Memory error - how to manage large data sets?
References: <488dfe6a.04506e0a.40cd.23a1@mx.google.com>
Message-ID: <g6ljfm$438$1@ger.gmane.org>

"Karthik" <rs.karthick at gmail.com> wrote in message 
news:488dfe6a.04506e0a.40cd.23a1 at mx.google.com...
> Forgot to include the following information,
> Platform - win32
> Version - 2.5.1
> Error message:
> Traceback (most recent call last):
>  File "C:\Python25\programs\fibo.py", line 10, in <module>
>    if i % 2 == 0:
> MemoryError

OK, It does look like you bust your memory allocation.

> Code:
>
>
>
> fib = []
> even = []

You don't really need two lists.

> def fibonacci(x,y):
>    return x+y

And this isn't really the fibonacci function its an addition
which you don;t need(see below)

> for i in range (0,1000000):

This creates a 3rd list of 1 million numbers, so thats
3 million * the storage of one number. Still not enough
to trouble most PCs nowadays...

>    if i < 2:
>        fib.append(i)
>    else:
>        i = fib[i-1] + fib[i-2]
>        if i % 2 == 0:
>            fib.append(i)

You want to append to fib on every number not just on evens?
So just take this outside the if.

>            even.append(i)

You don't need this because we can extract the even numbers
when we do the summation later. All its doing it gobbling up space.

>        else:
>            fib.append(i)

dispense with the else and just put the fib append outside.
ie your code becomes

for i in xrange (0,1000000):  # xranmge should avoid the extra list
    if i >= 2:
        i = fib[i-1] + fib[i-2]
    fib.append(i)

> total = reduce(fibonacci,even)

You could use the sum() function in Python 2.5 but for
your purpose I'd propose using the fib list and using slicing
to select every second element:

>>> L = range(10)
>>> L[::2]
[0, 2, 4, 6, 8]
>>>

So you could use

total = sum(fib[::2])

and dispense with evens entirely

> Any pointers would be of great help to me.

Frankly I'm puzzled why its using so much RAM.
I'd expect resource usage to be around 20-30MB
tops. hmmm, OK a bit of experimentation shows
that the fibonacci series generates very big numbers
very quickly so each entry is a long number - a very
long number!

21000 characters for the 100,000th entry!

No wonder it blows up.

You have two choices - use floats, which might still
not be big enough! ... It isn't,  98500 out of 100000 entries
were infinite using floats! So you need to calculate the
total as you go without saving the values

Or buy a much, much bigger computer! :-)

PS I did all of that investigation using the >>> prompt.
Its a very useful tool for trying things out, I just generated
the list (using 100,000 entries) and examined the contents
using various list comprehensions and len() etc

HTH,

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



From rdm at rcblue.com  Tue Jul 29 01:12:08 2008
From: rdm at rcblue.com (Dick Moores)
Date: Mon, 28 Jul 2008 16:12:08 -0700
Subject: [Tutor] Turtle problem: how to exit the .exe?
In-Reply-To: <g6lhac$tn9$1@ger.gmane.org>
References: <20080728204423.A7BCB1E400C@bag.python.org>
	<g6lhac$tn9$1@ger.gmane.org>
Message-ID: <20080728231221.BDEF71E4012@bag.python.org>

At 03:32 PM 7/28/2008, Alan Gauld wrote:

>"Dick Moores" <rdm at rcblue.com> wrote
>
>>But I'd like to make a version of the script that doesn't report 
>>any data. How can I write it so that the .exe can be easily exited 
>>by the user? If Tkinter instead of Turtle were involved, I could 
>>have an Exit button connected to command=root.quit .
>
>Tkinter is involved, turtle usesw Tkinter.

Yes, I allowed for that when I made the .exe:
python Makespec.py 
-FKc  E:\PyInstaller\MyScripts\randomTriangles_wo_named_colorsV13.exe

>But to exit I would expect the standard Windows exit key
>combination (Alt F4) to work fine?

Yes, but no. Try it yourself. Please. 
<http://www.rcblue.com/Misc/randomTriangles_wo_named_colorsV13_no_console.exe>

Dick



From john at fouhy.net  Tue Jul 29 01:48:11 2008
From: john at fouhy.net (John Fouhy)
Date: Tue, 29 Jul 2008 11:48:11 +1200
Subject: [Tutor] Memory error - how to manage large data sets?
In-Reply-To: <d356a5240807281126t6bd27dc5y6ef411305a9f5f5a@mail.gmail.com>
References: <d356a5240807281126t6bd27dc5y6ef411305a9f5f5a@mail.gmail.com>
Message-ID: <5e58f2e40807281648g4621d37doda5db90436a78039@mail.gmail.com>

On 29/07/2008, Daniel Sarmiento <dsarmientos at gmail.com> wrote:
>  I tried to run your code and checked (with top) the memory ussage and
>  it uses more than 2 Gb of memory.
>
>  I tried to modify the code a little bit to use less memory and came up
>  with this:
>
>  fib = {0:0,1:1}
>
> even = []
>
>  def fibonacci(x,y):
>    return x+y
>
> for j in xrange (2,1000000):
>     i = fib[j-1] + fib[j-2]
>     if i % 2 == 0:
>         even.append(i)
>     fib = {j-1:fib[j-1], j:i}
>
>
>  total = reduce(fibonacci,even)
>  print total
>
>  It looks like the progam still hangs and I did not notice any memory
>  imrovements when running it with 1 000 000

Well, let's see.  You're still storing all the even fibonacci numbers
that you compute.  By the looks of things, one third of fibonacci
numbers are even, so that's about 333,333 numbers that we're storing.

How big do these numbers get?  There's a closed-form expression for
Fibonacci numbers; it's: fib(n) = (phi**n - (1-phi)**n)/sqrt(5), where
phi is the golden ratio (about 1.6).  1-phi is -0.6, so when n is
large, (1-phi)**n is practically zero.  So fib(n) is roughly
phi**n/sqrt(5).  These numbers will quickly get beyond the size of
normal integers, and into long integers.  I don't know how many bytes
a long integer takes up, but I guess we can estimate it by looking at
the log to base 2.

So let's consider the millionth Fibonacci number.  fib(1000000) ~=
phi**1000000/sqrt(5).
So log(fib(1000000)) ~= log(phi**1000000/sqrt(5)) = 1000000*log(phi) -
log(sqrt(5)).

Taking logs to base 2, we get:

>>> 1000000*log(phi, 2) - log(sqrt(5), 2)
694240.75266657001

In other words, the best possible representation of the millionth
Fibonacci number will take almost 700,000 bits, or around 85
kilobytes.  I don't know how Python long integers actually work; it
may take up more space than that.

Of course, that's just the biggest one we're working out.  Let's try
to work out how much space the first million will take up.  This is:

sum_{i=1}^{1000000} i*log(phi, 2) - log(sqrt(5), 2)

== -1000000*log(sqrt(5), 2) + log(phi, 2)*sum_{i=1}^{1000000} i

Remembering the formula for summing integers (n(n+1)/2), this is:

>>> -1000000*log(sqrt(5), 2) + log(phi, 2)*(1000000*1000001/2)
347120142972.21808

This is a number of bits; divide by 8 to get bytes; divide by 8*1024
to get kilobytes, etc:

>>> _/(8*1024*1024*1024)
40.410103156722393

So ... that's about 40 gigabytes worth of numbers in this list you're
trying to build.  Well, actually you're only storing a third of the
Fibonacci numbers (the even ones), so we can cut that down to thirteen
gigabytes.  Assuming my maths is correct and there's not too much
overhead in Python long integers :-)

(the solution, of course, is to avoid storing all those numbers in the
first place)

-- 
John.

From cfuller084 at thinkingplanet.net  Tue Jul 29 02:18:48 2008
From: cfuller084 at thinkingplanet.net (Chris Fuller)
Date: Mon, 28 Jul 2008 19:18:48 -0500
Subject: [Tutor] Memory error - how to manage large data sets?
In-Reply-To: <488dfe6a.04506e0a.40cd.23a1@mx.google.com>
References: <488dfe6a.04506e0a.40cd.23a1@mx.google.com>
Message-ID: <200807281918.48230.cfuller084@thinkingplanet.net>


There's no need to keep any lists.  The sum can be done on the fly, which is 
perhaps a bit slower, but takes a constant amount of ram.  Even storing every 
other element (or every third, which is what he's trying to do: the elements 
that are even numbers, not every other element.. See his example code, or 
Project Euler, problem two, which seems to be the original source) will still 
take a lot of ram.

Something like this:

a = 0
b = 1

total = 0

while True:
   c = a+b
   a = b
   b = c

  if c>1e6:
    break

  if c%2 == 0:
    total += c

print total

By the way,  working through those problems will really exercise your 
programming and math skills.  It's a great way to get started, if you enjoy 
those kind of puzzles.


Can you see why every third element must be even?
Cheers

From alan.gauld at btinternet.com  Tue Jul 29 02:18:53 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 29 Jul 2008 01:18:53 +0100
Subject: [Tutor] Memory error - how to manage large data sets?
References: <488dfe6a.04506e0a.40cd.23a1@mx.google.com>
	<g6ljfm$438$1@ger.gmane.org>
Message-ID: <g6lnhk$dmm$1@ger.gmane.org>

"Alan Gauld" <alan.gauld at btinternet.com> wrote

> were infinite using floats! So you need to calculate the
> total as you go without saving the values
> 

I got curious so wrote the following function:

>>> def fibtot(N):
...   f0,f1,tot = 0,1,1
...   for n in range(N):
...     f = f0 + f1
...     f0,f1 = f1,f
...     if n % 2 == 0: tot += f
...   return tot

and here are the results...

>>> len(str(fibtot(10000)))
2090
>>> len(str(fibtot(100000)))
20899
>>> len(str(fibtot(200000)))
41798
>>> len(str(fibtot(400000)))
83595
>>> len(str(fibtot(500000)))
104494
>>> len(str(fibtot(600000)))
125393
>>> len(str(fibtot(800000)))
167190
>>> len(str(fibtot(1000000)))
208988
>>>

So the final total contains nearly 209 thousand digits!
Thats a very, very big number... and it took 5 minutes 
to compute on my PC (Dual core 2.8GHz with 2G RAM)

Now I really must go to bed :-)

-- 
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/20080729/e87468ad/attachment.htm>

From alan.gauld at btinternet.com  Tue Jul 29 02:30:44 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 29 Jul 2008 01:30:44 +0100
Subject: [Tutor] Turtle problem: how to exit the .exe?
References: <20080728204423.A7BCB1E400C@bag.python.org><g6lhac$tn9$1@ger.gmane.org>
	<20080728231221.BDEF71E4012@bag.python.org>
Message-ID: <g6lo7r$f9k$1@ger.gmane.org>


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

>>Tkinter is involved, turtle usesw Tkinter.
>
> Yes, I allowed for that when I made the .exe:
> python Makespec.py -FKc 
> E:\PyInstaller\MyScripts\randomTriangles_wo_named_colorsV13.exe

Means nothing to me, I've never found a need to make an exe
from a python program... :-)

>>But to exit I would expect the standard Windows exit key
>>combination (Alt F4) to work fine?
>
> Yes, but no. Try it yourself. Please. 
> <http://www.rcblue.com/Misc/randomTriangles_wo_named_colorsV13_no_console.exe>

Very odd, I assume the python script when executed normally
doesn't exhibit such odd behaviour? The only way I could stop
it was to kill the process from Task Manager. Are you sure you
aren't generating some kind of autostart option in your exe
building tool?

I have no further ideas...

Alan G. 



From rdm at rcblue.com  Tue Jul 29 04:27:50 2008
From: rdm at rcblue.com (Dick Moores)
Date: Mon, 28 Jul 2008 19:27:50 -0700
Subject: [Tutor] Turtle problem: how to exit the .exe?
In-Reply-To: <g6lo7r$f9k$1@ger.gmane.org>
References: <20080728204423.A7BCB1E400C@bag.python.org>
	<g6lhac$tn9$1@ger.gmane.org>
	<20080728231221.BDEF71E4012@bag.python.org>
	<g6lo7r$f9k$1@ger.gmane.org>
Message-ID: <20080729022803.22D811E4004@bag.python.org>

At 05:30 PM 7/28/2008, Alan Gauld wrote:

>"Dick Moores" <rdm at rcblue.com> wrote
>
>>>Tkinter is involved, turtle usesw Tkinter.
>>
>>Yes, I allowed for that when I made the .exe:
>>python Makespec.py -FKc 
>>E:\PyInstaller\MyScripts\randomTriangles_wo_named_colorsV13.exe
>
>Means nothing to me, I've never found a need to make an exe
>from a python program... :-)
>
>>>But to exit I would expect the standard Windows exit key
>>>combination (Alt F4) to work fine?
>>
>>Yes, but no. Try it yourself. Please. 
>><http://www.rcblue.com/Misc/randomTriangles_wo_named_colorsV13_no_console.exe>
>
>Very odd, I assume the python script when executed normally
>doesn't exhibit such odd behaviour?

When I try to stop the script from running not by a Ctrl+Q on the 
console window, but on the Turtle window, the only way is to use the 
Task Manager.

>The only way I could stop
>it was to kill the process from Task Manager.

Yes.

>  Are you sure you
>aren't generating some kind of autostart option in your exe
>building tool?

Well, since the behavior of the .exe is exactly the same as that of 
the running script, I'd say that isn't happening.

>I have no further ideas...

Well, thanks for trying, Alan.

Dick



From dsarmientos at gmail.com  Tue Jul 29 05:48:35 2008
From: dsarmientos at gmail.com (Daniel Sarmiento)
Date: Mon, 28 Jul 2008 22:48:35 -0500
Subject: [Tutor] Memory error - how to manage large data sets?
Message-ID: <d356a5240807282048y67164aa8p2398abd4705f3aba@mail.gmail.com>

>(the solution, of course, is to avoid storing all those numbers in the
>first place)

I tried this:

fib = {0:0,1:1}
sum = 0

for j in xrange (2,1000000):
    i = fib[j-1] + fib[j-2]
    if i % 2 == 0:
        sum += i
    fib = {j-1:fib[j-1], j:i}

print sum

I guess it should come up with the right answer (i compared sum to the
total value for small values in the range and they were the same)

Just storing the value of the sum doesn't use that much memory and
prints the sum for (2, 1 million) but it takes a long time to compute.
I know there has to be a way better solution.

From muchanek at gmail.com  Tue Jul 29 08:31:52 2008
From: muchanek at gmail.com (kinuthiA muchanE)
Date: Tue, 29 Jul 2008 09:31:52 +0300
Subject: [Tutor] Tutor Digest, Vol 53, Issue 99
In-Reply-To: <mailman.7986.1217286743.920.tutor@python.org>
References: <mailman.7986.1217286743.920.tutor@python.org>
Message-ID: <1217313112.5761.7.camel@www.kinuthia.com>


On Tue, 2008-07-29 at 01:12 +0200, tutor-request at python.org wrote:
> Message: 3
> Date: Mon, 28 Jul 2008 13:26:13 -0500
> From: "Daniel Sarmiento" <dsarmientos at gmail.com>
> Subject: Re: [Tutor] Memory error - how to manage large data sets?
> To: tutor at python.org
> Message-ID:
>         <d356a5240807281126t6bd27dc5y6ef411305a9f5f5a at mail.gmail.com>
> Content-Type: text/plain; charset=ISO-8859-1
> 
> Hi
> 
> I tried to run your code and checked (with top) the memory ussage and
> it uses more than 2 Gb of memory.
> 
> I tried to modify the code a little bit to use less memory and came up
> with this:
> 
> fib = {0:0,1:1}
> even = []
> 
> def fibonacci(x,y):
>    return x+y
> 
> for j in xrange (2,1000000):
>     i = fib[j-1] + fib[j-2]
>     if i % 2 == 0:
>         even.append(i)
>     fib = {j-1:fib[j-1], j:i}
> 
> total = reduce(fibonacci,even)
> print total
> 
> First, I replaced range with xrange.
> I figured that you only need the last two values in the fibonnaci
> series to calculate the next value, so I replaced the fib list with a
> dictionary to only store the last two values instead of the whole
> series.
> 
> It looks like the progam still hangs and I did not notice any memory
> imrovements when running it with 1 000 000
> 
> Am I wrong thinking that the modifications I made help use less
> memory?
> 
I have realised that when you need to work with large numbers, lists are
slow and tend to gobble up bytes. Another thing try to be as simple as
possible :). This is how I would approach the problem, without using
lists. It produces the result instantly, even for large numbers like a
100, 000, 000.

def fibonacci()
    a = 0
    b = 1
    evenTotal = 0
    while a < 100000000:
        a,b = b,a+b
        if a%2 == 0:
    	    evenTotal += a
    print evenTotal

Does this help?
Kinuthia...


From alan.gauld at btinternet.com  Tue Jul 29 09:38:30 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 29 Jul 2008 08:38:30 +0100
Subject: [Tutor] Turtle problem: how to exit the .exe?
References: <20080728204423.A7BCB1E400C@bag.python.org><g6lhac$tn9$1@ger.gmane.org><20080728231221.BDEF71E4012@bag.python.org><g6lo7r$f9k$1@ger.gmane.org>
	<20080729022803.22D811E4004@bag.python.org>
Message-ID: <g6mh9t$7qr$1@ger.gmane.org>


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

>>Very odd, I assume the python script when executed normally
>>doesn't exhibit such odd behaviour?
>
> When I try to stop the script from running not by a Ctrl+Q on the 
> console window, but on the Turtle window, the only way is to use the 
> Task Manager.

OK, let's eliminate some variables and go back to getting
the python script working.

I've used turtle many times and never seen this behaviour
before. What does the code look like?

Alan G. 



From alan.gauld at btinternet.com  Tue Jul 29 09:44:40 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 29 Jul 2008 08:44:40 +0100
Subject: [Tutor] Tutor Digest, Vol 53, Issue 99
References: <mailman.7986.1217286743.920.tutor@python.org>
	<1217313112.5761.7.camel@www.kinuthia.com>
Message-ID: <g6mhlf$8p7$1@ger.gmane.org>

"kinuthiA muchanE" <muchanek at gmail.com> wrote

> I have realised that when you need to work with large numbers, lists 
> are
> slow and tend to gobble up bytes.

The lists are not particularly slow (obviously if you want to
traverse them they take longer for more members) and they
don't take up much more memory that the sum of the sizes
of whats in them.

The problem here is that the data items themselves are huge.
Around 20K per item. Thus a million times 20K is 20G!

> This is how I would approach the problem, without using
> lists.

Yep, we all seem to be pretty much in agreement :-)

> It produces the result instantly, even for large numbers like a
> 100, 000, 000.

Umm, not instantly on my PC... 1 million took 5 minutes,
I've no idea how long 100 million would take!

> def fibonacci()
>    a = 0
>    b = 1
>    evenTotal = 0
>    while a < 100000000:
>        a,b = b,a+b
>        if a%2 == 0:
>        evenTotal += a
>    print evenTotal

Alan G 



From rdm at rcblue.com  Tue Jul 29 10:51:49 2008
From: rdm at rcblue.com (Dick Moores)
Date: Tue, 29 Jul 2008 01:51:49 -0700
Subject: [Tutor] Turtle problem: how to exit the .exe?
In-Reply-To: <g6mh9t$7qr$1@ger.gmane.org>
References: <20080728204423.A7BCB1E400C@bag.python.org>
	<g6lhac$tn9$1@ger.gmane.org>
	<20080728231221.BDEF71E4012@bag.python.org>
	<g6lo7r$f9k$1@ger.gmane.org>
	<20080729022803.22D811E4004@bag.python.org>
	<g6mh9t$7qr$1@ger.gmane.org>
Message-ID: <20080729085202.D870B1E400B@bag.python.org>

At 12:38 AM 7/29/2008, Alan Gauld wrote:

>"Dick Moores" <rdm at rcblue.com> wrote
>
>>>Very odd, I assume the python script when executed normally
>>>doesn't exhibit such odd behaviour?
>>
>>When I try to stop the script from running not by a Ctrl+Q on the 
>>console window, but on the Turtle window, the only way is to use 
>>the Task Manager.
>
>OK, let's eliminate some variables and go back to getting
>the python script working.

Remember, it does work.

>I've used turtle many times and never seen this behaviour
>before. What does the code look like?

<http://py77.python.pastebin.com/f414c8ce4>

Dick
===================================================
Have you seen Kelie Feng's video introducing the terrific and free
IDE, Ulipad? <http://www.rcblue.com/u3/>
Get Ulipad 3.9 from <http://code.google.com/p/ulipad/downloads/list>
svn for the latest revision <http://ulipad.googlecode.com/svn/trunk/>
Mailing list for Ulipad: <http://groups-beta.google.com/group/ulipad> 


From kent37 at tds.net  Tue Jul 29 12:22:03 2008
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 29 Jul 2008 06:22:03 -0400
Subject: [Tutor] Turtle problem: how to exit the .exe?
In-Reply-To: <20080728204423.A7BCB1E400C@bag.python.org>
References: <20080728204423.A7BCB1E400C@bag.python.org>
Message-ID: <1c2a2c590807290322y154a8201x165f52cb3bda45ea@mail.gmail.com>

On Mon, Jul 28, 2008 at 4:44 PM, Dick Moores <rdm at rcblue.com> wrote:
> Win XP, Python 2.51
>
> The script is at <http://py77.python.pastebin.com/f414c8ce4>  It calls the
> Windows console to show the printed data.
>
> I've successfully used PyInstaller to make an .exe for this.  For informed
> users, exiting the program before it finishes is easily and cleanly done by
> a Ctrl+Q on the console window.
>
> But I'd like to make a version of the script that doesn't report any data.
> How can I write it so that the .exe can be easily exited by the user? If
> Tkinter instead of Turtle were involved, I could have an Exit button
> connected to command=root.quit .

Take a look at the source for the turtle module (in
Python/Lib/lib-tk/turtle.py I think). It has a global _root object
which is the Tk instance.

You could make your own Pen class, subclassing from RawPen, that makes
whatever kind of window you would prefer. Then instead of using the
module functions forward(), down(), etc - which just delegate to a
global Pen instance - make an instance of your own pen and draw with
that.

Kent

From ppetto at apk.net  Tue Jul 29 12:58:25 2008
From: ppetto at apk.net (Peter Petto)
Date: Tue, 29 Jul 2008 06:58:25 -0400
Subject: [Tutor] newbie graphing question
In-Reply-To: <p06240801c4b21b28f90e@[192.168.1.124]>
References: <p06240801c4b21b28f90e@[192.168.1.124]>
Message-ID: <p06240804c4b4a5812361@[137.148.110.157]>

An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080729/199d65fe/attachment.htm>

From cfuller084 at thinkingplanet.net  Tue Jul 29 14:23:19 2008
From: cfuller084 at thinkingplanet.net (Chris Fuller)
Date: Tue, 29 Jul 2008 07:23:19 -0500
Subject: [Tutor] Memory error - how to manage large data sets?
In-Reply-To: <d356a5240807282048y67164aa8p2398abd4705f3aba@mail.gmail.com>
References: <d356a5240807282048y67164aa8p2398abd4705f3aba@mail.gmail.com>
Message-ID: <200807290723.19855.cfuller084@thinkingplanet.net>


The original post was a little ambiguous: "I need to find the sum of all 
numbers at even positions in the Fibonacci series upto 2 million."

But the project euler page 
(http://projecteuler.net/index.php?section=problems&id=2) is clear: "Find the 
sum of all the even-valued terms in the sequence which do not exceed four 
million."

Depending on which value you are after, it may not be necessary to enumerate a 
million terms of the fibonacci sequence.  In fact, only about thirty are 
needed.

Now if you want to do the harder problem, I suggest using GMP or some other 
Numerical extension, and not Python :)

Or play some interesting math tricks.  The wikipedia page on fibonaccis lists 
a lot of identities that could be exploited in intriguing ways.

Cheers

From muchanek at gmail.com  Tue Jul 29 14:37:00 2008
From: muchanek at gmail.com (kinuthiA muchanE)
Date: Tue, 29 Jul 2008 15:37:00 +0300
Subject: [Tutor] Memroy Error - how to manage large data sets?
In-Reply-To: <mailman.59.1217325614.25661.tutor@python.org>
References: <mailman.59.1217325614.25661.tutor@python.org>
Message-ID: <1217335020.5761.27.camel@www.kinuthia.com>


On Tue, 2008-07-29 at 12:00 +0200, tutor-request at python.org wrote:
> Message: 2
> Date: Tue, 29 Jul 2008 08:44:40 +0100
> From: "Alan Gauld" <alan.gauld at btinternet.com>
> Subject: Re: [Tutor] Tutor Digest, Vol 53, Issue 99
> To: tutor at python.org
> Message-ID: <g6mhlf$8p7$1 at ger.gmane.org>
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
>         reply-type=original
> 
> "kinuthiA muchanE" <muchanek at gmail.com> wrote
> 
> > I have realised that when you need to work with large numbers,
> lists 
> > are
> > slow and tend to gobble up bytes.
> 
> The lists are not particularly slow (obviously if you want to
> traverse them they take longer for more members) and they
> don't take up much more memory that the sum of the sizes
> of whats in them.
> 
> The problem here is that the data items themselves are huge.
> Around 20K per item. Thus a million times 20K is 20G!
> 
> > This is how I would approach the problem, without using
> > lists.
> 
> Yep, we all seem to be pretty much in agreement :-)
> 
> > It produces the result instantly, even for large numbers like a
> > 100, 000, 000.
> 
> Umm, not instantly on my PC... 1 million took 5 minutes,
> I've no idea how long 100 million would take!
I think the question is to calculate the sum of all even numbers in the
Fibonacci series which do not exceed a million, not the millionth term. 
Number 25 on Project Euler which asks for first term in the Fibonacci
series to contain 1000 digits, is the term-wise question ;)
> 
> > def fibonacci()
> >    a = 0
> >    b = 1
> >    evenTotal = 0
> >    while a < 100000000:
> >        a,b = b,a+b
> >        if a%2 == 0:
> >        evenTotal += a
> >    print evenTotal
> 
> Alan G 
> 
> 
> 
> 
> ------------------------


From rs.karthick at gmail.com  Tue Jul 29 16:35:58 2008
From: rs.karthick at gmail.com (Karthik Swaminathan)
Date: Tue, 29 Jul 2008 20:05:58 +0530
Subject: [Tutor] Memory Error problem solved
Message-ID: <67db0bf0807290735g3561ece5m3bf381b23c0e9f15@mail.gmail.com>

I was amazed by the response of the Python community. Hats off to all. I
stopped using the lists and got the issue resolved using just the
variables. Nevertheless, i learned a lot by starting this thread.

Thanks a million to Alan, Chris, John for spending your quality time in
helping this newbie.

Hope i havent spoiled Alan's sleep much.


On 7/29/08, tutor-request at python.org <tutor-request at python.org> wrote:
>
> Send Tutor mailing list submissions to
>        tutor at python.org
>
> To subscribe or unsubscribe via the World Wide Web, visit
>        http://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body 'help' to
>        tutor-request at python.org
>
> You can reach the person managing the list at
>        tutor-owner at python.org
>
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Tutor digest..."
>
>
> Today's Topics:
>
>   1. Re: Memory error - how to manage large data sets? (John Fouhy)
>   2. Re: Memory error - how to manage large data sets? (Chris Fuller)
>   3. Re: Memory error - how to manage large data sets? (Alan Gauld)
>   4. Re: Turtle problem: how to exit the .exe? (Alan Gauld)
>   5. Re: Turtle problem: how to exit the .exe? (Dick Moores)
>   6. Re: Memory error - how to manage large data sets?
>      (Daniel Sarmiento)
>   7. Re: Tutor Digest, Vol 53, Issue 99 (kinuthiA muchanE)
>
>
> ----------------------------------------------------------------------
>
> Message: 1
> Date: Tue, 29 Jul 2008 11:48:11 +1200
> From: "John Fouhy" <john at fouhy.net>
> Subject: Re: [Tutor] Memory error - how to manage large data sets?
> To: "Daniel Sarmiento" <dsarmientos at gmail.com>
> Cc: tutor at python.org
> Message-ID:
>        <5e58f2e40807281648g4621d37doda5db90436a78039 at mail.gmail.com>
> Content-Type: text/plain; charset=ISO-8859-1
>
> On 29/07/2008, Daniel Sarmiento <dsarmientos at gmail.com> wrote:
> >  I tried to run your code and checked (with top) the memory ussage and
> >  it uses more than 2 Gb of memory.
> >
> >  I tried to modify the code a little bit to use less memory and came up
> >  with this:
> >
> >  fib = {0:0,1:1}
> >
> > even = []
> >
> >  def fibonacci(x,y):
> >    return x+y
> >
> > for j in xrange (2,1000000):
> >     i = fib[j-1] + fib[j-2]
> >     if i % 2 == 0:
> >         even.append(i)
> >     fib = {j-1:fib[j-1], j:i}
> >
> >
> >  total = reduce(fibonacci,even)
> >  print total
> >
> >  It looks like the progam still hangs and I did not notice any memory
> >  imrovements when running it with 1 000 000
>
> Well, let's see.  You're still storing all the even fibonacci numbers
> that you compute.  By the looks of things, one third of fibonacci
> numbers are even, so that's about 333,333 numbers that we're storing.
>
> How big do these numbers get?  There's a closed-form expression for
> Fibonacci numbers; it's: fib(n) = (phi**n - (1-phi)**n)/sqrt(5), where
> phi is the golden ratio (about 1.6).  1-phi is -0.6, so when n is
> large, (1-phi)**n is practically zero.  So fib(n) is roughly
> phi**n/sqrt(5).  These numbers will quickly get beyond the size of
> normal integers, and into long integers.  I don't know how many bytes
> a long integer takes up, but I guess we can estimate it by looking at
> the log to base 2.
>
> So let's consider the millionth Fibonacci number.  fib(1000000) ~=
> phi**1000000/sqrt(5).
> So log(fib(1000000)) ~= log(phi**1000000/sqrt(5)) = 1000000*log(phi) -
> log(sqrt(5)).
>
> Taking logs to base 2, we get:
>
> >>> 1000000*log(phi, 2) - log(sqrt(5), 2)
> 694240.75266657001
>
> In other words, the best possible representation of the millionth
> Fibonacci number will take almost 700,000 bits, or around 85
> kilobytes.  I don't know how Python long integers actually work; it
> may take up more space than that.
>
> Of course, that's just the biggest one we're working out.  Let's try
> to work out how much space the first million will take up.  This is:
>
> sum_{i=1}^{1000000} i*log(phi, 2) - log(sqrt(5), 2)
>
> == -1000000*log(sqrt(5), 2) + log(phi, 2)*sum_{i=1}^{1000000} i
>
> Remembering the formula for summing integers (n(n+1)/2), this is:
>
> >>> -1000000*log(sqrt(5), 2) + log(phi, 2)*(1000000*1000001/2)
> 347120142972.21808
>
> This is a number of bits; divide by 8 to get bytes; divide by 8*1024
> to get kilobytes, etc:
>
> >>> _/(8*1024*1024*1024)
> 40.410103156722393
>
> So ... that's about 40 gigabytes worth of numbers in this list you're
> trying to build.  Well, actually you're only storing a third of the
> Fibonacci numbers (the even ones), so we can cut that down to thirteen
> gigabytes.  Assuming my maths is correct and there's not too much
> overhead in Python long integers :-)
>
> (the solution, of course, is to avoid storing all those numbers in the
> first place)
>
> --
> John.
>
>
> ------------------------------
>
> Message: 2
> Date: Mon, 28 Jul 2008 19:18:48 -0500
> From: Chris Fuller <cfuller084 at thinkingplanet.net>
> Subject: Re: [Tutor] Memory error - how to manage large data sets?
> To: tutor at python.org
> Message-ID: <200807281918.48230.cfuller084 at thinkingplanet.net>
> Content-Type: text/plain;  charset="utf-8"
>
>
> There's no need to keep any lists.  The sum can be done on the fly, which
> is
> perhaps a bit slower, but takes a constant amount of ram.  Even storing
> every
> other element (or every third, which is what he's trying to do: the
> elements
> that are even numbers, not every other element.. See his example code, or
> Project Euler, problem two, which seems to be the original source) will
> still
> take a lot of ram.
>
> Something like this:
>
> a = 0
> b = 1
>
> total = 0
>
> while True:
>   c = a+b
>   a = b
>   b = c
>
> if c>1e6:
>    break
>
> if c%2 == 0:
>    total += c
>
> print total
>
> By the way,  working through those problems will really exercise your
> programming and math skills.  It's a great way to get started, if you enjoy
> those kind of puzzles.
>
>
> Can you see why every third element must be even?
> Cheers
>
>
> ------------------------------
>
> Message: 3
> Date: Tue, 29 Jul 2008 01:18:53 +0100
> From: "Alan Gauld" <alan.gauld at btinternet.com>
> Subject: Re: [Tutor] Memory error - how to manage large data sets?
> To: tutor at python.org
> Message-ID: <g6lnhk$dmm$1 at ger.gmane.org>
> Content-Type: text/plain; charset="iso-8859-1"
>
> "Alan Gauld" <alan.gauld at btinternet.com> wrote
>
> > were infinite using floats! So you need to calculate the
> > total as you go without saving the values
> >
>
> I got curious so wrote the following function:
>
> >>> def fibtot(N):
> ...   f0,f1,tot = 0,1,1
> ...   for n in range(N):
> ...     f = f0 + f1
> ...     f0,f1 = f1,f
> ...     if n % 2 == 0: tot += f
> ...   return tot
>
> and here are the results...
>
> >>> len(str(fibtot(10000)))
> 2090
> >>> len(str(fibtot(100000)))
> 20899
> >>> len(str(fibtot(200000)))
> 41798
> >>> len(str(fibtot(400000)))
> 83595
> >>> len(str(fibtot(500000)))
> 104494
> >>> len(str(fibtot(600000)))
> 125393
> >>> len(str(fibtot(800000)))
> 167190
> >>> len(str(fibtot(1000000)))
> 208988
> >>>
>
> So the final total contains nearly 209 thousand digits!
> Thats a very, very big number... and it took 5 minutes
> to compute on my PC (Dual core 2.8GHz with 2G RAM)
>
> Now I really must go to bed :-)
>
> --
> 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/20080729/e87468ad/attachment-0001.htm
> >
>
> ------------------------------
>
> Message: 4
> Date: Tue, 29 Jul 2008 01:30:44 +0100
> From: "Alan Gauld" <alan.gauld at btinternet.com>
> Subject: Re: [Tutor] Turtle problem: how to exit the .exe?
> To: tutor at python.org
> Message-ID: <g6lo7r$f9k$1 at ger.gmane.org>
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
>        reply-type=response
>
>
> "Dick Moores" <rdm at rcblue.com> wrote
>
> >>Tkinter is involved, turtle usesw Tkinter.
> >
> > Yes, I allowed for that when I made the .exe:
> > python Makespec.py -FKc
> > E:\PyInstaller\MyScripts\randomTriangles_wo_named_colorsV13.exe
>
> Means nothing to me, I've never found a need to make an exe
> from a python program... :-)
>
> >>But to exit I would expect the standard Windows exit key
> >>combination (Alt F4) to work fine?
> >
> > Yes, but no. Try it yourself. Please.
> > <
> http://www.rcblue.com/Misc/randomTriangles_wo_named_colorsV13_no_console.exe
> >
>
> Very odd, I assume the python script when executed normally
> doesn't exhibit such odd behaviour? The only way I could stop
> it was to kill the process from Task Manager. Are you sure you
> aren't generating some kind of autostart option in your exe
> building tool?
>
> I have no further ideas...
>
> Alan G.
>
>
>
>
> ------------------------------
>
> Message: 5
> Date: Mon, 28 Jul 2008 19:27:50 -0700
> From: Dick Moores <rdm at rcblue.com>
> Subject: Re: [Tutor] Turtle problem: how to exit the .exe?
> To: tutor at python.org
> Message-ID: <20080729022803.22D811E4004 at bag.python.org>
> Content-Type: text/plain; charset="us-ascii"; format=flowed
>
> At 05:30 PM 7/28/2008, Alan Gauld wrote:
>
> >"Dick Moores" <rdm at rcblue.com> wrote
> >
> >>>Tkinter is involved, turtle usesw Tkinter.
> >>
> >>Yes, I allowed for that when I made the .exe:
> >>python Makespec.py -FKc
> >>E:\PyInstaller\MyScripts\randomTriangles_wo_named_colorsV13.exe
> >
> >Means nothing to me, I've never found a need to make an exe
> >from a python program... :-)
> >
> >>>But to exit I would expect the standard Windows exit key
> >>>combination (Alt F4) to work fine?
> >>
> >>Yes, but no. Try it yourself. Please.
> >><
> http://www.rcblue.com/Misc/randomTriangles_wo_named_colorsV13_no_console.exe
> >
> >
> >Very odd, I assume the python script when executed normally
> >doesn't exhibit such odd behaviour?
>
> When I try to stop the script from running not by a Ctrl+Q on the
> console window, but on the Turtle window, the only way is to use the
> Task Manager.
>
> >The only way I could stop
> >it was to kill the process from Task Manager.
>
> Yes.
>
> >  Are you sure you
> >aren't generating some kind of autostart option in your exe
> >building tool?
>
> Well, since the behavior of the .exe is exactly the same as that of
> the running script, I'd say that isn't happening.
>
> >I have no further ideas...
>
> Well, thanks for trying, Alan.
>
> Dick
>
>
>
>
> ------------------------------
>
> Message: 6
> Date: Mon, 28 Jul 2008 22:48:35 -0500
> From: "Daniel Sarmiento" <dsarmientos at gmail.com>
> Subject: Re: [Tutor] Memory error - how to manage large data sets?
> To: tutor at python.org
> Message-ID:
>        <d356a5240807282048y67164aa8p2398abd4705f3aba at mail.gmail.com>
> Content-Type: text/plain; charset=ISO-8859-1
>
> >(the solution, of course, is to avoid storing all those numbers in the
> >first place)
>
> I tried this:
>
> fib = {0:0,1:1}
> sum = 0
>
> for j in xrange (2,1000000):
>    i = fib[j-1] + fib[j-2]
>    if i % 2 == 0:
>        sum += i
>    fib = {j-1:fib[j-1], j:i}
>
> print sum
>
> I guess it should come up with the right answer (i compared sum to the
> total value for small values in the range and they were the same)
>
> Just storing the value of the sum doesn't use that much memory and
> prints the sum for (2, 1 million) but it takes a long time to compute.
> I know there has to be a way better solution.
>
>
> ------------------------------
>
> Message: 7
> Date: Tue, 29 Jul 2008 09:31:52 +0300
> From: kinuthiA muchanE <muchanek at gmail.com>
> Subject: Re: [Tutor] Tutor Digest, Vol 53, Issue 99
> To: tutor at python.org
> Message-ID: <1217313112.5761.7.camel at www.kinuthia.com>
> Content-Type: text/plain
>
>
> On Tue, 2008-07-29 at 01:12 +0200, tutor-request at python.org wrote:
> > Message: 3
> > Date: Mon, 28 Jul 2008 13:26:13 -0500
> > From: "Daniel Sarmiento" <dsarmientos at gmail.com>
> > Subject: Re: [Tutor] Memory error - how to manage large data sets?
> > To: tutor at python.org
> > Message-ID:
> >         <d356a5240807281126t6bd27dc5y6ef411305a9f5f5a at mail.gmail.com>
> > Content-Type: text/plain; charset=ISO-8859-1
> >
> > Hi
> >
> > I tried to run your code and checked (with top) the memory ussage and
> > it uses more than 2 Gb of memory.
> >
> > I tried to modify the code a little bit to use less memory and came up
> > with this:
> >
> > fib = {0:0,1:1}
> > even = []
> >
> > def fibonacci(x,y):
> >    return x+y
> >
> > for j in xrange (2,1000000):
> >     i = fib[j-1] + fib[j-2]
> >     if i % 2 == 0:
> >         even.append(i)
> >     fib = {j-1:fib[j-1], j:i}
> >
> > total = reduce(fibonacci,even)
> > print total
> >
> > First, I replaced range with xrange.
> > I figured that you only need the last two values in the fibonnaci
> > series to calculate the next value, so I replaced the fib list with a
> > dictionary to only store the last two values instead of the whole
> > series.
> >
> > It looks like the progam still hangs and I did not notice any memory
> > imrovements when running it with 1 000 000
> >
> > Am I wrong thinking that the modifications I made help use less
> > memory?
> >
> I have realised that when you need to work with large numbers, lists are
> slow and tend to gobble up bytes. Another thing try to be as simple as
> possible :). This is how I would approach the problem, without using
> lists. It produces the result instantly, even for large numbers like a
> 100, 000, 000.
>
> def fibonacci()
>    a = 0
>    b = 1
>    evenTotal = 0
>    while a < 100000000:
>        a,b = b,a+b
>        if a%2 == 0:
>            evenTotal += a
>    print evenTotal
>
> Does this help?
> Kinuthia...
>
>
>
> ------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
> End of Tutor Digest, Vol 53, Issue 100
> **************************************
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080729/1f77c0a8/attachment-0001.htm>

From thorpmj07 at cvxmck.edu.au  Tue Jul 29 13:27:47 2008
From: thorpmj07 at cvxmck.edu.au (Morgan Thorpe)
Date: Tue, 29 Jul 2008 21:27:47 +1000
Subject: [Tutor] (no subject)
Message-ID: <ADC81E78CCB7314284086D57C0C6E2A3F99CE34D8A@suppmsg01.supp.bne.catholic.edu.au>

Hello.

I'm am very new to the whole programming sence.
I am trying to catch on but as soon as i want to write a program i've been told to use like 'notepad' in windows XP and save it as a .py file
i have gotten this far. Am i wrong so far?
If i am right why is it that i can't run it in anyway besides it opening in 'notepad' i've tried opening with Python but it doesn't work.

Thanks,
   Morgan

-- 
This message has been scanned for viruses and dangerous content by the BCEC Security Gateway, and is believed to be clean. Brisbane Catholic Education however gives no warranties that this e-mail is free from computer viruses or other defects. Except for responsibilities implied by law that cannot be excluded, Brisbane Catholic Education, its employees and agents will not be responsible for any loss, damage or consequence arising from this e-mail.


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080729/89f7ddd9/attachment.htm>

From noufal at nibrahim.net.in  Tue Jul 29 18:05:37 2008
From: noufal at nibrahim.net.in (Noufal Ibrahim)
Date: Tue, 29 Jul 2008 21:35:37 +0530
Subject: [Tutor] (no subject)
In-Reply-To: <ADC81E78CCB7314284086D57C0C6E2A3F99CE34D8A@suppmsg01.supp.bne.catholic.edu.au>
References: <ADC81E78CCB7314284086D57C0C6E2A3F99CE34D8A@suppmsg01.supp.bne.catholic.edu.au>
Message-ID: <488F3FD1.7080306@nibrahim.net.in>

Morgan Thorpe wrote:
> Hello.
>  
> I'm am very new to the whole programming sence.

Welcome. :)

> I am trying to catch on but as soon as i want to write a program i've 
> been told to use like 'notepad' in windows XP and save it as a .py file
> i have gotten this far. Am i wrong so far?

It's fine so far. Computer programs (especially ones in python) are text 
files which are formatted in a specific way which can be understood and 
executed by Python.

When you write your program, you use an editor like notepad and save the 
program as a .py file.

You're okay this far. The next stage is to ask Python to execute this 
program. You do that by typing
python program.py
and hitting enter.

> If i am right why is it that i can't run it in anyway besides it opening 
> in 'notepad' i've tried opening with Python but it doesn't work.

How have you tried opening it in python? Can you show us your program?


P.S. It's a good idea to use a proper Subject line for your mail. :)

-- 
~noufal
http://nibrahim.net.in/

From spython01 at gmail.com  Tue Jul 29 18:06:43 2008
From: spython01 at gmail.com (S Python)
Date: Tue, 29 Jul 2008 12:06:43 -0400
Subject: [Tutor] (no subject)
In-Reply-To: <ADC81E78CCB7314284086D57C0C6E2A3F99CE34D8A@suppmsg01.supp.bne.catholic.edu.au>
References: <ADC81E78CCB7314284086D57C0C6E2A3F99CE34D8A@suppmsg01.supp.bne.catholic.edu.au>
Message-ID: <50a597410807290906t66f18aedie772986c06c3a05f@mail.gmail.com>

Hi Morgan,

Have you installed Python on your computer?  If you are using Microsoft
Windows, you can download and install Python from here:
http://python.org/download/releases/2.5.2/
and select "python-2.5.2.msi".

Once it's installed, you should have a directory on your machine called
"C:\python25".  If you save your program with a .py extension in that folder
(for example, call it morgan.py), then all you have to do is open a command
window (Start > Run and enter "cmd"), go to the C:\python25 directory, and
type:
python morgan.py

Personally, if you are just staring out to program, I would recommend using
the Python shell that comes with the package I referred to.  Alan's
tutorial, found here:
http://www.freenetpages.co.uk/hp/alan.gauld/

is very helpful, as is this site, which is what I used to start learning
Python:
http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/

Hope that helps.  Good luck!

Samir


On Tue, Jul 29, 2008 at 7:27 AM, Morgan Thorpe <thorpmj07 at cvxmck.edu.au>wrote:

>  Hello.
>
> I'm am very new to the whole programming sence.
> I am trying to catch on but as soon as i want to write a program i've been
> told to use like 'notepad' in windows XP and save it as a .py file
> i have gotten this far. Am i wrong so far?
> If i am right why is it that i can't run it in anyway besides it opening in
> 'notepad' i've tried opening with Python but it doesn't work.
>
> Thanks,
>    Morgan
> --
> This message has been scanned for viruses and dangerous content by the BCEC
> Security Gateway, and is believed to be clean. Brisbane Catholic Education
> however gives no warranties that this e-mail is free from computer viruses
> or other defects. Except for responsibilities implied by law that cannot be
> excluded, Brisbane Catholic Education, its employees and agents will not be
> responsible for any loss, damage or consequence arising from this e-mail.
> _______________________________________________
> 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/20080729/eb4bc334/attachment.htm>

From bgailer at gmail.com  Tue Jul 29 18:13:23 2008
From: bgailer at gmail.com (bob gailer)
Date: Tue, 29 Jul 2008 12:13:23 -0400
Subject: [Tutor] How to run a Python program under Windows.
In-Reply-To: <ADC81E78CCB7314284086D57C0C6E2A3F99CE34D8A@suppmsg01.supp.bne.catholic.edu.au>
References: <ADC81E78CCB7314284086D57C0C6E2A3F99CE34D8A@suppmsg01.supp.bne.catholic.edu.au>
Message-ID: <488F41A3.2020103@gmail.com>

Morgan Thorpe wrote:
> Hello.

Hi.
>  
> I'm am very new to the whole programming sence.

Welcome.

> I am trying to catch on but as soon as i want to write a program i've 
> been told to use like 'notepad' in windows XP and save it as a .py file
> i have gotten this far. Am i wrong so far?

No. There are also IDEs such as IDLE and Python For Windows that make 
development easier (for many of us).

> If i am right why is it that i can't run it in anyway besides it 
> opening in 'notepad' i've tried opening with Python but it doesn't work.

Now comes the art of asking good (effective) questions.

1 - provide a subject (as I did)

2 - tell us what you tried (opening with Python is too vague) Example 
"At the command prompt I entered "c:\\python25\\python test.py"

3 - tell us what happened. Example "I got the message "'python' is not 
recognized as an internal or external command, operable program or batch 
file."

4 - reply to the list.

Those are just examples. What did you do "open with Python" I'll bet you 
picked that from the context menu. If that is the case did you see a dos 
window flash ever so briefly? Try adding raw_input("press any key to 
exit") at the end of your program. Of course that will work only if 
there are no errors in the program.

Best way for now is from the command prompt (like "c:\\python25\\python 
test.py")

-- 
Bob Gailer
919-636-4239 Chapel Hill, NC


From srilyk at gmail.com  Tue Jul 29 18:14:14 2008
From: srilyk at gmail.com (W W)
Date: Tue, 29 Jul 2008 11:14:14 -0500
Subject: [Tutor] (no subject)
In-Reply-To: <50a597410807290906t66f18aedie772986c06c3a05f@mail.gmail.com>
References: <ADC81E78CCB7314284086D57C0C6E2A3F99CE34D8A@suppmsg01.supp.bne.catholic.edu.au>
	<50a597410807290906t66f18aedie772986c06c3a05f@mail.gmail.com>
Message-ID: <333efb450807290914j560fc49t595866dc4541da4@mail.gmail.com>

Another thing you might want to check, since you're using Windows:

Open up windows explorer, go the "tools" menu, "folder options", then click
the "view" tab, and then make sure the option "hide extensions for known
filetypes" is unchecked. If it's not, uncheck it, and click OK. Then go and
make sure your file has a filename like myfile.py, and not myfile.py.txt

Hope this helps!
-Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080729/f9531716/attachment.htm>

From mail at timgolden.me.uk  Tue Jul 29 18:15:39 2008
From: mail at timgolden.me.uk (Tim Golden)
Date: Tue, 29 Jul 2008 17:15:39 +0100
Subject: [Tutor] (no subject)
In-Reply-To: <488F3FD1.7080306@nibrahim.net.in>
References: <ADC81E78CCB7314284086D57C0C6E2A3F99CE34D8A@suppmsg01.supp.bne.catholic.edu.au>
	<488F3FD1.7080306@nibrahim.net.in>
Message-ID: <488F422B.5010101@timgolden.me.uk>

Noufal Ibrahim wrote:
> Morgan Thorpe wrote:
>> Hello.
>>  
>> I'm am very new to the whole programming sence.
> 
> Welcome. :)
> 
>> I am trying to catch on but as soon as i want to write a program i've 
>> been told to use like 'notepad' in windows XP and save it as a .py file
>> i have gotten this far. Am i wrong so far?
> 
> It's fine so far. Computer programs (especially ones in python) are text 
> files which are formatted in a specific way which can be understood and 
> executed by Python.
> 
> When you write your program, you use an editor like notepad and save the 
> program as a .py file.
> 
> You're okay this far. The next stage is to ask Python to execute this 
> program. You do that by typing
> python program.py
> and hitting enter.
> 
>> If i am right why is it that i can't run it in anyway besides it 
>> opening in 'notepad' i've tried opening with Python but it doesn't work.


Have a look at this:

http://www.python.org/doc/faq/windows/

and this:

http://docs.python.org/dev/using/windows.html

TJG

From alan.gauld at btinternet.com  Tue Jul 29 19:03:50 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 29 Jul 2008 18:03:50 +0100
Subject: [Tutor] Turtle problem: how to exit the .exe?
References: <20080728204423.A7BCB1E400C@bag.python.org><g6lhac$tn9$1@ger.gmane.org><20080728231221.BDEF71E4012@bag.python.org><g6lo7r$f9k$1@ger.gmane.org><20080729022803.22D811E4004@bag.python.org><g6mh9t$7qr$1@ger.gmane.org>
	<20080729085202.D870B1E400B@bag.python.org>
Message-ID: <g6nidt$sd6$1@ger.gmane.org>


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

>>OK, let's eliminate some variables and go back to getting
>>the python script working.
> 
> Remember, it does work.

Not if it doesn't close down cleanly. In my book that's broken!

>>I've used turtle many times and never seen this behaviour
>>before. What does the code look like?
> 
> <http://py77.python.pastebin.com/f414c8ce4>

I can't see anything that would cause this(*) but it might be 
interesting to add some debugging print statements to see 
what happens to the loop counters etc when you try to 
close the window.

(*) I see a few other things that raise my eyebrows but not 
that cause this... :-)

Alan G.



From srilyk at gmail.com  Tue Jul 29 19:02:16 2008
From: srilyk at gmail.com (W W)
Date: Tue, 29 Jul 2008 12:02:16 -0500
Subject: [Tutor] Style help: long strings with formatting
Message-ID: <333efb450807291002j2cc7962ei80bb64503c70c7f7@mail.gmail.com>

Hi,

I've been dinking around, making a program that will find out how different
factors affect what you *really* save on gas, and at the end I have it
output some information, but I'm not sure what the right style for
formatting is.


output = "At an average weekly savings of $%.02f, your monthly savings  will
be $%.02f. \n Your annual savings will be $%.02f." % (diff, monthly_savings,
annual_savings)
print output.

As you can see, it's very much longer than the 72 characters suggested in
the PEP 8 found here: http://www.python.org/dev/peps/pep-0008/

I know it would be fairly trivial to split it up into several strings, and
concatenating or printing each one. I've tried using the \ line continuation
to break up the string, however that leaves the indentation inside the
string. Breaking the string up with commas or even concatenation gives
issues with the % operation.

So my question is, what is the proper stylistic way to render my text? Also,
I don't know if I just looked over it, or if it honestly didn't exist
anywhere I looked for it, but I couldn't find any naming conventions for
regular ol' variables. I found plenty for functions, classes, etc., so I'm
not sure if my underscores are proper for my variables or if I should fix
those.

TIA,
Wayne

-- 
To be considered stupid and to be told so is more painful than being called
gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness,
every vice, has found its defenders, its rhetoric, its ennoblement and
exaltation, but stupidity hasn't. - Primo Levi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080729/d2af94fc/attachment.htm>

From alan.gauld at btinternet.com  Tue Jul 29 19:11:25 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 29 Jul 2008 18:11:25 +0100
Subject: [Tutor] Memroy Error - how to manage large data sets?
References: <mailman.59.1217325614.25661.tutor@python.org>
	<1217335020.5761.27.camel@www.kinuthia.com>
Message-ID: <g6nis4$u3k$1@ger.gmane.org>

"kinuthiA muchanE" <muchanek at gmail.com> wrote

>> Umm, not instantly on my PC... 1 million took 5 minutes,
>> I've no idea how long 100 million would take!
> I think the question is to calculate the sum of all even numbers in 
> the
> Fibonacci series which do not exceed a million, not the millionth 
> term.

That's not what the OP requested.

> Number 25 on Project Euler which asks for first term in the 
> Fibonacci
> series to contain 1000 digits, is the term-wise question ;)

Assuming the OP is using that problerm set then it looks like
he misinterpreted the problem. But the problem he asked us to
solve was adding every other number up to 2 million entries...

Alan G. 



From alan.gauld at btinternet.com  Tue Jul 29 19:17:48 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 29 Jul 2008 18:17:48 +0100
Subject: [Tutor] How to run a Python program under Windows.
References: <ADC81E78CCB7314284086D57C0C6E2A3F99CE34D8A@suppmsg01.supp.bne.catholic.edu.au>
	<488F41A3.2020103@gmail.com>
Message-ID: <g6nj84$vf0$1@ger.gmane.org>

"bob gailer" <bgailer at gmail.com> wrote

> Best way for now is from the command prompt (like 
> "c:\\python25\\python test.py")

Since many newbies have no idea how to start a command prompt I'll 
add:

go to

Start->Run

type CMD in the dialog and click OK

A black window should appear, this is the command prompt.

Typing

python<Return>

at the prompt should get you a Python >>> prompt.
Typing

Ctrl-Z<Return>

will exit it.

But as mentioned elsewhere using IDLE (or Python GUI
in the start menu) is a better option. Or if you got the ActiveState
version of python better still use PythonWin.

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 Jul 29 19:21:12 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 29 Jul 2008 18:21:12 +0100
Subject: [Tutor] Style help: long strings with formatting
References: <333efb450807291002j2cc7962ei80bb64503c70c7f7@mail.gmail.com>
Message-ID: <g6njef$ef$1@ger.gmane.org>


"W W" <srilyk at gmail.com> wrote

> output = "At an average weekly savings of $%.02f, your monthly 
> savings  will
> be $%.02f. \n Your annual savings will be $%.02f." % (diff, 
> monthly_savings,
> annual_savings)
> print output.
>
> As you can see, it's very much longer than the 72 characters 
> suggested in
> the PEP 8 found here: http://www.python.org/dev/peps/pep-0008/

Use a triple quoted string for multiline output

output = """
At an average weekly savings of \t$%.02f,
your monthly savings  will be     \t$%.02f.
Your annual savings will be       \t$%.02f.
""" % (diff, monthly_savings, annual_savings)

print output


> I know it would be fairly trivial to split it up into several 
> strings, and
> concatenating or printing each one.

Multiline strings are designed to save you having to do that.

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



From michaelperscheid at googlemail.com  Tue Jul 29 22:04:27 2008
From: michaelperscheid at googlemail.com (Michael Perscheid)
Date: Tue, 29 Jul 2008 22:04:27 +0200
Subject: [Tutor] Python Desktop Application for a Case Study
Message-ID: <488F77CB.4060903@googlemail.com>

Hi list,

I'm looking for a Python application with source code to analyse it with 
my small research project. The programm should have the following 
properties:

- Using a GUI framework at best PyQt
- Desktop application with small breaks. That means the software does 
nothing in that moments and is in a stationary phase and waits for the 
next user input.
- Not to simple but also not to complex that means in detail:
-- Only one process, however different threads are allowed
-- Between 10-25 features would be appropiated
- The example should be known from more than one person ;)

I have a notion that a date management, cookbook application or 
something else are very appropriate.

Thanks in advance!

Kind regards,
Michael

From sparkignited at gmail.com  Tue Jul 29 23:50:38 2008
From: sparkignited at gmail.com (sai krishna)
Date: Wed, 30 Jul 2008 03:20:38 +0530
Subject: [Tutor] Obtaining various combinations of a given word
Message-ID: <8ac6e24e0807291450n6fddc198ud830cae23b8ebd80@mail.gmail.com>

Hi,everyone.
My name is Sai krishna, and I'm new to Python as well as Programming.

I wanted to print out all the combinations of a given word.
I am doing it this way:

n='cat'
def arrange(n):
if len(n)==1: #length of word is 1
    print n
elif len(n)==2: # length of word is 2
    print n[0]+n[1]
    print n[1]+n[0]
elif len(n)==3:
    print n[0]+n[1]+n[2]
    print n[0]+n[2]+n[1]
    print n[1]+n[0]+n[2]
    print n[1]+n[2]+n[0]
    print n[2]+n[0]+n[1]
    print n[2]+n[1]+n[0]

This process is quite lengthy, and I have managed to do this for word
containing 5 letters,i,e.,120 combinations
Is there a better way?
Please help.

-- 
cheers!!!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080730/390e2773/attachment.htm>

From bgailer at gmail.com  Wed Jul 30 01:15:32 2008
From: bgailer at gmail.com (bob gailer)
Date: Tue, 29 Jul 2008 19:15:32 -0400
Subject: [Tutor] Obtaining various combinations of a given word
In-Reply-To: <8ac6e24e0807291450n6fddc198ud830cae23b8ebd80@mail.gmail.com>
References: <8ac6e24e0807291450n6fddc198ud830cae23b8ebd80@mail.gmail.com>
Message-ID: <488FA494.1080804@gmail.com>

An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080729/2951a8c5/attachment.htm>

From alan.gauld at btinternet.com  Wed Jul 30 01:17:36 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 30 Jul 2008 00:17:36 +0100
Subject: [Tutor] Python Desktop Application for a Case Study
References: <488F77CB.4060903@googlemail.com>
Message-ID: <g6o8ao$54v$1@ger.gmane.org>

"Michael Perscheid" <michaelperscheid at googlemail.com> wrote

> I'm looking for a Python application with source code to analyse it 
> with my small research project. The programm should have the 
> following properties:

Try Sourceforge.
There is a drawing tool - think Visio - that is in Python,
maybe that would do? Its called Dia and does UML diagrams.
Its based on GTk.

A simpler one is Skencil(sp?) but it has some bits in C for speed.

www.skencil.org

The documentation oddly refers to it as Sketch... it claims to
be built on Tkinter

Either might suit your needs?

Alan G.




From vsant at hcs.harvard.edu  Wed Jul 30 01:08:14 2008
From: vsant at hcs.harvard.edu (Vivek Sant)
Date: Tue, 29 Jul 2008 19:08:14 -0400
Subject: [Tutor] Obtaining various combinations of a given word
In-Reply-To: <8ac6e24e0807291450n6fddc198ud830cae23b8ebd80@mail.gmail.com>
References: <8ac6e24e0807291450n6fddc198ud830cae23b8ebd80@mail.gmail.com>
Message-ID: <1967CAE9-3A78-41E8-A0DC-A50C0F8D0F90@hcs.harvard.edu>

Hi Sai krishna,

I recently wrote a program that does something similar to what you  
want. If you are familiar with the game text-twist, I wrote up a  
"solver" that will untwist any word by generating all possible  
combinations and then checking against a dictionary. To be honest, I  
had a little help from the internet for the permute function. Below  
is the code.

To address your question, when you find yourself doing something like  
if 1, ..., if 2, ... ..., if 3, ... ... ..., you probably want to use  
recursion, which is what my permute function uses below. The whole  
point of programming is to make the computer do all the repetition,  
not you, the programmer in copy and pasting and changing! Hope this  
helps!

Regards,
Vivek


#!/usr/bin/env python
import sys
import os
import commands
import random

if len(sys.argv) == 1:
   print "Usage: "+sys.argv[0]+" word [len]"
   exit()

word = sys.argv[1].lower()
if len(sys.argv) == 2:
   n = len(word)
else:
   n = int(sys.argv[2])

a = []
for i in range(len(word)):
   a.append(word[i])

def permute(seq):
   if len(seq) <= 1:
     yield seq
   else:
     for i in xrange(0,len(seq)):
       for tail in permute( seq[:i] + seq[i+1:] ):
         yield [ seq[i] ] + tail

# Load dict in memory
dict = {}
infile = open("wordlist.txt", "r")
for t in infile.readlines():
   dict[t.rstrip()] = 1

printed_words = []

for o in permute(a):
   possible_string = ''.join(o)
   possible_word = possible_string[:n]
   if dict.has_key(possible_word):
     if possible_word in printed_words:
       continue
     else:
       printed_words.append(possible_word)
       print possible_word



On Jul 29, 2008, at 5:50 PM, sai krishna wrote:

>
> Hi,everyone.
> My name is Sai krishna, and I'm new to Python as well as Programming.
>
> I wanted to print out all the combinations of a given word.
> I am doing it this way:
>
> n='cat'
> def arrange(n):
> if len(n)==1: #length of word is 1
>     print n
> elif len(n)==2: # length of word is 2
>     print n[0]+n[1]
>     print n[1]+n[0]
> elif len(n)==3:
>     print n[0]+n[1]+n[2]
>     print n[0]+n[2]+n[1]
>     print n[1]+n[0]+n[2]
>     print n[1]+n[2]+n[0]
>     print n[2]+n[0]+n[1]
>     print n[2]+n[1]+n[0]
>
> This process is quite lengthy, and I have managed to do this for  
> word containing 5 letters,i,e.,120 combinations
> Is there a better way?
> Please help.
>
> -- 
> cheers!!!
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


From john at fouhy.net  Wed Jul 30 01:56:32 2008
From: john at fouhy.net (John Fouhy)
Date: Wed, 30 Jul 2008 11:56:32 +1200
Subject: [Tutor] Obtaining various combinations of a given word
In-Reply-To: <8ac6e24e0807291450n6fddc198ud830cae23b8ebd80@mail.gmail.com>
References: <8ac6e24e0807291450n6fddc198ud830cae23b8ebd80@mail.gmail.com>
Message-ID: <5e58f2e40807291656m2be00861mf74b93d424301fbe@mail.gmail.com>

On 30/07/2008, sai krishna <sparkignited at gmail.com> wrote:
> I wanted to print out all the combinations of a given word.

A thought for you:

Let's say you want to find permutations of the string 'abcd'.  Some of
those permutations will start with 'a' -- how many?  Can you list all
the permutations starting with 'a'?  Do you see any connection between
that list and your solution for n == 3?

(hint: the following is a function for computing factorials.  Do you
understand it?

def fac(n):
  if n == 0:
    return 1
  else:
    return n*fac(n-1)
)

(also, another thought for you, once you've solved this problem: what
answer would you expect for the string 'aaa'?)

-- 
John.

From brendan.rankin at gmail.com  Wed Jul 30 01:57:47 2008
From: brendan.rankin at gmail.com (Brendan)
Date: Tue, 29 Jul 2008 23:57:47 +0000 (UTC)
Subject: [Tutor] Obtaining various combinations of a given word
References: <8ac6e24e0807291450n6fddc198ud830cae23b8ebd80@mail.gmail.com>
Message-ID: <loom.20080729T235502-45@post.gmane.org>

sai krishna <sparkignited <at> gmail.com> writes:

> 
> 
> Hi,everyone.My name is Sai krishna, and I'm new to Python as well as
Programming.I wanted to print out all the combinations of a given word.I am
doing it this way:
> n='cat'def arrange(n):if len(n)==1: #length of word is 1??? print nelif
len(n)==2: # length of word is 2??? print n[0]+n[1]??? print n[1]+n[0]elif
len(n)==3:??? print n[0]+n[1]+n[2]
> ??? print n[0]+n[2]+n[1]??? print n[1]+n[0]+n[2]??? print n[1]+n[2]+n[0]???
print n[2]+n[0]+n[1]??? print n[2]+n[1]+n[0]This process is quite lengthy, and I
have managed to do this for word containing 5 letters,i,e.,120 combinations
> Is there a better way?Please help.-- cheers!!!

Found the following link while googleing.  It looks pretty nice and makes good
use of Python's generators.

http://www.daniweb.com/code/snippet553.html

Cheers,

- Brendan



From jdmccla at regence.com  Wed Jul 30 13:01:13 2008
From: jdmccla at regence.com (James D Mcclatchey)
Date: Wed, 30 Jul 2008 04:01:13 -0700
Subject: [Tutor] James D Mcclatchey is out of the office.
Message-ID: <OFDA7E6BD2.16A338CF-ON88257496.003C8954-88257496.003C8954@regence.com>


I will be out of the office starting  07/30/2008 and will not return until
08/04/2008.

I will respond to your message when I return.


***IMPORTANT NOTICE: This communication, including any attachment, contains information that may be confidential or privileged, and is intended solely for the entity or individual to whom it is addressed.  If you are not the intended recipient, you should delete this message and are hereby notified that any disclosure, copying, or distribution of this message is strictly prohibited.  Nothing in this email, including any attachment, is intended to be a legally binding signature.***


From norman at khine.net  Wed Jul 30 14:42:35 2008
From: norman at khine.net (Norman Khine)
Date: Wed, 30 Jul 2008 14:42:35 +0200
Subject: [Tutor] help with augumented assignment y += 1
Message-ID: <489061BB.1010505@khine.net>

Hello,

I am writing a poll application, which has two XML files:

1) survey.xml

<?xml version="1.0" encoding="UTF-8"?>
<survey>
<question code="a1" type="MCQ">
   <title>Is an augumented assignment such as 'x = x + 1' the same as x 
+= 1?</title>
   <option>Yes</option>
   <option>No</option>
   <option>Don't know</option>
</question>
<question code="a2" type="MAQ">
   <title>The statement 'x *= y + 1' is equivalent to:</title>
   <option>'x = (x * y) + 1'</option>
   <option>'x = x * (y + 1)</option>
   <option>'x = (y + 1) * x'</option>
   <option>All of the above</option>
</question>
</survey>

2) respons.xml

<?xml version="1.0" encoding="UTF-8"?>
<response>
<attempt username="1" date="2008-07-28 14:40">
   <question code="a1">
     <answer>1</answer>
   </question>
   <question code="a2">
     <answer>2</answer>
     <answer>3</answer>
   </question>
</attempt>
<attempt username="5" date="2008-07-28 15:00">
   <question code="a1">
     <answer>1</answer>
   </question>
   <question code="a2">
     <answer>1</answer>
     <answer>2</answer>
   </question>
</attempt>
<attempt username="3" date="2008-07-28 14:47">
   <question code="a1">
     <answer>3</answer>
   </question>
   <question code="a2">
     <answer>4</answer>
   </question>
</attempt>
</response>

Here is the code I have so far, poll.py:

####

from folder import Folder
from handlers import Text
...

class Survey(Text):
     """
     Here we create the actual survey.xml file
     """

     def new(self):
         self.questions = {}

     def _load_state_from_file(self, file):
         ....

     def to_str(self, encoding='UTF-8'):
         lines = ['<?xml version="1.0" encoding="%s"?>\n' % encoding,
                  '<survey>\n']
         # Business functions
         # Questions
         questions = self.questions
         codes = questions.keys()
         codes.sort()
         for code in codes:
             lines.append(questions[code].to_str(encoding))
         lines.append('</survey>')
         return ''.join(lines)


class Response(Text):
     """
     Here we create the actual response.xml file
     """

     def new(self):
         self.attempts = {}

     def _load_state_from_file(self, file):
         # TEST 015
         attempts = {}

     def to_str(self, encoding='UTF-8'):
         lines = ['<?xml version="1.0" encoding="%s"?>' % encoding,
                  '<response>']
         attempts = self.attempts
         for username in attempts:
             for attempt in attempts[username]:
                 lines.append(
                     '<attempt username="%s" date="%s" mark="%2.2f">'
                     % (username, attempt.date.strftime('%Y-%m-%d 
%H:%M'), attempt.mark))
                 questions = attempt.questions
                 for question_code in questions:
                     lines.append('  <question code="%s">' % question_code)
                     for answer in questions[question_code]:
                         lines.append('    <answer>%s</answer>' % answer)
                     lines.append('  </question>')
                 lines.append('</attempt>')
         lines.append('</response>')
         return '\n'.join(lines)

     def get_analysis(self):
         attempts = self.attempts
         for username in attempts:
             user = []
             question = []
             for attempt in attempts[username]:
                 user.append(username)
                 questions = attempt.questions
                 answers = []
                 for question_code in questions:
                     for answer in questions[question_code]:
                         answers.append(answer)
                         question.append(question_code)

             # [SEE NOTE 1]
             print user, question, answers


class Attempt(object):

     def __init__(self, username=None, date=None):
         self.username = username
         self.date = date
         self.questions = {}


class Poll(Folder):

     def new(self):
         Folder.new(self)
         self.cache['.survey'] = Survey()
         self.cache['.response'] = Response()

     def get_definition(self):
         return self.get_handler('.survey')
     definition = property(get_definition, None, None, '')

     def get_results(self):
         return self.get_handler('.response')
     results = property(get_results, None, None, '')

     def fill_form(self, context):
         user = context.user
         ...

     def analyse(self, context):
         user, root = context.user, context.root
         questions = self.definition.questions

         results = [{'question': x,
                     'title': y.title,
                     'options': [y.options]}
                          for x, y in questions.items()]
         # [SEE NOTE 2]
         print results


####

[NOTE 1] In the Response class I have a function 'get_analysis':

     def get_analysis(self):
             attempts = self.attempts
             ....

This returns:
['1'] ['1', '2', '2', '2'] [1, 1, 2, 4]
['0'] ['1', '2', '2'] [2, 2, 3]


[NOTE 2] In the Poll class, I have a function 'analyse':

    def analyse(self, context):
         user, root = context.user, context.root
         questions = self.definition.questions
         ...
This returns:

[{'question': 'a1', 'options': [[u'Yes', u'No', u"Don't know"]], 
'title': u"Is an augumented assignment such as 'x = x + 1' the same as x 
+= 1?"}, {'question': 'a2', 'options': [[u"'x = (x * y) + 1'", u"'x = x 
* (y + 1)", u"'x = (y + 1) * x'", u'All of the above']], 'title': u"The 
statement 'x *= y + 1' is equivalent to:"}]


This is where I get stuck and can't see the solution so that I can link both
.xml files and be able to return the totals for each answered question.

I would like to count the totals for each answer, so that:

options       | yes | no | don't know | 'x = (x * y) + 1' | 'x = x * (y 
+ 1)' |etc...
user 0        | 0   | 1  | 0          | 0                 | 1 
       |etc...
user 1        | 1   | 0  | 0          | 1                 | 1 
       |etc...
---------------------------------------------------------- 
-------------------
total         | 1   | 1  | 0          | 1                 | 2 
       |etc...
---------------------------------------------------------- 
-------------------

Ultimately, I would like to display the results as:

a1. Is an augumented assignment....
     [yes]         [1] [50%] *****
     [no]          [1] [50%] *****
     [don't know]  [0] [0%]

a2. The statement 'x *=....
     ['x = (x * y) + 1']         [1] [33%] ***
     ['x = x * (y + 1)']         [2] [77%] *******
    ....

Perhaps I would need a dictionary containing a list with totals for 
each, such as:

{'question': 'a1',
   'options': [{'option':  u'Yes',  'total': 1,
                 'option':  u'No',  'total': 1,
                 'option': u"Don't know", 'total: 0}],
   'title': u"Is an augumented assignment ...",
   'question': 'a2',
   'options': [{'option':  u'x = (x * y) + 1',  'total': 1,
                 'option':  u'x = x * (y + 1)',  'total': 2,
                 'option': u"...", 'total: 0}],
   'title': u"The statement..."}

But how do I calculate the total value for each option?

Any advise or suggestions and guidance in improving this much appreciated.


From bgailer at gmail.com  Wed Jul 30 15:31:23 2008
From: bgailer at gmail.com (bob gailer)
Date: Wed, 30 Jul 2008 09:31:23 -0400
Subject: [Tutor] How to run a Python program under Windows.
In-Reply-To: <ADC81E78CCB7314284086D57C0C6E2A3F99CE34D8B@suppmsg01.supp.bne.catholic.edu.au>
References: <ADC81E78CCB7314284086D57C0C6E2A3F99CE34D8A@suppmsg01.supp.bne.catholic.edu.au>,
	<488F41A3.2020103@gmail.com>
	<ADC81E78CCB7314284086D57C0C6E2A3F99CE34D8B@suppmsg01.supp.bne.catholic.edu.au>
Message-ID: <48906D2B.2060600@gmail.com>

Morgan Thorpe wrote:
> Hey Again.
>
> Okay i don't think my sad explantion did help at all.
> Would you be able to explain step by step what i need to do to run the simplest of simple program's everyone else has asked about where it is and what not. According to them i have everything where it needs to be.
>   

You have had a response from me and from Alan Gauld.

We have both offered advice and asked questions.

We can't do anything more for you until you try our advice and let us 
know where or how it is not helping, and answer our questions.

We realty want to help, and we need your cooperation to help effectively.


> I like to think i'm reasonable at most computer things or anything to do with them i've built 3 working computers and i'm working on another with a friend and still this stumps me.
>   

Skill with hardware has little to do with software skills.
> Of the 4 or 5 replies i think that you would be most help.
>   

We all can help.

AND PLEASE as I asked, reply to the list not just me.


-- 
Bob Gailer
919-636-4239 Chapel Hill, NC


From emile at fenx.com  Wed Jul 30 19:17:03 2008
From: emile at fenx.com (Emile van Sebille)
Date: Wed, 30 Jul 2008 10:17:03 -0700
Subject: [Tutor] help with augumented assignment y += 1
In-Reply-To: <489061BB.1010505@khine.net>
References: <489061BB.1010505@khine.net>
Message-ID: <g6q7mp$d3$1@ger.gmane.org>

Norman Khine wrote:
> Hello,
> 
> I am writing a poll application, which has two XML files:

Is this entire question consistent?  I ask because when you get to 
asking your question below, it sounds like you're trying to tie together 
two outputs:

<snip and paste from below>

 > This returns:
 > ['1'] ['1', '2', '2', '2'] [1, 1, 2, 4]
 > ['0'] ['1', '2', '2'] [2, 2, 3]

...and

 > This returns:
 > [{'question': 'a1', 'options': [[u'Yes', u'No', u"Don't know"]],
 > 'title': u"Is an augumented assignment such as 'x=x + 1' the same as x
 > += 1?"}, {'question': 'a2', 'options': [[u"'x=(x * y) + 1'", u"'x=x
 > *(y + 1)", u"'x=(y + 1) * x'", u'All of the above']], 'title': u"The
 > statement 'x *= y + 1' is equivalent to:"}]

The second is clearly the survey -- it's the first I question.  How do 
those two lines relate to the xml response?

If you could coalesce your example into a single executable or clearly 
relate those two lines to the xlm response it (presumably) derives from 
there's a better chance you'll get a more helpful reply.

Regards,

Emile


From norman at khine.net  Wed Jul 30 20:09:49 2008
From: norman at khine.net (Norman Khine)
Date: Wed, 30 Jul 2008 20:09:49 +0200
Subject: [Tutor] help with augumented assignment y += 1
In-Reply-To: <g6q7mp$d3$1@ger.gmane.org>
References: <489061BB.1010505@khine.net> <g6q7mp$d3$1@ger.gmane.org>
Message-ID: <9c2c8ffb0807301109p61822de5tbe8855e8250fbd7c@mail.gmail.com>

Hi,
Appologies, there was a typo, in that the first line is:

['1'] ['a1', 'a2', 'a2', 'a2'] [1, 1, 2, 4]

The way the first line relates to the survey is such that, it looks at
the response.xml file and returns what the individual user has
submitted.

So that:

['1'] ['a1', 'a2', 'a2', 'a2'] [1, 1, 2, 4]

['1'] - is the username
['a1', 'a2', 'a2', 'a2'] - is the question code
[1, 1, 2, 4] - is the key value that the user has submited

Whereas the second output, simply returns a list containing a
dictionaries with the actual question properties.

To narrow the my question to specifics, I suppose I would need to make
a dictionary such as:

{options: {'count': count}}

and then relate it back to the survey.xml file so that I can get the 'labels'

        ret = {}
        for option in options:
             if not ret.has_key(option):
                 ret[option] = {'count': 1}
             else:
                 ret[option]['count'] += 1
        return ret

This I think will return a count of all tha answered questions, but
how to generate the options dictionary and relate this to the
survey.xml file to get the related labels?

Hope this makes sense.

Cheers

Norman
On 7/30/08, Emile van Sebille <emile at fenx.com> wrote:
> Norman Khine wrote:
> > Hello,
> >
> > I am writing a poll application, which has two XML files:
> >
>
> Is this entire question consistent?  I ask because when you get to asking
> your question below, it sounds like you're trying to tie together two
> outputs:
>
> <snip and paste from below>
>
> > This returns:
> > ['1'] ['1', '2', '2', '2'] [1, 1, 2, 4]
> > ['0'] ['1', '2', '2'] [2, 2, 3]
>
> ...and
>
> > This returns:
> > [{'question': 'a1', 'options': [[u'Yes', u'No', u"Don't know"]],
> > 'title': u"Is an augumented assignment such as 'x=x + 1' the same as x
> > += 1?"}, {'question': 'a2', 'options': [[u"'x=(x * y) + 1'", u"'x=x
> > *(y + 1)", u"'x=(y + 1) * x'", u'All of the above']], 'title': u"The
> > statement 'x *= y + 1' is equivalent to:"}]
>
> The second is clearly the survey -- it's the first I question.  How do those
> two lines relate to the xml response?
>
> If you could coalesce your example into a single executable or clearly
> relate those two lines to the xlm response it (presumably) derives from
> there's a better chance you'll get a more helpful reply.
>
> Regards,
>
> Emile
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From emile at fenx.com  Wed Jul 30 21:04:48 2008
From: emile at fenx.com (Emile van Sebille)
Date: Wed, 30 Jul 2008 12:04:48 -0700
Subject: [Tutor] help with augumented assignment y += 1
In-Reply-To: <9c2c8ffb0807301109p61822de5tbe8855e8250fbd7c@mail.gmail.com>
References: <489061BB.1010505@khine.net> <g6q7mp$d3$1@ger.gmane.org>
	<9c2c8ffb0807301109p61822de5tbe8855e8250fbd7c@mail.gmail.com>
Message-ID: <g6qe0q$o1u$1@ger.gmane.org>

Norman Khine wrote:
> Hi,
> Appologies, there was a typo, in that the first line is:
> 
> ['1'] ['a1', 'a2', 'a2', 'a2'] [1, 1, 2, 4]

Yes -- that helps.

So, working from your xml samples, by doing something like:

responses = [ [a,b,c] for a,b,c in responseAnalysisGenerator ]

you can end up with responses and survey that look like:

responses = [
   [['1'],['a1', 'a2'],[1, [2,3]]],
   [['5'],['a1', 'a2'],[1, 2]],
   [['3'],['a1', 'a2'],[3, 4]]
   ]

survey = [{'question': 'a1',
   'options': [[u'Yes',
                u'No',
                u"Don't know"]],
    'title': u"Is an augumented assignment such as \
                'x = x + 1' the same as x += 1?"},
  {'question': 'a2',
   'options': [[u"'x = (x * y) + 1'",
                u"'x = x * (y + 1)",
                u"'x = (y + 1) * x'",
                u'All of the above']],
   'title': u"The statement 'x *= y + 1' is equivalent to:"}]

Now the questions evolves to extracting the appropriate formatted output
from these two structures.  This can take place in many ways and is 
directly a function of the range of questions you'd want to answer.  In 
addition to the totals by question, one of your output formats appeared 
to be a restatement by user of the survey.  This suggests a class 
structure where you initialize the class with something like:

myAnalyzer = SurveyAnalyzer(survey,responses)

and let it respond to queries like:

sampleRecap = myAnalyzer.recap()
sampleRecap = myAnalyzer.userResponse('3')

Does this help?

Emile


From jtp at nc.rr.com  Wed Jul 30 22:59:02 2008
From: jtp at nc.rr.com (James)
Date: Wed, 30 Jul 2008 16:59:02 -0400
Subject: [Tutor] Communication between threads
Message-ID: <e107b4ff0807301359i51e91cf7p784e63c1db83d445@mail.gmail.com>

All,

I'm looking for some thoughts on how two separate threads can
communicate in Python. From what I've read in a few Python books,
sharing data between threads can be done by writing and reading a
global variable in the parent of both threads. Is this the "best" way?
Is it the *only* way?

Also, any thoughts on how to best use "notify()"? I've found very
little documentation on how to "best" use notify() when dealing with
multiple threads. (many of the documents I've found explain how to use
notifyAll(), but I'm unsure "broadcasting" a message to all threads
like that is the best way to deal with a problem)

Sorry this question is so broad; threading (properly) seems to be a
complex subject and it seems I'm in over my head. I've read tons of
documents, however, and am still rather unclear about all the tiny
parts of the big picture.

Thoughts? :)

Thanks!
-j

From steve.poe at gmail.com  Wed Jul 30 23:27:45 2008
From: steve.poe at gmail.com (Steve Poe)
Date: Wed, 30 Jul 2008 14:27:45 -0700
Subject: [Tutor] understanding join
Message-ID: <BE612F80-E036-4419-AA44-CA46A9214F45@gmail.com>

Hi tutor list,

Just trying to add some clarity to the built-in function strings using  
join. The Python help
screen says it returns a string which is a concatenation of strings in  
sequence. I am concatenating
the string I am working on that maybe an issue of its own.

Here's my example:

string ='ab'

so, if I type:

print  string.join(string)

aabb

but if string is 'abc'

print string.join(string)
aabcbabcc


print string ='a' returns on a in this example, whit string='a '  
returns aa. So, I am not catching
the pattern.

Thanks.

Steve




From emile at fenx.com  Wed Jul 30 23:39:33 2008
From: emile at fenx.com (Emile van Sebille)
Date: Wed, 30 Jul 2008 14:39:33 -0700
Subject: [Tutor] Communication between threads
In-Reply-To: <e107b4ff0807301359i51e91cf7p784e63c1db83d445@mail.gmail.com>
References: <e107b4ff0807301359i51e91cf7p784e63c1db83d445@mail.gmail.com>
Message-ID: <g6qn2t$o05$1@ger.gmane.org>

James wrote:
> All,
> 
> I'm looking for some thoughts on how two separate threads can
> communicate in Python. From what I've read in a few Python books,
> sharing data between threads can be done by writing and reading a
> global variable in the parent of both threads. Is this the "best" way?
> Is it the *only* way?

I happened to see an article on this -- let's see...

http://www.ibm.com/developerworks/aix/library/au-threadingpython/index.html

Specifically the queues discussion.

HTH,

Emile


From john at fouhy.net  Wed Jul 30 23:54:06 2008
From: john at fouhy.net (John Fouhy)
Date: Thu, 31 Jul 2008 09:54:06 +1200
Subject: [Tutor] understanding join
In-Reply-To: <BE612F80-E036-4419-AA44-CA46A9214F45@gmail.com>
References: <BE612F80-E036-4419-AA44-CA46A9214F45@gmail.com>
Message-ID: <5e58f2e40807301454t68a759a2r521a502050b40116@mail.gmail.com>

On 31/07/2008, Steve Poe <steve.poe at gmail.com> wrote:
> Hi tutor list,
>
>  Just trying to add some clarity to the built-in function strings using
> join. The Python help
>  screen says it returns a string which is a concatenation of strings in
> sequence. I am concatenating
>  the string I am working on that maybe an issue of its own.
[...]
>  but if string is 'abc'
>
>  print string.join(string)
>  aabcbabcc

Hi Steve,

First up, a quick comment: There is a string module in the standard
library, and it has a function called join().  So it's generally a
good idea not to use 'string' as a variable name, as it can confuse
people :-)

Now, to your question: your string is 'abc'.  It doesn't matter that
you're using a string to join itself; what you've written is identical
to:

>>> 'abc'.join('abc')
'aabcbabcc'

Let's change the call slightly to make things more clear:

>>> 'abc'.join('ABC')
'AabcBabcC'

Does that make the pattern more clear?

-- 
John.

From john at fouhy.net  Thu Jul 31 00:35:22 2008
From: john at fouhy.net (John Fouhy)
Date: Thu, 31 Jul 2008 10:35:22 +1200
Subject: [Tutor] understanding join
In-Reply-To: <C754EFE6-8012-4115-92B4-2E72A3576463@gmail.com>
References: <BE612F80-E036-4419-AA44-CA46A9214F45@gmail.com>
	<5e58f2e40807301454t68a759a2r521a502050b40116@mail.gmail.com>
	<C754EFE6-8012-4115-92B4-2E72A3576463@gmail.com>
Message-ID: <5e58f2e40807301535r7a962244k9ea218298df0cb12@mail.gmail.com>

On 31/07/2008, Steve Poe <steve.poe at gmail.com> wrote:
>  Good point. I guess I am surprised a little that Python does not error
>  on that you cannot assign a variable to a module name.  I know I need
>  to learn proper coding techniques.

Well, that wouldn't really work because you don't know what other
modules people have.

>  Okay, I can see the order of the join is the same as mine, but
>  the join still seems to be out of sequence.  I am thinking it should be
>  'abcABC' or 'ABCabc' not at the beginning, middle, and end of the
>  original string. At least, I am trying to wrap my head around its
>  usefulness.

Say I have a sequence seq and a string s, and I call s.join(seq).
Here's what it does:

s.join(seq) == seq[0] + s + seq[1] + s + seq[2] + s + ...  + seq[-2] +
s + seq[-1]

So if you call 'abc'.join('ABC'), you get:

   'ABC'[0] + 'abc' + 'ABC'[1] + 'abc' + 'ABC'[2]

which is:

   'A' + 'abc' + 'B' + 'abc' + 'C'

Hope this helps.

-- 
John.

From kent37 at tds.net  Thu Jul 31 02:03:32 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 30 Jul 2008 20:03:32 -0400
Subject: [Tutor] understanding join
In-Reply-To: <5e58f2e40807301535r7a962244k9ea218298df0cb12@mail.gmail.com>
References: <BE612F80-E036-4419-AA44-CA46A9214F45@gmail.com>
	<5e58f2e40807301454t68a759a2r521a502050b40116@mail.gmail.com>
	<C754EFE6-8012-4115-92B4-2E72A3576463@gmail.com>
	<5e58f2e40807301535r7a962244k9ea218298df0cb12@mail.gmail.com>
Message-ID: <1c2a2c590807301703q6be950cv1f7a6287f818a053@mail.gmail.com>

> On 31/07/2008, Steve Poe <steve.poe at gmail.com> wrote:
>>  Okay, I can see the order of the join is the same as mine, but
>>  the join still seems to be out of sequence.  I am thinking it should be
>>  'abcABC' or 'ABCabc' not at the beginning, middle, and end of the
>>  original string. At least, I am trying to wrap my head around its
>>  usefulness.

Does this look useful?

In [3]: people = [ 'Tom', 'Dick', 'Harry' ]

In [4]: ', '.join(people)
Out[4]: 'Tom, Dick, Harry'

Your confusion is in thinking about the string 'ABC' as a single
entity. For the purposes of join(), it is a sequence of three letters.
The argument to join() is a sequence of strings, not a single string.

Kent

From bryan.fodness at gmail.com  Thu Jul 31 03:43:07 2008
From: bryan.fodness at gmail.com (Bryan Fodness)
Date: Wed, 30 Jul 2008 21:43:07 -0400
Subject: [Tutor] checking for expected types from input file
Message-ID: <fbf64d2b0807301843x3aaf2e85nd33bca64cca47e20@mail.gmail.com>

I am populating a dictionary from an input file, and would like to create an
error code if a string is sent to a variable that expects a float or int.

INPUT = {}
for line in open(infile):
    input_line = line.split(' = ')
    INPUT[input_line[0].strip()] = input_line[1].strip()

if INPUT.has_key('ReferencePositionX'):
    refx = float(INPUT['ReferencePositionX'])/10
    refy = float(INPUT['ReferencePositionY'])/10
    refz = float(INPUT['ReferencePositionZ'])/10

I have many variables of different types, and I want to do a check in
case something like ReferencePositionX = abc occurs.

-- 
"The game of science can accurately be described as a never-ending insult to
human intelligence." - Jo?o Magueijo
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080730/9caa5c50/attachment.htm>

From steve.poe at gmail.com  Thu Jul 31 04:14:27 2008
From: steve.poe at gmail.com (Steve Poe)
Date: Wed, 30 Jul 2008 19:14:27 -0700
Subject: [Tutor] checking for expected types from input file
In-Reply-To: <fbf64d2b0807301843x3aaf2e85nd33bca64cca47e20@mail.gmail.com>
References: <fbf64d2b0807301843x3aaf2e85nd33bca64cca47e20@mail.gmail.com>
Message-ID: <876BA19C-1E01-40E4-A9F4-63BDB7EFE652@gmail.com>

Bryan,

How about checking your input to see if they are digits or not?
 >>> input_data = '123ABC'
 >>> print input_data.isdigit()
False
 >>> input_data = '1234567889'
 >>> print input_data.isdigit()
True
 >>> input_data = '123ABC'
 >>> print input_data.isdigit()
False

or something like:

while INPUT.has_key('ReferencePositionX').isdigit() =='True':
>     refx = float(INPUT['ReferencePositionX'])/10
>     refy = float(INPUT['ReferencePositionY'])/10
>     refz = float(INPUT['ReferencePositionZ'])/10



Steve

On Jul 30, 2008, at 6:43 PM, Bryan Fodness wrote:

> I am populating a dictionary from an input file, and would like to  
> create an error code if a string is sent to a variable that expects  
> a float or int.
>
> INPUT = {}
> for line in open(infile):
>     input_line = line.split(' = ')
>     INPUT[input_line[0].strip()] = input_line[1].strip()
>
> if INPUT.has_key('ReferencePositionX'):
>     refx = float(INPUT['ReferencePositionX'])/10
>     refy = float(INPUT['ReferencePositionY'])/10
>     refz = float(INPUT['ReferencePositionZ'])/10
>
> I have many variables of different types, and I want to do a check  
> in case something like ReferencePositionX = abc occurs.
>
> -- 
> "The game of science can accurately be described as a never-ending  
> insult to human intelligence." - Jo?o Magueijo
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


From kepalapening at gmail.com  Thu Jul 31 04:19:56 2008
From: kepalapening at gmail.com (Kepala Pening)
Date: Thu, 31 Jul 2008 10:19:56 +0800
Subject: [Tutor] Memory error - how to manage large data sets?
Message-ID: <20080731.021956.906.1@SELINAPNOTE>

def sumEvenFibonacci( limit ):
	a, b = 1, 1  # don't waste with a = 0
	sum = 0
	while b < limit:
		if b%2 == 0: sum += b
		a, b = b, a + b
	return sum

print sumEvenFibonacci( 2000000 )



----- Original Message -----
From: Chris Fuller <cfuller084 at thinkingplanet.net>
To: tutor at python.org
Date: Mon, 28 Jul 2008 12:27:58 -0500
Subject: Re: [Tutor] Memory error - how to manage large data sets?

> On Monday 28 July 2008 10:56, Karthik wrote:
> > Hi,
> >
> >
> >
> > I am new to Python programming, I was trying to work out a few problems in
> > order to grasp the knowledge gained after going through the basic chapters
> > on Python programming. I got stuck with a memory error.
> >
> >
> >
> > Following is what I did,
> >
> >
> >
> > 1.     I need to find the sum of all numbers at even positions in the
> > Fibonacci series upto 2 million.
> >
> > 2.     I have used lists to achieve this.
> >
> > 3.     My program works good with smaller ranges. Say till 10,000 or even
> > 100,000. However when I compute the sum for bigger ranges it gives me the
> > memory error.
> >
> > 4.     Also could someone tell me how to get the result in the form of an
> > exponent. For instance, I would prefer 10^5 rather  100000.
> >
> >
> >
> > Thanks in advance,
> >
> > Karthik
> 
> It sounds like you are storing all the fibonacci numbers as you generate 
them.  
> Why?  You only need the previous two to find the next in the sequence.  The 
> sum is a single number that you can add every other element in the sequence 
> to.  You only need to store three numbers in memory.  Storing millions is 
> wasteful, and doesn't scale very well.
> 
> To find an exponent, use the "**" operator.  For instance, 2**3 is 8, and 
3**2 
> is 9.
> 
> Cheers
> 
> 
> 

From steve.poe at gmail.com  Thu Jul 31 04:23:31 2008
From: steve.poe at gmail.com (Steve Poe)
Date: Wed, 30 Jul 2008 19:23:31 -0700
Subject: [Tutor] understanding join
In-Reply-To: <1c2a2c590807301703q6be950cv1f7a6287f818a053@mail.gmail.com>
References: <BE612F80-E036-4419-AA44-CA46A9214F45@gmail.com>
	<5e58f2e40807301454t68a759a2r521a502050b40116@mail.gmail.com>
	<C754EFE6-8012-4115-92B4-2E72A3576463@gmail.com>
	<5e58f2e40807301535r7a962244k9ea218298df0cb12@mail.gmail.com>
	<1c2a2c590807301703q6be950cv1f7a6287f818a053@mail.gmail.com>
Message-ID: <503DEC08-ABC2-4072-9B62-BC4A0DD2135A@gmail.com>

> Does this look useful?
>
> In [3]: people = [ 'Tom', 'Dick', 'Harry' ]
>
> In [4]: ', '.join(people)
> Out[4]: 'Tom, Dick, Harry'
>
> Your confusion is in thinking about the string 'ABC' as a single
> entity. For the purposes of join(), it is a sequence of three letters.
> The argument to join() is a sequence of strings, not a single string.
>
> Kent


Kent,

Your explanation about my confusion is right on target.  Thank you!

Okay, now let's join people to people and what do we get?

Steve





From steve.poe at gmail.com  Thu Jul 31 04:31:24 2008
From: steve.poe at gmail.com (Steve Poe)
Date: Wed, 30 Jul 2008 19:31:24 -0700
Subject: [Tutor] understanding join
In-Reply-To: <5e58f2e40807301535r7a962244k9ea218298df0cb12@mail.gmail.com>
References: <BE612F80-E036-4419-AA44-CA46A9214F45@gmail.com>
	<5e58f2e40807301454t68a759a2r521a502050b40116@mail.gmail.com>
	<C754EFE6-8012-4115-92B4-2E72A3576463@gmail.com>
	<5e58f2e40807301535r7a962244k9ea218298df0cb12@mail.gmail.com>
Message-ID: <BF6B5CF3-6EEC-4492-8751-DAEC865342D5@gmail.com>

>
> Say I have a sequence seq and a string s, and I call s.join(seq).
> Here's what it does:
>
> s.join(seq) == seq[0] + s + seq[1] + s + seq[2] + s + ...  + seq[-2] +
> s + seq[-1]
>
> So if you call 'abc'.join('ABC'), you get:
>
>   'ABC'[0] + 'abc' + 'ABC'[1] + 'abc' + 'ABC'[2]
>
> which is:
>
>   'A' + 'abc' + 'B' + 'abc' + 'C'
>
> Hope this helps.
>
> -- 
> John.


John,

Your explanation is very help. It does make be wonder the usefulness
of join with strings. Do you have a practical example/situation?

Steve

From john at fouhy.net  Thu Jul 31 04:57:20 2008
From: john at fouhy.net (John Fouhy)
Date: Thu, 31 Jul 2008 14:57:20 +1200
Subject: [Tutor] understanding join
In-Reply-To: <BF6B5CF3-6EEC-4492-8751-DAEC865342D5@gmail.com>
References: <BE612F80-E036-4419-AA44-CA46A9214F45@gmail.com>
	<5e58f2e40807301454t68a759a2r521a502050b40116@mail.gmail.com>
	<C754EFE6-8012-4115-92B4-2E72A3576463@gmail.com>
	<5e58f2e40807301535r7a962244k9ea218298df0cb12@mail.gmail.com>
	<BF6B5CF3-6EEC-4492-8751-DAEC865342D5@gmail.com>
Message-ID: <5e58f2e40807301957x28b8be82q901e2511f81a360c@mail.gmail.com>

On 31/07/2008, Steve Poe <steve.poe at gmail.com> wrote:
>  Your explanation is very help. It does make be wonder the usefulness
>  of join with strings. Do you have a practical example/situation?

Kent's example is common: you might have a list of strings that you
want to display to the user, so you call ', '.join() on the list.
Calling ''.join() is the standard way in Python to concatenate a bunch
of strings.  If you've got some two-dimensional data structure that
you want to convert to CSV, you could use the csv module, but if your
data is simple, it might be easier to just do: '\n'.join(','.join(row)
for row in data)

I guess it depends what kind of programming you're doing, but in my
experience, .join() is definitely a useful function.

-- 
John.

From john at fouhy.net  Thu Jul 31 05:05:00 2008
From: john at fouhy.net (John Fouhy)
Date: Thu, 31 Jul 2008 15:05:00 +1200
Subject: [Tutor] checking for expected types from input file
In-Reply-To: <fbf64d2b0807301843x3aaf2e85nd33bca64cca47e20@mail.gmail.com>
References: <fbf64d2b0807301843x3aaf2e85nd33bca64cca47e20@mail.gmail.com>
Message-ID: <5e58f2e40807302005m79546b40teaa57ccfd02fa527@mail.gmail.com>

On 31/07/2008, Bryan Fodness <bryan.fodness at gmail.com> wrote:
> I am populating a dictionary from an input file, and would like to create an
> error code if a string is sent to a variable that expects a float or int.
>
> INPUT = {}
> for line in open(infile):
>     input_line = line.split(' = ')
>     INPUT[input_line[0].strip()] = input_line[1].strip()
>
> if INPUT.has_key('ReferencePositionX'):
>     refx = float(INPUT['ReferencePositionX'])/10
>      refy = float(INPUT['ReferencePositionY'])/10
>     refz = float(INPUT['ReferencePositionZ'])/10
>
> I have many variables of different types, and I want to do a check in case
> something like ReferencePositionX = abc occurs.

You could make a dictionary that contains the types you expect; e.g.:

variable_types = { 'ReferencePositionX':float,
'ReferencePositionY':float, 'NumberOfWidgets':int, 'MyFirstName':str }

Then when you're reading in your data:

INPUT = {}
for line in open(infile):
    input_line = line.split(' = ')
    var_name = input_line[0].strip()
    INPUT[var_name] = variable_types[var_name](input_line[1].strip())

This means that:

1. Your INPUT dictionary will have all the values as the right types
(floats will be floats, not strings like '123.4', etc).
2. If you meet a variable name you're not expecting, the code will
raise a KeyError which may alert you to broken data, or which you can
catch and deal with.
3. If a variable has a bad value (like a string where it should have a
float), the code will raise a ValueError, which again will alert you
to a problem.
(note that str() works on everything, and int() works on floats and
vice versa, so if you want to be really picky, you will need to write
your own validation functions)

-- 
John.

From alan.gauld at btinternet.com  Thu Jul 31 07:39:32 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 31 Jul 2008 06:39:32 +0100
Subject: [Tutor] Memory error - how to manage large data sets?
References: <20080731.021956.906.1@SELINAPNOTE>
Message-ID: <g6rj2t$os3$1@ger.gmane.org>


"Kepala Pening" <kepalapening at gmail.com> wrote

> def sumEvenFibonacci( limit ):
> a, b = 1, 1  # don't waste with a = 0
> sum = 0
> while b < limit:
> if b%2 == 0: sum += b
> a, b = b, a + b
> return sum
> 
> print sumEvenFibonacci( 2000000 )

Does it work for limit = 2?

Alan G.



From alan.gauld at btinternet.com  Thu Jul 31 07:49:15 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 31 Jul 2008 06:49:15 +0100
Subject: [Tutor] understanding join
References: <BE612F80-E036-4419-AA44-CA46A9214F45@gmail.com><5e58f2e40807301454t68a759a2r521a502050b40116@mail.gmail.com><C754EFE6-8012-4115-92B4-2E72A3576463@gmail.com><5e58f2e40807301535r7a962244k9ea218298df0cb12@mail.gmail.com><1c2a2c590807301703q6be950cv1f7a6287f818a053@mail.gmail.com>
	<503DEC08-ABC2-4072-9B62-BC4A0DD2135A@gmail.com>
Message-ID: <g6rjl4$q6q$1@ger.gmane.org>

"Steve Poe" <steve.poe at gmail.com> wrote 

>> In [3]: people = [ 'Tom', 'Dick', 'Harry' ]

> Okay, now let's join people to people and what do we get?

An error, join only works on a single string.

It joins the elements of a sequence of strings into a single
string using the 'owning' string. In some ways, from an 
OOP point of view the method is counterintuitive. It should 
really be a method of a sequejnce taking a string as argument:

[1,2,3].join('/')

makes more sense to me than

'/'.join(['1','2','3'])

But the second is the correct form.
I found the string module function more readable

import string
string.join(['1','2','3'], '/')

Not least because you could omit the second argument 
and get a default space. Making join a member of the 
sequence would have allowed the default behaviour 
to continue. But I assume there were subtle snags 
with that scheme.

Just my personal opinion...

Alan G.



From alan.gauld at btinternet.com  Thu Jul 31 07:56:00 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 31 Jul 2008 06:56:00 +0100
Subject: [Tutor] checking for expected types from input file
References: <fbf64d2b0807301843x3aaf2e85nd33bca64cca47e20@mail.gmail.com>
Message-ID: <g6rk1p$r03$1@ger.gmane.org>


"Bryan Fodness" <bryan.fodness at gmail.com> wrote

> I have many variables of different types, and I want to do a check 
> in
> case something like ReferencePositionX = abc occurs.

In Python its usual to tackle that using try/except.
If you get a TypeError then try type conversion.
The saying goes somethinng like:
"Its better to ask forgivness than permission"

Alan G. 



From alan.gauld at btinternet.com  Thu Jul 31 07:53:11 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 31 Jul 2008 06:53:11 +0100
Subject: [Tutor] understanding join
References: <BE612F80-E036-4419-AA44-CA46A9214F45@gmail.com><5e58f2e40807301454t68a759a2r521a502050b40116@mail.gmail.com><C754EFE6-8012-4115-92B4-2E72A3576463@gmail.com><5e58f2e40807301535r7a962244k9ea218298df0cb12@mail.gmail.com>
	<BF6B5CF3-6EEC-4492-8751-DAEC865342D5@gmail.com>
Message-ID: <g6rjsg$qlc$1@ger.gmane.org>


"Steve Poe" <steve.poe at gmail.com> wrote

> Your explanation is very help. It does make be wonder the usefulness
> of join with strings. Do you have a practical example/situation?

Its not really intended for strings but it needs to work that way to
be consistent because strings are just another type of collection
in Python and we want to treat collections (or sequences)
as consistently as possible.

But there are times when you want to separate the characters
of a string out for display and inserting a space or a comma
using join is convenient. It would be extremely rare to use

mystring.joing(mystring)

It is usually

myseparator.join(mysequence)

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



From steve.poe at gmail.com  Thu Jul 31 07:57:47 2008
From: steve.poe at gmail.com (Steve Poe)
Date: Wed, 30 Jul 2008 22:57:47 -0700
Subject: [Tutor] key/value order in dictionaries
Message-ID: <A0B4A6C8-999B-4E04-86B6-E6AFDFAE0A3E@gmail.com>

Hi tutor list,

In dictionaries, I know that the keys are immutable, and the values
can change  What about the place/order of the key/order?  I thought
that they were sequential and they do not change.


 >>> D={"AAA":1234,"BBB":3456,"CCC":7890}
 >>> print D
{'AAA': 1234, 'BBB': 3456, 'CCC': 7890}
 >>> D={}
 >>> D={"AAA":1234,"BBB":3456,"CCC":7890,"DDD":5555,"EEE":6666,"FFF": 
7777}
 >>> print D
{'AAA': 1234, 'BBB': 3456, 'EEE': 6666, 'FFF': 7777, 'CCC': 7890,  
'DDD': 5555}

If I know the key, then I can find the value, so the order it is in  
the dictionary
should not matter. I am just curious  why this happens.  If I have (4)  
key/value
pairs, the display order is the same as I entered the them. With 5 or  
more key/value
dictionaries, the printed result is not sequential.

Any thoughts?

Steve

From kepalapening at gmail.com  Thu Jul 31 08:22:22 2008
From: kepalapening at gmail.com (Kepala Pening)
Date: Thu, 31 Jul 2008 14:22:22 +0800
Subject: [Tutor] Memory error - how to manage large data sets?
Message-ID: <20080731.062222.812.1@SELINAPNOTE>

Since the question is less than 2000000, I used
	b < limit.
However, to have limit = 2, perhaps I should do
	while b <= limit.

Thanks Alan for pointing it out.

----- Original Message -----
From: "Alan Gauld" <alan.gauld at btinternet.com>
To: tutor at python.org
Date: Thu, 31 Jul 2008 06:39:32 +0100
Subject: Re: [Tutor] Memory error - how to manage large data sets?

> 
> "Kepala Pening" <kepalapening at gmail.com> wrote
> 
> > def sumEvenFibonacci( limit ):
> > a, b = 1, 1  # don't waste with a = 0
> > sum = 0
> > while b < limit:
> > if b%2 == 0: sum += b
> > a, b = b, a + b
> > return sum
> > 
> > print sumEvenFibonacci( 2000000 )
> 
> Does it work for limit = 2?
> 
> Alan G.
> 
> 
> 
> 
> 

From mail at timgolden.me.uk  Thu Jul 31 10:33:20 2008
From: mail at timgolden.me.uk (Tim Golden)
Date: Thu, 31 Jul 2008 09:33:20 +0100
Subject: [Tutor] key/value order in dictionaries
In-Reply-To: <A0B4A6C8-999B-4E04-86B6-E6AFDFAE0A3E@gmail.com>
References: <A0B4A6C8-999B-4E04-86B6-E6AFDFAE0A3E@gmail.com>
Message-ID: <489178D0.4000304@timgolden.me.uk>

Steve Poe wrote:
> Hi tutor list,
> 
> In dictionaries, I know that the keys are immutable, and the values
> can change  What about the place/order of the key/order?  I thought
> that they were sequential and they do not change.

You were wrong :)

A lot of electronic ink has been spilt on this subject
over the years, and if you Google for things like
"python ordered dictionary" you'll find various
discussions and implementations.

In CPython dictionaries won't generally change order
if nothing's inserted or changed. But you certainly don't
want to rely on that as a characteristic. A Python
dictionary is considered inherently unordered (rather
like a set).

TJG

From monjissvel at googlemail.com  Thu Jul 31 12:33:48 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Thu, 31 Jul 2008 10:33:48 +0000
Subject: [Tutor] key/value order in dictionaries
In-Reply-To: <489178D0.4000304@timgolden.me.uk>
References: <A0B4A6C8-999B-4E04-86B6-E6AFDFAE0A3E@gmail.com>
	<489178D0.4000304@timgolden.me.uk>
Message-ID: <e2f191310807310333x7c019b50r328ba619024d14ab@mail.gmail.com>

Python dictionaries are not ordered & the order you will get when you print
a dictionary is the order that the python virtual machines thinks optimal
for that dictionary for its own internal procedures.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080731/921eda8e/attachment.htm>

From tomazbevec at yahoo.com  Thu Jul 31 12:39:46 2008
From: tomazbevec at yahoo.com (Tomaz Bevec)
Date: Thu, 31 Jul 2008 03:39:46 -0700 (PDT)
Subject: [Tutor] Mixing in and Mixing out classes in python
Message-ID: <176387.51878.qm@web32803.mail.mud.yahoo.com>

Hello,

I am using the following function to mixin in classes into specific object instances (this is adapted from python-list written py J.Jacob "new-style-classes-mixin", Fri Aug 9 14:05:41 CEST 2002):

***************************************************************************
def doMixin(targetInstance, extraClass):
    """
    Mixin new style classes see thread python tutor list, 
    appends the given name                                                                         onto the class name
    """
    class NewClass(extraClass,targetInstance.__class__): pass
      NewClass.__name__=targetInstance.__class__.__name__+"_"+extraClass.__name__
    targetInstance.__class__=NewClass
    try:
        extraClass.initialize(targetInstance)
    except AttributeError:
        pass
***************************************************************************

Is there an analogous way to "Mixout" classes from an instance at runtime?

Thank you,
Tomaz


      

From monjissvel at googlemail.com  Thu Jul 31 13:11:00 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Thu, 31 Jul 2008 11:11:00 +0000
Subject: [Tutor] Communication between threads
In-Reply-To: <g6qn2t$o05$1@ger.gmane.org>
References: <e107b4ff0807301359i51e91cf7p784e63c1db83d445@mail.gmail.com>
	<g6qn2t$o05$1@ger.gmane.org>
Message-ID: <e2f191310807310411k482d631k9cb4ff8f1c7d77a7@mail.gmail.com>

>
> I'm looking for some thoughts on how two separate threads can
> communicate in Python
>

You will probably get out of your doubts by reading about the
SocketServer module
and SocketServer.ThreadingTCPServer class.

Once your get a server up & running you can run parallel threads, from
there you can build
a global dictionary & use it to share data between you threads.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080731/989e8760/attachment.htm>

From flaxeater at gmail.com  Thu Jul 31 13:26:59 2008
From: flaxeater at gmail.com (Chad Crabtree)
Date: Thu, 31 Jul 2008 07:26:59 -0400
Subject: [Tutor] Communication between threads
In-Reply-To: <e2f191310807310411k482d631k9cb4ff8f1c7d77a7@mail.gmail.com>
References: <e107b4ff0807301359i51e91cf7p784e63c1db83d445@mail.gmail.com>
	<g6qn2t$o05$1@ger.gmane.org>
	<e2f191310807310411k482d631k9cb4ff8f1c7d77a7@mail.gmail.com>
Message-ID: <584940990807310426v3e055e55p2962fb633e7ec9d2@mail.gmail.com>

This is a great suggestion.  I too learned how to do threading in
python from reading code.  For me I read the btdownloadheadless.py
code.  Which comes as part of the standard bittorrent client in linux.

On Thu, Jul 31, 2008 at 7:11 AM, Monika Jisswel
<monjissvel at googlemail.com> wrote:
>> I'm looking for some thoughts on how two separate threads can
>> communicate in Python
>
> You will probably get out of your doubts by reading about the SocketServer
> module
> and SocketServer.ThreadingTCPServer class.
>
> Once your get a server up & running you can run parallel threads, from there
> you can build
>
> a global dictionary & use it to share data between you threads.
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>

From spython01 at gmail.com  Thu Jul 31 15:07:22 2008
From: spython01 at gmail.com (S Python)
Date: Thu, 31 Jul 2008 09:07:22 -0400
Subject: [Tutor] Reading List from File
Message-ID: <50a597410807310607l189115a5qa3335e706d33c1f8@mail.gmail.com>

Hi Everyone,

I am trying to read a comma-delimitted list ("aaa","bbb","ccc") from a text
file and assign those values to a list, x, such that:

x = ["aaa", "bbb", "ccc"]

The code that I have come up with looks like this:

>>> x = []
>>> f = open(r'c:\test.txt', 'r')
>>> x.extend(f.readlines())
>>> x
['"aaa","bbb","ccc"']

If you look closely, there is an extra pair of single quotes (') that
encapsulates the string.  Therefore, len(x) returns 1, instead of 3.  Is
there a function to "separate" this list out?  I hope my question makes
sense.

Thanks in advance.

Samir
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080731/9f329f25/attachment.htm>

From emadnawfal at gmail.com  Thu Jul 31 15:33:37 2008
From: emadnawfal at gmail.com (=?WINDOWS-1256?Q?Emad_Nawfal_(=DA=E3=C7=CF_=E4=E6=DD=E1)?=)
Date: Thu, 31 Jul 2008 08:33:37 -0500
Subject: [Tutor] Reading List from File
In-Reply-To: <50a597410807310607l189115a5qa3335e706d33c1f8@mail.gmail.com>
References: <50a597410807310607l189115a5qa3335e706d33c1f8@mail.gmail.com>
Message-ID: <652641e90807310633m28cda7f4v1d38fdea2f49a1d5@mail.gmail.com>

On Thu, Jul 31, 2008 at 8:07 AM, S Python <spython01 at gmail.com> wrote:

> Hi Everyone,
>
> I am trying to read a comma-delimitted list ("aaa","bbb","ccc") from a text
> file and assign those values to a list, x, such that:
>
> x = ["aaa", "bbb", "ccc"]
>
> The code that I have come up with looks like this:
>
> >>> x = []
> >>> f = open(r'c:\test.txt', 'r')
> >>> x.extend(f.readlines())
> >>> x
> ['"aaa","bbb","ccc"']
>
> If you look closely, there is an extra pair of single quotes (') that
> encapsulates the string.  Therefore, len(x) returns 1, instead of 3.  Is
> there a function to "separate" this list out?  I hope my question makes
> sense.
>
> Thanks in advance.
>
> Samir
>
>
This is an answer by a novice, and it may not be the best around;
Why don't you first get rid of the quotation marks and then split on the
comma:

>>> f = open(r'c:\test.txt', 'r').read().replace('"', '')
>>> x = []
>>> x.extend(f.split(","))
>>> x
['aa', ' bb', ' cc']
>>> len(x)
3

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


-- 
?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....????
???????
"No victim has ever been more repressed and alienated than the truth"

Emad Soliman Nawfal
Indiana University, Bloomington
http://emnawfal.googlepages.com
--------------------------------------------------------
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080731/0029f5d2/attachment.htm>

From amingv at gmail.com  Thu Jul 31 15:49:09 2008
From: amingv at gmail.com (amingv at gmail.com)
Date: Thu, 31 Jul 2008 13:49:09 +0000 (GMT)
Subject: [Tutor] Reading List from File
In-Reply-To: <50a597410807310607l189115a5qa3335e706d33c1f8@mail.gmail.com>
Message-ID: <21375642421217512149272@fastmobile.com>

If your list is in the format:
aaa,bbb,ccc

You can use
foo = in_file.readline.split(',')

--
Amin Rainmaker
-------------- next part --------------
An embedded message was scrubbed...
From: "S Python" <spython01 at gmail.com>
Subject: [Tutor] Reading List from File
Date: Thu, 31 Jul 2008 09:07:22 -0400
Size: 5907
URL: <http://mail.python.org/pipermail/tutor/attachments/20080731/ace245b1/attachment-0001.eml>

From lupin at orcon.net.nz  Thu Jul 31 16:06:44 2008
From: lupin at orcon.net.nz (Brett Wilkins)
Date: Fri, 1 Aug 2008 02:06:44 +1200
Subject: [Tutor] Reading List from File
In-Reply-To: <21375642421217512149272@fastmobile.com>
References: <21375642421217512149272@fastmobile.com>
Message-ID: <7D6D61F0-00DB-44FC-952E-A1258713122D@orcon.net.nz>

This is what I'd use...
But it'd also be rather easy with regex...
Oh well.

Here:

 >>> f = open('intext', 'r')
 >>> foo = f.readline().strip().replace('"','').split(',')
 >>> foo
['aaa', 'bbb', 'ccc']


Cheers

On 1/08/2008, at 1:49 AM, amingv at gmail.com wrote:

> If your list is in the format:
> aaa,bbb,ccc
>
> You can use
> foo = in_file.readline.split(',')
>
> --
> Amin Rainmaker
> From: "S Python" <spython01 at gmail.com>
> Date: 1 August 2008 1:07:22 AM
> To: tutor at python.org
> Subject: [Tutor] Reading List from File
>
>
> Hi Everyone,
>
> I am trying to read a comma-delimitted list ("aaa","bbb","ccc") from  
> a text file and assign those values to a list, x, such that:
>
> x = ["aaa", "bbb", "ccc"]
>
> The code that I have come up with looks like this:
>
> >>> x = []
> >>> f = open(r'c:\test.txt', 'r')
> >>> x.extend(f.readlines())
> >>> x
> ['"aaa","bbb","ccc"']
>
> If you look closely, there is an extra pair of single quotes (')  
> that encapsulates the string.  Therefore, len(x) returns 1, instead  
> of 3.  Is there a function to "separate" this list out?  I hope my  
> question makes sense.
>
> Thanks in advance.
>
> Samir
>
>
>
>
> _______________________________________________
> 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/20080801/df19e007/attachment.htm>

From swati.jarial at gmail.com  Thu Jul 31 16:50:54 2008
From: swati.jarial at gmail.com (swati jarial)
Date: Thu, 31 Jul 2008 10:50:54 -0400
Subject: [Tutor] To Specify a directory path to download
Message-ID: <ac1b71c60807310750v15f7968x86ec4d6b6ddbbb01@mail.gmail.com>

Hello,

I am new to python this is the code I have written to download a file from
the internet and then send en email if any error occurs during download. I
just want know how to specify which folder to download my files. It
automatically downloads file to the directory where TEST1.txt sits...

import urllib
import traceback
import sys
import cStringIO
import ncbi_SendEmail
import os.path
import os

try:

    for url in open("test1.txt"):
        save_to = os.path.basename(url.strip())
        urllib.urlretrieve(url.strip(),save_to)

except:
    mssg = cStringIO.StringIO()
    traceback.print_exc(file=mssg)
    ncbi_SendEmail.email(mssg.getvalue());
    mssg.close()



Thanks a Ton!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080731/6e90a6f8/attachment.htm>

From emile at fenx.com  Thu Jul 31 17:14:46 2008
From: emile at fenx.com (Emile van Sebille)
Date: Thu, 31 Jul 2008 08:14:46 -0700
Subject: [Tutor] Reading List from File
In-Reply-To: <50a597410807310607l189115a5qa3335e706d33c1f8@mail.gmail.com>
References: <50a597410807310607l189115a5qa3335e706d33c1f8@mail.gmail.com>
Message-ID: <g6sksp$569$1@ger.gmane.org>

S Python wrote:
> Hi Everyone,
>  
> I am trying to read a comma-delimitted list ("aaa","bbb","ccc") 

In this case, the standard library provides csv for parsing comma 
separated files.  It's not the same as rolling your own, but it is made 
specifically for this use case...

Emile


From muchanek at gmail.com  Thu Jul 31 17:47:33 2008
From: muchanek at gmail.com (kinuthiA muchanE)
Date: Thu, 31 Jul 2008 18:47:33 +0300
Subject: [Tutor] Tutor Digest, Vol 53, Issue 110
In-Reply-To: <mailman.9691.1217512164.920.tutor@python.org>
References: <mailman.9691.1217512164.920.tutor@python.org>
Message-ID: <1217519253.5887.7.camel@www.kinuthia.com>



> 
> Message: 5
> Date: Thu, 31 Jul 2008 09:07:22 -0400
> From: "S Python" <spython01 at gmail.com>
> Subject: [Tutor] Reading List from File
> To: tutor at python.org
> Message-ID:
>         <50a597410807310607l189115a5qa3335e706d33c1f8 at mail.gmail.com>
> Content-Type: text/plain; charset="iso-8859-1"
> 
> Hi Everyone,
> 
> I am trying to read a comma-delimitted list ("aaa","bbb","ccc") from a
> text
> file and assign those values to a list, x, such that:
> 
> x = ["aaa", "bbb", "ccc"]
> 
> The code that I have come up with looks like this:
> 
> >>> x = []
> >>> f = open(r'c:\test.txt', 'r')
> >>> x.extend(f.readlines())
> >>> x
> ['"aaa","bbb","ccc"']
> 
> If you look closely, there is an extra pair of single quotes (') that
> encapsulates the string.  Therefore, len(x) returns 1, instead of 3.
> Is
> there a function to "separate" this list out?  I hope my question
> makes
> sense.
I think you are better off using the csv module. If you have a comma
separated file you could...

import csv
reader = csv.reader(open("some.csv", "rb"))
for row in reader:
    print row
I yanked this straight out of the Python Reference Library :)
> 
> Thanks in advance.
> 
> Samir
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL:
> <http://mail.python.org/pipermail/tutor/attachments/20080731/9f329f25/attachment-0001.htm>
> 


From monjissvel at googlemail.com  Thu Jul 31 18:15:48 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Thu, 31 Jul 2008 16:15:48 +0000
Subject: [Tutor] Reading List from File
In-Reply-To: <g6sksp$569$1@ger.gmane.org>
References: <50a597410807310607l189115a5qa3335e706d33c1f8@mail.gmail.com>
	<g6sksp$569$1@ger.gmane.org>
Message-ID: <e2f191310807310915q3693b361ke15ae1e048615417@mail.gmail.com>

Emile is right, in python you can do most of the stuff yourself by hand
coding it, or you can use pre-made bullet proof and ready to go modules,
here you can go for the csv module that comes part of the standard library.

import csv
myfile = open('file', 'r')  # open file for reading
data = csv.Reader(myfile, delimeter = ',') # let csv module load it
print data



2008/7/31 Emile van Sebille <emile at fenx.com>

> S Python wrote:
>
>> Hi Everyone,
>>  I am trying to read a comma-delimitted list ("aaa","bbb","ccc")
>>
>
> In this case, the standard library provides csv for parsing comma separated
> files.  It's not the same as rolling your own, but it is made specifically
> for this use case...
>
> Emile
>
>
> _______________________________________________
> 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/20080731/3efbb3dc/attachment.htm>

From emile at fenx.com  Thu Jul 31 19:21:57 2008
From: emile at fenx.com (Emile van Sebille)
Date: Thu, 31 Jul 2008 10:21:57 -0700
Subject: [Tutor] Reading List from File
In-Reply-To: <e2f191310807310915q3693b361ke15ae1e048615417@mail.gmail.com>
References: <50a597410807310607l189115a5qa3335e706d33c1f8@mail.gmail.com>	<g6sksp$569$1@ger.gmane.org>
	<e2f191310807310915q3693b361ke15ae1e048615417@mail.gmail.com>
Message-ID: <g6ssal$qt$1@ger.gmane.org>

Monika Jisswel wrote:
> Emile is right, in python you can do most of the stuff yourself by hand 
> coding it, or you can use pre-made bullet proof and ready to go modules, 
> here you can go for the csv module that comes part of the standard library.


Yes -- and you'll avoid the pitfalls of dealing with embedded commas and 
quotes in the data.  CSV can be messy.  See 
http://en.wikipedia.org/wiki/Comma-separated_values for an overview of 
csv file content.

Emile


From monjissvel at googlemail.com  Thu Jul 31 19:23:33 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Thu, 31 Jul 2008 17:23:33 +0000
Subject: [Tutor] To Specify a directory path to download
In-Reply-To: <ac1b71c60807310750v15f7968x86ec4d6b6ddbbb01@mail.gmail.com>
References: <ac1b71c60807310750v15f7968x86ec4d6b6ddbbb01@mail.gmail.com>
Message-ID: <e2f191310807311023y621b4ca9u273fc52455da6210@mail.gmail.com>

>
> urllib.urlretrieve(url.strip(),save_to)
>
could be changed into this :
folder = '/home/html-data/'
urllib.urlretrieve(url.strip(),folder+save_to)



2008/7/31 swati jarial <swati.jarial at gmail.com>

> Hello,
>
> I am new to python this is the code I have written to download a file from
> the internet and then send en email if any error occurs during download. I
> just want know how to specify which folder to download my files. It
> automatically downloads file to the directory where TEST1.txt sits...
>
> import urllib
> import traceback
> import sys
> import cStringIO
> import ncbi_SendEmail
> import os.path
> import os
>
> try:
>
>     for url in open("test1.txt"):
>         save_to = os.path.basename(url.strip())
>         urllib.urlretrieve(url.strip(),save_to)
>
> except:
>     mssg = cStringIO.StringIO()
>     traceback.print_exc(file=mssg)
>     ncbi_SendEmail.email(mssg.getvalue());
>     mssg.close()
>
>
>
> Thanks a Ton!
>
> _______________________________________________
> 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/20080731/346303ef/attachment-0001.htm>

From spython01 at gmail.com  Thu Jul 31 20:03:55 2008
From: spython01 at gmail.com (S Python)
Date: Thu, 31 Jul 2008 14:03:55 -0400
Subject: [Tutor] Reading List from File
In-Reply-To: <50a597410807310607l189115a5qa3335e706d33c1f8@mail.gmail.com>
References: <50a597410807310607l189115a5qa3335e706d33c1f8@mail.gmail.com>
Message-ID: <50a597410807311103u5bb38a82x943f412d2625b83b@mail.gmail.com>

Hi Everyone,

Thanks for the variety of responses in such a short amount of time.
This distribution list is incredible.

Sorry for the delayed reply as I wanted to test what everyone
suggested, so here goes:

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

@Amin:  I tried your suggestion, but perhaps I don't understand your
syntax.  Here is what I tried and the resulting error message:

>>> f = open(r'C:\test.txt', 'r')
>>> foo = f.readline.split(',')

Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    foo = f.readline.split(',')
AttributeError: 'builtin_function_or_method' object has no attribute 'split'

Do you know what I did wrong?

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

@Emad, Brett:  Thank you for your solutions.  They do exactly what I
was looking for.

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

@Chad:  Thanks for your suggestion.  I think I like it best for its simplicity.

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

@Emile, Monika, kinuthi:  The CSV standard library looks interesting
but I am having mixed results in implementing it.  For example, it
works when I try this:

>>> reader = csv.reader(open(r'c:\test.txt', 'rb'))
>>> for row in reader:
	print row

	
['aaa', 'bbb', 'ccc']

but it fails when I try:

>>> import csv
>>> myfile = open(r'c:\test.txt', 'r')
>>> data = csv.Reader(myfile, delimeter = ',')

Traceback (most recent call last):
  File "<pyshell#26>", line 1, in <module>
    data = csv.Reader(myfile, delimeter = ',')
AttributeError: 'module' object has no attribute 'Reader'

The error looks similar to what I received when I tried Amin's
approach.  Am I missing something?

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

It's interesting to note that for the solutions to work correctly, I
had to remove the quotation marks from the input file.

Thanks again to EVERYONE who took the time to respond.  I appreciate your help.

Samir

From monjissvel at googlemail.com  Thu Jul 31 20:20:28 2008
From: monjissvel at googlemail.com (Monika Jisswel)
Date: Thu, 31 Jul 2008 18:20:28 +0000
Subject: [Tutor] Reading List from File
In-Reply-To: <50a597410807311103u5bb38a82x943f412d2625b83b@mail.gmail.com>
References: <50a597410807310607l189115a5qa3335e706d33c1f8@mail.gmail.com>
	<50a597410807311103u5bb38a82x943f412d2625b83b@mail.gmail.com>
Message-ID: <e2f191310807311120u4e028e82qc7a35518f0c3039c@mail.gmail.com>

oops it is reader not Reader (all lower case), so this line : data =
csv.Reader(myfile, delimeter = ',')
should be data = csv.reader(myfile, delimeter = ',')


2008/7/31 S Python <spython01 at gmail.com>

> Hi Everyone,
>
> Thanks for the variety of responses in such a short amount of time.
> This distribution list is incredible.
>
> Sorry for the delayed reply as I wanted to test what everyone
> suggested, so here goes:
>
> -------------------------------
>
> @Amin:  I tried your suggestion, but perhaps I don't understand your
> syntax.  Here is what I tried and the resulting error message:
>
> >>> f = open(r'C:\test.txt', 'r')
> >>> foo = f.readline.split(',')
>
> Traceback (most recent call last):
>  File "<pyshell#16>", line 1, in <module>
>    foo = f.readline.split(',')
> AttributeError: 'builtin_function_or_method' object has no attribute
> 'split'
>
> Do you know what I did wrong?
>
> -------------------------------
>
> @Emad, Brett:  Thank you for your solutions.  They do exactly what I
> was looking for.
>
> -------------------------------
>
> @Chad:  Thanks for your suggestion.  I think I like it best for its
> simplicity.
>
> -------------------------------
>
> @Emile, Monika, kinuthi:  The CSV standard library looks interesting
> but I am having mixed results in implementing it.  For example, it
> works when I try this:
>
> >>> reader = csv.reader(open(r'c:\test.txt', 'rb'))
> >>> for row in reader:
>        print row
>
>
> ['aaa', 'bbb', 'ccc']
>
> but it fails when I try:
>
> >>> import csv
> >>> myfile = open(r'c:\test.txt', 'r')
> >>> data = csv.Reader(myfile, delimeter = ',')
>
> Traceback (most recent call last):
>  File "<pyshell#26>", line 1, in <module>
>     data = csv.Reader(myfile, delimeter = ',')
> AttributeError: 'module' object has no attribute 'Reader'
>
> The error looks similar to what I received when I tried Amin's
> approach.  Am I missing something?
>
> -------------------------------
>
> It's interesting to note that for the solutions to work correctly, I
> had to remove the quotation marks from the input file.
>
> Thanks again to EVERYONE who took the time to respond.  I appreciate your
> help.
>
> Samir
> _______________________________________________
> 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/20080731/7cdcb26c/attachment.htm>

From spython01 at gmail.com  Thu Jul 31 20:29:41 2008
From: spython01 at gmail.com (S Python)
Date: Thu, 31 Jul 2008 14:29:41 -0400
Subject: [Tutor] Reading List from File
In-Reply-To: <e2f191310807311120u4e028e82qc7a35518f0c3039c@mail.gmail.com>
References: <50a597410807310607l189115a5qa3335e706d33c1f8@mail.gmail.com>
	<50a597410807311103u5bb38a82x943f412d2625b83b@mail.gmail.com>
	<e2f191310807311120u4e028e82qc7a35518f0c3039c@mail.gmail.com>
Message-ID: <50a597410807311129j34b2f1beu4b28c191bee2f511@mail.gmail.com>

Monika,

Thanks for your help.  I got it to work using the following (also had
to spell "delimiter"):

>>> import csv
>>> myfile = open(r'c:\test.txt', 'r')
>>> data  = csv.reader(myfile, delimiter=',')
>>> print data
<_csv.reader object at 0x00D41870>
>>> for item in data:
	print item

	
['aaa', 'bbb', 'ccc']

I think it was referred to in another post, but I have found this page
to be helpful:
http://docs.python.org/lib/csv-examples.html

Thanks.

Samir

On Thu, Jul 31, 2008 at 2:20 PM, Monika Jisswel
<monjissvel at googlemail.com> wrote:
> oops it is reader not Reader (all lower case), so this line : data =
> csv.Reader(myfile, delimeter = ',')
> should be data = csv.reader(myfile, delimeter = ',')
>
>
> 2008/7/31 S Python <spython01 at gmail.com>
>>
>> Hi Everyone,
>>
>> Thanks for the variety of responses in such a short amount of time.
>> This distribution list is incredible.
>>
>> Sorry for the delayed reply as I wanted to test what everyone
>> suggested, so here goes:
>>
>> -------------------------------
>>
>> @Amin:  I tried your suggestion, but perhaps I don't understand your
>> syntax.  Here is what I tried and the resulting error message:
>>
>> >>> f = open(r'C:\test.txt', 'r')
>> >>> foo = f.readline.split(',')
>>
>> Traceback (most recent call last):
>>  File "<pyshell#16>", line 1, in <module>
>>    foo = f.readline.split(',')
>> AttributeError: 'builtin_function_or_method' object has no attribute
>> 'split'
>>
>> Do you know what I did wrong?
>>
>> -------------------------------
>>
>> @Emad, Brett:  Thank you for your solutions.  They do exactly what I
>> was looking for.
>>
>> -------------------------------
>>
>> @Chad:  Thanks for your suggestion.  I think I like it best for its
>> simplicity.
>>
>> -------------------------------
>>
>> @Emile, Monika, kinuthi:  The CSV standard library looks interesting
>> but I am having mixed results in implementing it.  For example, it
>> works when I try this:
>>
>> >>> reader = csv.reader(open(r'c:\test.txt', 'rb'))
>> >>> for row in reader:
>>        print row
>>
>>
>> ['aaa', 'bbb', 'ccc']
>>
>> but it fails when I try:
>>
>> >>> import csv
>> >>> myfile = open(r'c:\test.txt', 'r')
>> >>> data = csv.Reader(myfile, delimeter = ',')
>>
>> Traceback (most recent call last):
>>  File "<pyshell#26>", line 1, in <module>
>>    data = csv.Reader(myfile, delimeter = ',')
>> AttributeError: 'module' object has no attribute 'Reader'
>>
>> The error looks similar to what I received when I tried Amin's
>> approach.  Am I missing something?
>>
>> -------------------------------
>>
>> It's interesting to note that for the solutions to work correctly, I
>> had to remove the quotation marks from the input file.
>>
>> Thanks again to EVERYONE who took the time to respond.  I appreciate your
>> help.
>>
>> Samir
>> _______________________________________________
>> 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 emile at fenx.com  Thu Jul 31 20:34:56 2008
From: emile at fenx.com (Emile van Sebille)
Date: Thu, 31 Jul 2008 11:34:56 -0700
Subject: [Tutor] Reading List from File
In-Reply-To: <50a597410807311103u5bb38a82x943f412d2625b83b@mail.gmail.com>
References: <50a597410807310607l189115a5qa3335e706d33c1f8@mail.gmail.com>
	<50a597410807311103u5bb38a82x943f412d2625b83b@mail.gmail.com>
Message-ID: <g6t0j7$gbi$1@ger.gmane.org>

S Python wrote:
>>>> f = open(r'C:\test.txt', 'r')
>>>> foo = f.readline.split(',')

readline is the function/method name
readline() executes that function/method and returns a value

try typing in 'type(f.readline)' vs 'type(f.readline())'

you can't .split() a function but you may split its return value.

> but it fails when I try:
> 
>>>> import csv
>>>> myfile = open(r'c:\test.txt', 'r')
>>>> data = csv.Reader(myfile, delimeter = ',')
> 

Python is case sensitive -- reader is different from Reader.

HTH,

Emile


From amingv at gmail.com  Thu Jul 31 21:00:15 2008
From: amingv at gmail.com (amingv at gmail.com)
Date: Thu, 31 Jul 2008 19:00:15 +0000 (GMT)
Subject: [Tutor] Reading List from File
In-Reply-To: <g6t0j7$gbi$1@ger.gmane.org>
Message-ID: <7554699871217530815068@fastmobile.com>

Emile is rigth, there should be a () there.
I'm sorry, im writing this from my cellphone and there's not a pc around XD.
I didn,t know about the csv module either and had to do over complicated things to deal with embedded commas, thx for that too :).

--
Amin Rainmaker
-------------- next part --------------
An embedded message was scrubbed...
From: Emile van Sebille <emile at fenx.com>
Subject: Re: [Tutor] Reading List from File
Date: Thu, 31 Jul 2008 11:34:56 -0700
Size: 4341
URL: <http://mail.python.org/pipermail/tutor/attachments/20080731/fb30780f/attachment.eml>

From spython01 at gmail.com  Thu Jul 31 22:12:34 2008
From: spython01 at gmail.com (S Python)
Date: Thu, 31 Jul 2008 16:12:34 -0400
Subject: [Tutor] Reading List from File
In-Reply-To: <7554699871217530815068@fastmobile.com>
References: <g6t0j7$gbi$1@ger.gmane.org>
	<7554699871217530815068@fastmobile.com>
Message-ID: <50a597410807311312qbf42ce4td34e3dacdaeecf6b@mail.gmail.com>

Emile, Amin:  Thank you both for your replies.  I was able to get it
working using:

>>> f = open(r'c:\test.txt', 'r')
>>> foo = f.readline().split(',')

Samir

On Thu, Jul 31, 2008 at 3:00 PM,  <amingv at gmail.com> wrote:
> Emile is rigth, there should be a () there.
> I'm sorry, im writing this from my cellphone and there's not a pc around XD.
> I didn,t know about the csv module either and had to do over complicated things to deal with embedded commas, thx for that too :).
>
> --
> Amin Rainmaker
>
> ---------- Forwarded message ----------
> From: Emile van Sebille <emile at fenx.com>
> To: tutor at python.org
> Date: Thu, 31 Jul 2008 11:34:56 -0700
> Subject: Re: [Tutor] Reading List from File
> S Python wrote:
>>>>>
>>>>> f = open(r'C:\test.txt', 'r')
>>>>> foo = f.readline.split(',')
>
> readline is the function/method name
> readline() executes that function/method and returns a value
>
> try typing in 'type(f.readline)' vs 'type(f.readline())'
>
> you can't .split() a function but you may split its return value.
>
>> but it fails when I try:
>>
>>>>> import csv
>>>>> myfile = open(r'c:\test.txt', 'r')
>>>>> data = csv.Reader(myfile, delimeter = ',')
>>
>
> Python is case sensitive -- reader is different from Reader.
>
> HTH,
>
> Emile
>
> _______________________________________________
> 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 bgailer at gmail.com  Thu Jul 31 22:26:27 2008
From: bgailer at gmail.com (bob gailer)
Date: Thu, 31 Jul 2008 16:26:27 -0400
Subject: [Tutor] Memory error - how to manage large data sets?
In-Reply-To: <20080731.021956.906.1@SELINAPNOTE>
References: <20080731.021956.906.1@SELINAPNOTE>
Message-ID: <48921FF3.5000303@gmail.com>

Kepala Pening wrote:
> def sumEvenFibonacci( limit ):
> 	a, b = 1, 1  # don't waste with a = 0
> 	sum = 0
> 	while b < limit:
> 		if b%2 == 0: sum += b
> 		a, b = b, a + b
> 	return sum
>
> print sumEvenFibonacci( 2000000 )
>
>
>   
Every 3rd element in the Fibonacci series is an even number. So one 
could economize slightly:

def sumEvenFibonacci(limit):
    a, b = 1, 1  # don't waste with a = 0
    sum = 0
    while b < limit:
	a, b = b, a + b
	sum += b
	a, b = b, a + b
	a, b = b, a + b
    return sum


-- 
Bob Gailer
919-636-4239 Chapel Hill, NC


From ricaraoz at gmail.com  Wed Jul 30 15:03:25 2008
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Wed, 30 Jul 2008 10:03:25 -0300
Subject: [Tutor] Style help: long strings with formatting
In-Reply-To: <g6njef$ef$1@ger.gmane.org>
References: <333efb450807291002j2cc7962ei80bb64503c70c7f7@mail.gmail.com>
	<g6njef$ef$1@ger.gmane.org>
Message-ID: <4890669D.7010507@bigfoot.com>

Alan Gauld wrote:
> 
> "W W" <srilyk at gmail.com> wrote
> 
>> output = "At an average weekly savings of $%.02f, your monthly 
>> savings  will
>> be $%.02f. \n Your annual savings will be $%.02f." % (diff, 
>> monthly_savings,
>> annual_savings)
>> print output.
>>
>> As you can see, it's very much longer than the 72 characters suggested in
>> the PEP 8 found here: http://www.python.org/dev/peps/pep-0008/
> 
> Use a triple quoted string for multiline output
> 
> output = """
> At an average weekly savings of \t$%.02f,
> your monthly savings  will be     \t$%.02f.
> Your annual savings will be       \t$%.02f.
> """ % (diff, monthly_savings, annual_savings)
> 
> print output
> 
> 
>> I know it would be fairly trivial to split it up into several strings, 
>> and
>> concatenating or printing each one.
> 
> Multiline strings are designed to save you having to do that.
> 

Alan, you have a couple of \n that the OP did not ask for.

Wayne, besides Alan's suggestion you might be looking for something
like :

Output = ('At an average weekly savings of $%.02f, your monthly '
	'savings  will be $%.02f. \n Your annual savings will'
	' be $%.02f.') % (diff, monthly_savings, annual_savings)

or :

Output = (
	'At an average weekly savings of $%.02f, your monthly '
	'savings  will be $%.02f. \n Your annual savings will'
	' be $%.02f.'
	) % (	diff
		, monthly_savings
		, annual_savings)

Or whatever. Parenthesis will help a lot when formatting your code.

HTH