[Tutor] ADO problem

2007-07-16 Thread János Juhász
Dear All,

I have a good sample about using ADO to reach windows active directory.

import win32com.client 
c = win32com.client.Dispatch("ADODB.Connection") 
c.Open("Provider=ADSDSOObject") 

rs,rc=c.Execute(""" 
SELECT name, description, department
>From 'LDAP://DC=VELUX, DC=ORG' 
where objectClass='user' and name='*.ferbau' and department = 'IT'
order by name
""") 

while not rs.EOF: 
print rs.Fields[0].Value, rs.Fields[1].Value
rs.MoveNext() 

It print the next result:
IT (u'\xc1kos Szab\xf3',)
IT (u'Szabolcs K\xe1m\xe1n',)
...

So rs.Fields[1] is a tuple.
I tried to turn it to get the first item from this tuple like this

while not rs.EOF: 
print rs.Fields[0].Value, rs.Fields[1][0].Value
rs.MoveNext() 

But it gives the next error 

Traceback (most recent call last):
  File "D:\devel\python\admin\AD_ADO.py", line 13, in ?
print rs.Fields[0].Value, rs.Fields[1][0].Value
  File "c:\Python24\Lib\site-packages\win32com\client\dynamic.py", line 
228, in
__getitem__
raise TypeError, "This object does not support enumeration"
TypeError: This object does not support enumeration


How can I print that unicode string?



János Juhász
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] ADO problem

2007-07-16 Thread Tim Golden
János Juhász wrote:
> while not rs.EOF: 
> print rs.Fields[0].Value, rs.Fields[1].Value
> rs.MoveNext() 
> 
> It print the next result:
> IT (u'\xc1kos Szab\xf3',)
> IT (u'Szabolcs K\xe1m\xe1n',)
> ...
> 
> So rs.Fields[1] is a tuple.

Well, here's the most obvious thing:

By the look of it: rs.Fields[1] is *not* a tuple.
It's an instance of some sort. rs.Fields[1].Value
*is* a tuple. So something like this:

rs.Fields[1].Value[0]

should work. I'm not quite clear why that second
field returns a tuple while the first one doesn't.
(Assuming you have reproduced the code and output
faithfully).

To do this specific thing, you might find it easier
to use a module wrapper:

http://tgolden.sc.sabren.com/python/active_directory.html

where your query would become something like (untested):


import active_directory

for user in active_directory.search (
   objectClass="User",
   name="*.ferbeau",
   department="IT"
):
   print user.name, user.description, user.department



Hope that helps somewhat.

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


Re: [Tutor] Bundle help!

2007-07-16 Thread Jason Massey

A nice tutorial on using regular expressions in Python:

http://www.amk.ca/python/howto/regex/



On 7/15/07, bhaaluu <[EMAIL PROTECTED]> wrote:


Hi!

http://docs.python.org/lib/module-re.html

Regular Expressions module.

On 7/15/07, Sara Johnson <[EMAIL PROTECTED]> wrote:
> 
>
> Just curious, but in this link ('
> http://xahlee.org/perl-python/sort_list.html ') you
> mentioned, what does the "re" part mean?  At first I thought it was the
name
> of the list or 'return' but that's included later.
>
>
> ***
>
> def myComp (x,y):
> import re
> def getNum(str): return float(re.findall(r'\d+',str)[0])
> return cmp(getNum(x),getNum(y))
>
> li.sort(myComp)
> print li # returns ['web7-s.jpg', 'my23i.jpg', 'fris88large.jpg',
> 'my283.jpg']
>
> Thanks,
> Sara

Someone recently showed this to me:

$ python

>>> import re

>>> dir(re)

['DOTALL', 'I', 'IGNORECASE', 'L', 'LOCALE', 'M', 'MULTILINE', 'S',
'U', 'UNICODE',
'VERBOSE', 'X', '__all__', '__builtins__', '__doc__', '__file__',
'__name__', 'compile',
'engine', 'error', 'escape', 'findall', 'finditer', 'match', 'purge',
'search', 'split', 'sub',
'subn', 'template']

>>> dir(re.match)

['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__',
'__getattribute__', '__hash__', '__init__', '__module__', '__name__',
'__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__',
'func_closure',
'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals',
'func_name']

All those quoted things that the dir() function spit out are in the
module.

>>> dir(re.match.__doc__)

'Try to apply the pattern at the start of the string, returning\n
a match object, or None if no match was found.'

You can find all sorts of stuff like this. It's somewhat cryptic at first,
but with the above documentation in hand, you can figure it out
eventually. =)

--
bhaaluu at gmail dot 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] How to improve

2007-07-16 Thread taserian

Thank you both, Alan and Gregor. Sorry I didn't reply earlier; just a bit
overwhelmed with a family situation over here.

Alan, looks like I'll have to go over list comprehension as a way to
initialize variables. I recall when I first started programming this, I
tried wordlist = [] * 31, completely overlooking the fact that all of the
list were in fact the same, and when debugging finding that my wordlist had
been copied 31 times!

Gregor, I like your version since you don't have to constrain the list
artificially, as I did. For this problem in particular, the longest
interlaced word I could find was 11 characters long, and the longer you go,
the less probable it is that you'll find one. 31 seemed like a good enough
value, but I'll probably change my version to look like yours.

Thanks again, guys!

Tony R.

On 7/12/07, Gregor Lingl <[EMAIL PROTECTED]> wrote:


taserian schrieb:
> I've been programming for years before encountering Pythoin, but in
> much more verbose languages, and I appreciate the fact that Python is
> so terse and still accomplishes so much. Still, I have difficulty
> thinking in Python, and tend to revert to longer programs for what
> seems to be simple tasks. Sometimes it's because I'm just not aware of
> a library function, but many times it's because there's just some
> elegant way to solve my kludge.
>
> As an exercise in Python, I decided to solve a toy problem called
> "interleave". The idea is that I want to determine how many words in
> the English language are decomposable into two words by taking it
> apart one letter at a time. So the word "theorems" could be decomposed
> into "term" and "hoes" (original word = abababab, decomposed words =
>  and , with all letters in the same order as in the original
> word).
>
> I'd like to see how I could improve the program below for this, and
> make it more Python-ish.
>
Hi taserian,

I've just produced an alternative solution of your problem
(based on your ideas). The main difference is, that I use
a wordlength-dictionary. This version has the advantage, that
it doesn't make an assumption about the max word length.
I don't consider it to be an improvement, just an example
that uses different language elements of Python in some places.
Hope you enjoy it.

 START

