Re: [Tutor] Question regarding syntax

2007-07-11 Thread Eric Brunson
Michael Klier wrote:
> Dave Kuhlman wrote:
>   
>> On Wed, Jul 11, 2007 at 11:03:18AM -0400, John Morris wrote:
>> 
>>> I'm editing some code from Mailman and seeing:
>>>
>>> legend = _("%(hostname)s Mailing Lists")
>>>
>>>   
>
> I am no python pro but I guess that funtction _() ist just a wrapper
> function around gettext.gettext from the gettext module (used for
> localization). I`ve seen that in lots of places and I think that`s
> common practise (don`t beat me if I am wrong ;-)).
>
>   
>> Mailman is a great product. But that bit of code is not, I think,
>> very good code.  
>> 
>
> Even the python gettext docs [1] use it that way.
>
> [1] http://docs.python.org/lib/node732.html
>
>   

I've seen it before, too.  From the example in the manual I imagine it's 
more convention than anything hard and fast, probably to make the string 
stand out more than the function call since it's essentially just doing 
a translation.

However, by assigning gettext.getttext to the local variable '_', you do 
avoid a module lookup every time it's used.  It's useful when you do 
something like this (contrived example):

import math

f = math.cos
for x in range(0, 10):
print x, f(x)



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


Re: [Tutor] How do you install EGG files

2007-07-11 Thread Eric Brunson
Terry Carroll wrote:
> On Wed, 11 Jul 2007, shawn bright wrote:
>
>   
>> Hey there all,
>> i got the news that storm was released as open source. Storm is a db orm for
>> python.
>> i have a downloaded package and i would like to play with it, but it does
>> not come with any install instructions.
>> i found the package here https://storm.canonical.com/FrontPage
>> there is a makefile in the top level folder, so should i use gcc and try to
>> 'make'  'make install' or is that not necessarily the way to go here?
>> 
>
> Yeah, the docs at https://storm.canonical.com/Install leave a little bit 
> to be desired.
>
> I see it comes in an EGG format, which is just a ZIP file.   What will (I 
> think) work is to open the EGG file with your favorite unzipper and unzip 
> into your site-packages directory (making sure to use the directory names 
> from the EGG file).
>
> Just for the heck of it, I tried this out.  Before the unzipping:
>
>   
 import storm
 
> Traceback (most recent call last):
>   File "", line 1, in 
> ImportError: No module named storm
>
> Then I unzipped as described above:
>
>   
 import storm
 dir(storm)
 
> ['Undef', 'UndefType', '__builtins__', '__doc__', '__file__', '__name__', 
> '__path__']
>   
 print storm.__doc__
 
> None
>   
 print storm.__path__
 
> ['C:\\Python25\\lib\\site-packages\\storm']
>   
>
> So that seems to work.
>
> But the larger question is, "What do I do with an EGG file?"  I know 
> there's a more straightforward way of having Python process an EGG file, 
> just as Java processes a JAR file.  I've just never had to learn it.
>
> I'm retitling this thread in the hopes that someone who knows will assist; 
> then I'll learn something, too.
>   

Add the full path of the egg to a .pth file in a directory in your 
python path.

> ___
> 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] Here is newbie doc on how to implement generators

2007-07-13 Thread Eric Brunson
Dave Kuhlman wrote:
> I find iterators and generators fascinating.  So, in order to try
> to understand them better myself, I've written up some notes.  I'm
> hoping that these notes might help someone new to the generators
> and iterators in Python.  You can find it here:
>
> http://www.rexx.com/~dkuhlman/python_comments.html
> 
> http://www.rexx.com/~dkuhlman/python_comments.html#iterators-and-generators
>
> I'll appreciate any comments and suggestions that might help me
> improve it.
>
> Please pass the above link along to anyone you think it might help.
>
> And, I have a question -- If you look at the example of the
> iterative (non-recursive) generator (the Doubler class), you will
> see that it walks a list, not a tree.  That's because I was *not*
> able to figure out how to implement a non-recursive tree walk
> generator.
>
> I found examples showing non-recursive/iterative solutions to how
> to walk a *binary* tree.  Those examples are at:
>
> Lib/test/test_generator.py   # in the Python distribution
> http://en.wikipedia.org/wiki/Inorder_tree_walk
>
> But, I could not find a example that shows a non-recursive way to
> walk a tree in which each node has an arbitrary number of children.
>   

If you store your tree data in an adjacency list iteration becomes trivial.

> Alas, I could not write that non-recursive tree walk.  The recusive
> walk is easy and clean.  So, maybe I should not worry about the
> non-recursive approach.  Still, it really bothers me that I could
> not do it.
>
> So, if you know where there are some examples, that would help me
> improve my notes on iterators and generators, please give me a
> link.
>
> Dave
>
>
>
>   

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


Re: [Tutor] Importing question

2007-07-13 Thread Eric Brunson
Dick Moores wrote:
> At http://wiki.python.org/moin/SimplePrograms I found this code:
>
> 
> import itertools
>
> def iter_primes():
>  # an iterator of all numbers between 2 and +infinity
>  numbers = itertools.count(2)
>
>  # generate primes forever
>  while True:
>  # get the first number from the iterator (always a prime)
>  prime = numbers.next()
>  yield prime
>
>  # this code iteratively builds up a chain of
>  # filters...slightly tricky, but ponder it a bit
>  numbers = itertools.ifilter(prime.__rmod__, numbers)
>
> for p in iter_primes():
> if p > 1000:
> break
> print p
> 
>
> It works for me in Win XP, Python 2.5.
>
> However, in trying to dig into the code to understand it, I'm not able 
> to find itertools.py, even though itertools is found in the docs at < 
> http://www.python.org/doc/2.4/lib/module-itertools.html>.
> A search of my Python25 directory doesn't turn up an itertools.py.
>
> So my question is, how does the first line of the code work? /Where 
> /is itertools?

On my Fedora 7 system it is in 
/usr/lib/python2.5/lib-dynload/itertoolsmodule.so.

Note the difference in naming for built in binary objects.

>
> Thanks,
>
> Dick Moores
> 
>
> ___
> 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] CGI Calculator

2007-07-16 Thread Eric Brunson
Darren Williams wrote:
> Hi all,
>  
> I am a Python convert coming from a JavaScript background

Welcome to Python, Darren.

> (as you can probably tell) and am currently writing my first 
> application using Python which will be a calculator for an online game 
> I used to play (thought it would be a decent first project) but am not 
> sure on the syntax for referencing an HTML form input field, I tried 
> this (which returns an error) -
>  
> XHTML form -
>  
> 
>  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd";>
> http://www.w3.org/1999/xhtml"; xml:lang="en" lang="en">
> 
> DopeWars Junkie Calculator
> 
> 
> 
> http://newspyn.com/cgi-bin/JunkieCalc.py";>
> Coat Size: 
> Used Pockets: 
> Lab Space: 
> Total Junkies:  name="totalJunkies">
> Dealer Visits Remaining:  name="DVR">
> 
> 
> 
> 
>  
> junkieCalc.py -
>  
> #!/usr/bin/env python
>  
> import cgi
>  
> def main():
> print "Content-type: text/html\n"
> form = cgi.FieldStorage()
> if form.has_key("coatSize") and form.has_key("usedPockets") and 
> form.has_key("labSpace") and form.has_key("totalJunkies") and 
> form.has_key("DVR") and form["coatSize"].value != "" and 
> form["usedPockets"].value != "" and form["labSpace"].value != "" and 
> form["totalJunkies"].value != "" and form["DVR"].value != "":
> Tokens = 0
> while usedPockets > (totalJunkies - labSpace) * 17:
> Tokens = Tokens + 1
> usedPockets = (usedPockets - totalJunkies + labSpace) * 17
> totalJunkies = totalJunkies + 1
> print "Tokens"
> else:
> print "Try again"
>  
> main()
>  
> This is the error i'm getting -
>  
> Traceback (most recent call last): File 
> "D:\inetpub\vhosts\newspyn.com\cgi-bin\JunkieCalc.py", line 23, in ? 
> main() File "D:\inetpub\vhosts\newspyn.com\cgi-bin\JunkieCalc.py", 
> line 10, in main while usedPockets > (totalJunkies - labSpace) * 17: 
> UnboundLocalError: local variable 'usedPockets' referenced before 
> assignment

So, you get an error on line 10, which is:

while usedPockets > (totalJunkies - labSpace) * 17:

and it says that your variable is referenced before assignment.  Have 
you assigned a value to it?  In your intro you ask how to reference an 
HTML form field, well you're already doing it in your if statement: 
form["labSpace"].value, so if you want a local variable named 
usedPockets, you should assign a value to it, like:  usedPockets = 
form["usedPockets"].value


As an aside, a nice tool for helping debug CGI scripts is the CGI 
Traceback module.  Add this as the first line of the program (after the 
shebang line, before the import cgi:

import cgitb; cgitb.enable()

Hope that helps,
e.

>  
> Thanks in advance for any help :)
> 
>
> ___
> 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] CGI Calculator

2007-07-16 Thread Eric Brunson
Darren Williams wrote:
> Ok, now i've modified my script but am getting another error, i've 
> commented a few useless (hopefully) lines out -
>
> #!/usr/bin/env python
>
> import cgitb; cgitb.enable()
> import cgi
>
>
[snip]
> 17 while usedPockets > totalJunkies - labSpace * 17:
>
> 18 Tokens = Tokens + 1
>
> 19 usedPockets = (usedPockets - totalJunkies + 
> labSpace) * 17
>
>  usedPockets = '192000', totalJunkies = '200', labSpace = '0'
>
> TypeError: unsupported operand type(s) for -: 'str' and 'str'
>  args = ("unsupported operand type(s) for -: 'str' and 'str'",)
>

What does "dog" - "cat" mean?  Similarly, what does "100" - "12" mean?  
It's not the same in Python as 100 - 12, because those are numbers, 
"100" and "12" are strings which happen to represent numbers.

You need to coerce those strings into integers, maybe like this:

usedPockets = int(form["usedPockets"].value)

When you do that, you'll probably need to catch any exception that could 
occur if the string can't be converted.

>
>
> It's confused me - it says I can't subtract a string from a string but 
> then gives the value's of the variables (that I randomly entered into 
> the form) at the bottom - usedPockets = '192000', totalJunkies = 
> '200', labSpace = '0'
>

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


Re: [Tutor] CGI Calculator

2007-07-16 Thread Eric Brunson
Darren Williams wrote:
> Now another problem - the script is just printing the word 'Tokens' 
> over and over again, it's supposed to work like this (JavaScript 
> version made by me) - http://nazkyn.brinkster.net/1.8.html
>
> Thanks in advance for any help :)

It's doing exactly what you've told it to do:

   while usedPockets > totalJunkies - labSpace * 17:
   Tokens = Tokens + 1
   usedPockets = (usedPockets - totalJunkies + labSpace) * 17
   totalJunkies = totalJunkies + 1
   print "Tokens"

The print statement is inside the while loop and you've quoted the work 
"Tokens" so it's printing the string rather than the variable.

How about grabbing a short tutorial on Python and reading through it to 
better understand the differences between Python and Javascript.  If 
you're an experienced JS programmer it shouldn't take very long.

This is probably closer is what I infer you're looking for:

   while usedPockets > totalJunkies - labSpace * 17:
   Tokens = Tokens + 1
   usedPockets = (usedPockets - totalJunkies + labSpace) * 17
   totalJunkies = totalJunkies + 1
   print "Tokens: %s" % Tokens

e.

>
> - Original Message - From: "Eric Brunson" <[EMAIL PROTECTED]>
> To: "Darren Williams" <[EMAIL PROTECTED]>
> Cc: 
> Sent: Monday, July 16, 2007 2:01 PM
> Subject: Re: [Tutor] CGI Calculator
>
>
>> Darren Williams wrote:
>>> Ok, now i've modified my script but am getting another error, i've 
>>> commented a few useless (hopefully) lines out -
>>>
>>> #!/usr/bin/env python
>>>
>>> import cgitb; cgitb.enable()
>>> import cgi
>>>
>>>
>> [snip]
>>> 17 while usedPockets > totalJunkies - labSpace * 17:
>>>
>>> 18 Tokens = Tokens + 1
>>>
>>> 19 usedPockets = (usedPockets - totalJunkies + 
>>> labSpace) * 17
>>>
>>>  usedPockets = '192000', totalJunkies = '200', labSpace = '0'
>>>
>>> TypeError: unsupported operand type(s) for -: 'str' and 'str'
>>>  args = ("unsupported operand type(s) for -: 'str' and 'str'",)
>>>
>>
>> What does "dog" - "cat" mean?  Similarly, what does "100" - "12" 
>> mean? It's not the same in Python as 100 - 12, because those are 
>> numbers, "100" and "12" are strings which happen to represent numbers.
>>
>> You need to coerce those strings into integers, maybe like this:
>>
>> usedPockets = int(form["usedPockets"].value)
>>
>> When you do that, you'll probably need to catch any exception that 
>> could occur if the string can't be converted.
>>
>>>
>>>
>>> It's confused me - it says I can't subtract a string from a string 
>>> but then gives the value's of the variables (that I randomly entered 
>>> into the form) at the bottom - usedPockets = '192000', totalJunkies 
>>> = '200', labSpace = '0'
>>>
>>
>>
>

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


Re: [Tutor] CGI Calculator

2007-07-16 Thread Eric Brunson

Here's a start by Guido:  http://docs.python.org/tut/tut.html

And here's a bunch more:  http://www.python.org/doc/Intros.html

I'm not sure of your level of expertise, so I can't recommend any of 
them in particular.

Darren Williams wrote:
> That's just printing Tokens: 1 Tokens: 2 ... Tokens: 6000 etc...
>
> Can you recommend any tutorials for me?
>  
> ----- Original Message - 
> From: "Eric Brunson" <[EMAIL PROTECTED]>
> To: "Darren Williams" <[EMAIL PROTECTED]>
> Cc: 
> Sent: Monday, July 16, 2007 2:48 PM
> Subject: Re: [Tutor] CGI Calculator
>
>
>   
>> Darren Williams wrote:
>> 
>>> Now another problem - the script is just printing the word 'Tokens' 
>>> over and over again, it's supposed to work like this (JavaScript 
>>> version made by me) - http://nazkyn.brinkster.net/1.8.html
>>>
>>> Thanks in advance for any help :)
>>>   
>> It's doing exactly what you've told it to do:
>>
>>   while usedPockets > totalJunkies - labSpace * 17:
>>   Tokens = Tokens + 1
>>   usedPockets = (usedPockets - totalJunkies + labSpace) * 17
>>   totalJunkies = totalJunkies + 1
>>   print "Tokens"
>>
>> The print statement is inside the while loop and you've quoted the work 
>> "Tokens" so it's printing the string rather than the variable.
>>
>> How about grabbing a short tutorial on Python and reading through it to 
>> better understand the differences between Python and Javascript.  If 
>> you're an experienced JS programmer it shouldn't take very long.
>>
>> This is probably closer is what I infer you're looking for:
>>
>>   while usedPockets > totalJunkies - labSpace * 17:
>>   Tokens = Tokens + 1
>>   usedPockets = (usedPockets - totalJunkies + labSpace) * 17
>>   totalJunkies = totalJunkies + 1
>>   print "Tokens: %s" % Tokens
>>
>> e.
>>
>> 
>>> - Original Message - From: "Eric Brunson" <[EMAIL PROTECTED]>
>>> To: "Darren Williams" <[EMAIL PROTECTED]>
>>> Cc: 
>>> Sent: Monday, July 16, 2007 2:01 PM
>>> Subject: Re: [Tutor] CGI Calculator
>>>
>>>
>>>   
>>>> Darren Williams wrote:
>>>> 
>>>>> Ok, now i've modified my script but am getting another error, i've 
>>>>> commented a few useless (hopefully) lines out -
>>>>>
>>>>> #!/usr/bin/env python
>>>>>
>>>>> import cgitb; cgitb.enable()
>>>>> import cgi
>>>>>
>>>>>
>>>>>   
>>>> [snip]
>>>> 
>>>>> 17 while usedPockets > totalJunkies - labSpace * 17:
>>>>>
>>>>> 18 Tokens = Tokens + 1
>>>>>
>>>>> 19 usedPockets = (usedPockets - totalJunkies + 
>>>>> labSpace) * 17
>>>>>
>>>>>  usedPockets = '192000', totalJunkies = '200', labSpace = '0'
>>>>>
>>>>> TypeError: unsupported operand type(s) for -: 'str' and 'str'
>>>>>  args = ("unsupported operand type(s) for -: 'str' and 'str'",)
>>>>>
>>>>>   
>>>> What does "dog" - "cat" mean?  Similarly, what does "100" - "12" 
>>>> mean? It's not the same in Python as 100 - 12, because those are 
>>>> numbers, "100" and "12" are strings which happen to represent numbers.
>>>>
>>>> You need to coerce those strings into integers, maybe like this:
>>>>
>>>> usedPockets = int(form["usedPockets"].value)
>>>>
>>>> When you do that, you'll probably need to catch any exception that 
>>>> could occur if the string can't be converted.
>>>>
>>>> 
>>>>> It's confused me - it says I can't subtract a string from a string 
>>>>> but then gives the value's of the variables (that I randomly entered 
>>>>> into the form) at the bottom - usedPockets = '192000', totalJunkies 
>>>>> = '200', labSpace = '0'
>>>>>
>>>>>   
>>>> 
>> 

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


Re: [Tutor] interpreter restarts

2007-07-17 Thread Eric Brunson

Sara,

Stick with ssh, IDE's are a crutch.  ;-)

But that's just my opinion, others may differ.

However, if you were running an X server on your local machine, you 
could use SSH to allow you to run GUI programs from your remote server.  
There are a couple of free X servers for Windoze, but running Linux on 
your local machine would give you the greatest success.  If you are 
interested in pursuing this, google up and install an X server, then 
post back.

Sincerely,
e.

Sara Johnson wrote:
> Luke, Jacob, et. al...
>  
> Dumb question (may be slightly off course from what you two were 
> discussing), but are you both describing how to get the IDLE to run 
> along with the editor?  I may just be getting too many things 
> confused.  I've tried to run IDLE, but that's not working.  I have the 
> same function through opening it separately from the Start menu but 
> then it doesn't work as IDLE should work with the editor (or so I've 
> been told that happens).  I can type the word Python in my editor and 
> it comes up, but then the editor is gone.  I've gone so long with just 
> SSH, but at this point it's worth it if I find a way that makes 
> sense.  As someone mentioned from this list, at least it'll be code 
> that is easier to read for a newbie like myself. 
>  
> (Hope that didn't confuse or cause unnecessary headaches...)
>  
> Sara
>
> - Original Message 
> From: Luke Paireepinart <[EMAIL PROTECTED]>
> To: Tiger12506 <[EMAIL PROTECTED]>
> Cc: tutor@python.org
> Sent: Monday, July 16, 2007 7:00:53 PM
> Subject: Re: [Tutor] interpreter restarts
>
> Tiger12506 wrote:
> >> But there's an exception to that - if you right-click a file in Windoze
> >> and 'edit' it,
> >> IDLE won't open up its subprocess, and as such, it can't restart the
> >> interpreter session because it's running in the same
> >> process as IDLE, and to restart the interpreter would mean restarting
> >> IDLE.
> >> Boy, that 'edit with idle' thing sure does cause some problems, 
> don't it?
> >> :)
> >> -Luke
> >>
> >
> > Thanks, Luke. I hadn't thought of that. Question: Why won't IDLE 
> open up its
> > subprocess?
> >
> > This is the command that is in the registry concerning the Edit with 
> IDLE
> > menu.
> > "C:\Python25\pythonw.exe" "C:\Python25\Lib\idlelib\idle.pyw" -n -e "%1"
> >
> > This is the Target for the shortcut in the Start Menu (Note: the 
> Target box
> > was disabled!)
> > Python 2.5.1
> >
> > I thought that this was incredibly strange, so I opened this 
> shortcut in a
> > hex editor to see what was different about this shortcut. (Normally, 
> they
> > have a path in the target box)
> >
> > What I found surprised me. The title of the file in the hex editor said
> > "python_icon.exe"
> > I started laughing maniacally and checked the full path of the file 
> from
> > within the hex editor.
> > 
> C:\windows\installer\{3184-6386-4999-a519-518f2d78d8f0}\python_icon.exe
> >
> > IDLE is started in two *very* different ways. So my next question 
> was: Can
> > you pass arguments to this python_icon.exe? Simple navigations to that
> > directory and a confirmation... Yuck. You can't even execute it from
> > explorer. A low-level ZwTerminateProcess function from ntdll is 
> called ...
> > Let me try something...
> >
> > Woah... {3184-6386-4999-a519-518f2d78d8f0} appears in the 
> registry in
> > alot of places. The Uninstall key for Add/Remove Programs, some 
> weird data
> > thing... Okay, this is beyond me. I don't know the registry or 
> understand
> > CLSIDs very well. Someone who knows Windows inside and out has done 
> a number
> > with the python installer, or at least the msi installer does this all
> > automatically. Interesting. I wonder just how python_icon.exe starts 
> IDLE.
> > If I could figure that out, I could emulate it with the Edit w/Idle 
> menu
> > item and get IDLE to start a subprocess! But how any ideas?
> >  
> It sounds like python_icon.exe is a fake executable that just contains
> the icon for python programs...
> hence the name.
> You probably stumbled across the path to the icon to use, instead of the
> path that is used when running the 'Edit with IDLE' thing.
> Try this:
> open an Explorer window, via Start Button -> Run -> explorer {ENTER}
> or your favorite method.  Use the My Computer shortcut if you want,
> either way.
> Now hit "Alt, t, o" to browse to the Tools -> Folder Options menu setting.
> Go to the File Types tab, and scroll down till you find "PY"
> click the Advanced button.
> You should now see a dialog box with Edit with IDLE listed under actions.
> Click Edit when "Edit with IDLE" is selected.
> in the "Application used to perform action:" field you should see
> something like this:
>
> "C:\Python24\pythonw.exe" "C:\Python24\Lib\idlelib\idle.pyw" -n -e "%1"
>
> Basically, this is the same as saying:
> python idle.py
> except it's more verbose because python may not be on your path (and
> pythonw is used instead of python so there's no dos box)
> As you

Re: [Tutor] Style question with classes and modules

2007-07-19 Thread Eric Brunson
Tino Dai wrote:
> On 7/19/07, *Kent Johnson* <[EMAIL PROTECTED] > 
> wrote:
>
> > The two advantages that I can see are, I don't need to type as
> much, and
> > there would be a speed up in the execution of code.
>
> Why do you expect a speedup?
>
>
> In the  Python  Reference by David Beazley on p. 40, he substituted 
> import math
> with from math import sqrt and he switched out d = d + math.sqrt(i) with
> sqrt(i). He said that that change made the program run twice as fast.  
> So therefore
> I was under the impression that "from somemodule import someclass" 
> would always be
> faster than import somemodule.

The reason it's faster is because to get the actual function for 
math.sqrt() after importing math, you have to do a dictionary lookup in 
the "math" namespace.  I don't think it should run twice as fast.  I 
would only worry about it if you had some situation where you were using 
the same name over and over:

import math
for i in range( 0, 10 ):
x = math.sqrt(i)

That's 10 dictionary lookups.  Importing just the sqrt name 
would avoid those lookups, so would:

import math
f = math.sqrt
for i in range( 0, 10 ):
   x = f(i)

Does that make sense?

>
> > Is there a reason why I shouldn't?
>
> If they belong together, put them in a package and use __init__.py. if
> they don't belong together you are just obscuring the design for very
> little savings.
>
>
> Ok, so I will keep the code as is. Thank you Luke and Kent!
>
> -Tino
>
> 
>
> ___
> 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] python: how do I create a list of definitions?

2007-07-19 Thread Eric Brunson
elis aeris wrote:
> like, I am doing string substitution:
>
>
> if  x = 2243:
> string = string + "e"
> if  x = 2234:
>string = string + "p"

If I'm following correctly...

How about using a dict:

list = { 1: 'a', 2: 'b', 3: 'c', 2342: 'p', 4234: 'e' }

if x in list:
string += list[x]

But I'm not sure what that outer loop is good for in your final example, 
so I may not understand what you're asking.

>
> and so forth.
>
>
> how do I create this:
>
>
> list = [
> (2342,p)
> (4234,e)
>   and so forth,
>
>
>]
>
>
>
> so I can use it like this:
>
> for a in range(10):
> If x = list[a][0]:
> string = string + list[a][1]
>
>
> ?
> 
>
> ___
> 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] python: how do I create a list of definitions?

2007-07-19 Thread Eric Brunson
Tiger12506 wrote:
>> I don't understand dict
>> 
>
> Think of dict as a dictionary. Literally. You have a word, you look up it's 
> definition in the dictionary. A dictionary is made up of key, value pairs. 
> So for your example:
>
> a_dict = {2243 : 'e',
>2234 : 'p',
>2235 : 'lol',
>'how' : 'under'}
>
> if x in a_dict:
>   string = string + a_dict[x]
>
>
>   

How can one get through any tutorial on Python and not come across dicts?

In more standard computer parlance a python dictionary is an associative 
array.



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


Re: [Tutor] python: how do I create a list of definitions?

2007-07-19 Thread Eric Brunson
Luke Paireepinart wrote:
> elis aeris wrote:
>   
>> like, I am doing string substitution:
>>
>>
>> if  x = 2243:
>> 
> this will always evaluate to true.
>   

Good eye, I missed that completely...

However, that will actually throw an exception.

 >>> if x = 1:
  File "", line 1
if x = 1:
 ^
SyntaxError: invalid syntax

Guido did it that way just to avoid programming errors like that.  
Python ain't C (thankfully).

> x is being assigned the value of 2243.  2243 is being returned by the 
> assignment.
> You can observe this in the following situation:
>  >>> y = x = 2243
>  >>> y
> 2243
>
> As you can see, (x = 2243) assigns the variable name to the integer 
> 2243, then assigns y to this integer object as well.
> so in essence you're saying
> if 2243:
> which is the same as saying 'if ' and anything nonzero, which is True.
> so basically the following line
>   
>> string = string + "e"
>> 
> is always being executed.
>   
>> if  x = 2234:
>>string = string + "p"
>> 
> same with this one.
>   
>> how do I create this:
>> list = [
>> (2342,p)
>> (4234,e)
>>   and so forth,
>>]
>>
>> so I can use it like this:
>>
>> for a in range(10):
>> If x = list[a][0]:
>> 
> If is invalid.  Python is case sensitive.  'if' and 'If' are not the same.
> Also, you're using an assignment instead of a comparison again.
>   
>> string = string + list[a][1]
>>
>>
>> ?
>> 
> You could probably solve this easily with a dictionary.
> -Luke
> ___
> 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] IDLE Usage - was Interpreter Restarts

2007-07-22 Thread Eric Brunson
Alan Gauld wrote:
> "Dave Kuhlman" <[EMAIL PROTECTED]> wrote
>
>   
>> If you find yourself opening multiple sessions to the same
>> UNIX/Linux box, you might want to look into screen, which enables
>> you to create and switch between multiple sessions.
>> 
>
>   
>> For more on screen, do "man screen" and look here:
>>
>>http://en.wikipedia.org/wiki/GNU_Screen
>> 
>
> I've heard of screen but never used it.
> The biggest problem I can see with it is that you can only see one 
> screen(sic) at a time or use split screens to see partial screens.
>   

You can only see one screen at a time as far as I know.  If you need 
split screens, use emacs.

> Can you copy/paste between sessions?
>   

Yes, either with your native ssh client cut and paste, or with screen's 
somewhat cumbersome cut and paste, which I personally never use.

> Does it run on a remote server within the SSH client? If so how 
>   

Yes.

> does it determine screen/window sizes?
>   

SIGWINCH+GNU doublegood magic.  Screen has its own terminfo/termcap 
entry, clients write using screens window controls, then the screen 
application translates those directive to whatever term you're using at 
the time.

> And do you know if you can get it for cygwin - its not installed by 
> default, at least not on my cygwin.
>   

It's in the repos.

The best thing (in my book) about screen, which I've been using for 
about 17 years, is you can disconnect from a screen session and 
reconnect from another login.  I regularly start a long running process 
at work, then go home and use "screen -RD" to remotely detach the screen 
session and reconnect it to my current login.  Plus, you don't have to 
worry about a compilation/database import/whatever dying because your 
VPN/dialup/cable modem dropped, everything keeps running and you just 
reattach.

My *only* complaint about screen is its default control key is Ctrl-a, 
which is "beginning of line" in emacs parlance.  You have to get used to 
using "Ctrl-a A" to go to the start of the line, but in all, it's a 
minor inconvenience.

> Alan G
>
> ___
> 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] IDLE Usage - was Interpreter Restarts

2007-07-23 Thread Eric Brunson
Alan Gauld wrote:
> "Eric Brunson" <[EMAIL PROTECTED]> wrote
>
>   
>>>>http://en.wikipedia.org/wiki/GNU_Screen
>>>>
>>>> 
>> You can only see one screen at a time as far as I know.  If you need
>> split screens, use emacs.
>> 
>
> The wiki page shows a split screen session and claims you can
> split any session or have multiple sessions in split windows.
>   

Well, if you knew the answer, why'd you ask?

You're right, I never new you could do that.

>   
>> My *only* complaint about screen is its default control key is 
>> Ctrl-a,
>> 
>
> How bizarre, but I guess they need to avoid collisions with the
> clients control key
>
> Thanks for the info.
>
> Alan G. 
>
>
> ___
> 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] IDLE Usage - was Interpreter Restarts

2007-07-23 Thread Eric Brunson
Eric Brunson wrote:
> Alan Gauld wrote:
>   
>> "Eric Brunson" <[EMAIL PROTECTED]> wrote
>>
>>   
>> 
>>>>>http://en.wikipedia.org/wiki/GNU_Screen
>>>>>
>>>>> 
>>>>>   
>>> You can only see one screen at a time as far as I know.  If you need
>>> split screens, use emacs.
>>> 
>>>   
>> The wiki page shows a split screen session and claims you can
>> split any session or have multiple sessions in split windows.
>>   
>> 
>
> Well, if you knew the answer, why'd you ask?
>   

There should have been a smiley after than comment.  :-)

> You're right, I never new you could do that.
>   

It's kinda cool. 

I thought the most annoyingly keystroke confusing thing I'd ever do was 
when I was writing and debugging an IRC bot.  I had a screen session 
with the bot running in one session for debug output, a multi-buffer 
emacs session in another editing the bot source and the module source, 
and a BitchX session with multiple screens for the python-help channel, 
the bot's control channel and the channel the bot was interacting on.  
Talk about brain stymie trying to get around in that. 

But now I can throw multiple screen regions on top of it all?  That's 
awesome!

>   
>>   
>> 
>>> My *only* complaint about screen is its default control key is 
>>> Ctrl-a,
>>> 
>>>   
>> How bizarre, but I guess they need to avoid collisions with the
>> clients control key
>>
>> Thanks for the info.
>>
>> Alan G. 
>>
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>   
>> 
>
> ___
> 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] sorting objects in lists by 2 attr

2007-07-23 Thread Eric Brunson
Philippe Niquille wrote:
>
> Hi
>
>
> I have a hard time sorting an object list. Perhaps this is kind of a 
> noob question, but I would very much appreciate any help!
>
>
> Using django I get a QuerySet of Score objects which are sorted by the 
> actual score, the actual score divided by the max. possible score (so 
> sorting by two db fields).
>
> I then need to loop through that queryset and sum up all the score 
> objects which belong to the same user into one Score objects. This 
> works (see code below).
>
>
> The problem I now have, is that I lost the sorting order, as described 
> above. How would I resort it with a python algortithm instead of SQL?
>

This is not the question you're asking, but my first though was, why not 
have SQL do the summing for you using sum() and group by?

>
> scores = Score.objects.order_by('score', 'score2','owner') # filter by 
> course, MC !!
>
> # loop through scores to regroup by user
>
> newscore = []
>
> for s in scores:
>
> i = False
>
> # loop through new object container and check for existant user index, 
> add scores if existant
>
> for ns in newscore:
>
> if s.owner == ns.owner:
>
> ns.score = int(ns.score) + int(s.score)
>
> ns.maxscore = int(ns.maxscore) + int(s.maxscore)
>
> i = True
>
> # otherwise append new user index object, work with it later, perhaps 
> (if more user objects exist)
>
> if i == False:
>
> newscore.append(s)
>
>
> -
>
>
> I did fiddle around with .sort() but didn't get any useful results 
> (and it would only sort by one object..).
>
>
> class CmpAttr:
>
> def __init__(self, attr):
>
> self.attr = attr
>
> def __call__(self, x, y):
>
> return cmp(getattr(x, self.attr), getattr(y, self.attr))
>
>
> newscore.sort(CmpAttr("score"))
>
>
>
> ps. could it be, that this maillist is blocking some e-mail addresses?
>
> 
>
> ___
> 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] sorting objects in lists by 2 attr

2007-07-23 Thread Eric Brunson

SQL databases are cool.  Make them do as much as they can for you.  :-)

Philippe Niquille wrote:
> Tanks a mill!
>
> I don't know why I searched so far..
>
> Anyway, I wrapped the django custom SQL call and built a nice 
> dictionary out of the resulting rows (which is similar to querysets). 
> See http://www.djangosnippets.org/snippets/207/ 
> <http://www.djangosnippets.org/snippets/207/> for details.
>
> Philippe
>
> Am 23.07.2007 um 19:28 schrieb Eric Brunson:
>> Philippe Niquille wrote:
>>>
>>>  
>>> Hi
>>>
>>>  
>>>
>>>  
>>> I have a hard time sorting an object list. Perhaps this is kind of a 
>>> noob question, but I would very much appreciate any help!
>>>
>>>  
>>>
>>>  
>>> Using django I get a QuerySet of Score objects which are sorted by 
>>> the actual score, the actual score divided by the max. possible 
>>> score (so sorting by two db fields).
>>>
>>>  
>>> I then need to loop through that queryset and sum up all the score 
>>> objects which belong to the same user into one Score objects. This 
>>> works (see code below).
>>>
>>>  
>>>
>>>  
>>> The problem I now have, is that I lost the sorting order, as 
>>> described above. How would I resort it with a python algortithm 
>>> instead of SQL?
>>>
>>>  
>>
>>  
>> This is not the question you're asking, but my first though was, why 
>> not have SQL do the summing for you using sum() and group by?
>>
>>  
>>>
>>>  
>>> scores = Score.objects.order_by('score', 'score2','owner') # filter 
>>> by course, MC !!
>>>
>>>  
>>> # loop through scores to regroup by user
>>>
>>>  
>>> newscore = []
>>>
>>>  
>>> for s in scores:
>>>
>>>  
>>> i = False
>>>
>>>  
>>> # loop through new object container and check for existant user 
>>> index, add scores if existant
>>>
>>>  
>>> for ns in newscore:
>>>
>>>  
>>> if s.owner == ns.owner:
>>>
>>>  
>>> ns.score = int(ns.score) + int(s.score)
>>>
>>>  
>>> ns.maxscore = int(ns.maxscore) + int(s.maxscore )
>>>
>>>  
>>> i = True
>>>
>>>  
>>> # otherwise append new user index object, work with it later, 
>>> perhaps (if more user objects exist)
>>>
>>>  
>>> if i == False:
>>>
>>>  
>>> newscore.append(s)
>>>
>>>  
>>>
>>>  
>>> -
>>>
>>>  
>>>
>>>  
>>> I did fiddle around with .sort() but didn't get any useful results 
>>> (and it would only sort by one object..).
>>>
>>>  
>>>
>>>  
>>> class CmpAttr:
>>>
>>>  
>>> def __init__(self, attr):
>>>
>>>  
>>> self.attr = attr
>>>
>>>  
>>> def __call__(self, x, y):
>>>
>>>  
>>> return cmp(getattr(x, self.attr), getattr(y, self.attr))
>>>
>>>  
>>>
>>>  
>>> newscore.sort(CmpAttr("score"))
>>>
>>>  
>>>
>>>  
>>>
>>>  
>>> ps. could it be, that this maillist is blocking some e-mail addresses?
>>>
>>>  
>>> 
>>>
>>>  
>>> ___
>>> Tutor maillist  -   Tutor@python.org <mailto:Tutor@python.org>
>>> http://mail.python.org/mailman/listinfo/tutor
>>>   
>>
>>  
>
>

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


Re: [Tutor] Running Python on Gentoo

2007-07-26 Thread Eric Brunson

What does the command "which python" say?

Khamid Nurdiev wrote:
> Yes, I have the same problem with running python scripts from console 
> in Debian, the line "#! /usr/bin/python" doesn't help. I have to type 
> "python script.py" in order to run the script.py file.
>
> On 7/26/07, *Greg Lindstrom* <[EMAIL PROTECTED] 
> > wrote:
>
> Hello,
> I am running python 2.4.2 on Gentoo Unix and am having problems
> running
> programs.  I have a script, hello.py as such:
>
> #! /usr/bin/python
> print 'hello, world'
>
> that I save and add executable permission.  Then at the prompt I
> type in..
>
> $ ./hello.py
> -bash: ./hello.py: /usr/bin/python: bad interpreter: Permission denied
>
> If I type
> $ python hello.py
> I get "hello, world" as expected.
>
> I was hoping that the "shabang" would have the script execute.  Am I
> missing something?  Can you help me?  BTW, when I type /usr/bin/python
> at the prompt I get the python interpreter, so at least that's
> working.
>
> Thanks,
> --greg
>
> ___
> Tutor maillist  -  Tutor@python.org 
> http://mail.python.org/mailman/listinfo/tutor
>
>
> 
>
> ___
> 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] Livewires questions

2007-07-26 Thread Eric Brunson
Tonu Mikk wrote:
> Tiger12506 wrote:
>   
>>> Based on your guidance, I figured it out.  I need to use a return 
>>> statement, which I had not encountered before.  Now I wrote my 
>>> definitions in this way:
>>>
>>> def collided():
>>>if player_x == robot_x+0.5 and player_y == robot_y+0.5:
>>>   return True
>>> 
>>>   
>>  
>> This could be simplified more.
>> Here's an example as a hint. These two functions are the same.
>>
>> def f():
>>   if a == b and c == d:
>> return True
>>
>> def g():
>>   return (a==b and c == d)
>>
>>   
>> 
> I got it.  I will do it like this:
> def collided():
> return (player_x == robot_x+0.5 and player_y == robot_y+0.5)
>
>   

I believe that will only work if the robot collides with the player from 
the southeast.

I'm not sure of the rules of the game, but if that's not the case, then 
see my previous note.


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


Re: [Tutor] Livewires questions

2007-07-26 Thread Eric Brunson
Tiger12506 wrote:
>> Based on your guidance, I figured it out.  I need to use a return 
>> statement, which I had not encountered before.  Now I wrote my 
>> definitions in this way:
>>
>> def collided():
>>if player_x == robot_x+0.5 and player_y == robot_y+0.5:
>>   return True
>> 

Granting that I have not looked at any of the Livewires modules, I just 
wanted to say...

A general check for collision would probably involve the distance 
formula from geometry

collided( (x1,y1), (x2,y2) ):
   return( sqrt( (x1-x2)**2 + (y1-y2)**2 ) < 1 )

but could probably be simplified to something like:

def collided( (x1,y1), (x2,y2) ):
   return( abs( x1 - x2 ) < .5 and abs( y1 - y2 ) < .5 )

>  
> This could be simplified more.
> Here's an example as a hint. These two functions are the same.
>
> def f():
>   if a == b and c == d:
> return True
>
> def g():
>   return (a==b and c == d)
>
>
>   
>> Then I use that value in another definition like this:
>>
>> def check_collisions():
>>if collided() == 1:
>>   print "You have been caught"
>> 
>
> And ~
>
> if collided():
>   print "You have been caught"
>   
> ___
> 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] Running Python on Gentoo

2007-07-26 Thread Eric Brunson
Greg Lindstrom wrote:
> Eric Brunson wrote:
>   
>> What does the command "which python" say?
>> 
> [EMAIL PROTECTED] ~ $ which python
> /usr/bin/python
>
> HTH,
> --greg
>
>
>   

Wow, Gentoo sucks more than I thought.  ;-)

I can't think of why that wouldn't work, unless you have some odd, 
non-printing character at the end of your interpreter line.

Do other interpreters work?

Try:

#!/usr/bin/perl
print "Perl Sucks!!!\n";

or:

#!/usr/bin/expect
puts "I hate TCL"


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


Re: [Tutor] Pass variable on command line

2007-07-26 Thread Eric Brunson
jason wrote:
> Hello,
>  
> I have a situation where I have 2 lists
>  
> List1 = ['blue', 'red', green']
> List2 = ['red', 'yellow', 'orange']
>  
> And I would like to pass the list name on the command line like so
>  
> ./test.py List1
>  
> I know I can get the argument using sys.argv[1]
>  
> But how can I then use the values in that list inside my program?
>  
> If I do a VALUES = sys.argv[1], then I get List1 as the values.  I 
> want the actual list elements.\\

The easiest way to do this would be to define your lists in a dictionary:


lists = { 'List1': ['blue', 'red', green'], 'List2': ['red', 'yellow', 
'orange'] }

if len(sys.argv) > 1 and sys.argv[1] in lists:
VALUES = lists[sys.argv[1]]


>  
> Is this possible?
>  
> Thank you
>  
> Jason
>  
>  
>  
> 
>
> ___
> 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] Livewires questions

2007-07-26 Thread Eric Brunson
Tonu Mikk wrote:
> Eric Brunson wrote:
>   
>> Tiger12506 wrote:
>>   
>> 
>>>> Based on your guidance, I figured it out.  I need to use a return 
>>>> statement, which I had not encountered before.  Now I wrote my 
>>>> definitions in this way:
>>>>
>>>> def collided():
>>>>if player_x == robot_x+0.5 and player_y == robot_y+0.5:
>>>>   return True
>>>> 
>>>>   
>>>> 
>> Granting that I have not looked at any of the Livewires modules, I just 
>> wanted to say...
>>
>> A general check for collision would probably involve the distance 
>> formula from geometry
>>
>> collided( (x1,y1), (x2,y2) ):
>>return( sqrt( (x1-x2)**2 + (y1-y2)**2 ) < 1 )
>>
>> but could probably be simplified to something like:
>>
>> def collided( (x1,y1), (x2,y2) ):
>>return( abs( x1 - x2 ) < .5 and abs( y1 - y2 ) < .5 )
>>
>>   
>> 
> Thanks Eric for your suggestions.  I believe Livewires modules have 
> simplified collision checking for programming novices like myself.  
> There are two shapes that I am working with, a circle and a square.  The 
> position of the circle is defined by the center coordinates whereas the 
> position of the square is defined by the lower left corner of the 
> square.  When my circle is 0.5 points in diameter, I can add this much 
> to both x and y coordinates of the square which will then give me the 
> point where the square is sitting on top of the circle.  It took me a 
> long time to figure this out.  I had to re-read the Graphics guide sheet 
> that came with Livewires multiple times to try to get it to work 
> correctly.  I believe this part of my code is OK. 
>
>   

Good deal and good luck.



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


Re: [Tutor] Shelve del not reducing file size

2007-07-27 Thread Eric Brunson
Andreas Kostyrka wrote:
> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA1
>
>
>
> Barton David wrote:
>   
>> I mean no offense and lay no blame. It's simply that I feel like I've
>> been led up a nice gentle beach and suddenly I'm dodging boulders at the
>> bottom of a cliff.
>>
>> I've learned to program with Python (and can hardly conceive of a better
>> language to be honest)- and I still think the core language is great:
>> elegant, easy to use and brilliantly documented.
>>
>> But the more I explore the standard library and third party modules, the
>> more I run into trouble: a chaotic library structure that seems to
>> conceal capabilities rather than promote them, similar modules that
>> don't work in similar ways, a whole new level of opaque programming
>> lingo that makes me feel excluded, behaviours that I don't understand,
>> don't want, and that I can't find documentation to explain, and so on.
>>
>> I guess it's not Python's fault: I'm guess I'm just too stupid. But I'm
>> just getting really disenchanted. Sorry.
>> 
>
> No, the Python documentation is sometimes brief. And some places are not
> really documented (like some dusty corners in the hotshot profiler). But
> OTOH, it's also hard on newbies, because it usually documents but does
> not explain what a module does, e.g., it often expects the reader to
> know the protocols involved, sometimes it expects the reader to know
> computer science basics.
>   

It seems like new programmers today expect to be spoonfed their 
information like they were in grammar school.  They don't know what it 
is to hack a Makefile to get a package to compile or break out an RFC to 
understand a protocol.  If you don't understand something and the 
documentation is lacking, then strap on a pair and read the source, 
write some test cases, dig a little.  In our environment most of the 
code you'd have to read is just more Python, anyway.

Just me being a grouchy old programmer.  In my day we had to program in 
4 feet of snow, uphill... both ways!

> Andreas
>
>   
>>  
>>
>> -Original Message-
>> From: Kent Johnson [mailto:[EMAIL PROTECTED] 
>> Sent: 27 July 2007 13:07
>> To: Barton David
>> Cc: tutor@python.org
>> Subject: Re: [Tutor] Shelve del not reducing file size
>>
>> Barton David wrote:
>> 
>>> *sigh* I'm really going off Python.
>>>   
>> In what way is it Python's fault that the dbm database doesn't reclaim
>> disk space?
>>
>> Kent
>>
>>
>> 

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


Re: [Tutor] Shelve del not reducing file size

2007-07-27 Thread Eric Brunson
Barton David wrote:
>
> *Eric Brunson* wrote:
>
> > It seems like new programmers today expect to be spoonfed their
> > information like they were in grammar school.  They don't know what it
> > is to hack a Makefile to get a package to compile or break out an 
> RFC to
> > understand a protocol.  If you don't understand something and the
> > documentation is lacking, then strap on a pair and read the source,
> > write some test cases, dig a little.  In our environment most of the
> > code you'd have to read is just more Python, anyway.
> >
> > Just me being a grouchy old programmer.  In my day we had to program in
> > 4 feet of snow, uphill... both ways!
>
> heh. Well give me some credit. I taught myself to program, from 
> scratch, without access to (or time for) any courses whatsoever, while 
> doing a PhD in genetics. I've been using it for about 5 years now and 
> I know the core language and certain standard modules pretty well. I 
> doubt I would have got as far as I have if Python wasn't so 
> newbie-friendly. My only complaint is that I'm starting to feel like I 
> won't get much further than that without a computer science degree.

I'll disagree with you on that, if you can get a PhD in genetics then 
programming should be a snap... with the right attitude.  My BS was in 
Applied Mathematics and I've never taken a formal programming class 
since 11th grade high school.  But, I've been doing it for about 20 
years and there comes a point when you realize that you've read all the 
tutorials you can, internalized all the documentation that has been 
written and you *are* actually the smartest person in the room.  At that 
point you have to look other places for your documentation, like the 
source code or the RFCs.

I keep mentioning RFCs because I answer a lot of questions about using 
this to send mail or that to talk to an HTTP server or another thing to 
pull a file off FTP.  Most of python's protocol libraries are a very 
thin layer over the top of the actual network protocol, so in order to 
use any but the most common operations, you have to understand the 
underlying protocol.  So, what do you do?  Read the RFC for SMTP?  Or 
complain that there's not a single function call that allows you to 
automatically connect to a non-WKS port to send uuencoded emails using 
custom headers?

You seem like a smart guy that's having a bad day, so I'm cutting you 
slack.  You'll get to a point in programming where the only thing left 
before you is the epi-genome and I've got news for you, there's no 
documentation on the dark matter.  Personally, I seldom use the low 
level interfaces provided by the standard libraries except to write high 
level wrapper functions that meet the needs of my environment and the 
task at hand.

So, keep your chin up, you're not alone.  :-)

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

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


Re: [Tutor] Remove certain tags in html files

2007-07-27 Thread Eric Brunson
Sebastien Noel wrote:
> Hi,
>
> I'm doing a little script with the help of the BeautifulSoup HTML parser 
> and uTidyLib (HTML Tidy warper for python).
>
> Essentially what it does is fetch all the html files in a given 
> directory (and it's subdirectories) clean the code with Tidy (removes 
> deprecated tags, change the output to be xhtml) and than BeautifulSoup 
> removes a couple of things that I don't want in the files (Because I'm 
> stripping the files to bare bone, just keeping layout information).
>
> Finally, I want to remove all trace of layout tables (because the new 
> layout will be in css for positioning). Now, there is tables to layout 
> things on the page and tables to represent tabular data, but I think it 
> would be too hard to make a script that finds out the difference.
>
> My question, since I'm quite new to python, is about what tool I should 
> use to remove the table, tr and td tags, but not what's enclosed in it. 
> I think BeautifulSoup isn't good for that because it removes what's 
> enclosed as well.
>   

You want to look at htmllib:  http://docs.python.org/lib/module-htmllib.html

If you've used a SAX parser for XML, it's similar.  Your parser parses 
the file and every time it hit a tag, it runs a callback which you've 
defined.  You can assign a default callback that simply prints out the 
tag as parsed, then a custom callback for each tag you want to clean up.

It took me a little time to wrap my head around it the first time I used 
it, but once you "get it" it's *really* powerful and really easy to 
implement.

Read the docs and play around a little bit, then if you have questions, 
post back and I'll see if I can dig up some examples I've written.

e.

> Is re the good module for that? Basically, if I make an iteration that 
> scans the text and tries to match every occurrence of a given regular 
> expression, would it be a good idea?
>
> Now, I'm quite new to the concept of regular expressions, but would it 
> ressemble something like this: re.compile("")?
>
> Thanks for the help.
> ___
> 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] Remove certain tags in html files

2007-07-27 Thread Eric Brunson
Eric Brunson wrote:
> Sebastien Noel wrote:
>   
>> Hi,
>>
>> I'm doing a little script with the help of the BeautifulSoup HTML parser 
>> and uTidyLib (HTML Tidy warper for python).
>>
>> Essentially what it does is fetch all the html files in a given 
>> directory (and it's subdirectories) clean the code with Tidy (removes 
>> deprecated tags, change the output to be xhtml) and than BeautifulSoup 
>> removes a couple of things that I don't want in the files (Because I'm 
>> stripping the files to bare bone, just keeping layout information).
>>
>> Finally, I want to remove all trace of layout tables (because the new 
>> layout will be in css for positioning). Now, there is tables to layout 
>> things on the page and tables to represent tabular data, but I think it 
>> would be too hard to make a script that finds out the difference.
>>
>> My question, since I'm quite new to python, is about what tool I should 
>> use to remove the table, tr and td tags, but not what's enclosed in it. 
>> I think BeautifulSoup isn't good for that because it removes what's 
>> enclosed as well.
>>   
>> 
>
> You want to look at htmllib:  http://docs.python.org/lib/module-htmllib.html
>   

I'm sorry, I should have pointed you to HTMLParser:  
http://docs.python.org/lib/module-HTMLParser.html

It's a bit more straightforward than the HTMLParser defined in htmllib.  
Everything I was talking about below pertains to the HTMLParser module 
and not the htmllib module.

> If you've used a SAX parser for XML, it's similar.  Your parser parses 
> the file and every time it hit a tag, it runs a callback which you've 
> defined.  You can assign a default callback that simply prints out the 
> tag as parsed, then a custom callback for each tag you want to clean up.
>
> It took me a little time to wrap my head around it the first time I used 
> it, but once you "get it" it's *really* powerful and really easy to 
> implement.
>
> Read the docs and play around a little bit, then if you have questions, 
> post back and I'll see if I can dig up some examples I've written.
>
> e.
>
>   
>> Is re the good module for that? Basically, if I make an iteration that 
>> scans the text and tries to match every occurrence of a given regular 
>> expression, would it be a good idea?
>>
>> Now, I'm quite new to the concept of regular expressions, but would it 
>> ressemble something like this: re.compile("")?
>>
>> Thanks for the help.
>> ___
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>   
>> 
>
> ___
> 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] Shelve del not reducing file size

2007-07-27 Thread Eric Brunson

One thing I don't think people realize, or at least don't talk about 
often enough, is that good programming, like good art, takes talent.

I can draw a cat to make my 2yo happy or sketch my house well enough 
that someone could pick it out driving down the street, but if I paint 
every day for the next 100 years, I'll never be a Picasso or a Monet.  I 
remember back when the web was starting to prosper, offices would hand 
their secretary a copy of FrontPage and tell them to make a web page for 
the company and *bam* she's a web designer.  The fact is, good web 
design takes talent. 

You can go to school for math, engineering, architecture, art, music or 
computer science, but that's not going to turn the average student into 
a John Nash, a Gustave Eiffel, a Frank Lloyd-Wright, a Vincent Van Gogh, 
an Eddie van Halen or an Alan Turing.  Of course, there are plenty of 
people that make a living at those occupations that aren't the towering 
persona's of the field, but having talent will get you good faster and 
having no talent means you're going to have to work hard to achieve 
mediocrity.

Now *this* thread has gone seriously philosophical...

Alan Gauld wrote:
> "Eric Brunson" <[EMAIL PROTECTED]> wrote
>
>   
>>> newbie-friendly. My only complaint is that I'm starting to feel 
>>> like I
>>> won't get much further than that without a computer science degree.
>>>   
>> I'll disagree with you on that, if you can get a PhD in genetics 
>> then
>> programming should be a snap...
>> 
>
> I'm not sure I agree. There is a reason that CS is a degree subject,
> and that you can get PhDs in it too. There is a lot of advanced 
> programming
> stuff that does need specialist training to *do it well*. Of course 
> you
> can do virtually anything with a buit of brute force. But without 
> actually
> understanding concepts like boolean algenra, lambda and predicate 
> calculii,
> algorithm design, finite state automata thery etc much will either be 
> inelegant
> or just cut n paste.
>
> I often see comments lie software engineering is different to other
> engineering because theres no mathematical basis. Thats plain false,
> and although the basis is less complete and certainly not a unified
> whole almost every aspect of programming can be validated and proved
> mathemaically. Programs can be designed and specified formally.
> But most programmers aren't trained. And those that are are
> discourageed from doing so because its quicker to "just hack it"
> As an applied mathematics man you probably know most of that
> stuff at some levelk. Not surprising since CS started off as a branch
> of math after all.
>
> BTW This trend has been true in almost every engineering discipline
> and the only thing that corrects it is when companies and programmes
> start getting sued and put in prison for writing faulty software. 
> (Just like
> civil engineers were when bridges started falling down, and Electrical
> engineers were when householders got electrocuted switching on lamps!)
>
>   
>> written and you *are* actually the smartest person in the room.  At 
>> that
>> point you have to look other places for your documentation, like the
>> source code or the RFCs.
>> 
>
> Absolutely true. Not good but its where we are.
> (And continuing the simile, the same is true in electronics, sometimes
> you just have to reverse engineer the circuit board! but you never do 
> it
> for fun!)
>
> (*)BTW My own position is that I majored in Electrical/Electronic 
> engineering
> but early on decided software was my interest so took every CS related
> class going. I also spent a lot of time doing background reading (and 
> still do)
> on the formal math side of CS - formal logic etc being one of those 
> areas where
> I have an almost constant learning curve.
>
>   

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


Re: [Tutor] Remove certain tags in html files

2007-07-27 Thread Eric Brunson


Man, the docs on the HTMLParser module are really sparse.

Attached is some code I just whipped out that will parse and HTML file, 
supress the ouput of the tags you mention and spew the html back out.  
It's just a rough thing, you'll still have to read the docs and make 
sure to expand on some of the things it's doing, but I think it'll 
handle 95% of what it comes across.  Be sure to override  all the 
"handle_*()" methods I didn't.


My recommendation would be to shove your HTML through BeautifulSoup to 
ensure it is well formed, then run it through the html parser to do 
whatever you want to change it, then through tidy to make it look nice.


If you wanted to take the time, you could probably write the entire tidy 
process in the parser.  I got a fair ways there, but decided it was too 
long to be instructional, so I pared it back to what I've included.


Hope this gets you started,
e.

Eric Brunson wrote:

Eric Brunson wrote:
  

Sebastien Noel wrote:
  


Hi,

I'm doing a little script with the help of the BeautifulSoup HTML parser 
and uTidyLib (HTML Tidy warper for python).


Essentially what it does is fetch all the html files in a given 
directory (and it's subdirectories) clean the code with Tidy (removes 
deprecated tags, change the output to be xhtml) and than BeautifulSoup 
removes a couple of things that I don't want in the files (Because I'm 
stripping the files to bare bone, just keeping layout information).


Finally, I want to remove all trace of layout tables (because the new 
layout will be in css for positioning). Now, there is tables to layout 
things on the page and tables to represent tabular data, but I think it 
would be too hard to make a script that finds out the difference.


My question, since I'm quite new to python, is about what tool I should 
use to remove the table, tr and td tags, but not what's enclosed in it. 
I think BeautifulSoup isn't good for that because it removes what's 
enclosed as well.
  

  

You want to look at htmllib:  http://docs.python.org/lib/module-htmllib.html
  



I'm sorry, I should have pointed you to HTMLParser:  
http://docs.python.org/lib/module-HTMLParser.html


It's a bit more straightforward than the HTMLParser defined in htmllib.  
Everything I was talking about below pertains to the HTMLParser module 
and not the htmllib module.


  
If you've used a SAX parser for XML, it's similar.  Your parser parses 
the file and every time it hit a tag, it runs a callback which you've 
defined.  You can assign a default callback that simply prints out the 
tag as parsed, then a custom callback for each tag you want to clean up.


It took me a little time to wrap my head around it the first time I used 
it, but once you "get it" it's *really* powerful and really easy to 
implement.


Read the docs and play around a little bit, then if you have questions, 
post back and I'll see if I can dig up some examples I've written.


e.

  

Is re the good module for that? Basically, if I make an iteration that 
scans the text and tries to match every occurrence of a given regular 
expression, would it be a good idea?


Now, I'm quite new to the concept of regular expressions, but would it 
ressemble something like this: re.compile("")?


Thanks for the help.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
  

  

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



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


from HTMLParser import HTMLParser

class MyParser( HTMLParser ):
def __init__( self ):
HTMLParser.__init__( self )
self.supress = ( 'table', 'tr', 'td' )

def handle_starttag( self, tag, attrs ):
if tag not in self.supress:
print "<%s%s%s>" % ( tag,
 " " if attrs else "",
 " ".join( "%s='%s'" % pair for pair in attrs ) ),

def handle_data( self, data ):
print data,

def handle_endtag( self, tag ):
if tag not in self.supress:
print "" % ( tag, ),

MyParser().feed( open( 'index.html' ).read() )

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


Re: [Tutor] Which GUI?

2007-07-27 Thread Eric Brunson
scott wrote:
> Hi,
>
>   now that I have a very basic understanding of Python I would like to 
> take a look at programming in a GUI.  Which GUI is generally the easiest 
> to learn?
>
>   

Easiest depends on your background.  I was a Mac developer back in the 
day, so WXPython was easy for me.  If you're a KDE programmer, then PyQT 
is probably your cup of tee.  Similarly, GTK programmers will probably 
like PyGTK.  I cannot make any statements about Tkinter, since I eschew 
everything TCL related.

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


Re: [Tutor] Shelve del not reducing file size

2007-07-27 Thread Eric Brunson

Python is like democracy.  It isn't perfect, but it's the best thing 
come up with so far.  ;-)


Barton David wrote:
> Eric Brunson wrote:
> > You seem like a smart guy that's having a bad day, so I'm cutting you
> > slack.
>  
> Thanks Eric. Yes I did indeed have a bad day (and it got much much worse),
> and this is most definitely a case of a bad workman blaming his tools. I
> apologise to all concerned for voicing my frustrations: it was clearly 
> ill-advised.
> Still.. call me idealistic but I feel like a good toolmaker should try 
> to listen to her
> clients.
>  
> I am not a dedicated programmer. I have other stuff on my plate. I 
> probably
> wouldn't be a programmer at all if Python wasn't (in the early stages) so
> fabulously friendly.
>  
> Alan Gauld wrote:
> > But Pythons library is not newbie friendly, sorry. How does
> > a newbie know when to use pickle v cpickle? or urllib v urllib2? And
> > which of the xml parsers? And as for thev mess that is 
> glob/os/path/shutil?
> > Its not clear to me even after 10 years of using Python which function
> > sits where and why. And what about the confusion over system(),
> > popen(),commands(),spawn(), subprocess() etc. or why is there time
> > and datetime? Sure it makes sense once you've played with Python
> > for a while it makes some sense and you learn the role of history.
>  
> This is very much how this particular 'newbie' has experienced things. I'm
> not here to damn Python, but to praise it, for opening my eyes to a whole
> bunch of stuff. But you know when I teach biology and genetics, and the
> kids don't get it, I feel like the onus is on me to improve my 
> teaching. And
> if I code a tool for people in my lab, and they can't use it, then I 
> feel like
> I've got some work to do, either in teaching or in making the tool 
> easier to
> use.
>  
> That's just me, Tiger, and I'm sorry it makes you spit venom. Not my
> intention at all. But it's Alan's hand that I want to shake, because as
> far as I can tell, he's looking to the future, to the next generation, to
> the ugly reality and the bright potential, and quite frankly, you're not.
>
> This message has been checked for viruses but the contents of an 
> attachment may still contain software viruses, which could damage your 
> computer system: you are advised to perform your own checks. Email 
> communications with the University of Nottingham may be monitored as 
> permitted by UK legislation.
>
> 
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>   

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


Re: [Tutor] Shelve del not reducing file size

2007-07-28 Thread Eric Brunson
Alan Gauld wrote:
> "Andreas Kostyrka" <[EMAIL PROTECTED]> wrote
>
>   
>>> a lot to build the Tacoma Narrows bridge... Similarly you don't 
>>> need
>>> much math to build a GUI friont end to a database, but you need
>>>   
>> I would question even that one can write a good GUI frontend to a
>> database without the theory behind it. Database design has a number 
>> of
>> important theoretical foundations 
>> 
>
> But the math is in the design of the database. If it already exists 
> the
> GUI design is usually more a matter of good usability design. There
> might be a bit of SQL going on but usually a data browser GUI doesn't
> need anything sophisticated, that should be hidden in an application
> (with API) or in a set of stored proceduresbin the database itself.
>   

I'm definitely a believer that if you get the data model correct first, 
the software almost writes itself.  I've usually found that when I have 
trouble accessing the data I want, I didn't design the schema correctly.

>   
>> Well, the advanced stuff was there. But the Modula2 introduction to
>> programming was a joke, most students did not even understand the
>> concept of local variables and procedure parameters after one 
>> semester.
>> 
>
> Thats bad. As I say our Pascal course was a fairly dull but complete
> introduction to elementary programming including file handling and
> dynamic data structures. Our final program was Conways game of Life
> which had to be able to be paused and saved to disk, and later
> restored...
>
> Ahhh, the memories!
>
> Alan G. 
>
>
> ___
> 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] Shelve del not reducing file size

2007-07-28 Thread Eric Brunson
On Sat, July 28, 2007 4:01 am, Thorsten Kampe wrote:
> * Kent Johnson (Fri, 27 Jul 2007 08:06:33 -0400)
>
>> Barton David wrote:
>>
>>> *sigh* I'm really going off Python.
>>>
>>
>> In what way is it Python's fault that the dbm database doesn't reclaim
>> disk space?
>
> It's actually how most databases work. Even a simple Outlook pst file
> (which is a database, too) works this way. I thought everyone knows or
> heard about this.

I don't even think mysql reclaims disk space unless you intervene.




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


Re: [Tutor] Shelve del not reducing file size

2007-07-28 Thread Eric Brunson
Andreas Kostyrka wrote:
> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA1
>
>
>
> Eric Brunson wrote:
>   
>> On Sat, July 28, 2007 4:01 am, Thorsten Kampe wrote:
>> 
>>> * Kent Johnson (Fri, 27 Jul 2007 08:06:33 -0400)
>>>
>>>   
>>>> Barton David wrote:
>>>>
>>>> 
>>>>> *sigh* I'm really going off Python.
>>>>>
>>>>>   
>>>> In what way is it Python's fault that the dbm database doesn't reclaim
>>>> disk space?
>>>> 
>>> It's actually how most databases work. Even a simple Outlook pst file
>>> (which is a database, too) works this way. I thought everyone knows or
>>> heard about this.
>>>   
>> I don't even think mysql reclaims disk space unless you intervene.
>> 
>
> As this thread got already very philosophical, I'd like to add that the
> jury is still out if mysql is a RDBMS. I personally interpret it as a
> datafile access library that tries to pretend to be a database system :)
>   

I had 13 years of Oracle experience under my belt when I tried MySQL 
version 3.x.  Then it was a toy database and barely worth my attention.  
We're now using 5.0 and it is definitely no longer simply pretending to 
be a database. 

At work we have a system that is storing over 1.5 billion records and 
makes our Oracle installations pale in comparison.  Another system is 
running distributed in a cluster running multiple masters in ring 
replication.  Oracle was either impressed or threatened enough to buy 
the rights to InnoDB, that has to say something about the state of 
MySQL.  With the addition of stored procedures, triggers and views in 
5.0, it has definitely met all but my most esoteric needs.

I'm not saying MySQL is perfect, I have several bugs and feature 
requests logged with MySQL that I'm still waiting to be addressed, but 
if you haven't used it lately, you're missing out.


> Andreas
> -BEGIN PGP SIGNATURE-
> Version: GnuPG v1.4.2 (GNU/Linux)
> Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org
>
> iD8DBQFGq7m7HJdudm4KnO0RAr6CAKCTSLxA5blSX19IVfpN1RVywRZvSACghExR
> iRDi3pk+NBPhIcQdd1QkP70=
> =eS7Q
> -END PGP SIGNATURE-
> ___
> 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] don't repeat yourself; question about code optimization CORRECTION

2007-07-29 Thread Eric Brunson
[EMAIL PROTECTED] wrote:
>
>
> On 7/23/07, *Bob Gailer* <[EMAIL PROTECTED] 
> > wrote:
>
> A correction to the code at the end. The test of
> self.total_num_of_items
> should precede the pop(0)
>
>
>
> Bob, I spent today studying what you've been telling me and I put the 
> finishing touches to make your code pass my battery of tests.  It 
> still is repetitive, i.e., table.append(tuple(row)),

I see you're also repeating the use of "=" quite a bit, as well as 
multiple uses of the word "if".  Maybe you could work on that.

Sorry for the sarcasm, but there's a big different between repeating an 
assignment and a type coersion versus a multi line block of code that 
could be converted to a function.  :-)

> but I've found guidance in what Alan had to say about code readability 
> and easy maintenance, and am no longer going to press the matter:
>
> class Table_Creator(object):
> def __init__(self, total_num_of_items, max_num_of_items_per_row):
> self.given_items = range(total_num_of_items)
> self.max_num_of_items_per_row = max_num_of_items_per_row
>
> def create_grid(self):
> table = []
> while True:
> row = []
> while len(row) < self.max_num_of_items_per_row:
> if not self.given_items:
> if row:
> table.append(tuple(row))
> return table
> row.append(self.given_items.pop(0))
> table.append(tuple(row))
>  
>
>
> 
>
> ___
> 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] build a really simple "json" api from a db

2007-07-30 Thread Eric Brunson
Picio wrote:
> The beginning idea was to build a json API myself. Since I need only
> to generate json from a db, maybe Django is too much. I'm a Django
> beginner. I don't know Turbogears.
> I've not found anything like: "how to build a json api".
> Maybe MySqldb+simplejson is the enough?
> Or
> Is It more simple to learn how to use Django to create a json api?
>   

Picio,

You seem to be in analysis paralysis.  You don't understand the 
underlying technology, which is making the task seem daunting.  Break it 
down into component parts and learn the ones you don't already understand.

It seems the most important aspects of the project are getting info out 
of the database, converting it to JSON and publishing it via HTTP.  Do 
you have a web server?  Then write the simplest example of a CGI script 
to query a database and serve serve it up using simplejson.   If you 
don't have a web server, then wrap it in a little CGIHTTPServer 
(http://docs.python.org/lib/module-CGIHTTPServer.html).

I'm not trying to criticize on you or make you mad, but if you'd jumped 
in and tried it out instead of posting here all weekend, you'd probably 
have a working prototype by now.  You'll probably go through 10 
different iterations before you have a final product and you'll be able 
to reuse any of the code you come up with.  Just do it and we'll help 
you with any questions you have along the way.

Go, go, go.  It's your birthday, you can do this.  :-)

e.

> 2007/7/28, Alan Gauld <[EMAIL PROTECTED]>:
>   
>> "Picio" <[EMAIL PROTECTED]> wrote
>>
>> 
>>> Hello, I'd like to know the necessary steps to build a json api for
>>> two table on my db.
>>>   
>> Since you seem to be using Django are you sure that isn't built in?
>>
>> I use Turbo Gears and JSON is a standard feature turned on by
>> an option in a method. Django is quite similar to TG in most respects
>> so I'll be surprised if it can't do JSON directly.
>>
>> 
>>> I've seen this snippet on the djangosnippet site.
>>> http://www.djangosnippets.org/snippets/154/
>>> Is It the right way.
>>>   
>> If its on the Django web site and you are using Django then
>> probably! :-)
>>
>> It certainly looks like a recommendation to me.
>>
>> --
>> Alan Gauld
>> Author of the Learn to Program web site
>> http://www.freenetpages.co.uk/hp/alan.gauld
>>
>>
>> ___
>> 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] attribute error - quick addition

2007-07-30 Thread Eric Brunson
Sara Johnson wrote:
> No luck finding tutors.  I don't make enough. 

Sara,

Alan didn't say to find a tutor, he suggested you read a tutorial.

You seem to be having problems with very basic python concepts and his 
suggestion was to take an hour or two and *read* some gentle 
introductions that will lead you through concepts like tuples and 
lists.  Without those basic understandings you're going to continue to 
struggle with simple tasks.

We're here to help, but the approach you're taking isn't getting you 
where you need to go quickly.

Here are a couple of starting points:
http://docs.python.org/tut/
http://www.sthurlow.com/python/
http://www.diveintopython.org/toc/index.html
http://en.wikibooks.org/wiki/Non-Programmer's_Tutorial_for_Python/Contents

Glance through those and pick one that looks like you're style and 
speed.  Skim though the sections you already understand and pay more 
attention to the bits you don't.

A little time spent up front is going to save you immense time later.  
Let us know how it goes.

Sincerely,
e.

> It seems to be this script that's throwing me off.  But I understand 
> and I'll take what I've learned to date and something will work 
> eventually.
>  
> Thanks for your concern and support. 
>  
> Sara

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


Re: [Tutor] passing form data into a class

2007-07-31 Thread Eric Brunson
Dave Kuhlman wrote:
> On Mon, Jul 30, 2007 at 08:32:55PM -0700, [EMAIL PROTECTED] wrote:
>   
>> dear fellow Python enthusiasts, let's say I have a dictionary of keys and
>> values obtained from a form submitted by a user.  For each submitted form I
>> will create the Application and Candidate classes, and I want to be able to
>> call Application(Candidate(**submitted_data)).display() to create an html
>> representation of the user submitted data.  Depending on the applicant's
>> preferences and location, the number of fields on the form, and thus the
>> size of this dictionary, is variable, and not all fields are required.  I
>> seem to recall a setargs function in Python that would take any argument
>> passed into a class and set that argument as a member variable in a class.
>> A Google search turned up no such construct, so here I am asking you, is
>> there a way for me to create a class that accepts a dictionary of submitted
>> data and uses each key ad value to create a corresponding member variable ?
>> The current way I do this is with a very long argument list, and line by
>> line:
>> 
>
> You have already gotten one good solution from Kent.  But,
> depending on your needs, you might also focus on the request side
> rather than on when the class or instance is created.  That might
> enable you to add a bit of the security checking that Ken Fouey was
> concerned about.
>
> Here is an example of a class which looks a name up in a dictionary
> when the attribute is requested.  It does not create attributes for
> the keys in the dictionary:
>
> class Bunch(object):
> def __init__(self, vardict=None):
> if vardict is None:
> self.vardict = vardict
> else:
> self.vardict = vardict
> def __getattr__(self, name):
> if name in self.vardict:
> return self.vardict[name]
> else:
> raise AttributeError, 'Bunch has no attribute: %s' % name
>   

Since this is tutor, I'll add my $.02...

Kent's version of Bunch is great, I use that sort of definition all the 
time in my code when I want to use "instance.thing = blah" to save 
typing and make my code more readable, but also want to use dict 
nomenclature for iteration over keys, etc, rather than "getattr( 
instance, key )," again, primarily for neatness of code.

However, this version from Dave has the advantage of segregating your 
"special data" from the regular class attributes.  If you wanted to, for 
example, keep a count of the number of form keys that were passed into 
the form, you couldn't store that in an instance attribute without it 
getting mixed up with all your form variables.

I'm not saying either is better than the other overall, they each have 
their place and I use both, but in this *specific* case, I think you'd 
want to use Dave's version.

Just my opinion, I could be wrong.  :-)

e.

> def test():
> d = {'aaa': 111, 'bbb': 222, }
> b = Bunch(d)
> print b.aaa
> print b.ccc
>
> test()
>
> Dave
>
>
>   

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


Re: [Tutor] Textual Captchas: Would like to show that bots can crack a simple text captcha

2007-08-01 Thread Eric Brunson
Kyle Brooks wrote:
> Hi.
>
> Please look up captcha... I did not mean capture.
>
> Your response is hilarious, frankly, but not appropriate for this list :-)
>   

Seeing that a) this is your second post here and b) you are the one 
asking the list for help, I don't think it's your place to decide what 
is and isn't appropriate for this list.

Also, I'm pretty sure he *did* look up captcha and was using the process 
through which he researched and replied as a metaphor for how your 
program might work.

> - Kyle Brooks
>
> On 8/1/07, Bob Gailer <[EMAIL PROTECTED]> wrote:
>   
>> Kyle Brooks wrote:
>> 
>>> Hi.
>>>
>>> My name is Kyle Brooks, and I hereby introduce myself with this post.
>>>
>>> I have seen a lot of text captchas.
>>>
>>>   
>> I wonder how a computer program would respond to the previous sentence?
>> Could it simulate the path I took?
>>
>> "captcha"? Did he mean "capture"? Is this one more poster who does not
>> know how to spell?
>> But the rest of the email is good english!
>> Oh yes - ask Google.
>> *visualizae me reading the wikipedia article on captchas. Light bulbs
>> and ahas going on.*
>> Oh yes this is a really good question.
>> Should I respond? What would I say? Why would I say it?
>> *visualize me typing the above and hitting send
>>
>>
>> 
> ___
> 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] gendata.py

2007-08-01 Thread Eric Brunson

What is it that you think makes it Unix specific?

Que Prime wrote:
>
> This script appears to be written for Unix systems.  Is there a way to 
> get it to work for PythonWin?
>
> from random import randint, choice
> from string import lowercase
> from sys import maxint
> from time import ctime
>
> doms = ( 'com', 'edu', 'net', 'org', 'gov' )
>
> for i in range(randint(5, 10)):
> dtint = randint(0, maxint-1)#pick date
> dtstr = ctime(dtint)#date string
>
>
> shorter = randint(4,7)  #login shorter
> em = ''
> for j in range(shorter):#generate login
> em += choice(lowercase)
>
> longer = randint(shorter, 12)   #domain longer
> dn = ''
> for j in range(longer): #create domain
> dn += choice(lowercase)
>
> print '%s::[EMAIL PROTECTED]::%d-%d-%d' % (dtstr, em, dn, choice(doms), 
> dtint, shorter, longer) 
> 
>
> ___
> 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] Which GUI?

2007-08-02 Thread Eric Brunson
Richard Querin wrote:
> On 8/2/07, Eric Brunson <[EMAIL PROTECTED]> wrote:
>
>   
>> Switching gears from linear to event driven programming is a pretty
>> significant paradigm shift.  Will this book help him get his head around
>> that?
>>
>> 
>
> That's one of the main reasons why I bought it actually. I couldn't
> grasp in any significant way how it worked. I could build a working
> wxpython program based on tutorials etc. but didn't really know
> why/how it worked. There are early sections in the book dealing with
> the basics of the event-driven paradigm as well as a section
> discussing the Model-View-Controller pattern too. It's not exhaustive
> on the subject by any means, but cleared up a lot of questions for me.
>
> It doesn't just throw you into building a detailed wxpython app
> without any background as to how it works - although it does get you
> going immediately with some small hello world type stuff to
> immediately build a little confidence. ;)
>   

Sounds like a good book, I wish I'd had something similar 15 years ago 
when I was learning to program on Mac OS.  Thanks for the review, I hope 
it helps the original poster.

e.

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


Re: [Tutor] Which GUI?

2007-08-02 Thread Eric Brunson
Richard Querin wrote:
> On 8/2/07, scott <[EMAIL PROTECTED]> wrote:
>
>   
>> I was thinking about finding a copy of that book, so maybe starting
>> WxPython would be easier then and not worry about Tkinter.  Is "WxPython
>> in Action" a very good book?
>>
>> 
>
> I'm no programmer by trade, but dabble in Python/wxPython for fun and
> bought the book several months ago. I've found it to be very good.
> There are a lot of good online tutorials as well, but I was never sure
> if they were up to date with the later versions of the framework - so
> the book was blessing to me. I found the book to be very useful and
> clearly written. It's no reference manual (the online docs serve that
> purpose) but I think it really helped me get a good foundation in how
> to program with wxPython. 

Switching gears from linear to event driven programming is a pretty 
significant paradigm shift.  Will this book help him get his head around 
that?

> IMO a good book is still more useful and
> efficient than online articles or tutorials for a newbie (like me)
> most of the time. It's nice to be able to thumb through and study some
> concept without flipping back and forth to some web page.
>
> I own a lot of computer books, and I've found Learning Python (an
> O'Reilly Book) and wxPython in Action to be my two most useful ones.
>
>
> RQ
> ___
> 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] Ingenious script (IMO)

2007-08-06 Thread Eric Brunson
Dick Moores wrote:
> At 06:49 AM 8/6/2007, Kent Johnson wrote:
>   
>> Dick Moores wrote:
>> 
>>> http://www.rcblue.com/Python/changeMaker_revised_for_US_denominations.py
>>> I'm still working at Python--been at it a while--and thought the 
>>> script was ingenious. Do the Tutors agree? Or is it just 
>>> run-of-the-mill programming? Could it have been more simply written?
>>>   
>> I don't find it either ingenious or well-written. The algorithm is 
>> the same one you would use to count out an amount by hand so it 
>> doesn't seem so unusual. IMO the code relies too much on indices. If 
>> you rewrite it using a dict (or, even better, defaultdict(int)) for 
>> coinCount, there is no need for indices at all. Even with coinCount 
>> as a list, it could be better written.
>>
>> coinCount = []
>> for d in denominations:
>> coinCount.append(0)
>>
>> =>
>>
>> coinCount = [0] * ndenominations
>>
>>
>> The main loop could be
>> for deno in range(ndenominations):
>>   if not remaining:
>> break
>>
>> or
>> for i, deno in enumerate(denominations):
>> # i is now the index, deno is the actual denomination
>>
>>
>> but I would write it this way and avoid the use of the index completely:
>>
>> 
> >from collections import defaultdict
>   
>> coinCount = defaultdict(int)
>> remaining = change
>>
>> #   Loop until either we have given all the change or we have
>> #   run out of coin denominations to check.
>> for deno in denominations:
>> if not remaining:
>> break
>>
>> #   For one denomination, count out coins of that denomination
>> #   as long as the remaining amount is greater than the denomination
>> #   amount.
>>
>> while remaining >= deno:
>> coinCount[deno] += 1
>> print "remaining =", remaining
>> remaining -= deno
>>
>> #   Report the results.
>> print "Your change is $%.02f"% (float(change) / CPD)
>> for deno in denominations:
>> if coinCount[deno] > 0:
>> if deno >= 100:
>> print "$%d bills:\t" % (deno / CPD), coinCount[deno]
>> else:
>> print "%d-cent coins:\t" % (deno), coinCount[deno]
>>
>>
>> Kent
>> 
>
> Thanks Kent!
>
> Here's what I have after incorporating your suggestions:
>
> =
> #!/usr/bin/env python
> #coding=utf-8
> from collections import defaultdict
>
> CPD = 100
> cost = int(CPD * float(raw_input("Enter the cost: ")))
> tend = int(CPD * float(raw_input("Enter the tendered amount: ")))
>
> #   Calculate the change.
> change = tend - cost
>
> coinCount = defaultdict(int)
> print coinCount
> remaining = change
> denominations = (2000, 1000, 500, 100, 50, 25, 10, 5, 1)
>
> #   Loop until either we have given all the change or we have
> #   run out of coin denominations to check.
> for deno in denominations:
>  if not remaining:
>  break
>
>
>  #   For one denomination, count out coins of that denomination
>  #   as long as the remaining amount is greater than the denomination
>  #   amount.
>
>
>  while remaining >= deno:
>  coinCount[deno] += 1
>  remaining -= deno
>
>   

Try something like:

def makechange( amount, denominations ):

coins = {}
for d in denominations:
coins[d] = int( amount/d )
amount = amount%d

return coins

> #   Report the results.
> print "Your change is $%.02f"% (float(change) / CPD)
> for deno in denominations:
>  if coinCount[deno] > 0:
>  if deno >= 100:
>  print "$%d bills:\t" % (deno / CPD), coinCount[deno]
>  else:
>  print "%d-cent coins:\t" % (deno), coinCount[deno]
> 
>
> Gotta say though, I still don't understand how the defaultdict works here.
>
> Dick
>
>
>
> ___
> 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] Ingenious script (IMO)

2007-08-06 Thread Eric Brunson

Multiple subtractions is called division.  It's a much more efficient loop.

In this version you have exactly as many iterations as denominations.  
It the original, if you wanted to know how many 200 coins are in 
10, you would iterate ~500 times.

Here's a timing test:

denominations = ( 200, 100, 50, 25, 10, 5, 1 )

def makechange( amount, denominations ):

coins = {}
for d in denominations:
coins[d] = int( amount/d )
amount = amount%d

return coins

def oldmakechange( amount, denominations ):

coins = {}
for d in denominations:
coins[d] = 0
while amount >= d:
coins[d] += 1
amount -= d

return coins

def comparetimings( trials=1, amount=1000 ):
from timeit import Timer
global denominations

new = Timer( "makechange( %s, denominations )" % amount, "from __main__ 
import makechange, denominations" ).timeit( trials )
old = Timer( "oldmakechange( %s, denominations )" % amount, "from __main__ 
import oldmakechange, denominations" ).timeit( trials )

print old, new, old/new


if __name__ == '__main__':
comparetimings()



Yields:  2.83604502678 0.000821828842163 3450.89498114

i.e. the division version runs about 3500 times faster for $100,000.

It's a minor thing, but you asked how we'd improve the code.  Math is a 
good thing to know.  ;-)

Dick Moores wrote:
> On 8/6/07, *Eric Brunson* <[EMAIL PROTECTED] 
> <mailto:[EMAIL PROTECTED]> > wrote:
>
> Try something like:
>
> def makechange( amount, denominations ):
>
> coins = {}
> for d in denominations:
> coins[d] = int( amount/d )
> amount = amount%d
>
> return coins
>
> Sorry, but could you spell out your point?
>
> Dick

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


Re: [Tutor] Ingenious script (IMO)

2007-08-06 Thread Eric Brunson
Dick Moores wrote:
> At 10:16 AM 8/6/2007, Eric Brunson wrote:
>
> Your point about efficiency is well-taken.
>
>> def makechange( amount, denominations ):
>>
>> coins = {}
>> for d in denominations:
>> coins[d] = int( amount/d )
>> amount = amount%d
>>
>> return coins
>
> OK, I used this this way:
>
> 
> def makechange( amount, denominations ):
>
>coins = {}
>for d in denominations:
>coins[d] = int( amount/d )
>amount = amount%d
>
>return coins
>
> denominations = (2000, 1000, 500, 100, 50, 25, 10, 5, 1)
> amount = 2218
> print makechange(2218, denominations)
> ==
>
> And get:
> {1: 3, 100: 2, 5: 1, 1000: 0, 10: 1, 2000: 1, 50: 0, 500: 0, 25: 0}
>
> That's the correct change: 3 pennies, 2 $1 bills, 1 nickel, no $10 
> bills, 1 dime, 1 $20 bill, no half-dollars, no $5 bills, no quarters.
>
> For amount = 3288:
> {1: 3, 100: 2, 5: 0, 1000: 1, 10: 1, 2000: 1, 50: 1, 500: 0, 25: 1}
>
> Why those weird orders?

Dictionary keys are not guaranteed to return in the order you add them.

You can sort them manually if it's important:

change = makechange( 2218, denominations )
print [ ( k, change[k] ) for k in sorted( change ) ]

Or, since you have a sorted list of denominations already:

change = makechange( 2218, denominations)
print [ ( k, change[k] ) for k in denominations ) ]

Or, if you know you're going to want them sorted use:

coins = []
for d in denominations:
   coins.append( ( d, int( amount/d ) )
   amount = amount%d

to get an ordered list of tuples.


Isn't programming fun?



>
> Dick
>
>
>
> ==
>   Bagdad Weather
> <http://weather.yahoo.com/forecast/IZXX0008_f.html>

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


Re: [Tutor] comparing two numpy arrays

2007-08-07 Thread Eric Brunson
Bob Gailer wrote:
> Andy Cheesman wrote:
>   
>> Hi people,
>>
>> If I've two numpy arrays, is there a non-looping way of finding common
>> values. (the example below has identical shapes for the arrays but this
>> may not be the case in my scenario)
>>
>> e.g
>> a = array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>> b = array([ 5,  6,  7,  8,  9, 10, 11, 12, 13, 14])
>>
>> answer = array([ 5,6,7,8,9])
>> 
> Set union?
>
>   
Did you mean Set intersection?

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


Re: [Tutor] Large Scale Python websites

2007-08-07 Thread Eric Brunson
Alan Gauld wrote:
> "OkaMthembo" <[EMAIL PROTECTED]> wrote
>
>   
>> Is anyone aware of any large scale web apps developed in Python? 
>> Please let
>> me know of any that you know of...
>> 
>
> The Zope web site has many examples.
>
> But it depends how you define large scale. Most of the really big ones 
> (Google,
> Yahoo, IBM, BBC etc - anything with several million hits a day)  use 
> Java or C++
> in my experience. But a lot of large and busy sites do exist using one 
> or other
> of the Pyhon web frameworks, check the frameworks and you will find 
> case
> histories.
>
> And even the biggest sites often use languages like Python etc for
> experimental features or occasional access areas or for administration
> or test duties. One of the good things abourt web developments is that
> its pretty easy to mix frameworks and have it appear seamless to the 
> user.
>   

YouTube runs primarily on Python with critical code sections compiled 
using psyco.

http://highscalability.com/youtube-architecture

Akamai is also a big python shop, from what I understand (no citation 
available).

Those big enough for you?


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


Re: [Tutor] subprocess and signals

2007-08-07 Thread Eric Brunson
Noufal Ibrahim wrote:
> Hello everyone,
>I've come across a situation which is somewhat confusing to me.
>I googled for some details and came across another email thread on 
> this very list but couldn't really glean a solution out of it.
>
>I have a program (a compiled binary) for which I need to write a 
> wrapper (in python). The wrapper will construct some sane command line 
> defaults for this binary and then execute it while storing some 
> statistics like who launched it, where and when.
>
>Now this program will continuously print output (it's a parallel 
> version of make). It it receives a SIGINT (via a Ctrl-C), it will print 
> some statistics and go on with the build. If it receives a Ctrl-\ 
> (SIGQUIT I think), it will terminate. I want my wrapper to be able to 
> read the output of this program and print it while allowing these two 
> signals to be passed to it.
>
>My wrapper (let's call it wrapper.py) has something like this
>
> --
> def createSignalDelegator(p):
>  def sighandler(signal,frame,pmake = p):
>  os.kill(pmake.pid,signal)
>  return sighandler
>
> pmake = subprocess.Popen(pmake_cmd, bufsize = 1, stdout = 
> subprocess.PIPE, stderr = subprocess.STDOUT)
>
> signal.signal(signal.SIGINT,createSignalDelegator(pmake))
> signal.signal(signal.SIGQUIT,createSignalDelegator(pmake))
> for op in pmake.stdout:
> print "-- %s"%str(op).strip()
> --
>
> I've substituted my actual binary with a simple python script that 
> continuously prints a string and which traps sigint and sigquit to 
> appear like the binary. It seems to be receiving the signals fine (since 
> I log it's activity into a separate file) but the problems I get are like so
>   

I'm not an expert on the subprocess module, but I've used it a bit and 
I'm referring to the docs as I write this.

> 1. I don't see any output (from my 'build') on screen when I run my 
> wrapper.
>   

Why do you think you should?  You've asked subprocess to pipe its output 
you your parent process, I believe you would need to use the 
communicate() method to get the output generated by the subprocess.


> 2. When I send a ^C to the wrapper, I don't see the output from the 
> build script.
>   

Fix #1 first and then this should fall into place.

> 3. I sometimes get a pipe error and the whole wrapper dies leaving the 
> other program running.
>   

Exact error messages help a lot.  :-)

> I'd appreciate any insights into the problem. I'm not sure where to 
> start looking.
>
> Thanks.
>
>
>   

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


Re: [Tutor] Losing the expressiveness of C's for-statement?/RESENDwith example

2007-08-07 Thread Eric Brunson
Stephen McInerney wrote:
> Hi Alan,
>
>
>   
[ snipage ]
>> As to your particular case one non while option would be a generateor:
>>
>> def half(n):
>> while int(n) > 0:
>>n = n/2
>>yield n
>>
>> for x in half(300): print x,
>> 
>
> It's ok but it's visually clunky. while-loop wins for clarity. lambda would 
> also be too quirky.
> I know the generator is more runtime-efficient.
> It's regrettable we have to choose between the clear and the efficient, in 
> this situation.
>   

That statement seems to be founded on the assumption that the C syntax 
is clear, which has not been established.  It is clear to you because it 
is what you're used to seeing.  Slap it down in front of a programmer 
that has never seen the idiom and see what they make of it.

Any time you change languages you have to accustom yourself to it's 
nuances.  C is probably one of the hardest languages I ever learned, I 
can't remember how many times I read and re-read the K&R chapter on 
pointer syntax.

e.

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


Re: [Tutor] variable * raw_input

2007-08-09 Thread Eric Brunson
Dewight Kramer wrote:
> Hello,
>
> So i am new to Python, and really to programming.  I picked up book  
> and so far I like it. right now I am trying to figure out a problem  
> that I cant.
>
> It is a tipping program and I have assigned certain words to be a  
> certain % and then I ask the user to type raw input of one of those  
> names.   After which I am trying to mutiply the Bill by the Service  
> quality.  But I dont understand something below is code.
>
> Thanks
> D
>
> # Tip Calulator - Ver
> # Challenges Ch2 - Question 3
> # Developed by, Dewight
> # Developed on, 8/7/2007
>
>
> # establish variables
> bill = float(0.0)
> bad = float (0.0)
> ok = float(0.10)
> good = float (0.15)
> great = float (0.20)
>   

Speaking as a former waiter, this should probably read:

great = float (0.25)
good = float (0.20)
ok = float(0.15)
bad = float (0.10)
eatathomeyoucheapskatebagofcrap = float(0.0)


;-)

I now return you to your regularly scheduled Python discussion.

> service="nothing"
> tip = float ()
> total = float ()
>
> print "This is a tipping calculator."
>
> bill = raw_input ("\nWhat was the total bill amount?  ")
> service = raw_input("Please input one of the following to"+
>  " discribe the service:"+"\nbad\nok\ngood\ngreat 
> \n")
>
> tip = bill * service
> total = bill + tip
> print "Then you should leave a" + tip + "tip. This will bring the  
> total to" + total +"."
>
>
> raw_input("\n\nPlease press enter to exit.")
> ___
> 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] Security [Was: Re: Decoding]

2007-08-14 Thread Eric Brunson
Michael Sparks wrote:
> Tiger12506,
>
>
> You are COMPLETELY missing the point. The __following__ code
>
>   
> foo = raw_input(...)
> x = eval(foo)
>   
>
> ONLY works if the user has console access to the machine.
>
> If they have console access to the machine 
> AND you're worried about them damaging it
> THEN an eval(raw_input( ...)) construct is the least of your worries.
>
> I'm not referring to text taken from
>* a network connection
>* a file
>* a web form
>* a P2P network
>
> I was JUST referring to the ONE context of immediately eval'ing user input. 
> (an unlikely one at that)
>   

No, I think you're missing the point.  If the program was not 
interacting with the user through the console, then why would you be 
using raw_input()?  raw_input() is used to get user input from the 
controlling terminal.  Am I missing some other use for raw_input()?

Using eval() on untrusted input of any kind is a security risk.

Reading the rest of your email, I get the feeling that what you're 
saying is:  if a user has access to "the console", then using eval( 
raw_input() ) is the least of your worries because the person can do 
anything they want.  Is that your assertion?

If it is, then it's an invalid argument.  raw_input() is not only useful 
on "the console", it can be used to interact with any terminal and can 
be done securely so that exiting the program is either impossible, or 
restarts the program or else simply disconnects from the terminal and 
leaves the user with no access at all.  The only thing I can imagine is 
that you're stuck in some DOS mindset that if you're able to type into 
"the console" then you have ultimate access to the machine, which is not 
the case when using a true multi-user operating system like *nix or VMS.

But, most strange to me is why you're this fired up over such a simple 
issue.  It seems to me like just a misunderstanding.


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


Re: [Tutor] Security [Was: Re: Decoding]

2007-08-14 Thread Eric Brunson
Michael Sparks wrote:
> On Monday 13 August 2007 21:53, Kent Johnson wrote:
>   
>> Hmm...could be a remote connection such as ssh, which precludes the
>> sledgehammer though probably not the sort of mischief you can get into
>> with eval()...perhaps there are untrusted remote connections where
>> eval() would still be a significant risk, I don't know...
>> 
>
> If they can ssh into a box, the likelihood of that ssh connection *only* 
> allowing them access to run that single python program strikes me as 
> vanishingly small :-)
>   

Unless you set it up that way specifically, i.e. making the interactive 
python program their login shell or specifying it to be run in their 
.ssh/config.

> Generally speaking I agree that eval is a good opportunity for problems, but 
> if its in response to raw_input, I think the likelihood of it being the 
> biggest potential security problem is low :)
>
> (After all, if they're ssh'ing in, they're more likely to ssh in, *then* run 
> the code. They could happily delete and trash all sorts of things either 
> inside or outside python. They could even write their own scripts to assist 
> them in their devilish plans too, far exceeding the minor demon of eval ;-)
>
> Eval can however be an amazingly useful function, especially when combined 
> with exec.
>
>
> Michael.
> ___
> 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] Security [Was: Re: Decoding]

2007-08-14 Thread Eric Brunson
Michael Sparks wrote:
> On Monday 13 August 2007 21:53, Kent Johnson wrote:
>   
>> Hmm...could be a remote connection such as ssh, which precludes the
>> sledgehammer though probably not the sort of mischief you can get into
>> with eval()...perhaps there are untrusted remote connections where
>> eval() would still be a significant risk, I don't know...
>> 
>
> If they can ssh into a box, the likelihood of that ssh connection *only* 
> allowing them access to run that single python program strikes me as 
> vanishingly small :-)
>
>   

Unless you set it up that way specifically, i.e. making the interactive 
python program their login shell or specifying it to be run in their 
.ssh/config.


P.S.
Michael, sorry for the double post to you, I missed the "reply all" 
button the first time.

> Generally speaking I agree that eval is a good opportunity for problems, but 
> if its in response to raw_input, I think the likelihood of it being the 
> biggest potential security problem is low :)
>
> (After all, if they're ssh'ing in, they're more likely to ssh in, *then* run 
> the code. They could happily delete and trash all sorts of things either 
> inside or outside python. They could even write their own scripts to assist 
> them in their devilish plans too, far exceeding the minor demon of eval ;-)
>
> Eval can however be an amazingly useful function, especially when combined 
> with exec.
>
>
> Michael.
> ___
> 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] Security [Was: Re: Decoding]

2007-08-14 Thread Eric Brunson
Luke Paireepinart wrote:
> Eric Brunson wrote:
>> Michael Sparks wrote:
>>  
>>> On Monday 13 August 2007 21:53, Kent Johnson wrote:
>>>  
>>>> Hmm...could be a remote connection such as ssh, which precludes the
>>>> sledgehammer though probably not the sort of mischief you can get into
>>>> with eval()...perhaps there are untrusted remote connections where
>>>> eval() would still be a significant risk, I don't know...
>>>>   
>>> If they can ssh into a box, the likelihood of that ssh connection 
>>> *only* allowing them access to run that single python program 
>>> strikes me as vanishingly small :-)
>>>
>>>   
>>
>> Unless you set it up that way specifically, i.e. making the 
>> interactive python program their login shell or specifying it to be 
>> run in their .ssh/config.
>>
>>
>> P.S.
>> Michael, sorry for the double post to you, I missed the "reply all" 
>> button the first time.
>>   
> I don't think you  missed on account of me receiving two e-mails as 
> well. :)
> -Luke

Python:  easy
Email: hard

;-)



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


Re: [Tutor] Question re Tutor List Etiquette

2007-08-14 Thread Eric Brunson
Dick Moores wrote:
> When sending a reply to a post, to the list, should we also address 
> the reply to the author of the post to which we are replying? 
> (There's gotta be an easier way to say that..) If we do so, then the 
> author gets a duplicate of our reply.
>
> I've run some statistics (but no more bar graphs ;-) ). My Eudora 
> mailbox for Tutor contains 12,114 emails (I've deleted the duplicates 
> I've received). Of these, 9,424 are replies. Of these replies, 4,338 
> (46%) were addressed ONLY to the list. So 54% WERE also sent to the 
> author being replied to.
>
> Is there a rule about this? Or should one be made? Or does it matter?
>
> Replying only to the list takes a bit of trouble. The default 
> behavior seems to be that the "Reply" button addresses the author 
> only and not the list; "Reply to all" addresses both the list, the 
> author, and any others included in the To: or Cc: headers of the post 
> being replied to. Or at least that's how Eudora and Gmail work.
>
> Ten years ago or so I managed a Majordomo list, and I recall that it 
> was possible for the list manager to configure the list to include a 
> "Reply-To" header. If this would be possible for the admins to do 
> with Tutor -- to include a "Reply-To: tutor@python.org" header in the 
> posts sent out by the list, it would enable us to address a reply 
> only to the list by hitting the "Reply" button.
>   

If you search those 12,114 emails you'll find a discussion of this from 
about 6 weeks ago.  Consensus was split, so the list manager chose to 
leave the policy unchanged.

> Dick Moores
>
> ___
> 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] Security [Was: Re: Decoding]

2007-08-14 Thread Eric Brunson

Whatever.  I make it a point to discontinue any debate that degenerates 
into someone quoting their work experience to me.  At that point you've 
basically told me that you are convinced you know better than I do and 
nothing I say will convince you otherwise, because you've been doing 
this for so long you couldn't possibly be wrong.

No matter how many perfectly valid scenarios have been put forth, you've 
shot them down as being outlying border cases that can't compete with 
your assertion that if you have access to type at a keyboard, then your 
security is already compromised such that any damage done by 
eval(raw_input()) is trivial in comparison.

I think the basic point that everyone has been making is:  Using eval() 
on any uncontrolled input is a security risk, now matter what the source.


Michael Sparks wrote:
> On Tuesday 14 August 2007 16:48, Eric Brunson wrote:
> ...
>   
>> The only thing I can imagine is 
>> that you're stuck in some DOS mindset that if you're able to type into
>> "the console" then you have ultimate access to the machine, which is not
>> the case when using a true multi-user operating system like *nix or VMS.
>>
>> But, most strange to me is why you're this fired up over such a simple
>> issue.  It seems to me like just a misunderstanding.
>> 
>
> I'm not particularly fired up, text comes across much harsher than it looks. 
> (Also people being particularly patronising, like you have above, is 
> particularly irritating. Last time I used VMS was 12 years ago. I'm not 
> missing your point or anyone else's, and I've not used DOS for 10 years so 
> I'm hardly stuck in a DOS mindset (been developing under linux for over 10 
> years).
>
> Yes, there are a tiny set of scenarios where doing eval(raw_input(...)) could 
> be a problem. The idea that its always a gaping security hole is completely 
> bogus.
>
> The scenario's raised I've never once seen happen. Despite having seen
> a number of systems where you either ssh in or telnet into a specialise
> console (routers and other network appliances).
>
> What was irritating was I was saying:
>* Scenario A (and only that scenario) is hardly a risk considering 
>  in >99% of cases where the user can type something in response to
>  eval(raw_input(...)) they have FAR more ways of causing problems.
>
>* The response I was getting a told was that this was wrong because
>  *other scenarios* were dangerous. 
>
> Yes, other scenarios are wrong. Denouncing a piece of code as a gaping 
> security hole without discussing the context is irresponsible.
>
> That and being taught to suck eggs is irritating. I've been evaluating 
> security of network systems for 10 years and coding for 25 years. 
>
> After all piece of code is never a security risk by itself. It's how that
> code is deployed and used that _can_ be.
>
>
> Michael.
>
>   

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


Re: [Tutor] Need help on "How to Think Like a Computer Scientist: Learning with Python".

2007-08-15 Thread Eric Brunson

I don't know of an answer key, but feel free to post questions about 
what you're having trouble with and we'd be happy to discuss various 
approaches among the list members.

Vanneth Tea wrote:
> Hello All,
>
> I am new to computer programming and chose to learn
> Python.  Now I am stuck with certain codes that I need
> help.  Please let me know if there is an answer list
> to the exercises in "How to Think Like a Computer
> Scientist: Learning with Python."
>
> I followed and did good on most of the exercises but I
> have been stuck on a few of them which burned me up
> after spending days and nights trying to make them
> works.  
>
> I hope you understand the feeling when you are stuck
> and need a drop of water to keep alive.  I really
> appreciate any assistance you can give.
>
> Thanks.
>
>
>
>
>
>   
> 
> Fussy? Opinionated? Impossible to please? Perfect.  Join Yahoo!'s user panel 
> and lay it on us. http://surveylink.yahoo.com/gmrs/yahoo_panel_invite.asp?a=7 
>
> ___
> 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] Getting Date/Time from a file and using it in calculations

2007-08-15 Thread Eric Brunson
[EMAIL PROTECTED] wrote:
> Hello there
>
> Messing around with certain time and datetime objects, I have managed to 
> subtract a date/time from the present time thusly:
>   

datetime is definitely a module that takes a little getting used to.

> from time import *
>   

(Bad form)

> import datetime
>
> one = datetime.datetime.now()
> two  = datetime.datetime(2007, 8, 29, 11, 15, 00)
>
> difference = one - two
>
> print difference
>
> However, I have to take a date from a file and then insert it to where two 
> should be, however to no success. I have managed to get a string containing 
> the above date/time, but that is as far as I've gotten without it not 
> working.
>   

You don't show the format of the date string, but I'll show an example:

 >>> from datetime import datetime
 >>> start = datetime.strptime( '10:24:03 2006-11-01', '%H:%M:%S %Y-%m-%d' )
 >>> end = datetime.strptime( '11:10:33 2006-11-01', '%H:%M:%S %Y-%m-%d' )
 >>> delta = end - start
 >>> print delta.seconds
2790

Is that what you need?

Take a skim through the library reference for the entire module.  The 
result of the subtraction is a timedelta object, you kind of need to 
know what's available overall to be able to pick out the right 
functionality.

Hope that helps,
e.

> Does anyone have any ideas on how to do this properly?  
>
> Also I wish to display the result only in seconds left, rather than the 
> current result, which just displays days/hours/minutes/seconds/milliseconds 
> left, but am again struggling to progress.
>
> Any help would be amazingly appreciated :)
>
> Thanks again
>
> -Dave
> ___
> 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] Need to convert 1,987,087,234,456 to an int

2007-08-15 Thread Eric Brunson
Dick Moores wrote:
> At 06:58 PM 8/15/2007, John Fouhy wrote:
>   
>> You could do this:
>>
>> 
> def decomma(*t):
>   
>> ...  return int(''.join(str(i) for i in t))
>> 
>
> What's that asterisk doing in decomma(*t)? Where do I go in the docs 
> to look it up?
>
>   

It's the opposite of "def f( *args )"

It's easiest to show by example:

 >>> def f( *args ):
... print args
...
 >>> f( 1 )
(1,)
 >>> f( 1, 2, 3 )
(1, 2, 3)
 >>> f( (1, 2, 3) )
((1, 2, 3),)
 >>> f( *(1, 2, 3) )
(1, 2, 3)

This is your brain on python.  Any questions?

:-)


> Thanks,
>
> Dick
>
>
> ___
> 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] Efficiency of Doxygen on Python vs C++?

2007-08-17 Thread Eric Brunson
Stephen McInerney wrote:
> Hi Alan,
>
>   
>>> My friend clarifies: "It's not the efficiency of doxygen that's the
>>> question. The problem is that you can add fields to objects as you go in
>>> Python so you need to do a deep analysis of the code to determine the 
>>>   
>> class
>> 
>>> structure which you don't have to do with C++ (or Java)."
>>>   
>> That's true it's one of the "benefits" of a dynamic language, but it does
>> make the code harder to parse.
>> 
>
> Is this not just evidence of a very bad Python coding style?
> Should we not always declare *all* class fields in the class definition
> by assigning to them, even if the assignment is token or dummy
> i.e. 'None', "", [], {} etc.
>
>   

Absolutely not.  I have several classes that build themselves 
dynamically at runtime.  As an example, one of them reads the data 
dictionary of a database.  You may as well suggest that you define all 
your dictionary keys at the beginning of the program.

>>> He mentioned numbers like maybe ~20+x slower on lines-of-code
>>> for Python vs C++.
>>>   
>> That sounds high, I would have expected no more than 5-10 times longer.
>> But of course against that we have the advantage that there will be far 
>> fewer
>> lines to parse in a Python project,  typically only a third or a quarter of
>> the number of lines - sometimes less than that.
>> 
>
> Can you cite us a literature source for saying that Python is 3-4x more
> expressive  per line-of-code than C++?
> Would come in handy for evangelizing.
>
>   
>>> A second friend of mine who is an XML/Java enthusiast echoed similar
>>> comments about scalability in large builds with weakly-typed dynamic
>>> languages such as Python.
>>>   
>> The concept of a "large build" doesn't really exist in an interpreted
>> language like Python. OTOH I probably wouldn't usePython for a
>> very large project - say over a million lines of code in C++ - for a
>> variety of other reasons. eg. Python could do it but the coordination of
>> multi team projects becomes harder without tools like static type
>> checking.
>> 
>
> Has anyone ever tried pragmas for hinting about member types as I suggested?
>
> Stephen
>
> _
> A new home for Mom, no cleanup required. All starts here. 
> http://www.reallivemoms.com?ocid=TXT_TAGHM&loc=us
>
> ___
> 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] Efficiency of Doxygen on Python vs C++?

2007-08-17 Thread Eric Brunson

We're definitely on the same wavelength, Alan.  :-)

Alan Gauld wrote:
> "Stephen McInerney" <[EMAIL PROTECTED]> wrote
>
>   
>> Eric, you misunderstood my point.
>> I said you make a **token** assignment in the class defn simply
>> to do two things:
>> - 1) identify all the members in one place
>> - 2) annotate each member's type, as much as you can
>> 
>
> I'm sure Eric can explain for himself but what I think he was saying
> was that his classes define themselves at runtime. They read the
> names of the fields and type information from the database metadata
> and create the attributes accordingly. Thus he doesn't know what
> his class attributes will be until the program runs. He may not even
> know the names of his classes until he reads the database
> tablenames.
>
> This is exactly the kind of tricky coding that is possible in a 
> dynamic
> language which is next tio impossible in static compiled code, unless
> you write your own 'little language interpreter' inside the compiled
> program. This kind of abstract meta programming is extremely tricky
> to get right but at least it's possible in something like Python.
> But it makes analyzing the code very complex since much of the
> working code is being created by the config code at runtime.
>
> I've never actually tried this in Python but have done similar things
> in Lisp. In C++ you usually have to create classes in advance for
> every possible eventuality then use a factory class (or big switch
> statement) to create the desitred instances. That's a lot of excess
> code which is still less reliable and robust.
>
> Of course I could be misreading Eric's intent...
>
> Alan G. 
>
>
> ___
> 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] Efficiency of Doxygen on Python vs C++?

2007-08-18 Thread Eric Brunson
Stephen McInerney wrote:
> Kent,
>
>   
>>> I was asking if it's a recognized good programming practice to
>>> declare and initialize *all* members in the class defn.
>>>   
>> What do you mean by "initialize *all* members in the class defn"?
>> 
> - obviously I meant to say do it in the __init__() method,
> I wrote the snippet as I was rushing out the door to an exam,
> but I think the intent was clear.
>
>   
>> If you mean to initialize the variables in the __init__() method:
>> maybe this is more common but I don't think I have ever seen it recommended 
>> to initialize all variables in the __init__() method. Certainly there are 
>> times when it makes sense to have some of the initialization in other 
>> methods that are called from __init__().
>> 
>
> I only said "make a token dummy assignment in __init__() to hint
> to the static analyzer the name and expected type, I didn't say
> "you must do all the actual initialization itself in __init__()".
>   

I guess my only thought is that this "static analyzer" is simply a 
holdover from your Java/C++ programming experience. It just doesn't 
really make sense in a dynamic language. I'd rather spend my time 
actually writing the documentation than litter my code so some other 
software can do it for me.

I'm not saying it isn't a good idea in Java, I'm just not sold on the 
concept in python. Just write doc strings, people have already written 
utilities to parse and display them.

> In the context of the original question
> "where and how should we assign class members in order
> to flag member names and types to static analyzers like
> Doxygen or pylint?"
> I understood that people were agreeing
> "Yes, assigning each member token values in the __init__()
> method is a good practice".
>
>   
>>> I think I'm hearing a general yes on that - any other opinions?
>>>   
>> Not sure where you think you are hearing a yes, I am hearing a lot of 
>> objections.
>> 
>
> No they didn't - they said that this cannot be done for true dynamic code,
> which is true, but obviously doesn't apply to working with
> static analysis tools, which is what the question was about.
>
> Regards,
> Stephen
>
> _
> Messenger Café — open for fun 24/7. Hot games, cool activities served daily. 
> Visit now. http://cafemessenger.com?ocid=TXT_TAGHM_AugHMtagline
>
>   
> 
>
> ___
> 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] Convert bmp to mpeg

2007-08-21 Thread Eric Brunson
Per Jr. Greisen wrote:
> Hi,
>
> I would like to make a method where I give a number of bmp-file as 
> argument and than create a mpeg format from these - is that possible 
> with python and which packages should I use?

On my platform the ffmpeg suite is one of the de facto standards for 
creating or manipulating mpegs.  The PyMedia project purports to provide 
an interface to this library, check it out here: 
http://pymedia.org/faq.html


>
> Thanks in advance
> -- 
> Best regards
> Per Jr. Greisen
> 
>
> ___
> 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] subprocess and su

2007-08-21 Thread Eric Brunson
Tino Dai wrote:
> Hi there,
>
>  I'm have a tough time figuring out how to get su and subprocess 
> working. I have
>
> PIPE=subprocess.pipe
>
> sbp=subprocess.Popen(["su","-",stdin=PIPE,stdout=PIPE,close_fds=True,shell=True)
>  
>
>
> how I thought that it was supposed to work was it would allow me to 
> use sbp.communicate() to
> send stuff to the stdin, and get information out. What do get is a 
> prompt ask for my password. 

I think you have the right understanding of Popen, you seem to be 
missing out on "su".  What happens when you type "su -" on the command line?

> Does
> anybody have an example that I can see (I have already check most of 
> the entries in google( or should
> I just use pexpect instead?
>
> -Thanks,
> Tino
>
> 
>
> ___
> 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] A fun puzzle

2007-08-22 Thread Eric Brunson
R. Alan Monroe wrote:
> I wrote a lame, but working script to solve this in a few minutes. A
> fun puzzle.
>
> http://weblogs.asp.net/jgalloway/archive/2006/11/08/Code-Puzzle-_2300_1-_2D00_-What-numbers-under-one-million-are-divisible-by-their-reverse_3F00_.aspx
>
>   

Fun!

for x in xrange(1, 100):
if x%10 == 0:
continue
reverse = int( str( x )[::-1] )
if reverse == x or reverse > x:
continue
if not x%reverse:
print x

8712
9801
87912
98901
879912
989901

I thought I'd do it in a single list comprehension, but in order to do 
that I had to calculate the reverse multiple times.


> Alan
>
> ___
> 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] Converting code to string

2007-08-23 Thread Eric Brunson
Bernard Lebel wrote:
> Hi Kent,
>
> When try your approach, I get an IOError.
>
>   
 import inspect
 def myFunc():
 
> ... print 'hello world'
> ...
>   
 s = inspect.getsource(myFunc)
 
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "C:\Python24\lib\inspect.py", line 552, in getsource
> lines, lnum = getsourcelines(object)
>   File "C:\Python24\lib\inspect.py", line 541, in getsourcelines
> lines, lnum = findsource(object)
>   File "C:\Python24\lib\inspect.py", line 410, in findsource
> raise IOError('could not get source code')
> IOError: could not get source code
>   

My guess is that's because you're doing it interactively.  Try putting 
that in a file and it should work.

>
>
> Why? Because I'm using an API (the Softimage|XSI scripting API) where
> I have to create a custom GUI (using that API's GUI toolkit).
>
> I have to attach a logic callback to a number of widgets that can
> change from one execution to the next.
>
> The only way to do that, in that API, is to define the callback
> functions "on-the-fly". And to define such a callback, the API
> requires that the function must be represented as a string. All
> strings are then joined and "injected" (the terminology used in the
> doc) into the GUI object.
>   

Then why not just define them as text strings?  Then you can inject 
them, or if you need to execute them outside of the API, you can still 
compile and run them.

If that's not a good idea, them my next thought would be to put all 
these callbacks in a single file.  You then have the options of 
importing the functions from the file (module), or to parse the file 
assigning the functions to a dictionary indexed by the name of the 
function. 

You make it seem like it wasn't your choice to use this API, but without 
knowing more about it, it sounds incredibly lame.

> Since the XSI API also supports JScript, it is my feeling that this
> part of the GUI toolkit was designed with JScript's toString() method
> in mind, which works beautifully. I'm looking to do the same in
> Python.
>
>
> Thanks!
> Bernard
>
>
>
>
>
>
> On 8/23/07, Kent Johnson <[EMAIL PROTECTED]> wrote:
>   
>> Bernard Lebel wrote:
>> 
>>> Hello,
>>>
>>> I'm looking for a way to convert Python code into a string.
>>>
>>> For example, let say I have this function:
>>>
>>> def myFunc():
>>> print 'hello world'
>>>
>>>
>>> Now in the same module, I'd like to take this function and convert it
>>> into a string:
>>>
>>> """def myFunc():
>>> print 'hello world'\n"""
>>>   
>> Try inspect.getsource(myFunc). But why?
>>
>> Kent
>>
>> 
> ___
> 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] capturing process's status with python

2007-08-23 Thread Eric Brunson

I'm a bit more of a Linux expert than a Python guru, so I don't know if 
there's a facility in python to do that.  However, if you look in /proc, 
every running process has a directory corresponding to its PID and in 
that directory is a pseudo-file called "status" that you can get state 
information from:

foxtrot(~)$ grep State: /proc/*/status | head -10
/proc/10065/status:State:   S (sleeping)
/proc/10125/status:State:   S (sleeping)
/proc/10793/status:State:   S (sleeping)
/proc/10801/status:State:   S (sleeping)
/proc/10/status:State:  S (sleeping)
/proc/1125/status:State:S (sleeping)
/proc/1126/status:State:S (sleeping)
/proc/1128/status:State:S (sleeping)
/proc/1129/status:State:S (sleeping)
/proc/11/status:State:  S (sleeping)

Convert that to python and you're in:

import glob

for file in glob.glob( '/proc/*/status' ):
f = open( file )
for line in f:
if line.startswith( 'State:' ):
junk, state, text = line.split( None, 2 )
print state, text

I'm interested to know if there's a portable python interface to the 
kernel process table, though, because that is very Linux specific.

Hope that helps,
e.

Flaper87 wrote:
> Hi everybody!
>
> i would like to know how can i capture the system process's status 
> with python, i need to know if they are sleeping, zombie or runing.
>
> I use Debian lenny, GNU/Linux
>
> thanks
>
> -- 
> Flavio Percoco Premoli, A.K.A. [Flaper87]
> http://www.flaper87.com
> Usuario Linux registrado #436538
> Geek by nature, Linux by choice, Debian of course.
> Key Fingerprint: CFC0 C67D FF73 463B 7E55  CF43 25D1 E75B E2DB 15C7
> 
>
> ___
> 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] Off Topic: xrange, WAS: Re: the and command

2007-08-24 Thread Eric Brunson
Kent Johnson wrote:
> Dave Kuhlman wrote:
>   
>> I thought xrange() returned an iterator.  I was wrong.
>>
>> Actually xrange() returns an xrange object which, according to the
>> docs, is "an opaque sequence".
>> 
>
> Interesting. So an xrange object is an iterable sequence, not an iterator.
>
>   

It's a fine distinction to the language lawyers.  Most of the time I see 
the term "iterator" used, the speaker is referring to an "iterable 
container", which is a container that defines an "__iter__()" method.  
That method returns the actual "iterator object", i.e. an object that 
implements an "__iter__()" and a "next()" method which returns the next 
item from the container until exhausted, then raises StopIteration.

So, xrange doesn't implement the next() method, but the object returned 
by xrange.__iter__() does, and *that* is the iterator object, though 
xrange can be referred to as "iterable".

Just semantics, but important when trying to be ultra-clear.  :-)

e.

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


Re: [Tutor] Equivalent of && in Python?

2007-08-27 Thread Eric Brunson
wormwood_3 wrote:
> I have a script that reads some local system information, performs some 
> calculations, and then launches some terminal windows:
>
> # Spawn the 4 terminals, with needed positions and sizes, then exit
> commands.getoutput("%s --geometry=%dx%d+%d+%d --working-directory=%s" % \
> (terminal, t1width, t1height, t1posx, t1posy, workingdir))
> commands.getoutput("%s --geometry=%dx%d+%d+%d --working-directory=%s" % \
> (terminal, t2width, t2height, t2posx, t2posy, workingdir))
> commands.getoutput("%s --geometry=%dx%d+%d+%d --working-directory=%s" % \
> (terminal, t3width, t3height, t3posx, t3posy, workingdir))
> commands.getoutput("%s --geometry=%dx%d+%d+%d --working-directory=%s" % \
> (terminal, t4width, t4height, t4posx, t4posy, workingdir))
>
>
> The oddity: When I call this script, sometimes all four terminals launch, one 
> right after another, which is the desired behaviour. 

That is what's actually odd.  Just reading the script without being well 
versed in the intricacies of the command module, I would expect them to 
be run sequentially.

> At other times, one will launch, and ONLY after I close it will the second 
> launch, and so on until the fourth. I do not understand how this is 
> happening. I thought each line in a script which does anything has to be done 
> before the next one is executed, but I may be way off on this. 
>
> If this were in a bash script, I could add " &&" after each line, but what to 
> do in a Python script?
>   

Actually, I think you mean a single ampersand.  "&&" is condition 
execution of the next command and is done synchronously.

I would say try putting an ampersand after the command in getoutput(), 
have you tried that?  If that doesn't work, then make sure getoutput() 
is using a shell, since the shell is the mechanism through which the 
ampersand works, or else read the docs for getoutput() to see if there's 
some way to get it in the background.  If none of those solutions work, 
you could spawn a thread for each command, or finally, use the 
subprocess module, which I know can be instructed to use a subshell.

> -Sam
>
>
> ___
> 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] Shared Class Attribute

2007-08-28 Thread Eric Brunson
Ricardo Aráoz wrote:
> Hi,
>   

Hi Ricardo,

In the future, please start a new thread with a new email and not a 
reply to an existing thread.  Compliant mail clients thread based on 
headers you may or may not see in your client, and this email is part of 
the thread you replied to called "[Tutor] PyCon 2008 - Call for Tutorial 
Ideas".  In addition, you send a copy of your message to 
[EMAIL PROTECTED] and many who reply using a "Reply All" 
function in their mailer will spam that list, too.

> if I have this class :
>
> class myClass :
> ClassCount = 0
> def __init__(self) :
> (here I want to increment ClassCount for the whole class)
>   self.InstanceAttr = 1
>   

You always reference a class variable by the class name:

 >>> class myclass:
... count = 0
... def __init__( self ):
... myclass.count += 1
...
 >>> c = myclass()
 >>> print c.count
1
 >>> d = myclass()
 >>> print d.count
2
 >>> print c.count
2
 >>> e = myclass()
 >>> print e.count, myclass.count
3 3

Hope that helps.

Sincerely,
e.

> How would I increment the shared class attribute (ClassCount) from
> INSIDE the class?
> I can do it from the outside by stating myClass.ClassCount = 22 and it
> will change for all instances. But haven't found a way to do it from inside.
> ___
> 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] Shared Class Attribute

2007-08-28 Thread Eric Brunson
Ricardo Aráoz wrote:
> Eric Brunson wrote:
>   
>> Ricardo Aráoz wrote:
>> 
>>> Hi,
>>>   
>>>   
>> Hi Ricardo,
>>
>> In the future, please start a new thread with a new email and not a 
>> reply to an existing thread.  Compliant mail clients thread based on 
>> headers you may or may not see in your client, and this email is part of 
>> the thread you replied to called "[Tutor] PyCon 2008 - Call for Tutorial 
>> Ideas".  In addition, you send a copy of your message to 
>> [EMAIL PROTECTED] and many who reply using a "Reply All" 
>> function in their mailer will spam that list, too.
>> 
>
> Hi Eric.
>
> Sorry, thought that by changing the subject I was changing the thread,
> won't happen again.
>   

No worries, everyone has to learn sometime.

> BTW, I did a 'reply all', is that bad?
>   

No, that's preferred.  :-)

> Thanks for the info on the class attribute.
>
>   
No problem, good luck.

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


Re: [Tutor] Trouble with script not parsing out text

2007-08-29 Thread Eric Brunson
Tim Finley wrote:
> I get the following when running a script.
>  
> TypeError: argument 1 must be string or read-only character buffer, 
> not _sre.SRE_Pattern

First, please post the entire error report when asking for help.  In 
this case I can tell you what the problem is, but in others the context 
of the error may not be so apparent.

>  
> Here is the script I am trying to run.   I am trying to verify that my 
> search is returning what I am trying to search for, but due to the 
> error I can verify it.
>  
> import re
>  
> log = open('audit.log') # Opens audit log
> log2 = open('timaudit.log','w')
> for line in log:
> line =re.compile(r"""

I think you want to use a different variable name than "line".  You're 
using it for the current line, then setting it to the compiled regular 
expression.

> \w  #match any alphanumeric character
> \Audit report for user+
> \User reported as inactive+
> """, re.VERBOSE)
> line.search('Audit report for user () User reported as inactive')
> log2.write(line)

Hence the error.  Write expects a line of text, but it doesn't point to 
the line of text you read any more.

Hope that helps,
e.

>  
> log.close()
> log2.close()
>  
> Thank you,
>  
> Tim Finley
> Novell IT Services Engineer
> Novell Technical Services
> Novell
> 
>
> ___
> 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] Starting classes

2007-08-31 Thread Eric Brunson
Ara Kooser wrote:
> Hello,
>   I read Alan Gauld's and How to Think Like a Computer Scientist
> section on classes. So I tried to write a simple room class. My goal
> is to write a short text adventure using classes. Here is the code:
>
> class Area:
> def _init_(self, name, description):
>   

Not enough underscores, you need two before and after the word "init".

> self.name = name
>
>
> def look(here):
> "Look around the place you are in"
> print here.description
>
>
> outside1 = Area("Outside")
> outside1.description = "You are standing outside with the town gate to
> your back"
>   

Why not:

outside1 = Area( "Outside", "You are standing outside..." )

and store self.description in the constructor?



> self.contents.append("dirt")
>   

What is self?  You've only defined self in the class methods and you're 
outside the class definition.  Was that just a cut and paste error? 

>
> look(bedroom)
>   

You'll get another error here, I  think you want:  outside1.look( bedroom )

> I get the following error.
> Traceback (most recent call last):
>   File "/Users/ara/Documents/text_advent.py", line 11, in 
> outside1 = Area("Outside")
> TypeError: this constructor takes no arguments
>
> Do the outside1 = Area("Outside) need to be nested in the class or can
> they be outside of it?
>   

No, that's correct, because you are instantiating the class and naming 
that instance "outside1".

> Thank you.
>
> Ara
>
>
>
>   

Hope that all helps,
e.

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


Re: [Tutor] or synxtax in if statement

2007-08-31 Thread Eric Brunson
David Bear wrote:
> I think I want to be lazy and express this
>
> if a == b | a = c
> (if a equal b or a equals c)
> using
>
> if a == b | c
>
> it seems to work.. but I'm not sure if it is correct -- and I haven't seen
> any documentation on using this type of syntax.
>
>
>   
The pipe is the "bitwise or" operator.  I think you're looking for "or".

And... "if a==b or c" won't work.

e.

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


Re: [Tutor] parsing response from SOAPpy request

2007-09-01 Thread Eric Brunson
Alan Gauld wrote:
> "Sean Cronin" <[EMAIL PROTECTED]> wrote
>
>   
>> The response comes back as XML document but when I check it with
>> type(result) it shows the the response is a string.
>> 
>
> Thats right the string is the XML document, just as if you had read it
> from a file with the read() method.
>
>   
>> Does anyone have any suggestions on getting relevant data?
>> 
>
> You need to parse the xml.
>
> The classic way to do that is using DOM or sax parsing,

Bleah.  ;-)

>  but
> Python now has the ElementTree parser which is usually
> much easier to use. Look at the module docs and for a lot
> more detail visit the ElementTree homepage:
>
> http://effbot.org/zone/element-index.htm
>   

I've used ElementTree a tiny bit, but preferred BeautifulSoup as it 
seemed more "pythonic" to me.  You should look at both and pick the one 
that suits you.  BeautifulSoup has the advantage of not choking on 
choking on XML that is not well formed.

e.


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


Re: [Tutor] advanced sorting

2007-09-04 Thread Eric Brunson

What version of python are you using?

chinni wrote:
>
>
> In Advance Sorting by giving the keywords to sort the list.But, iam 
> getting the fallowing errors
>
> >>> x = ['srikanth', 'kumar', 'muppandam', 'will', 'be', 'a']
> >>> x.sort(key=len)
> Traceback (most recent call last):
>   File "", line 1, in ?
> TypeError: sort() takes no keyword arguments
> >>> x.sort(reverse=True)
> Traceback (most recent call last):
>   File "", line 1, in ?
> TypeError: sort() takes no keyword arguments
>
>
> -Best Regards,
> M.srikanth.
> 
>
> ___
> 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] Python / CGI

2007-09-06 Thread Eric Brunson
Michael Connors wrote:
> Hi,
> If you have your own server to run it on, I think it would make sense 
> to use one of the Python web frameworks that are out there. I used 
> cherrypy for my first web-based python project and I found it very 
> easy to learn and develop in quickly.

That's debatable.  I find the frameworks to be overly complicated and 
obfuscated.  They're great when you're going through the tutorials, but 
try to do something "outside the box" and I find myself digging through 
documentation for longer than it would take me to write it from scratch.

For this you'd need:  some sort of backing store and some display 
routines with a simple interface to click on a slot and enter your name 
in it.  I think I could write it in about 75 lines of python.  Maybe 50.

Just my opinion,
e.

> Regards,
> Michael
>
> On 06/09/07, *Fiyawerx* <[EMAIL PROTECTED] 
> > wrote:
>
> Hi guys, quick question, I've been trying to learn python lately,
> and have written a few little apps to help with some day to day
> stuff I do, and recently my fiance asked me if it was possible to
> come up with a simple web based schedule she can use with the
> other teachers in her school to schedule library time. (She's the
> librarian). Basically, it will be a small calendar like app that
> will have 'slots' teachers can sign up for. It doesn't sound like
> it would be too complicated, and may be a good learning project. I
> was wondering if python as cgi would be good for this, and if
> there are any pitfalls I need to watch out for before I start
> delving into it. I'm also fairly new to writing my own html so
> will basically be learning it all from scratch.
>
> TIA,
>  Lee McClintock
>
> ___
> Tutor maillist  -  Tutor@python.org 
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
>
> -- 
> Michael Connors
> 
>
> ___
> 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] Python / CGI

2007-09-06 Thread Eric Brunson
Kent Johnson wrote:
> Eric Brunson wrote:
>   
>> Michael Connors wrote:
>> 
>>> Hi,
>>> If you have your own server to run it on, I think it would make sense 
>>> to use one of the Python web frameworks that are out there. I used 
>>> cherrypy for my first web-based python project and I found it very 
>>> easy to learn and develop in quickly.
>>>   
>> That's debatable.  I find the frameworks to be overly complicated and 
>> obfuscated.  They're great when you're going through the tutorials, but 
>> try to do something "outside the box" and I find myself digging through 
>> documentation for longer than it would take me to write it from scratch.
>> 
>
> Hmm. As my boss likes to say, "Reasonable people may disagree." I have 
> been developing with Django for about six months now and I love it. Much 
> of what I have wanted to do is directly supported and easy in Django; 
> sometimes I have to push at it but only a few times have I really felt 
> like I was trying to make it do something it really didn't want to do. I 
> find both the documentation and code informative and easy to read.
>   

I'll admit, though I looked at it briefly, Django was not one of the 
frameworks I spent much time on (didn't care for the templating style).  
I do most of my web development to run under mod_python and I've 
developed my own libraries to do what I need to do the way I think it 
should be done.  :-)



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


Re: [Tutor] making math problems mmmm fun

2007-09-10 Thread Eric Brunson

When you get done with this math problem you should consider a book on 
punctuation. Not using it makes your sentences run together and 
difficult to read. :-) Honestly, I just gave up after the first two lines.

max baseman wrote:
> haha :) yeah it's the new imp stuff i like parts of the idea but  
> other parts i really dislike basically it TRIES   to make math more  
> interactive and world like i really enjoy how most of it is really  
> programable stuff :) where compared to normal math books it's a bit  
> harder to program just a problem instead of a story but imp needs  
> help with it's grading and teaching the grading is terrible i can get  
> a A as long as i can explain and know how my way of doing it wrong  
> "works" but will fail if i just write the write answer without  
> explanation i dont mind the explanations bit but that what i write  
> matters more than if i can do the work  is odd
> adn i just haven't learned anything new yet :)
>
> On Sep 10, 2007, at 7:16 PM, wormwood_3 wrote:
>
>   
>> Don't have any ideas to Pythonize this problem for you, but I must  
>> say that I hope this problem was listed in a chapter entitled  
>> "Cruel and Unusual"!
>>
>> -Sam
>> 
>> - Original Message 
>> From: max baseman <[EMAIL PROTECTED]>
>> To: tutor@python.org
>> Sent: Monday, September 10, 2007 6:28:23 PM
>> Subject: [Tutor] making math problems  fun
>>
>> hello all this is a homework in math i dont need to program it but i
>> would like to :)  so like any other time pleas  dont just give a
>> answer tutorials or a explanation. i dont like to use script
>> something i dont understand :)
>>
>> thanks
>>
>> basically the problem is to find a bunch of ways to put 1,2,3,4,5
>> into different math problems to that equal 1-25, i haven't spent to
>> much time thinking about how to do this but i cant think of a way to
>> do it it without writing making the program rather long here is the
>> page from the book for the rules i will be working on this for the
>> next week or so thanks for any help :)
>>
>>
>>
>>
>>   . you may use any of the four basic arithmetic operations-
>> addition, subtraction, multiplication, and division (according to the
>> order of operations rules). for example, 2+1x3-4 is a 1-2-3-4
>> expression for the number 1.
>>
>> . you may use exponents. for example, 2² - 4 - 1 is a 1234 expression
>> for the number 3
>>
>> . you may use radicals for EX: √4x2+1 is equal to 3 so 3+√4x2+1 is
>> a 1234 expression for 6
>>
>> . you may use factorials for EX: 4! means 4x3x2x1 so 3+4!+1-2 is a
>> 1234 expression for the number 26
>>
>>
>> . you  may juxtapose two or more digits (that is put them next to
>> each other) to form a number such as 12. for example 43-12 is a 1234
>> expression for 31
>>
>> . you may use parentheses and brackets to change the meaning of a
>> expression for example according to the rules of order of operations 1
>> +4x3² is a 1234 expression for 37. you can add parentheses and
>> brackets to get [(1+4)x3]² which is a 1234 expression for 225
>>
>> . must use 1,2,3,4 exactly once
>>
>>
>>
>> thanks for the help ill post if i find anything
>> ___
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
>> 
>
> ___
> 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] Apache, CGI-BIN, Python

2007-09-10 Thread Eric Brunson
Alan Gauld wrote:
> "Ryan" <[EMAIL PROTECTED]> wrote
>
>   
>> I am running a Linux box and cannot find my Apache cgi-bin to put 
>> some
>> python scripts in. I know I probably have to create one but don't 
>> know
>> where and how.
>> 
>
> I think there are several places that you can create cgi-bin depending
> on how you configure apache. But the place I usually see it is 
> directly
> under the apache root directory - ie the one that is equivalent to / 
> in
> the url.
>   

But, if you read the apache configuration files, it will tell you were 
it is.  :-)

>   
>> everything works fine except:
>>
>> form = cgi.FieldStorage()
>>
>> #This is where everything goes wrong
>> #I get error messages for either the lastname line or firstname
>> 
>
> Can you tell us
> a) exactly what error messages and
> b) How you are invoking the script - where are the values
> supposed to be coming from?
>
>   
>> lastname = form['lastname'].value
>> firstname =form['firstname'].value
>> message = firstname + " " + lastname
>> print reshtml % message
>> 
>
> HTH,
>
>
>   

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


Re: [Tutor] Fw: Apache, CGI-BIN, Python

2007-09-11 Thread Eric Brunson
ALAN GAULD wrote:
> Forwarding to the list
>
> NB Use Reply-All when replying to the tutor list.
>
> Alan G.
>
> - Forwarded Message 
> From: Ryan <[EMAIL PROTECTED]>
> To: Alan Gauld <[EMAIL PROTECTED]>
> Sent: Tuesday, 11 September, 2007 5:32:33 AM
> Subject: Re: [Tutor] Apache, CGI-BIN, Python
>
> Alan Gauld wrote:
>   
>> "Ryan" <[EMAIL PROTECTED]> wrote
>>
>>   
>> 
>>> I am running a Linux box and cannot find my Apache cgi-bin to put 
>>> some
>>> python scripts in. I know I probably have to create one but don't 
>>> know
>>> where and how.
>>> 
>>>   
>> I think there are several places that you can create cgi-bin depending
>> on how you configure apache. But the place I usually see it is 
>> directly
>> under the apache root directory - ie the one that is equivalent to / 
>> in
>> the url.
>>
>>   
>> 
>>> everything works fine except:
>>>
>>> form = cgi.FieldStorage()
>>>
>>> #This is where everything goes wrong
>>> #I get error messages for either the lastname line or firstname
>>> 
>>>   
>> Can you tell us
>> a) exactly what error messages and
>> b) How you are invoking the script - where are the values
>> supposed to be coming from?
>>
>>   
>> 
>>> lastname = form['lastname'].value
>>> firstname =form['firstname'].value
>>> message = firstname + " " + lastname
>>> print reshtml % message
>>> 
>>>   
>> The HTML Doc:
>>   
>> 
> 
>
> 
>  Enter your first name:
> 
> 
> 
> 
> 
> 
>
> Error:
>
> Mod_python error: "PythonHandler mod_python.publisher"
>   

You don't use the cgi module when using the mod_python publisher 
handler.  Your function will be called with the form variables as named 
parameters, like this:

def handle_form_input( req, firstname, lastname ):
# do something here

I would recommend giving defaults for the parameters so if the user 
doesn't submit a value it, it doesn't throw an exception, like this:

def handle_form_input( req, firstname=None, lastname=None ):
# whatever

And, I've been known to simulate the cgi behavior like this:

def handler_form_input( req, **form ):
# access your form variables as an array
print "You entered %s %s" % ( form[lastname], form[firstname] )

But, remember that this "form" is a simple dict, not a cgi.FieldStorage 
and I don't know what it does with multiple values with the same key.  
FieldStorage puts them in an array, you'd have to experiment with this 
in the publisher handler.

See how much better answers you get when you ask good questions and 
include error messages.  :-)

Hope that helps,
e.


> Traceback (most recent call last):
>
>   File "/usr/lib/python2.5/site-packages/mod_python/apache.py", line 299, in 
> HandlerDispatch
> result = object(req)
>
>   File "/usr/lib/python2.5/site-packages/mod_python/publisher.py", line 204, 
> in handler
> module = page_cache[req]
>
>   File "/usr/lib/python2.5/site-packages/mod_python/cache.py", line 82, in 
> __getitem__
> return self._checkitem(name)[2]
>
>   File "/usr/lib/python2.5/site-packages/mod_python/cache.py", line 124, in 
> _checkitem
> value = self.build(key, name, opened, entry)
>
>   File "/usr/lib/python2.5/site-packages/mod_python/publisher.py", line 77, 
> in build
> return ModuleCache.build(self, key, req, opened, entry)
>
>   File "/usr/lib/python2.5/site-packages/mod_python/cache.py", line 371, in 
> build
> exec opened in module.__dict__
>
>   File "/var/www/python/test1.py", line 16, in 
> lastname = form['lastname'].value
>
>   File "cgi.py", line 567, in __getitem__
> raise KeyError, key
>
> KeyError: 'lastname'
>
> But I can get this script to work properly:
> def index(req):
> return "Test succesful";
>
>
>
>   
>> HTH,
>>
>>
>>   
>> 
>
>
>
>
> ___
> 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] Fw: Apache, CGI-BIN, Python

2007-09-11 Thread Eric Brunson
Eric Brunson wrote:
> ALAN GAULD wrote:
>   
>> Forwarding to the list
>>
>> NB Use Reply-All when replying to the tutor list.
>>
>> Alan G.
>>
>> - Forwarded Message 
>> From: Ryan <[EMAIL PROTECTED]>
>> To: Alan Gauld <[EMAIL PROTECTED]>
>> Sent: Tuesday, 11 September, 2007 5:32:33 AM
>> Subject: Re: [Tutor] Apache, CGI-BIN, Python
>>
>> Alan Gauld wrote:
>>   
>> 
>>> "Ryan" <[EMAIL PROTECTED]> wrote
>>>
>>>   
>>> 
>>>   
>>>> I am running a Linux box and cannot find my Apache cgi-bin to put 
>>>> some
>>>> python scripts in. I know I probably have to create one but don't 
>>>> know
>>>> where and how.
>>>> 
>>>>   
>>>> 
>>> I think there are several places that you can create cgi-bin depending
>>> on how you configure apache. But the place I usually see it is 
>>> directly
>>> under the apache root directory - ie the one that is equivalent to / 
>>> in
>>> the url.
>>>
>>>   
>>> 
>>>   
>>>> everything works fine except:
>>>>
>>>> form = cgi.FieldStorage()
>>>>
>>>> #This is where everything goes wrong
>>>> #I get error messages for either the lastname line or firstname
>>>> 
>>>>   
>>>> 
>>> Can you tell us
>>> a) exactly what error messages and
>>> b) How you are invoking the script - where are the values
>>> supposed to be coming from?
>>>
>>>   
>>> 
>>>   
>>>> lastname = form['lastname'].value
>>>> firstname =form['firstname'].value
>>>> message = firstname + " " + lastname
>>>> print reshtml % message
>>>> 
>>>>   
>>>> 
>>> The HTML Doc:
>>>   
>>> 
>>>   
>> 
>>
>> 
>>  Enter your first name:
>> 
>> 
>> 
>> 
>> 
>> 
>>
>> Error:
>>
>> Mod_python error: "PythonHandler mod_python.publisher"
>>   
>> 
>
> You don't use the cgi module when using the mod_python publisher 
> handler.  Your function will be called with the form variables as named 
> parameters, like this:
>
> def handle_form_input( req, firstname, lastname ):
> # do something here
>
> I would recommend giving defaults for the parameters so if the user 
> doesn't submit a value it, it doesn't throw an exception, like this:
>
> def handle_form_input( req, firstname=None, lastname=None ):
> # whatever
>
> And, I've been known to simulate the cgi behavior like this:
>
> def handler_form_input( req, **form ):
> # access your form variables as an array
> print "You entered %s %s" % ( form[lastname], form[firstname] )
>
>   

It's late, that should read:

def handler_form_input( req, **form ):
# access your form variables as a dict
return "You entered %s %s" % ( form['lastname'], form['firstname'] )



> But, remember that this "form" is a simple dict, not a cgi.FieldStorage 
> and I don't know what it does with multiple values with the same key.  
> FieldStorage puts them in an array, you'd have to experiment with this 
> in the publisher handler.
>
> See how much better answers you get when you ask good questions and 
> include error messages.  :-)
>
> Hope that helps,
> e.
>
>
>   
>> Traceback (most recent call last):
>>
>>   File "/usr/lib/python2.5/site-packages/mod_python/apache.py", line 299, in 
>> HandlerDispatch
>> result = object(req)
>>
>>   File "/usr/lib/python2.5/site-packages/mod_python/publisher.py", line 204, 
>> in handler
>> module = page_cache[req]
>>
>>   File "/usr/lib/python2.5/site-packages/mod_python/cache.py", line 82, in 
>> __getitem__
>> return self._checkitem(name)[2]
>>
>>   File "/usr/lib/python2.5/site-packages/mod_python/cache.py", line 124, in 
>> _checkitem
>> value = self.build(key, name, opened, entry)
>>
>>   File "/usr/lib/python2.5/site-packages/mod_python/publisher.py", line 77, 
>> in build
>> return ModuleCache.build(self, key, req, opened, entry)
>>
>>   File "/usr/lib/python2.5/site-packages/mod_python/cache.py", line 371, in 
>> build
>> exec opened in module.__dict__
>>
>>   File "/var/www/python/test1.py", line 16, in 
>> lastname = form['lastname'].value
>>
>>   File "cgi.py", line 567, in __getitem__
>> raise KeyError, key
>>
>> KeyError: 'lastname'
>>
>> But I can get this script to work properly:
>> def index(req):
>> return "Test succesful";
>>
>>
>>
>>   
>> 
>>> HTH,
>>>
>>>
>>>   
>>> 
>>>   
>>
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>   
>> 
>
> ___
> 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] extract hosts from html write to file

2007-09-11 Thread Eric Brunson
sacha rook wrote:
> Hi I wonder if anyone can help with the following
>  
> I am trying to read a html page extract only fully qualified hostnames 
> from the page and output these hostnames to a file on disk to be used 
> later as input to another program.
>  
> I have this so far
>  
> import urllib2
> f=open("c:/tmp/newfile.txt", "w")
> for line in urllib2.urlopen("_http://www.somedomain.uk_ 
> "):
> if "href" in line and "http://"; in line:
> print line
> f.write(line)
> f.close()
> fu=open("c:/tmp/newfile.txt", "r")
>
> for line in fu.readlines():
> print line  
>  
> so i have opened a file to write to, got a page of html, printed and 
> written those to file that contain href & http:// references.
> closed file opened file read all the lines from file and printed out
>  
> Can someone point me in right direction please on the flow of this 
> program, the best way to just extract the hostnames and print these to 
> file on disk?

I would start with a Regular Expression to match the text of the URL, it 
will match exactly the text of the URL and you can extract that.  You 
can probably even find one in a web search.  Read up on regular 
expressions to start with, they're extremely powerful, but a little bit 
of a learning curve to start with.  Google "regular expression tutorial" 
or search the list archive for a reference.

>  
> As you can see I am newish to this
>  
> Thanks in advance for any help given!
>  
> s
>
> 
> Do you know a place like the back of your hand? Share local knowledge 
> with BackOfMyHand.com 
> 
>
> ___
> 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] Image Analysis

2007-09-11 Thread Eric Brunson

Just my opinion, but I didn't mind the attachments, I felt they added 
quite a bit to the discussion and I certainly appreciated the input on 
the application of the libraries.

My opinion on your tone, I'll keep to myself.

Dave Kuhlman wrote:
> On Wed, Sep 12, 2007 at 01:57:35AM +0200, Eike Welk wrote:
>
>   
>> I have attached the program, the input image, and the output image.
>>
>> 
>
> Please do not stuff 1 MB emails in my mailbox.  Either (1) post the
> images on the Web and provide a link or (2) ask before emailing
> large attachments.
>
> Thank you.
>
> Dave
>
>
>   

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


Re: [Tutor] Class Inheritance

2007-09-13 Thread Eric Brunson
Lamonte Harris wrote:
> Okay
>
> class A:
>def __init__(self,x,y):
>  self.x = x
>  self.y = y
>
>def save(self,fn):
>  f = open(fn,"w")
>  f.write(str(self.x)+ '\n') 
> # convert to a string and add newline
>  f.write(str(self.y)+'\n')
>  return f # for child objects to use
>
>def restore(self, fn):
>  f = open(fn)
>
>  self.x = int(f.readline()) # convert back to original type
>  self.y = int(f.readline())
>  return f
>  
> class B(A):
>def __init__(self,x,y,z):
>  A.__init__(self,x,y)
>
>  self.z = z
>
>def save(self,fn):
>  f = A.save(self,fn)  # call parent save
>  f.write(str(self.z)+'\n')
>  return f # in case further children exist
>
>
>def restore(self, fn):
>  f = A.restore(self,fn)
>  self.z = int(f.readline())
>  return f
> In the class B,  I'm not understanding the A.__init(self,x,y) part.  
> So its initializing the class A, and basically you can use the A class 
> like normal?

Essentially, yes, but the way you've worded it is imprecise.  Any 
instance of B is a subclass of A, essentially an A:  Every boy is a 
male, but not all males are boys.  When you override a method in a 
subclass you have essentially turned off all behavior in the parent 
method, including "magic" methods like the constructor.  You have to 
call the parent constructor explicitly to get its benefits.

A method of an instance can be called like this:  instance.method() and 
python makes sure that a pointer to the instance is passed in as the 
first argument, generally "self".  But a method of a class can be called 
without instantiating the class, but you have to supply "self" on you own.

The method you are using is valid,  yet depricated.  Using "new style 
classes" (which aren't actually that new) you'd write your code like this:

class A(object):
def __init__(self, a):
self.aye = a

class B(A):
def __init__(self, a, b):
self.bee = b
super( B, self ).__init__( a )

Notice that you don't have to supply self.

You can use any method of A in an instance of B that you haven't 
overridden in B without having to use super().

> Part im confused about is the self.z, does that belong to the class A 
> or class B?  

z is an attribute B only.

Hope that helps,
e.

> Else I think I'm understanding it correctly.
> 
>
> ___
> 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] evaluating AND

2007-09-13 Thread Eric Brunson

The first is how I would code it.  Python guarantees that compound 
boolean statements are processed from left to right and also that the 
AND operator will "short circuit" the rest of the evaluation, since the 
rest of the line cannot change the falseness of the entire statement.

Orest Kozyar wrote:
> Given a variable x that can either be None or a tuple of two floats [i.e.
> (0.32, 4.2)], which syntax is considered most appropriate under Python
> coding standards?
>
> if x and x[0] > 0:
>   pass
>
> =OR=
>
> if x:
>   if x[0] > 0:
>   pass
>
>
> In the first, I'm obviously making the assumption that if the first
> condition evaluates to false, then the second condition won't be evaluated.
> But, is this a good/valid assumption to make?  Is there a more appropriate
> design pattern in Python?
>
> Thanks!
> Orest
>
> ___
> 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] Class Inheritance

2007-09-14 Thread Eric Brunson

You're still using the wrong terminology...

A "subclass" is "derived" (or "subclassed") from its "parent class" (or 
"super" class)
A function that is part of the class definition (def func1(self): pass) 
is a "method"
A variable that is part of the class definition or added after 
instantiation is an "attribute"
When you create an object (a = A()) you are "instantiating" the class 
and the resultant object is an "instance"

Lamonte Harris wrote:
> So ok, when I inherit a class, all the classes 

methods.  Classes have methods (functions) and attributes (variables).

> in the parent class will overwrite 

override.

> all the functions 

methods.

> in the class I inherited the parent class into?

No, exactly the opposite.

>   If they have the same class names that is?

# declare a class
class A(object):
this = "is a class attribute"
def method1(self):
self.thisthing = "is an attribute"
print "class A: method1"

def method2(self):
print "class A: method2"

# subclass it
class B(A):
def method2(self):
print "class B: method2"

def method3(self):
print "class B: method3"

# create an "instance" of each class
a = A()
b = B()

a.method1()
OUTPUT> classA: method1

a.method2()
OUTPUT> classA: method2

b.method1()
OUTPUT> classA: method1

b.method2()
OUTPUT> classB: method2

super(B,b).method2()
OUTPUT> classA: method2
# super() only works because B is a subclass of "object" by virtue or A 
being derived from "object"

b.method3()
OUTPUT> classB: method3

a.method3()
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: A instance has no attribute 'method3'

When you derive a subclass from another class all methods of the parent 
class are available

Is that clear?

>
> On 9/13/07, *Eric Brunson* <[EMAIL PROTECTED] 
> <mailto:[EMAIL PROTECTED]>> wrote:
>
> Lamonte Harris wrote:
> > Okay
> >
> > class A:
> >def __init__(self,x,y):
> >  self.x = x
> >  self.y = y
> >
> >def save(self,fn):
> >  f = open(fn,"w")
> >  f.write(str(self.x)+ '\n')
> > # convert to a string and add newline
> >  f.write(str(self.y)+'\n')
> >  return f # for child objects to use
> >
> >def restore(self, fn):
> >  f = open(fn)
> >
> >  self.x = int(f.readline()) # convert back to original type
> >  self.y = int(f.readline())
> >  return f
> >
> > class B(A):
> >def __init__(self,x,y,z):
> >  A.__init__(self,x,y)
> >
> >  self.z = z
> >
> >def save(self,fn):
> >  f = A.save(self,fn)  # call parent save
> >  f.write(str(self.z)+'\n')
> >  return f # in case further children exist
> >
> >
> >def restore(self, fn):
> >  f = A.restore(self,fn)
> >  self.z = int(f.readline())
> >  return f
> > In the class B,  I'm not understanding the A.__init(self,x,y) part.
> > So its initializing the class A, and basically you can use the A
> class
> > like normal?
>
> Essentially, yes, but the way you've worded it is imprecise.  Any
> instance of B is a subclass of A, essentially an A:  Every boy is a
> male, but not all males are boys.  When you override a method in a
> subclass you have essentially turned off all behavior in the parent
> method, including "magic" methods like the constructor.  You have to
> call the parent constructor explicitly to get its benefits.
>
> A method of an instance can be called like
> this:  instance.method() and
> python makes sure that a pointer to the instance is passed in as the
> first argument, generally "self".  But a method of a class can be
> called
> without instantiating the class, but you have to supply "self" on
> you own.
>
> The method you are using is valid,  yet depricated.  Using "new style
> classes" (which aren't actually that new) you'd write your code
> like this:
>
> class A(object):
> def __init__(self, a):
> self.aye = a
>
> class B(A):
> def __init__(self, a, b):
> self.bee = b
> super( B, self ).__

Re: [Tutor] Problem with assigning list elements

2007-09-14 Thread Eric Brunson

That is not the expected behavior and not the behavior I see:

Python 2.5.1 (r251:54863, May  1 2007, 13:27:01) [C] on sunos5
 >>> z = [[1,2],[3,4]]
 >>> z[0][0]=100
 >>> print z
[[100, 2], [3, 4]]


[EMAIL PROTECTED] wrote:
> I'm having a problem assigning numbers to a 2-D list.
>
> for the 2d list z for example, when I type in
>
> z[0][0]=67
>
> every zeroth element of every sublist will be set to 67, instead of just 
> element
> [0,0] being set to 67.
>
> If z = [[1,2],[3,4]]
>
> then z[0][0]=100 results in
>
> z= [[100,2],[100,4]]
>
> Is this normal for python? And is there a way to assign to a specific element 
> of
> a 2-dimensional list?
>
> Thanks
>
> ___
> 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] Finding even and odd numbers

2007-09-19 Thread Eric Brunson


 >>> t = timeit.Timer( '1000%2')
 >>> t.timeit(100)
0.25893402099609375
 >>> t = timeit.Timer( '1000&1')
 >>> t.timeit(100)
0.2567589282989502

It's almost insignificantly faster.

However as a programmer and a mathematician, I disagree with your 
position that the bitwise operation is more or less readable than the 
modulus operation. 

If you wrap either in a function called "isOdd()" that's all someone has 
see to know what it's doing.  My internal implementation of "isOdd()" 
should be of no consequence to someone unless they are modifying that 
particular piece of code, and if they're doing that, % is just as common 
an operation as &.

However, with that said, the overhead of the function call is 
significantly greater than the cost of the actual operation, around four 
times slower:

 >>> t = timeit.Timer( 'isOdd(1000)', 'def isOdd(num): return num&1')
 >>> t.timeit(100)
1.1442101001739502
 >>> t = timeit.Timer( 'isOdd(1000)', 'def isOdd(num): return num%2')
 >>> t.timeit(100)
1.1032519340515137


Terry Carroll wrote:
> On Wed, 19 Sep 2007, Boykie Mackay wrote:
>
>   
>> if not n&1:
>> return false
>>
>> The above should return false for all even numbers,numbers being
>> represented by n.I have tried to wrap my head around the 'not n&1' but
>> I'm failing to understand what's going on.Could someone please explain
>> the statement.
>> 
>
> Others have explained why this works, but let me rail against this code 
> for a moment.  IMHO, a bitwise operation is appropriate only when the 
> field being operated on is a set of bits with bitwise information; for 
> example, if the right-most bit was a flag bit of some sort, N&1 is a 
> perfectly appropriate operation.
>
> But evenness/oddness is a property of numbers, and the code would be much 
> easier to understand if the parameter was treated as a number, rather than 
> as a field of bits, i.e.:
>
>   
 def isodd(n):
 
> ...  return bool(n%2)
> ...
>   
 isodd(4)
 
> False
>   
 isodd(7)
 
> True
>   
>
> Mind you, I'll bet that the bit-checking method is slightly faster than
> the modulus operation in my little piece of code above.  

 ><
> I'll also bet
> that, if you added up the amount of time that was saved by using the
> bitwise approach over the modulus approach, over all executions of the
> program everywhere, it probably would be a smaller amount of time than it
> would take for a programmmer maintaining the program to find out what that
> line of code is supposed to do.
>
> 
>
> ___
> 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] Threading in Python

2007-09-19 Thread Eric Brunson
James wrote:
> Thanks for the quick reply.
>
> Interesting.  I'm a little overwhelmed with the different terminology  
> (fork, spawn, thread, etc.).  I'm under the impression that I'm  
> supposed to use os.fork() or os.spawn() for something like what I'm  
> trying to do (start multiple instances of the I/O utility from one  
> Python script).
>   

A fork is a fundamental system call in which the OS makes a nearly 
identical copy of the running process.  I know it's a kind of *-hole 
thing to say, but... if you don't know why you'd want to fork your 
process, you probably don't need to.  Forking is usually used for 
disassociating yourself from your parent process to become a daemon.  
However, it's a basic function of the system an intrinsic in many other 
higher level actions.

One you don't mention is "exec", which is to replace your running 
process image with a new process image.  You can do it from the shell, 
type "exec somebinary" and that binary replaces your shell process, so 
when the exec'd process exits, your session is terminated.

I mention that because when you combine a fork with an exec, you get a 
spawn.  Your parent process duplicates itself, but the child process 
chooses to exec another process.  So the child copy of the initial 
process is replaced by new running binary and you have a spawned process 
running as a child of the first.

Finally, a thread (sometimes referred to as a "lightweight process" or 
"lwp") is kind of like a fork, except a fork duplicates everything about 
the initial process (except a return code) while a thread shares state 
with the parent process and all its sibling threads.

The interesting thing about a python thread is that it is not an OS 
level thread, it is a separate execution thread, but still controlled by 
the python interpreter.  So, while a dual processor computer can choose 
to execute two different processes or thread simultaneously, since 
there's only one python interpreter (per python process) a python thread 
is never run concurrently with another thread in the same python 
process.  It's more of a conceptual thing,

> However, from what I gather from the documentation, os.fork() is  
> going to fork the python Python script that calls the original fork  
> (so fork won't directly start off the programs that I need).  How  
> would I go about forking + then executing an application?  Isn't this  
> what spawn does?  Or should I stick with fork + exec*?
>   

However, what you are trying to do, i.e. spawn multiple concurrent child 
processes, could actually take advantage of a multi processor system 
using python threads.  If you created multiple threads, many of which 
spawned an independent subprocess, those subprocesses could be executed 
concurrently by different processors, while their status was still being 
coordinated via the python thread model.

Just give it a go knowing that it is an efficient design, and drop us a 
line if you have more questions or any problems.

Sincerely,
e.

> Lots to learn, I guess.  ;)
>   

Always.  ;-)  When you think there's nothing else to learn, you've 
already become obsolete.

> .james
>
> On Sep 19, 2007, at 10:19 PM, Kent Johnson wrote:
>
>   
>> James wrote:
>> 
>>> Hi.  :)
>>> I have a question regarding threading in Python.  I'm trying to  
>>> write  a wrapper script in Python that will spin off multiple  
>>> (lots!) of  instances of an I/O benchmark/testing utility.  I'm  
>>> very interested  in doing this in Python, but am unsure if this is  
>>> a good idea.  I  thought I read somewhere online that because of  
>>> the way Python was  written, even if I spun off (forked off?)  
>>> multiple instances of a  program, all those child processes would  
>>> be restricted to one CPU.   Is this true?
>>>   
>> Python *threads* are limited to a single CPU, or at least they will  
>> not run faster on multiple CPUs. I don't think there is any such  
>> restriction for forked processes.
>>
>> 
>>> I'm not sure if the utility I'm forking is CPU-intensive; it may  
>>> very  well be.  Does Python indeed have this limitation?
>>>   
>> I would think an I/O benchmark is more likely to be I/O bound...
>>
>> 
>>> Also, should I be using os.fork() for this kind of program?
>>>   
>> There is a fair amount of activity these days around making Python  
>> friendly to multi-processing. See
>> http://wiki.python.org/moin/ParallelProcessing
>>
>> Kent
>> 
>
> ___
> 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] Optimisation of prime number program (cont. from finding prime numbers)

2007-09-21 Thread Eric Brunson
Boykie Mackay wrote:
> Ok,I have learnt how to generate prime numbers and how to 'split'
> input.The above was to help me solve the second 'SPOJ'
> challenge,PRIME1.The challenge can be found at
>  
>
> I have written my solution and tested it and it works fine,but
> unfortunately it is times out when tested by 'SPOJ'.I don't know whether
> it times out because it is inherently slow or because a certain
> condition takes it into endless loops.I think it is simply because it
> needs further optimisation.I have researched as much as I could but
> can't find any way to improve the speed of the program (problem with
> being a newbie is you don't know what you don't know!)
>   

One optimization, and this is only good for printing a list of primes, 
is that you only need to test a number's divisibility by all *primes* 
less than the square root of the number.

By keeping a list of the primes already calculated, I saw a 3 times 
increase in speed counting all the prime numbers between 2 and one million:

# test all numbers below sqrt(n)
ebrunsonlx(~)$ time python primes.py
78498 primes below 100

real0m14.496s
user0m14.367s
sys 0m0.127s

# keeping a list of primes
ebrunsonlx(~)$ time python primes.py
78498 primes below 100

real0m5.570s
user0m5.551s
sys 0m0.017s


Here's the code I used:

primes = []

def isPrime1( n ):
s = n**.5
for d in xrange( 2, int(s)+1 ):
if not n%d:
return False

return True

def isPrime2( n ):
global primes
s = n**.5
for d in primes:
if d>s:
break
if not n%d:
return False

primes.append( n )
return True



That's just the most obvious optimization.  I'd like to compare to the 
performance of Sieve of Eratosthanes, but I don't feel like coding it.

> Could you please look at the program (attached) and advise possible
> optimisations or point me to possible resources that would help solve
> this challenge.
>
> Thanks,
>
> Boyks 
>   
> 
>
> ___
> 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] Quick question

2007-09-21 Thread Eric Brunson
There are quite a few ways to do what you want.  Here's are a few 
variations on a theme:

try:
if not any( ( len(queuePacket['procSeq']),
  len(queuePacket['opacSeq']),
  len(queuePacket['keySeq']) ) ):
# Do your stuff here
do_stuff()
except KeyError:
pass


Or, using a generator:

try:
if not any( len(queuePacket[key]) 
for key in ( 'procSeq', 'opacSeq', 'keySeq' ) ):
# Do your stuff here
do_stuff()
except KeyError:
pass


Or, using a list comprehension:

try:
if not [ 1 for key in ( 'procSeq', 'opacSeq', 'keySeq' ) if 
len(queuePacket[key]) != 0 ] ):
# Do your stuff here
do_stuff()
except KeyError:
pass


Tino Dai wrote:
> Is there a more pythonic way of doing this:
>
>   if queuePacket.has_key('procSeq') and \
>   queuePacket.has_key('opacSeq') and \
>   queuePacket.has_key('keySeq') and \
>   len(queuePacket['procSeq']) == 0 and \
>   len(queuePacket['opacSeq']) == 0 and \
>  len(queuePacket['keySeq']) == 0:
>
>
> ?
>
> -Thanks,
> Tino
>
> 
>
> ___
> 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] print array

2007-09-26 Thread Eric Brunson
Fangwen Lu wrote:
> Dear all-
>  
> Let a=(3,4,7), b=[3,4,7].
> If I type
> print '%d + %d = %d' %(a)
> I get
> 3 + 4 = 7
>  
> But if I type  print '%d + %d = %d' %(b), I get errors.
>  
> If there is a way for doing this kind of type dirrectly from array.

No, but it's trivial to convert an array to a tuple:

 >>> b=[3,4,7]
 >>> print '%d + %d = %d' % tuple(b)
3 + 4 = 7

>  
> Thank you!
>  
> Fangwen
> 
>
> ___
> 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] questions about tuples

2007-09-26 Thread Eric Brunson
Fangwen Lu wrote:
> Dear all-
>  
> I want to do some loops. Each loop will generate a tuple. Eventually I 
> want to put tuples together in a higher level of tuple. Do you know 
> how to do this?
>  
> Say a=(1,2,3), b=(4,3,2),c=(9,5,6). I want to get a tuple as ((1,2,3), 
> (4,3,2),(9,5,6)).
>  
> If there are just 2 tuples, I can write x=a and then x=(x,b). But for 
> 3 tuples or more, I will get something like (((1,2,3), (4,3,2)),(9,5,6)).
 >>> a=(1,2,3)
 >>> b=(4,3,2)
 >>> c=(9,5,6)
 >>> x = (a,b,c)
 >>> print x
((1, 2, 3), (4, 3, 2), (9, 5, 6))


Or:

 >>> x = []
 >>> x.append(a)
 >>> x.append(b)
 >>> x.append(c)
 >>> print x
[(1, 2, 3), (4, 3, 2), (9, 5, 6)]
 >>> x = tuple(x)
 >>> print x
((1, 2, 3), (4, 3, 2), (9, 5, 6))


You can't use append() on a tuple, because a tuple is, by design, immutable.
>  
> Thanks.
>  
> Fangwen
> 
>
> ___
> 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] how to convert array into tuple

2007-09-26 Thread Eric Brunson
Fangwen Lu wrote:
> Dear all-
>  
> If I have an array array([1, 2, 3, 4, 5, 6]), and I want to get 
> ((1,2),(3,4),(5,6)). What should I do?

First, you read some documentation and tutorials on the language, then 
you iterate over the list and build tuples out of the elements.

>  
> Thank you!
>  
> Fangwen
> 
>
> ___
> 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] detecing palindromic strings

2007-09-28 Thread Eric Brunson
Christopher Spears wrote:
> I'm trying to write a script that detects if a string
> is palindromic (same backward as it is forward).  This
> is what I have so far:
>
> #!/usr/bin/env python
>
> my_str = raw_input("Enter a string: ")
> 
> string_list = []
>
> for s in my_str:
> string_list.append(s)
>
> string_list_orig = string_list
>
> string_list.reverse()
>
> print string_list_orig
> print string_list
>
> The problem is that the script gives results like so:
> [EMAIL PROTECTED] ./chap6 117> python palindromic.py
> Enter a string: abc
> ['c', 'b', 'a']
>   

Well, since you've converted the string to a list, what you would like 
to do is:

print "".join( string_list_orig )

to connect them back together.

However, you can simplify the code greatly:

 >>> s = "abcd"
 >>> print s[::-1]
dcba
 >>> if s == s[::-1]:
... print "yay"
...
 >>> s = "abcdcba"
 >>> if s == s[::-1]:
... print "yay"
...
yay


> ['c', 'b', 'a']
>
> Now I understand pointers and Python!  :-)  Since
> string_list_orig is pointing to string_list, when I
> reversed string_list, string_list_orig was reversed as
> well.
>
> How do I get around this?  Is there a better way to
> write this script?  I can't figure out how to loop
> through a string starting from the last character.
>
>
> "I'm the last person to pretend that I'm a radio.  I'd rather go out and be a 
> color television set."
> -David Bowie
>
> "Who dares wins"
> -British military motto
>
> "I generally know what I'm doing."
> -Buster Keaton
> ___
> 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] A simple Question...

2007-10-02 Thread Eric Brunson
Alan Gauld wrote:
> "Suzanne Peel" <[EMAIL PROTECTED]> wrote
>
>   
>> However both suggestions will only give me that name of the 1st file
>> executed eg  when I use  execfile('EA_Owner.py') the name returned 
>> when
>> the __file__ or sys.argv[0] is executed always EA_Owner.py .
>> 
>
> You didn't mention you were doing wacky stuff like using execfile...
> That makes it a bit more challenging. Is there any reason why you
> need to use execfile rather than just importing the file?
>
> execfile acts as if another interpreter session was running so its
> quite tricky to find out the name of the file that the original 
> interpreter
> was running. You might be able to do it by setting a global variable
> to the current __file__ before calling execfile...
>   

I agree with Alan that execfile can usually be replaced with a more 
elegant solution.  But if you're not looking to rearchitect the code and 
are looking for the least amount of work, you could try wrapping or 
decorating the execfile function.

Possibly something like this (off-the-top-of-my-head and untested):

create a module, say, myExec.py:

def myExecfile( filename ):
doSomeLoggingOn( filename )
return execfile( filename )

Then, in your code:

from myExec import myExecfile as execfile

No other code should have to change.

>   
>> The trace-back feature provides this - can I force an error of sorts 
>> that
>> will not suspend programming but will report the file/module/script 
>> that
>> it is running ??? (Probably a bit dramatic but I am at a loss..)
>> 
>
> Look at the traceback module. I think its possible but messy.
> It would be better if you can find a way to avoid using execfile.
>
> HTH,
>   

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


Re: [Tutor] finding square roots

2007-10-05 Thread Eric Brunson
Elaine wrote:
> Does anyone know which is the more efficient way of
> finding a square root in Python:
>
> sqrt(x)  or   x ** 0.5
>   

I dunno, let's check:

 >>> import timeit
 >>> t = timeit.Timer( "12 ** .5" )
 >>> print t.timeit(1000)
2.29147315025
 >>> t = timeit.Timer( "sqrt(12)", "from math import sqrt" )
 >>> print t.timeit(1000)
7.17679214478

Looks like ** is about three times faster than sqrt(), but that could be 
the function overhead.

> ???
>
> Thanks,
>  Elaine
>
>
>
> 
> Building a website is a piece of cake. Yahoo! Small Business gives you all 
> the tools to get online.
> http://smallbusiness.yahoo.com/webhosting 
> ___
> 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] questions about previous emails

2007-10-05 Thread Eric Brunson
Fangwen Lu wrote:
> Dear all-
>
> I am a new-comer to [EMAIL PROTECTED] I guess  a lot of my future 
> questions may have been asked by others already.
>
> As I am a new-comer, I don't have the previous emails.
>
> I wonder whether there is a way for searching for previous questions 
> and answers so that I don't need to ask simple questions to overload 
> the message flows.

Click on the link at the bottom of every message and there is a link in 
the middle of the page directing you to the archives.

Hope the helps,
e.

>
> Thanks.
>
> Fangwen
>
> 
> Be a better Heartthrob. Get better relationship answers 
> from
>  
> someone who knows.
> Yahoo! Answers - Check it out.
> 
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>   

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


  1   2   >