Re: [Tutor] A Really Quick Question

2005-10-22 Thread Todd Maynard
Hi Steve,

Here is the python documentation.  Hopefully it is a *little* clearer

http://docs.python.org/lib/bltin-file-objects.html

*** readlines ***

readlines(  [sizehint])
 Read until EOF using readline() and return a list containing the lines thus 
read. If the optional sizehint argument is present, instead of reading up to 
EOF, whole lines totalling approximately sizehint bytes (possibly after 
rounding up to an internal buffer size) are read. Objects implementing a 
file-like interface may choose to ignore sizehint if it cannot be 
implemented, or cannot be implemented efficiently.

*** read ***
read(  [size])
 Read at most size bytes from the file (less if the read hits EOF before 
obtaining size bytes). If the size argument is negative or omitted, read all 
data until EOF is reached. The bytes are returned as a string object. An 
empty string is returned when EOF is encountered immediately. (For certain 
files, like ttys, it makes sense to continue reading after an EOF is hit.) 
Note that this method may call the underlying C function fread() more than 
once in an effort to acquire as close to size bytes as possible. Also note 
that when in non-blocking mode, less data than what was requested may be 
returned, even if no size parameter was given.

***

If you want to only read X bytes at a time then read would be more 
appropriate.

Have fun learning,

--Todd


On Saturday 22 October 2005 10:18, Steve Haley wrote:
> Folks,
>
>
>
> I am running Python 2.1 which ships with ArcView 9.1.  I am going through
> the 2.1 tutorial and came across readlines().  Simply put it doesn't seem
> to be behaving as the tutorial describes.  Specifically, I created a small
> text file as shown below:
>
>
>
> f=open("c:/python21/sfh_modules/test.txt", "w")
>
> f.write("This is the second line\n")
>
> f.write("This is the second line\n")
>
> f.close()  # then closed and reopened in read mode
>
> f=open("c:/python21/sfh_modules/test.txt", "r")
>
> f.readlines(2)  # Here's my problem
>
> ['This is the first line\n', 'This is the second line\n']  # please note
> this output
>
>
>
> The tutorial seems to be telling me that 'f.readlines(2) should read out 2
> bytes plus what is needed to complete the current line.  Instead, it is
> reading out the entire file no matter what I enter as a parameter.  I know
> I am going to feel really dumb when I hear the explanation but please
> remember I'm new to this.
>
>
>
> Thanks very much,
>
> Steve
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Indexing in a series for a newbie

2006-01-19 Thread Todd Maynard
Another approach would be to change your data structure to include the words 
and hints together as tuples in the same tuple.

ie...

WORDS=( ("python","The python hint"),("program","The program hint"),
("code","The code hint") )

then you can do...

word, hint = random.choice(WORDS)


>>> WORDS=( ("python","The python hint"),("program","The program hint"),
("code","The code hint") )
>>> word, hint = random.choice(WORDS)
>>> word
'code'
>>> hint
'The code hint'
>>>


Happy coding,

-- Todd Maynard


On Thursday 19 January 2006 10:36, Jon Moore wrote:
> Hello
>
> I need some help for a program I am writing as a newbie to Python.
>
> I have created a series:
>
> WORDS = ("python", "program", "code", "xylophone")
>
> and then assigned one of them randomly to the variable 'word':
>
> word = random.choice(WORDS)
>
> I know that if I do:
>
> print word
>
> The randomly chosen word will be displayed. I also know that if I type:
>
> print WORDS[x]
>
> I will get the corresponding word back. But how do I find 'programaticaly'
> the index number for the string that random.choice has chosen?
>
> The reason I ask is that I an writing a simple word jumble game and need to
> link the randomly chosen word to a hint should the user need one.
>
> --
> Best Regards
>
> Jon Moore

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


Re: [Tutor] Starbucks does not use two-phase commit

2006-01-21 Thread Todd Maynard
Danny,

I want to thank you for ruining my plans for a relaxing Saturday morning.  As 
a thread newbie I killed several hours playing around with your code.

One thing I noticed is that sometimes the program would hang, which I figured 
was the Queue code blocking in the Ticket claim function. I used exception 
handling to deal with that situation cleanly. 