wordlengthdict = {}

for word in open("wordlist.txt").read().split():
wordlengthdict.setdefault(len(word),[]).append(word)

outfile = open('InterleaveEnglishYAWL.txt', 'w')

for l in sorted(wordlengthdict.keys()):
print l
for w in wordlengthdict[l]:
wordtriple = (w1, w2, dummy)  = w[0::2], w[1::2], w
if  w1 in wordlengthdict.get(len(w1),[]) and w2 in
wordlengthdict.get(len(w2),[]):
outfile.write("(%s, %s, %s)\n" % wordtriple)
print wordtriple

outfile.close();

 END

Best regards,
Gregor

> = = = = START
>
> def decompose(longword):
> word1 = longword[0::2]
> word2 = longword[1::2]
> return (word1, word2)
>
> wordlengthlist = [None] * 31
> for i in range(0,len(wordlengthlist)):
> wordlengthlist[i] = []
> results = []
>
> for lineread in open("word.list"):
> for word in lineread.split():
> if len(word)<31:
> wordlengthlist[len(word)].append(word)
>
> outfile = open('InterleaveEnglishYAWL.txt', 'w')
>
> for x in range(4, 31):
> print x
> for i in wordlengthlist[x]:
> twowords = decompose(i)
> word1 = twowords[0]
> word2 = twowords[1]
> if word1 in wordlengthlist[len(word1)] and word2 in
> wordlengthlist[len(word2)]:
> outfile.write("(" + word1 + ", " + word2 + ", " + i + ")\n")
> print (word1, word2, i)
>
> outfile.close();
>
> = = = = END
>
> Tony R.
>
> 
>
> ___
> 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] tutor

2007-07-16 Thread bhaaluu
Greetings Alan, et al,

On 7/14/07, ALAN GAULD <[EMAIL PROTECTED]> wrote:
> > > What do you find challenging?

I find _ALL OF IT_ [computer programming] challenging.
Perhaps that is why computer programming is my hobby.
If it wasn't challenging, it wouldn't hold my interest for very long.

Part of my hobby is collecting used-books about computer programming.
I have shelves filled with books about BASIC, Pascal, C, C++,
Intel 8086 Assembly, Perl, and a smattering of others. I think I've
maybe read one of them from cover to cover. Otherwise, I use them
for the examples they contain. They are a library of code snippets in
various languages. I have several old computers with various OSes
on them, that have various old compilers and interpreters installed.

What does this have to do with Python?
First of all, Python is the latest 'flavor' of programming language that
I'm trying to learn. One of the best things about learning Python is this list:

Excerpts from: http://mail.python.org/mailman/listinfo/tutor

1. Tutor -- Discussion for learning programming with Python.

2. This [Tutor] list  is for folks who want to ask questions
regarding how to learn computer programming with
the Python [programming] language.

3. ...[M]any feel [Python] is a good first language, because
it makes it easy to express the fundamental concepts of
programming such as data structures and algorithms with
a syntax which many find easy to read and write.

4. Folks interested in learning about programming with Python
are encouraged to join, as are folks interested in helping
others learn. While the list is called tutor, anyone, whether
novice or expert, can answer questions.

5. If individuals wish to start off-line conversations about a
particular concept and become one-on-one tutor/tutee, that's
fine. If either party wants to summarize what they learned
for others to benefit, that's fine too.
---

Re:#1. This is a mailing list devoted to "learning programming".
Specifically, the Python language is used to learn programming.

Re:#2. People who are interested in learning HOW TO program a
   computer may ask questions on this list. They are encouraged
   to ask their questions, using the Python programming language.

Re:#3. Pyhton is considered a good 'first language' to learn. It doesn't
  have to be your first language, but if it is, it is probably a good
  one to start with. Why? Because the concepts of computer
 programming are considered by many people to be easy to grasp
  and express in the Python language.

Re:#4. Anyone can answer other's questions, even if they are novices.
   The list is 'inclusive'. Anyone, no matter what their level of
   experience is, is invited to join and participate in the discussions.

Re:#5. The discussions can take place on-list, or off-list. If they take place
 off-list, participants are encouraged to post a summary of what they've
 learned, so others can benefit from the off-list discussion.

Whew! That is way cool! That probably means that
you probabl;y won't hear too much "RTFM" on this list, right? =)

However, one of the NICE things about Python is that there is an
abundance of documentation written at every imaginable level,
available online, for free (or for whatever it costs you to be online).

Sometimes, "RTFM" [Read The Fine Manual] is an appropriate
first answer to a question. However, just the reply, "RTFM", usually isn't
enough... most experienced programmers are aware that many
less experienced programmers probably aren't very familiar with
the exisiting documentation yet. In fact, it is quite possible that
a new user to the Tutor list is ALSO a new computer user, AND new to
the Internet, who is also interested in learning how to program
their new machine. (After all, the most fascinating thing about
computers is: they are programmable.) So, an "RTFM" reply
(if deemed appropriate as an answer to a question), is usually
accompanied by a link to where The Fine Manual is located,
ie. a viable URL [Web address].

A Noob, or Newbie can be Anyone! If a person continues learning
throughout their lifespan, then they will always be a Noob at something.
No one is born just knowing everything, automatically. However, some
have been gifted with more raw intelligence than others, and they
usually learn more quickly than someone who isn't as gifted. Those
people are encouraged to stay on the list and help others learn
Python, even as they are learning more advanced aspects of the
language.

So, after all that is said and done the question seems to be:
How do we ask and answer questions on the Tutor list, so as not
to be flamed? (Asbestos underwear are mighty uncomfortable!)

1. It is usually considered good Network "ettiquette" to read a FAQ
[Frequently Asked Questions] about a mailing list before, or
shortly after joining the 

[Tutor] Basic DB question

2007-07-16 Thread z machinez

Hi All,

I am just starting out with Python and was hoping someone could point me in
the direction of reading materials for working with RDBMS? In particular, I
am working with two various relational databases. One of which stores
real-time data for trading. In Python I am planning on building various time
series models to collate historical tick data and real-time data. As I am
very new to Python, I was hoping someone could recommend some docs/books.

I have read up on the DBAPI, but do not think this is what I need. I might
be wrong though.

Thanks in advance for the help.

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


Re: [Tutor] eyeD3 module installation on XP

2007-07-16 Thread Terry Carroll
On Fri, 13 Jul 2007, Richard Querin wrote:

> Any pointers on how to go about installing this module? There's a file
> called 'setup.py.in' as well. Not sure what that does..

Richard; I'm stumped.  Can you try version 0.6.10?  See why below.

I'm using eyeD3-0.6.10, so I know it's possible to install on XP.  I took 
your question as an opportunity to upgrade to eyeD3-0.6.14, planning to 
write down how I did it an respond to your message.  No joy.

I think the appropriate sequence is config / setup build / setup install ;
But I can't get it working.  (BTW, I have Cygwin installed, which is where 
I get my "sh" command).

When I did the "sh configure", I got:

F:\installs\Python\eyed3\eyeD3-0.6.14>sh configure
checking whether make sets $(MAKE)... yes
checking for python... /cygdrive/c/Python25//python
checking if /cygdrive/c/Python25//python is version 2.3 or greater... yes
configure: creating ./config.status
config.status: creating Makefile
config.status: WARNING:  Makefile.in seems to ignore the --datarootdir setting
config.status: creating setup.py
config.status: error: cannot find input file: etc/eyeD3.spec.in

I think that warning and error are fatal to the install.

When I try to setup build, I get:

F:\installs\Python\eyed3\eyeD3-0.6.14>python setup.py build
running build
running build_py
error: package directory 'src\eyeD3' does not exist

So, bottom line, I think the warning message:

 Makefile.in seems to ignore the --datarootdir setting

is the key.

I just retried the configure in the .10 version and did *not* get this 
error:

F:\installs\Python\eyed3\eyeD3-0.6.10>sh configure
checking whether make sets $(MAKE)... yes
checking for python... /cygdrive/c/Python25//python
checking if /cygdrive/c/Python25//python is version 2.3 or greater... yes
configure: creating ./config.status
config.status: creating Makefile
config.status: creating setup.py
config.status: creating etc/eyeD3.spec
config.status: creating src/eyeD3/__init__.py
config.status: creating doc/eyeD3.1

You might want to try downloading .10 instead of the current release and 
see if that works for you.  See http://eyed3.nicfit.net/releases/

Sorry I can't help more. 

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


Re: [Tutor] Basic DB question

2007-07-16 Thread Andreas Kostyrka
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

DBAPI is an interface standard describing what you can expect in a
database access module, like psycopg.

Andreas

z machinez wrote:
> Hi All,
>  
> I am just starting out with Python and was hoping someone could point me
> in the direction of reading materials for working with RDBMS? In
> particular, I am working with two various relational databases. One of
> which stores real-time data for trading. In Python I am planning on
> building various time series models to collate historical tick data and
> real-time data. As I am very new to Python, I was hoping someone could
> recommend some docs/books.
>  
> I have read up on the DBAPI, but do not think this is what I need. I
> might be wrong though.
>  
> Thanks in advance for the help.
>  
> Z.
>  
> 
> 
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.2 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFGm5i8HJdudm4KnO0RAgxtAKDLosrBW+t1pRHdo9EBH+V8TreSwQCg6A9a
oNXWmoAk25u7GxiiVeO4YdU=
=D7JY
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] CGI Calculator

2007-07-16 Thread Darren Williams
Hi all,

I am a Python convert coming from a JavaScript background (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: 
Dealer Visits Remaining: 





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

Thanks in advance for any help :)___
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] eyeD3 module installation on XP

2007-07-16 Thread Richard Querin
Sorry Tino,

Missed your response completely. Your advice on using cygwin was
spot-on. I hadn't thought of using that.

Per my response to Terry, I've got the .10 version up and running now.

Thanks.

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


[Tutor] Fwd: eyeD3 module installation on XP

2007-07-16 Thread Richard Querin
On 7/16/07, Terry Carroll <[EMAIL PROTECTED]> wrote:

> You might want to try downloading .10 instead of the current release and
> see if that works for you.  See http://eyed3.nicfit.net/releases/
>
> Sorry I can't help more.

Nope. That's fine. Based on your response I was able to upgrade my
Cygwin (didn't have the make utility installed) and then was able to
download the .10 version and it's installed and working here right
now. Awesome. I won't be doing much coding here at work but I like to
dabble now and then ;). I'll (hopefully) be able to install the .deb
package without problem on my ubuntu box at home.

Thanks a lot.

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


Re: [Tutor] CGI Calculator

2007-07-16 Thread Darren Williams
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

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
coatSize = form["coatSize"].value
usedPockets = form["usedPockets"].value
labSpace = form["labSpace"].value
totalJunkies = form["totalJunkies"].value
DVR = form["DVR"].value

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

main()

Here's the error using the CGI Traceback Module -

  D:\inetpub\vhosts\newspyn.com\cgi-bin\JunkieCalc.py
 21 print "Tokens"

 22 #else:

 23 #print "Try again... beeyatch"

 24

 25 main()

  main = 
   D:\inetpub\vhosts\newspyn.com\cgi-bin\JunkieCalc.py in main()
 15 DVR = form["DVR"].value

 16

 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'",)



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'

Thanks in advance for any help :)

- Original Message - 
From: "Eric Brunson" <[EMAIL PROTECTED]>
To: "Darren Williams" <[EMAIL PROTECTED]>
Cc: 
Sent: Monday, July 16, 2007 12:50 PM
Subject: Re: [Tutor] CGI Calculator


> 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
>> 
>> 
>> 
>> > action="http://newspyn.com/cgi-bin/JunkieCalc.py";>
>> Coat Size: 
>> Used Pockets: > name="usedPockets">
>> 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

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 Darren Williams
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 :)

- 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
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 Darren Williams
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


[Tutor] curses

2007-07-16 Thread Tiger12506
curses does not run on my Windows XP computer.
Is this supposed to be a Linux only module?

Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python25\lib\curses\__init__.py", line 15, in 
from _curses import *
ImportError: No module named _curses



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


Re: [Tutor] curses

2007-07-16 Thread Tino Dai

On 7/16/07, Tiger12506 <[EMAIL PROTECTED]> wrote:


curses does not run on my Windows XP computer.
Is this supposed to be a Linux only module?

Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python25\lib\curses\__init__.py", line 15, in 
from _curses import *
ImportError: No module named _curses



That and cygwin.

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


Re: [Tutor] curses

2007-07-16 Thread Luke Paireepinart
Tino Dai wrote:
>
>
> On 7/16/07, *Tiger12506* <[EMAIL PROTECTED] 
> > wrote:
>
> curses does not run on my Windows XP computer.
> Is this supposed to be a Linux only module?
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "C:\Python25\lib\curses\__init__.py", line 15, in 
> from _curses import *
> ImportError: No module named _curses
>
>
> That and cygwin.
>
> -Tino
There's a Console module that you can use to do the same thing at a DOS 
prompt in windows, but that's not cross-platform either.
-Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] curses