I then decided that it wasn't very nice of Starbucks to close after accepting 
my order without giving me my Latte, so I changed that part of the code to:

 def schedule(self,job):
"""Schedules a job and returns a "ticket" the user can later use 
to get the result."""
if self.acceptNew == True:
  outputQueue=Queue()
  self.queue.put((job,outputQueue))
  return Ticket(outputQueue)
else:
   print "Server not accepting any new requests."
   return None

 def scheduleShutdown(self):
"""Add a job that shuts the system down."""
print "Telling server to shut down"
self.queue.put((Server._QUIT_NICELY,None))

 def _jobLoop(self):
"""Continue looping through tasks."""
while True:
   print "Looping ... "
   (nextJob, outputQueue) = self.queue.get()
   if nextJob is server._QUIT_NOW:
  return
   if nextJob is server._QUIT_NICELY:
self.acceptNew = False
self.queue.put((Server._QUIT_NOW,None))
   else:
  returnValue=self._doJob(nextJob)
  outputQueue.put(returnValue)


I am 99.44% sure that this is thread safe, reasoning being:
 setting the acceptNew to False and adding the QUIT_NOW happens in the 
same 
thread so it is impossible for another job to get scheduled after the 
QUIT_NOW - so no thread will end up hanging...

However, I would sleep a little better if you could reassure me that I am 
right, and would sleep even better if you could give me a method to test 
this.  This kinda stuff looks tricky to test with standard unittest 
methodology

Thanks again for the enligntenment all you guys bring to this awesome 
language.

My bastardized code is below for reference.

--Todd Maynard < [EMAIL PROTECTED] >


[It is] best to confuse only one issue at a time.
-- K&R


**


from threading import Thread
from Queue import Queue,Empty

class Ticket(object):
   """A small token we can use to claim our result."""
   def __init__(self, q):
  self.q = q
  self.result = None
  self.done=False

   def claim(self):
  if not self.done:
 try:
self.result=self.q.get(True,5)
self.done=True
 except Empty:
print "We lost the server!"
self.result=None
  return self.result


class Server(object):
 _QUIT_NOW=['Quit!']
 _QUIT_NICELY=['Quit Nicely']

 def __init__(self):
"""A queue will contain 2-tuples of (job, outputQueue) 
elements."""
self.queue=Queue()
self.acceptNew=True

 def startServer(self):
"""Brings the server online."""
Thread(target=self._jobLoop).start()

 def schedule(self,job):
"""Schedules a job and returns a "ticket" the user can later use 
to get the result."""
if self.acceptNew == True:
  outputQueue=Queue()
  self.queue.put((job,outputQueue))
  return Ticket(outputQueue)
else:
   print "Server not accepting any new requests."
   return None

 def scheduleShutdown(self):
"""Add a job that shuts the system down."""
print "Telling server to shut down"
self.queue.put((Server._QUIT_NICELY,None))

 def _jobLoop(self):
"""Continue looping through tasks."""
while True:
   print "Looping ... "
   (nextJob, outputQueue) = self.queue.get()
   if nextJob is server._QUIT_NOW:
  return
   if nextJob is server._QUIT_NICELY:
self.acceptNew = False
self.queue.put((Server._QUIT_NOW,None))
   else:
  returnValue=self._doJob(nextJob)
  outputQueue.put(returnValue)

 def _doJob(self,job):
print "I'm doing " , job
return job + job #Something to show

Re: [Tutor] Starbucks does not use two-phase commit

2006-01-22 Thread Todd Maynard
Well Danny, now I know how I am gonna spend my Sunday

Thanks for the great explanation and the resources.   Of course do you think I 
could manage to get the code to break - of course not Usually I have the 
opposite problem.  Anyways I think that your explanation makes perfect sense.

My problem with your original code is that _jobLoop could sometimes return 
when there where still jobs (from separateCaller) still left in the queue.  
When separateCaller tried to ticket.claim , the self.result = self.q.get() 
would block, causing the program to hang indefinitely.  This is what I was 
trying to prevent by using the timeout in the get() call and then handling 
the possible Empty exception. 