2007-07-16 Thread bhaaluu
On 7/16/07, Tiger12506 <[EMAIL PROTECTED]> wrote:
> curses does not run on my Windows XP computer.
> Is this supposed to be a Linux only module?
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "C:\Python25\lib\curses\__init__.py", line 15, in 
> from _curses import *
> ImportError: No module named _curses
>
> JS

There IS a way to try Linux, Python, and curses WITHOUT
installing anything to the hard-drive of your MSWindowsXP
computer, and that is to download a Linux LiveCD ISO image,
and make a bootable CD from that image. Your computer
BIOS should be setup to boot from a CD. Put the LiveCD in
the CD drive, and reboot. The LiveCD runs in RAM, so you
need at LEAST 128MB RAM to run it (for good results).
Since it runs in RAM, nothing touches the HD. When you
are finished, simply Shutdown the computer, take out the CD,
and reboot into MSWindowsXP.

Warning: there are over 200 Linux LiveCDs to choose from!
Not all of them are designed for developers, so they may
or may not have Python installed by default. One easy-to-use
general-purpose Linux LiveCD is called SimplyMEPIS.
You can find a download mirror here:
http://www.mepis.org/mirrors
You should have a fast connection to download this ISO image.
The SimplyMEPIS LiveCD is about 700MB in size!

Python is already installed, as well as the curses module.

This is a general-purpose desktop OS that runs the K Desktop
Environment (KDE), and has all sorts of interpreters and compilers
on it besides Python. It has a 75% 'Ubuntu' core with a 25% MEPIS
wrapper that makes things work out of the box.

A Linux LiveCD can be carried with you, and used on remote
computers without having to install anything on the remote computer.
So you can have Python with you, wherever you go. =)
-- 
bhaaluu at gmail dot com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] ADO problem

2007-07-16 Thread János Juhász
Hi Tim,

thanks your help.
It is clear for me now.

> From: Tim Golden <[EMAIL PROTECTED]>
> Subject: Re: [Tutor] ADO problem

> J?nos Juh?sz wrote:
> > while not rs.EOF:
> > print rs.Fields[0].Value, rs.Fields[1].Value
> > rs.MoveNext()
> >
> > It print the next result:
> > IT (u'\xc1kos Szab\xf3',)
> > IT (u'Szabolcs K\xe1m\xe1n',)
> > ...
> >
> > So rs.Fields[1] is a tuple.

> Well, here's the most obvious thing:

> By the look of it: rs.Fields[1] is *not* a tuple.
> It's an instance of some sort. rs.Fields[1].Value
> *is* a tuple. So something like this:

> rs.Fields[1].Value[0]

> should work. I'm not quite clear why that second
> field returns a tuple while the first one doesn't.

Yes, It works.

So, I have to use
rs.Fields[1].Value[0] 
instead of
rs.Fields[1][0].Value


> To do this specific thing, you might find it easier
> to use a module wrapper:

> http://tgolden.sc.sabren.com/python/active_directory.html

> where your query would become something like (untested):

Your module works perfectly.
You should know something about the recordsets :)

> 
> import active_directory

> for user in active_directory.search (
> objectClass="User",
> name="*.ferbeau",
> department="IT"
> ):
> print user.name, user.description, user.department
> 
> 

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


Re: [Tutor] curses

2007-07-16 Thread Luke Paireepinart
Hey bhaaluu - I've enjoyed your posts to the list so far.  They're very 
informative and well-written.
-Luke

bhaaluu wrote:
> On 7/16/07, Tiger12506 <[EMAIL PROTECTED]> wrote:
>   
>> curses does not run on my Windows XP computer.
>> Is this supposed to be a Linux only module?
>>
>> Traceback (most recent call last):
>>   File "", line 1, in 
>>   File "C:\Python25\lib\curses\__init__.py", line 15, in 
>> from _curses import *
>> ImportError: No module named _curses
>>
>> JS
>> 
>
> There IS a way to try Linux, Python, and curses WITHOUT
> installing anything to the hard-drive of your MSWindowsXP
> computer, and that is to download a Linux LiveCD ISO image,
> and make a bootable CD from that image. Your computer
> BIOS should be setup to boot from a CD. Put the LiveCD in
> the CD drive, and reboot. The LiveCD runs in RAM, so you
> need at LEAST 128MB RAM to run it (for good results).
> Since it runs in RAM, nothing touches the HD. When you
> are finished, simply Shutdown the computer, take out the CD,
> and reboot into MSWindowsXP.
>
> Warning: there are over 200 Linux LiveCDs to choose from!
> Not all of them are designed for developers, so they may
> or may not have Python installed by default. One easy-to-use
> general-purpose Linux LiveCD is called SimplyMEPIS.
> You can find a download mirror here:
> http://www.mepis.org/mirrors
> You should have a fast connection to download this ISO image.
> The SimplyMEPIS LiveCD is about 700MB in size!
>
> Python is already installed, as well as the curses module.
>
> This is a general-purpose desktop OS that runs the K Desktop
> Environment (KDE), and has all sorts of interpreters and compilers
> on it besides Python. It has a 75% 'Ubuntu' core with a 25% MEPIS
> wrapper that makes things work out of the box.
>
> A Linux LiveCD can be carried with you, and used on remote
> computers without having to install anything on the remote computer.
> So you can have Python with you, wherever you go. =)
>   

___
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-16 Thread Kent Johnson
John Fouhy wrote:
> def walkTree(tree):
> # stack to hold nodes as we walk through
> stack = []
> stack.append(tree)
> 
> while stack:
> value, children = stack.pop()
> for child in reversed(children):  # reverse children to get
> the right order.
> stack.append(child)

FWIW this could be written as
   stack.extend(reversed(children))

Kent
___
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-16 Thread Kent Johnson
Dave Kuhlman wrote:
> On Fri, Jul 13, 2007 at 12:39:40PM +1200, John Fouhy wrote:
>> On 13/07/07, Dave Kuhlman <[EMAIL PROTECTED]> wrote:
>>> 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.
>> You should just be able to use a stack -- push the children onto a
>> stack, then pop them off and walk through them.
>>
>> Here's an example, using tuples and lists as a basic tree data type:
>>
>> ### treetest.py #
>>
>> TREE = (0, [(1, [(2, [(3, []),
>>   (4, []),
>>   (5, [(6, []),
>>(7, []),
>>(8, []),
>>(9, []),
>>]),
>>   (10, [(11, []),
>> (12, []),
>> ]),
>>   ]),
>>  (13, [(14, []),
>>(15, []),
>>(16, [])]),
>>  (17, []),
>>  (18, []),
>>  ]),
>> (19, []),
>> (20, []),
>> ])
>>
>> def walkTree(tree):
>> # stack to hold nodes as we walk through
>> stack = []
>> stack.append(tree)
>>
>> while stack:
>> value, children = stack.pop()
>> for child in reversed(children):  # reverse children to get
>> the right order.
>> stack.append(child)
>> yield value
>>
>> if __name__ == '__main__':
>> for value in walkTree(TREE):
>> print value
>>
>> ### treetest.py #
> 
> John -
> 
> That is so cool.  I can't believe that it is so simple and elegant. 
> I thought that a stack was involved in the solution, but I could
> not figure out how to use it.  Thanks.
> 
> And, to extend this a bit more, here are two slightly modified
> versions of your solution that implement classes whose
> instances are iterators.
> 
> 
> #
> # Version #1 -- This version has a next() method, as required by
> #   the iterator protocol.
> #
> class Node(object):
> def __init__(self, value='', children=None):
> self.value = chr(value + 97) * 3
> if children is None:
> children = []
> else:
> self.children = children
> def walk_tree(self):
> # stack to hold nodes as we walk through
> stack = []
> stack.append(self)
> while stack:
> node = stack.pop()
> # reverse children to get the right order.
> stack.extend(reversed(node.children))
> yield node
> def __iter__(self):
> self.iterator = self.walk_tree()
> return self
> def next(self):
> return self.iterator.next()
> 
> 
> #
> # Version #2 -- This version does not have a next() method, but
> #   the iterators returned by __iter__() do have a next().
> #
> class Node(object):
> def __init__(self, value='', children=None):
> self.value = chr(value + 97) * 3
> if children is None:
> children = []
> else:
> self.children = children
> def walk_tree(self):
> # stack to hold nodes as we walk through
> stack = []
> stack.append(self)
> while stack:
> node = stack.pop()
> # reverse children to get the right order.
> stack.extend(reversed(node.children))
> yield node
> def __iter__(self):
> return self.walk_tree()

I think Version 2 is preferable. Not only is it shorter, but it is 
safer. Version 1 has essentially a singleton iterator so any code that 
tries to iterate the same node more than once will fail.  For example 
multi-threaded code, or perhaps during an iteration there could be a 
reason to start a new iteration.

Kent
___
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-16 Thread Kent Johnson
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.

In the Consumers section, the first time you mention the iterator 
protocol, you omit mention of __init__() - this is a required method of 
an iterator.

In the section "The iterator protocol", the __iter__() bullet, "(2) 
return the value returned by a generator method" is not correct. An 
iterator must return self from __iter__(). An object that returns a 
(new) generator from __iter__() is an iterable, not an iterator.

In some cases there is no need to write a separate generator method and 
call it in __iter__(); __iter__() itself can be written as a generator 
method using yield. This works if the generator method doesn't need any 
arguments.

Your Doubler class will not behave correctly because of the 
re-initialization of the index in __iter__(). Calling __iter__() should 
not have any side effects. Here is an example of why this is a problem, 
using Doubler as you have written it:

In [9]: d=Doubler(range(5))
In [10]: d.next()
Out[10]: 0
In [11]: d.next()
Out[11]: 2
In [12]: for i in d: print i
:
0
2
4
6
8

Notice how the for loop resets the iterator (because it calls __iter__() 
to make sure it has an iterator). Compare with a correctly implemented 
iterator:

In [13]: it = iter(range(5))
In [14]: it.next()
Out[14]: 0
In [15]: it.next()
Out[15]: 1
In [16]: for i in it: print i
:
2
3
4

Double would actually be easier to implement with __iter__() as a 
generator method.

I already commented on the pitfalls of making an object its own 
iterator. In the standard library, a file is its own iterator. That 
makes sense because it is a wrapper around a singleton state - the seek 
position of the file. I don't think it makes much sense in general to 
have an object be its own iterator unless the object is just an iterator.

Another reference is the What's New doc for Python 2.2:
http://www.python.org/doc/2.2.3/whatsnew/node4.html
and the following page.

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


Re: [Tutor] interpreter restarts

2007-07-16 Thread Tiger12506
> 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?

JS 

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


Re: [Tutor] curses

2007-07-16 Thread Tiger12506
> There IS a way to try Linux, Python, and curses WITHOUT
> installing anything to the hard-drive of your MSWindowsXP
> computer, and that is to download a Linux LiveCD ISO image,
> and make a bootable CD from that image. Your computer
> BIOS should be setup to boot from a CD.

*That* is the problem. I have *NEVER* been able to get a computer to boot 
from a CD. Yes, the BIOS settings are there, the CDs all seem valid (they 
all have the appropriate MBRs etc.) and yet *none* of the computers I have 
ever come in contact with will boot from a CD. You can imagine the hell I 
have to work through trying to repair damaged XP installations. (The Windows 
OS installer fits on SIX floppy disks, and if you choose an install option 
that you didn't mean to, you can't go back. You have to restart and run 
through all six disks AGAIN).

> Put the LiveCD in
> the CD drive, and reboot. The LiveCD runs in RAM, so you
> need at LEAST 128MB RAM to run it (for good results).
> Since it runs in RAM, nothing touches the HD. When you
> are finished, simply Shutdown the computer, take out the CD,
> and reboot into MSWindowsXP.

RAM isn't a problem. Nothing touches the HD unless I want it to... ;-)
It would be great to be able to boot from a CD, it seems that the
the computers that fall into my lap all need to be tweaked from a bootdisk
before they will boot Windows.

> Warning: there are over 200 Linux LiveCDs to choose from!
> Not all of them are designed for developers, so they may
> or may not have Python installed by default. One easy-to-use
> general-purpose Linux LiveCD is called SimplyMEPIS.
> You can find a download mirror here:
> http://www.mepis.org/mirrors
> You should have a fast connection to download this ISO image.
> The SimplyMEPIS LiveCD is about 700MB in size!

The size of a CD. Aah. To stuff your media as tightly as possible. That 
worries me. I like very clean, very efficient things. ;-)

> Python is already installed, as well as the curses module.
>
> This is a general-purpose desktop OS that runs the K Desktop
> Environment (KDE), and has all sorts of interpreters and compilers
> on it besides Python. It has a 75% 'Ubuntu' core with a 25% MEPIS
> wrapper that makes things work out of the box.
>
> A Linux LiveCD can be carried with you, and used on remote
> computers without having to install anything on the remote computer.
> So you can have Python with you, wherever you go. =)