I am now gonna play with this some more to see if I can build a robust/clean 
coffeeshop framework, with customers placing orders with a cashier , the 
cashier passing the orders to a barista and the barista processing the orders 
and delivering to the customers.  The idea of course being that the 
customers, cashier, and baristas each run in different threads.  Then to 
enhance with multiple cashiers and baristas

but first I need to put another pot of coffee on.

If you don't hear from me in a while, I've probably suffered a caffeine 
overdose.  


Thanks for the inspiration,

Todd Maynard


-- 
The tao that can be tar(1)ed
is not the entire Tao.
The path that can be specified 
is not the Full Path.

We declare the names
of all variables and functions.
Yet the Tao has no type specifier.

Dynamically binding, you realize the magic.
Statically binding, you see only the hierarchy.

Yet magic and hierarchy
arise from the same source,
and this source has a null pointer.

Reference the NULL within NULL,
it is the gateway to all wizardry.


On Sunday 22 January 2006 03:13, Danny Yoo wrote:
> On Sat, 21 Jan 2006, Todd Maynard wrote:
> > I want to thank you for ruining my plans for a relaxing Saturday
> > morning.  As a thread newbie I killed several hours playing around with
> > your code.
>
> Hi Todd,
>
> Sorry about that.  I hope you were relaxing in a cafe while playing with
> the code.
>
> > One thing I noticed is that sometimes the program would hang, which I
> > figured was the Queue code blocking in the Ticket claim function. I used
> > exception handling to deal with that situation cleanly.
>
> That's odd.  There shouldn't be anything that blocks the code.  Oh!  Did
> you make changes to the test code, or did the hanging occur in the
> original code in:
>
> http://mail.python.org/pipermail/tutor/2006-January/044567.html
>
> I'm curious because nothing there should fundamentally block, assuming
> that _doJob() doesn't dies badly with an exception.  If _doJob() dies, the
> server dies, and that's bad.  *grin*
>
> Do you mind showing what the exception handling looks like in your code?
>
> > I then decided that it wasn't very nice of Starbucks to close after
> > accepting my order without giving me my Latte, so I changed that part of
> > the code to:
>
> [code cut]
>
> > I am 99.44% sure that this is thread safe, reasoning being:
> >  setting the acceptNew to False and adding the QUIT_NOW happens in the
> > same thread so it is impossible for another job to get scheduled after
> > the QUIT_NOW - so no thread will end up hanging...
>
> Bad news: no.  *grin*
>
> There's a "race condition".  Let's go into some detail with this, since
> this is not obvious stuff.
>
> First, let's look at the code again --- I'll label three lines with (a),
> (b), and (c), to make it a little easier to see the race.
>
>
> ###
> def schedule(self,job):
> if self.acceptNew == True:   ## (a)
> outputQueue=Queue()
> self.queue.put((job,outputQueue))
> return Ticket(outputQueue)
> else:
>  print "Server not accepting any new requests."
>  return None
>
> def scheduleShutdown(self):  ## (b)
> self.queue.put((Server._QUIT_NICELY,None))
>
> def _jobLoop(self):
> while True:
> print "Looping ... "
> (nextJob, outputQueue) = self.queue.get()
> if nextJob is server._QUIT_NOW:
> return
> if nextJob is server._QUIT_NICELY:   ## (c)
> self.acceptNew = False
> self.queue.put((Server._QUIT_NOW,None))
> else:
> returnValue=self._doJob(nextJob)
> outputQueue.put(returnValue)
> ##
>
>
> Let's imagine three threads, which I'll name C1, C2, and S

Re: [Tutor] G'day

2006-02-18 Thread Todd Maynard
John,

Just as an FYI, Dive into Python is available in printed form.   The 
http://diveintopython.org website has a link to it on Amazon.com. It might be 
cheaper than printing it out yourself..

--Todd Maynard



-- 
The world is coming to an end ... SAVE YOUR BUFFERS!!!