I tried to install linux on one of my old desktop machines. The boot install 
floppy that I used put junk characters on the screen, and certainly didn't 
bring up the install menu ;-)
Debian looked the most promising at the time for easy install and casual 
trans to linux.

Thanks for the advice, though.
JS

PS
> Hey bhaaluu - I've enjoyed your posts to the list so far.  They're very
> informative and well-written.
> -Luke

I agree completely!!!

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


Re: [Tutor] Searching for word in text file

2007-07-16 Thread Kent Johnson
Vladimir Strycek wrote:
> Hi all,
> 
> i need script which open two text files and take first word from the 
> first file, runn throught first fords of second file and give me result 
> if its there or not...
> 
> what i have so far is:
> 
> import re, string
> 
> # Nacitanie suborov na porovnanie
> subor1 = open("snow.txt", "r")
> subor2 = open("anakin.txt", "r")
> 
> def prehladaj(najdi):
> for riadok1 in subor2.readlines():
> z = riadok1.rsplit(" ")
> if najdi in z[2]:
> return z[3]
>
> def porovnaj():
> for riadok in subor1.readlines():
> x = riadok.rsplit(" ") #rozdelime do array dany riadok kde v 2 
> bude nazov a verzia v 3
> print x[2] + "" + x[3]
> print prehladaj(x[2])
>
>
> 
> #vytvorenie tabulky
> print " Server: snow  Server: anakin"
> print ""
> print "   Name Version   Version"
> porovnaj()
> 
> subor1.close()
> subor2.close()
> 
> 
> 
> the snow.txt looks like:
> 
>   B3693AA C.03.86.00 HP GlancePlus/UX for s800 11i
>   B3901BA B.11.11.14 HP C/ANSI C Developer's Bundle for HP-UX (S800)
>   B3913DB C.03.65HP aC++ Compiler (S800)
>   B4967AA C.03.86.00 HP MeasureWare Server Agent for s800 11i
>   B5458DA C.01.18.04 HP-UX Runtime Environment for Java*
>   B5725AA B.3.5.89   HP-UX Installation Utilities (Ignite-UX)
> 
> etc...
> 
> anakint.txt is the same but different versions of programs im not 
> sure why tmi script dont work ( only for first one )
> 
> 
> What i basicaly need is to look up if version of programs match on bouth 
> text files diff in linux wont work for it cause there are not the same 
> programs on the same lines...
> 
> Any idea why mi script is not working or any suggestion for different 
> aproach ?

You don't say how it is failing, but one problem is that the 
subor2.readlines() in prehladaj() will only work the first time. I'm 
pretty sure that if you want to read the lines from the file again you 
will have to close and re-open the file.

If the files are long this approach will be slow. Possibly a better way 
to do this is to build a dict from the data in anakin.txt though this 
assums that field 2 in anakin.txt is unique and that you want to do 
exact match searching which is not what your program does. The keys can 
be  field 2 (that you search on) and the values field 3. For example,

subor2 = open("anakin.txt", "r")
d = {} # you can think of a better name, I'm sure
for riadok1 in subor2.readlines():
 z = riadok1.rsplit(" ")
 d[z[2]] = z[3]

Then the matching is
 if najdi in d:
 return d[najdi]
with no looping over subor2 needed.

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


Re: [Tutor] reading random line from a file

2007-07-16 Thread Tiger12506
Perhaps ~this~ is what you are worried about performance-wise?
Image NameMem Usage
-
python.exe11,096 K

That's not too bad considering ~this~
explorer.exe   14,356 K
svchost.exe24,000 K

And I worry about the mp3 player I wrote in C using 2,520 K
I keep thinking I could cut that down if I mess with the compiler settings 
;-)

I wouldn't worry about it too much. Reading the whole file in at once is a 
performance issue when you are dealing with millions and millions of lines 
of text. An example is DNA sequences. Or databases.

JS

> max baseman wrote:
>> cool thanks
>>
>> oh for performance eventualy i would like the file to contain many quotes
> Using readlines isn't exactly going to cause a performance bottleneck.
> I used the following code
> #make the file.py
> f = file("temp.txt","w")
> x = 10
> while x > 0:
>f.write("\n")
>x -= 1
> f.close()
> #---
> this creates a file with a whole lot of lines of 'a's.
> 100,000 lines, to be exact, and 4,200,000 bytes.
>
> In other words, this is a fair approximation for if you had, say, 25,000
> quotes (since your quotes are likely to be, on average, longer than the
> amount of 'a's I used.)
> I think you'll agree that that's quite a few quotes.
>
> Now how long does it take to use readlines() on this file?
>
> #test performance.py
> import timeit
> string = "f = file('temp.txt','r');f.readlines();f.close()"
> temp = timeit.Timer(stmt=string)
> print "1000 iterations took: " + str(temp.timeit(1000))
> #-
> what this code does is opens, reads all the text of the file, and closes
> the file.
> We call timeit with 1000 as the argument, so it repeats this process
> 1000 times.
>
> The output of this program on my machine is:
> 1000 iterations took: 51.0771701431
>
> In other words, if you have 25,000 quotes, you could read all of them
> into memory in 51.07717/1000 (approximately)
> or 0.05107 seconds.  And I'm skeptical that you would even have that
> many quotes.
> So, like i said before, I doubt this will cause any significant
> performance problem in pretty much any normal situation.
>
> Also, by the way - please reply to me on-list so that others get the
> benefit of our conversations.
> -Luke

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


Re: [Tutor] interpreter restarts

2007-07-16 Thread Luke Paireepinart
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 will notice, there are some parameters there at the end.
the -n is the one you're interested in .
-n means no subprocess.
Just remove that, and you will have a subprocess on the 'Edit with IDLE' 
feature.
There is some caveat here - it doesn't work correctly on some systems, 
I'm told.
I've never had problems changing this, but I don't recommend it to 
people randomly just in case it were to cause problems for them.
Then I'd feel bad.
But since you asked, I thought I'd give you all the info you need.
HTH,
-Luke
P.S. nice detective skillz ;)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Serve a file using http

2007-07-16 Thread Sebastian Lara
Hello all,

I'm using a SimpleXMLRPCServer to update a file remotely from a simple
xml-rpc python client.  After that, I need to serve this file but I
don't know if I can do this with SimpleXMLRPCServer or if I need
another server.

Thanks in advance
-- 
Sebastián Lara Menares
Ingeniería Civil Electrónica
Universidad de Concepción
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] curses

2007-07-16 Thread max baseman
hello all sorry to bother I'm working on my first curses program ive  
been wanting to learn curses for a while now and now that a have a  
lop top with fedora core running in run level 3 ware im trying to  
program all the tools i'll use but curses will be my only gui ALAN  
has been helping me with this program

import curses
from time import sleep
scr=curses.initscr()
population=0
seconds=0
try:
 scr.nodelay(1)
 scr.leaveok(0)
 max_y, max_x = scr.getmaxyx()
 while 1:
 sleep(1)
 second=seconds=+1
 population=population+2.5
 scr.addstr(0,0,"seconds",seconds)
 scr.addch,max_y/2, max_x/2, str(population)[0]
 scr.refresh()
finally:
 curses.endwin()


depending on ware i run this i get different results on may mac OSX  
10.4 i only get a wired second thing in the top left corner that  
looks like this secooes

and when i run this on fedora core 6 i get the seconds word in top  
left but no number and i get a single digit in the midle that changes  
i think the single digit is part of population but not all i cant  
find out what is wrong


any help would be great :)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] interpreter restarts

2007-07-16 Thread Sara Johnson
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 will notice, there are some parameters there at the end.
the -n is the one you're interested in .
-n means no subprocess.
Just remove that, and you will have a subprocess on the 'Edit with IDLE' 
feature.
There is some caveat here - it doesn't work correctly on some systems, 
I'm told.
I've never had problems changing this, but I don't recommend it to 
people randomly just in case it were to cause problems for them.
Then I'd feel bad.
But since you asked, I thought I'd give you all the info you need.
HTH,
-Luke
P.S. nice detective skillz ;)
___
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] tutor

2007-07-16 Thread Tiger12506
> please think about your first programming class, and then think about how
> long it took the prof to teach the concept of array.
>
> yes, it's about a week, if he is really good.

[gentle rant]
Yes, and I find that most idiots in math classes NEVER gain the concept of
multiplying fractions (longer than a week - 2 years for my peers). Very
simple. Multiply the top numbers together. Multiply the bottom numbers
together. But can they understand? No. They "learn" by mimicking, like a
monkey. They don't think. They don't understand. And they can't follow rules
or *syntax*, that *documentation* provides. And the worst part: They don't
try. All they can do is produce the same result - give the answer that
someone else provides. That is the world today.
[/gentle rant]

If the "prof" is good, it will take ten minutes to explain the concept of an
array. Having said that, it is usually not the professor nor the language
that is the problem: it's the student. The student *must* be willing to
learn. The student *must* be willing to study material. If someone
references tutorials, then the student *must* be willing to read and work
through those tutorials. These list members are not providing links for no
reason. They have provided many tutorials for beginner programmers. They
have provided many links for people who have never seen what a programming
language is before in their life. *If* you can say that you have honestly
read, worked, and asked questions about those tutorials, and you still don't
have the fundamentals, then perhaps programming is not for you. The problem
is - you have to work ALL THE WAY THROUGH THEM. You cannot expect to write
files, for example, if you've read the first chapter that tells you how to
use
print "Hello World".  And you would not know how to add to a formatting
string unless you read the next part of the tutorial for example.

I apologize for my harshness. But the statement about my first programming
class, and arrays, and a week... @!#$%   I am not lucky enough to be able to
pay for a programming class. And yet using the same tutorials that those on
the list have quoted I learned python well enough to do what you are
attempting in a few days. Granted, I couldn't write GUI apps using Tkinter, 
but I TRIED. And I listened to the advice of Alan, Kent, Danny, and the 
others when they said I should read this or that tutorial. And no. I didn't 
have ANY previous programming
experience. If it really takes professors a week to teach the concept of an
array, then they should be sacked and replaced with one of the excellent
tutorials these list members have mentioned.

JS

PS - if you had read those tutorials through, you would understand that this
f.write("\"%s\"" % title) --which someone on the list gave to you--  
provided the
answer to this:

###
organge = 5

f.write( "there are orange "florida" oranges on the counter")
##

which should be


orange = 5
f.write("there are %s \"florida\" oranges on the counter" % orange)
###

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


Re: [Tutor] reading random line from a file

2007-07-16 Thread Tiger12506
If you truly wish to kill yourself trying to make it as efficient memory as
possible, then you can follow this example. (This is more like what I would
write in C).
The getrandomline function picks a random byte between the beginning and the
end of the file, then backs up until the beginning of the line and uses
readline to return the whole line.
I tested it :-)


#
from os import stat
from random import randint

def getrandomline(f, length):
pos = randint(0,length)
f.seek(pos)
while f.read(1)!='\n':
try:
  f.seek(-2,1)
except IOError:   # This is to catch seeking before the
beginning of the file
  f.seek(0)
return f.readline()

f = file("quotes.txt","rb")
sizeoffile = stat("quotes.txt")[6]

while (1):
  print getrandomline(f, sizeoffile),

f.close()
###

This holds at 3,688 K mem usage, whereas with the same file (100,000 lines),
using readlines gives me 47,724 K.  Big difference. Maybe not important to
you, but I'm strange.

Hope this helps.

JS

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


Re: [Tutor] interpreter restarts

2007-07-16 Thread Tiger12506
Hmmm. You should read closer ;-)

> It sounds like python_icon.exe is a fake executable that just contains the 
> icon for python programs...
> hence the name.

Perhaps. If that's the case though, someone needs to talk to the guys who 
design the setup file for python. It is an inefficient waste of space to 
store icons in a dead executable. An .ico file is better. That is for what 
they are designed. I believe that it is not a dead executable, because those 
writers have more sense than that. Also the odd location of the executable 
suggests it has another purpose. And it has to have a purpose, otherwise 
IDLE never would get started.

> 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.

As my message said, I already have that. I was trying to find the path that 
the icon in the start menu uses to start IDLE, so that I could compare them.

> 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"

And you can also get to Folder Options by opening Control Panel.
You can also get there by typing in Folder Options in any open folder.

Quoting my own message:

>> 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"

Yes~ I know about Folder Options. ~smirk~ I also know where in the Windows 
Registry that Folder Options stores those file extensions.

> As you will notice, there are some parameters there at the end.
> the -n is the one you're interested in .
> -n means no subprocess.

Yes. Yes. That is what I'm interested in.
Sigh. I know Windows very well for my background. The command line 
parameters for pythonw.exe ~ not so much.

JS 

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


[Tutor] IDLE Usage - was Interpreter Restarts