On Saturday 18 February 2006 07:11, John Connors wrote:
> G'day,
>
> Thanks to the people who replied, I only found them today and hopefully I
> didn't miss any. For some reason hotmail was sending them to junk even
> though it allowed the 1st message through and I had added tutor@python.org
> to my contact list. Should be sorted now I hope!
>
> > > print "Hello, World!"
> > >
> > > print ' 'Goodbye, World!"
> >
> >If you are referring to the bit on page 25 it is the same style of
> >quote in both examples in my copy of the book. Are you sure
> >its different? Or are you looking at another page?
>
> It was a library book and I have taken it back, there was typos all through
> it. I figured out that most of the syntax errors I was getting were from
> incorrect indentation. I knew indentation was important in python but I
> didn't realise it would return a syntax error if it was wrong. Not the
> authors fault BTW, just errors in the printing I think.
>
> I'm now using an ebook I found called Dive Into Python. I much prefer using
> a book so I can duck back a few pages to refresh my memory and reading on
> the monitor is a real pain. It seems an excellent reference though so I'll
> get around to printing it out sooner or latter (when the Mrs isn't here so
> she won't complain about me wasting ink and paper).
>
> John
>
> _
> realestate.com.au: the biggest address in property
> http://ninemsn.realestate.com.au
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor



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


Re: [Tutor] First Try

2006-02-19 Thread Todd Maynard
Nice Job John.  I made a few comments below on a few things I noticed.

On Sunday 19 February 2006 05:33, John Connors wrote:
> G'day :)
>
> I started getting sick of reading tutorials so for a bit of a break I set
> myself the task of writing a program to pick lotto numbers, 6 numbers
> between 1 and 44 (inclusive). I had done this many years before in basic
> and I thought back then it would be a simple task but I struck a problem of
> the random number generator repeating numbers occasionally so I had to
> check each number against the other and generate another random number if
> there were duplicates.
>
> So I was prepared for the same problem with python but I found that python
> takes care of that for me so the program would only have to be one line. I
> decided to make it a little more user friendly and allow the user to pick
> home many games they want generated. Then I made the output a little easier
> to read with a few blank lines. Here is what I came up with:
>
>
> import random
>
> numberof = int(raw_input('Enter how many games you would like generated
> :')) #user input for number of games to choose

10,000 lines of code or 6months later (whichever comes first...) will you 
remember what numberof represents?   Number of times the cow jumped over the 
moon?  I try not to end a var with a prep (and will usually just omit it).  I 
would personally go for num_games_wanted or num_tickets.  (Actually to tell 
the truth I am a mixedCase kinda guy so would really go for numGamesWanted or 
numTickets, but that is not really PEP 8 [1] friendly so I am trying to break 
my ways.)

>
> print
> print
> print "Here are your numbers :"
> print
>

If you desire you can use "\n" for return to reduce this all into one line:
   print "\n\n\Here are your numbers :\n\n"
No big deal.

> for games in range(1, numberof + 1): #loop for the number of games selected
> by user
> lotto = random.sample(xrange(1,45), 6) #generate 6 random numbers
> between 1 and 44 inclusive
> print games, lotto
> print
>
> else:
> print
> print "Hope you win!"
You don't need an else block (you will always enter it, ).

You can just do:

for games in range(1,numberof + 1):
lotto = random.sample(xrange(1,45),6)
print games, lotto
print
print "\nHope you win!"

>
>
> I know this is a very simple program but... could I have done this a better
> way?

Looks pretty good to me. If you want to expand this a little more you can 
try:

1.)  Assign all the lottery tickets to a variable and then print out the 
lottery tickets after you have them all.  ( A list would be helpful here...)

2.)  Break your program into functions so that you can do something like:

(num_tickets_wanted, min_num, max_num) = get_user_input()
lotto_tickets=generate_tickets(num_tickets_wanted, min_num,max_num)
print_results(lotto_tickets)

NOTE: It would be pure evil to drop that alll into one line.
print_results(generate_tickets(get_user_input()))

I shouldn't have even mentioned that, but you get the idea.
>
> John
>
> _
> Search for local singles online @ Lavalife - Click here
> http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Flavalife9%2Eninemsn%2Ecom%2
>Eau%2Fclickthru%2Fclickthru%2Eact%3Fid%3Dninemsn%26context%3Dan99%26locale%3
>Den%5FAU%26a%3D21550&_t=21550&_r=endtext&_m=EXT
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

Have some fun with itat least until you win the lottery.

--Todd Maynard

-- 
Computers are unreliable, but humans are even more unreliable.
Any system which depends on human reliability is unreliable.
-- Gilb
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] First Try

2006-02-19 Thread Todd Maynard
and for a belated footnote:

[1] = http://www.python.org/peps/pep-0008.html
Style Guide for python code.

--Todd


On Sunday 19 February 2006 06:27, Todd Maynard wrote:
> Nice Job John.  I made a few comments below on a few things I noticed.
>
> On Sunday 19 February 2006 05:33, John Connors wrote:
> > G'day :)
> >
> > I started getting sick of reading tutorials so for a bit of a break I set
> > myself the task of writing a program to pick lotto numbers, 6 numbers
> > between 1 and 44 (inclusive). I had done this many years before in basic
> > and I thought back then it would be a simple task but I struck a problem
> > of the random number generator repeating numbers occasionally so I had to
> > check each number against the other and generate another random number if
> > there were duplicates.
> >
> > So I was prepared for the same problem with python but I found that
> > python takes care of that for me so the program would only have to be one
> > line. I decided to make it a little more user friendly and allow the user
> > to pick home many games they want generated. Then I made the output a
> > little easier to read with a few blank lines. Here is what I came up
> > with:
> >
> >
> > import random
> >
> > numberof = int(raw_input('Enter how many games you would like generated
> >
> > :')) #user input for number of games to choose
>
> 10,000 lines of code or 6months later (whichever comes first...) will you
> remember what numberof represents?   Number of times the cow jumped over
> the moon?  I try not to end a var with a prep (and will usually just omit
> it).  I would personally go for num_games_wanted or num_tickets.  (Actually
> to tell the truth I am a mixedCase kinda guy so would really go for
> numGamesWanted or numTickets, but that is not really PEP 8 [1] friendly so
> I am trying to break my ways.)
>
> > print
> > print
> > print "Here are your numbers :"
> > print
>
> If you desire you can use "\n" for return to reduce this all into one line:
>print "\n\n\Here are your numbers :\n\n"
> No big deal.
>
> > for games in range(1, numberof + 1): #loop for the number of games
> > selected by user
> > lotto = random.sample(xrange(1,45), 6) #generate 6 random numbers
> > between 1 and 44 inclusive
> > print games, lotto
> > print
> >
> > else:
> > print
> > print "Hope you win!"
>
> You don't need an else block (you will always enter it, ).
>
> You can just do:
>
> for games in range(1,numberof + 1):
>   lotto = random.sample(xrange(1,45),6)
>   print games, lotto
>   print
> print "\nHope you win!"
>
> > I know this is a very simple program but... could I have done this a
> > better way?
>
> Looks pretty good to me. If you want to expand this a little more you
> can try:
>
> 1.)  Assign all the lottery tickets to a variable and then print out the
> lottery tickets after you have them all.  ( A list would be helpful
> here...)
>
> 2.)  Break your program into functions so that you can do something like:
>
> (num_tickets_wanted, min_num, max_num) = get_user_input()
> lotto_tickets=generate_tickets(num_tickets_wanted, min_num,max_num)
> print_results(lotto_tickets)
>
> NOTE: It would be pure evil to drop that alll into one line.
> print_results(generate_tickets(get_user_input()))
>
> I shouldn't have even mentioned that, but you get the idea.
>
> > John
> >
> > _
> > Search for local singles online @ Lavalife - Click here
> > http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Flavalife9%2Eninemsn%2Ecom
> >%2
> > Eau%2Fclickthru%2Fclickthru%2Eact%3Fid%3Dninemsn%26context%3Dan99%26local
> >e%3 Den%5FAU%26a%3D21550&_t=21550&_r=endtext&_m=EXT
> >
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
>
> Have some fun with itat least until you win the lottery.
>
> --Todd Maynard

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