2007-07-16 Thread Tiger12506
> 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

Not quite what we were discussing, but I think you may have given just 
enough clues that i can be of some help. Just for reference ~ which editor 
are you using?

IDLE is both an editor and a python shell or interpreter. It is not the same 
thing as typing python.exe wherever you might be typing it.

Typing Python into an editor should put the word "Python" into your 
currently open file. I don't believe that this is what you mean. Perhaps you 
are confusing what exactly is an editor?

You use Windows you've mentioned before. So here's what you can do. Start -> 
Programs -> Python 2.5 -> Python (commandline)

This is the python interpreter. As you might already know.

And then this.
Start -> Programs -> Python 2.5 -> IDLE (Python GUI)

This is IDLE. As you probably know.

Two windows should come up when you click IDLE. One is an editor. The other 
is the python shell, or interpreter. You can open .py files in IDLE by right 
clicking and selecting "Edit with IDLE". At any time that you wish to run a 
program that is open in the editor half of IDLE, hit F5 and the Python shell 
half of IDLE comes to the top and runs the program.

If doing all that doesn't do what I expect it to do, or you have something 
else in mind, reply back. If it does, then great!

Oh. And tell me which editor you are using which magically opens a python 
interpreter when you type Python into it. ;-)

JS 

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


Re: [Tutor] IDLE Usage - was Interpreter Restarts

2007-07-16 Thread Sara Johnson
First off, yes, I was referring to (I guess you could say) a non-python editor. 
 I use an SSH editor set up by my school.  If I type python at the prompt in 
SSH, I get the Python shell.  My problem is, I can't open a GUI no matter what 
I subscribe to or purchase.  I have Python 2.3 and yes, I can access the 
commandline, but that does not work the way it's been described to work.

If this still doesn't make any sense, just ignore me...

Sara



>>Not quite what we were discussing, but I think you may have given just 
enough clues that i can be of some help. Just for reference ~ which editor 
are you using?

IDLE is both an editor and a python shell or interpreter. It is not the same 
thing as typing python.exe wherever you might be typing it.

Typing Python into an editor should put the word "Python" into your 
currently open file. I don't believe that this is what you mean. Perhaps you 
are confusing what exactly is an editor?

You use Windows you've mentioned before. So here's what you can do. Start -> 
Programs -> Python 2.5 -> Python (commandline)

This is the python interpreter. As you might already know.

And then this.
Start -> Programs -> Python 2.5 -> IDLE (Python GUI)

This is IDLE. As you probably know.

Two windows should come up when you click IDLE. One is an editor. The other 
is the python shell, or interpreter. You can open .py files in IDLE by right 
clicking and selecting "Edit with IDLE". At any time that you wish to run a 
program that is open in the editor half of IDLE, hit F5 and the Python shell 
half of IDLE comes to the top and runs the program.

If doing all that doesn't do what I expect it to do, or you have something 
else in mind, reply back. If it does, then great!

Oh. And tell me which editor you are using which magically opens a python 
interpreter when you type Python into it. ;-)

JS 

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


 

It's here! Your new message!  
Get new email alerts with the free Yahoo! Toolbar.
http://tools.search.yahoo.com/toolbar/features/mail/___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] interpreter restarts

2007-07-16 Thread Luke Paireepinart
Tiger12506 wrote:
> Hmmm. You should read closer ;-)
>   
Heh.  You're right, I didn't read your whole message.  I just skimmed it :P
>   
>> It sounds like python_icon.exe is a fake executable that just contains the 
>> icon for python programs...
>> hence the name.
>> 
>
> Perhaps. If that's the case though, someone needs to talk to the guys who 
> design the setup file for python. It is an inefficient waste of space to 
> store icons in a dead executable. An .ico file is better. That is for what 
> they are designed. I believe that it is not a dead executable, because those 
> writers have more sense than that. Also the odd location of the executable 
> suggests it has another purpose. And it has to have a purpose, otherwise 
> IDLE never would get started.
>   
If you really desire to know, you should ask the folks over at 
comp.lang.python.
They're more likely to know what's going on there.
Or maybe some Windows python list.
>   
>> 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.
>> 
>
> As my message said, I already have that. I was trying to find the path that 
> the icon in the start menu uses to start IDLE, so that I could compare them.
>   
Ah, okay.
>
> And you can also get to Folder Options by opening Control Panel.
> You can also get there by typing in Folder Options in any open folder.
>   
Didn't know about the Folder Options thing.  Neat-o.
> Quoting my own message:
>
>   
>>> 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"
>>>   
>
> Yes~ I know about Folder Options. ~smirk~ I also know where in the Windows 
> Registry that Folder Options stores those file extensions.
>   
I didn't realize that was what you were doing <_<.
>   
>> As you will notice, there are some parameters there at the end.
>> the -n is the one you're interested in .
>> -n means no subprocess.
>> 
>
> Yes. Yes. That is what I'm interested in.
> Sigh. I know Windows very well for my background. The command line 
> parameters for pythonw.exe ~ not so much.
>   
Oh well.  Sorry for restating you. :)
It was a situation where I thought I knew what you needed without 
reading the full e-mail.  I'll be more considerate in the future.
-Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] IDLE Usage - was Interpreter Restarts

2007-07-16 Thread Luke Paireepinart
Sara Johnson wrote:
> First off, yes, I was referring to (I guess you could say) a 
> non-python editor.  I use an SSH editor set up by my school.  If I 
> type python at the prompt in SSH, I get the Python shell.  My problem 
> is, I can't open a GUI no matter what I subscribe to or purchase.  I 
> have Python 2.3 and yes, I can access the commandline, but that does 
> not work the way it's been described to work.
>  
> If this still doesn't make any sense, just ignore me...
I'm not sure what your problem is.  Does the SSH program provide a file 
transfer utility? could you write your code on your local computer then 
just transfer the final code to the server?  A lot of Python programmers 
use Vi for writing their code.  do you have access to that through SSH?
I'm not quite sure what you mean by "SSH editor."
-Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 200 dollar questions!

2007-07-16 Thread Rikard Bosnjakovic
On 01/07/07, elis aeris <[EMAIL PROTECTED]> wrote:

[...]

>  GainFocus(handle)
>
>  Keyboard_event ( "hello python!")
>  Mouse_event (x,y, left, 2)
>
>  the (x,y) = should be relative to the active window and independent of the
> window's position.
>  2 as in clicking twice.

This sounds the rentacoder-job I got some weeks ago. Are you perhaps
by chance the same buyer?


-- 
- Rikard - http://bos.hack.org/cv/
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor