how can i read a mail using uid?

2005-02-21 Thread Raghul
I want to read the content of the mail and split it words using uid.If
the word is found in my database I want to delete the mail using  its
uid.

-- 
http://mail.python.org/mailman/listinfo/python-list


Problem with the sort() function

2005-02-21 Thread clementine
Hi,

I have an array of arrays in the form of 
list = [[3,'fork',0.3,1],[2,'fork,0.1,2],[3,'exec',0.2,2]]

The in-built sort(),list.sort() sorts on the first element, if the first
elts are equal then it sorts on the second elt and so on...But i really
dont want to search on the second elt if the first elts are equal...the
1-D lists shud be left in the same position i.e. i want the sorted list to
be [[2,'fork',0.1,2],[3,'fork,0.3,1],[3,'exec',0.2,2]] and not
[[2,'fork',0.1,2],[3,'exec',0.2,2],[3,'fork,0.3,1]].

I tried the following code:

def mysort(x,y):
return x[0]-y[0]

list.sort(mysort)

This somehow seems to work for a small subset of my input...but not for my
real input which has more than 2000 sub-lists(and so obviously i cant trace
each pass..). Can someone tell me what i'm missing?
 

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: UTF-8 / German, Scandinavian letters - is it really this difficult?? Linux & Windows XP

2005-02-21 Thread Do Re Mi chel La Si Do
Hi !

For test your system, please, read this url :
http://sivanataraja.free.fr/config/test.htm  (french)
http://www.alanwood.net/unicode/  (english)

And many explains : http://en.wikipedia.org/wiki/Unicode


And, to reassure you:  I had no problème for use unicode chars with Tk (my
tests on : French, German/Deutch, Cyrillic (russian), Grec).


@-salutations
-- 
Michel Claveau





-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Fwd: Re: [Uuu-devel] languages] <-- Why Python

2005-02-21 Thread Mike Meyer
Ville Vainio <[EMAIL PROTECTED]> writes:

>> "Mike" == Mike Meyer <[EMAIL PROTECTED]> writes:
>
> Mike> IPython's pysh seems a little clumsy for interactive use, as
> Mike> it requires special characters to distinguish between
> Mike> commands to be passed to the shell and commands to be passed
> Mike> to the scripting language. This should be contrasted with
>
> What do you mean by "the commands to be passed to the shell"? Commands
> on the path (the normal situation in Unix) can be executed directly
> just like in bash et al. Ditto for "magic" functions if "automagic" is
> on.

Ok, I missed that. My bad.
>
> Mike> I'll say it again - if you're arguing about which language
> Mike> to use, you're arguing about the wrong thing.
>
> In a sense C is the native language of Unix and Windows (system calls
> are in C). It might make sense to expose the OS as Python objects.

Ugh. It would make more sense to expose it as (say) CORBA objects, so
you aren't tied to a specific language. Following the Plan 9 approach
and exposing it as a file system would probably require more work, but
would allow more flexibility. Then again, both approaches get you into
a recursion when you start trying to expose the facilities that are
used by the exposing infrastructure.

http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: UTF-8 / German, Scandinavian letters - is it really this difficult?? Linux & Windows XP

2005-02-21 Thread "Martin v. Löwis"
Mike Dee wrote:
If I have this in the beginning of my Python script in Linux:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
should I - or should I not - be able to use non-ASCII characters 
in strings and in Tk GUI button labels and GUI window titles and in 
raw_input data without Python returning wrong case in manipulated 
strings and/or gibberished characters in Tk GUI title? 
If you use byte strings, you should expect moji-bake. The coding
declaration primarily affects Unicode literals, and has little
effect on byte string literals. So try putting a "u" in front
of each such string.
With non-ASCII characters I mean ( ISO-8859-1 ??) stuff like the 
German / Swedish / Finnish / etc "umlauted" letter A  (= a diaresis; 
that is an 'A' with two dots above it, or an O with two dots above.)
You explicitly requested that these characters are *not* ISO-8859-1,
by saying that you want them as UTF-8. The LATIN CAPITAL LETTER A WITH
DIAERESIS can be encoded in many different character sets, e.g.
ISO-8859-15, windows1252, UTF-8, UTF-16, euc-jp, T.101, ...
In different encodings, different byte sequences are used to represent
the same character. If you pass a byte string to Tk, it does not know
which encoding you meant to use (this is known in the Python source,
but lost on the way to Tk). So it guesses ISO-8859-1; this guess is
wrong because it really is UTF-8 in your case.
OTOH, if you use a Unicode string, it is very clear what internal
representation each character has.
How would you go about making a script where a) the user types in any text 
(that might or might not include umlauted characters) and b) that text then 
gets uppercased, lowercased or "titled" and c) printed? 
Use Unicode.
Isn't it enough to have that 'UTF-8 encoding declaration' in the beginning,
and then just like get the user's raw_input, mangle it about with .title() 
or some such tool, and then just spit it out with a print statement?
No.
One can hardly expect the users to type characters like unicode('\xc3\
xa4\xc3\xb6\xc3\xbc', 'utf-8')u'\xe4\xf6\xfc' u"äöü".encode('utf-8') or 
whatnot, and encode & decode to and fro till the cows come home just to 
get a letter or two in their name to show up correctly. 
This is not necessary.
Am I beyond hope?
Perhaps not. You should, however, familiarize yourself with the notion
of character encodings, and how the same character can have different
byte represenations, and the same byte representation can have different
interpretations as a character. If libraries disagree on how to
interpret bytes as characters, you get moji-bake (ghost characters;
a Japanese term for the problem, as Japanese users are familiar with
the problem for a long time)
The Python Unicode type solves these problems for good, but you
need to use it correctly.
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: global var

2005-02-21 Thread Jeff Shannon
Nick Coghlan wrote:
Michael Hoffman wrote:
raver2046 wrote:
How to have a global var in python ?
"global var" will give you a global variable named "var".
Whether this advice is correct or not depends greatly on what the OP 
means by 'global' :)

Module global, it's right, application global it's wrong. Given the 
nature of the question, I suspect the latter.
And even there, one must be careful.  "global var" won't really give you 
a global variable; it will cause the name "var", when used locally, to 
refer to a pre-existing module-level reference "var".  No variables are 
actually created in the execution of "global var".

Jeff Shannon
--
http://mail.python.org/mailman/listinfo/python-list


Re: Considering python - have a few questions.

2005-02-21 Thread Simon John
I'd go with a MySQL / Python / Apache route, but if it's Windows, maybe
not.

Also, you shouldn't store images in a database - images should be on
the filesystem with their paths stored in the database.

I'd definitely say going the web application route would be easier (and
more portable) than the GUI route, and a free Windows PyQt is still a
long way off, so stick with wxPython if you want a non-web GUI.

-- 
http://mail.python.org/mailman/listinfo/python-list


Copy functio in imaplib

2005-02-21 Thread Raghul
What is message_set in the python documentation for copy in imaplib? Is
they referring message set  to the particular mail message in my inbox
or something else.

copy(   message_set, new_mailbox)
Copy message_set messages onto end of new_mailbox.

-- 
http://mail.python.org/mailman/listinfo/python-list


UID python reading mail

2005-02-21 Thread Raghul
I am totally confused of using uid .Can anyone help me in giving a
sample code for reading mail nad printing their uid's. I think this
would be more useful for freshers like me.

Thanks  in advance

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pyrex just in time compilation

2005-02-21 Thread Simon Wittber
> Before I try this myself, has anyone else already written any code to do this?

Yes, someone has.

http://www.prescod.net/pyximport/

I should have googled more thoroughly before posting. :-)

sw.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: copying or moving the mail message using imaplib

2005-02-21 Thread Raghul
Thanx I got some clear view about this. In the above program I used uid
method to copy thje mail to "Inbox".This shows the out put of my mail
messages and In the copy of messages I got the output
when printing the "dat"

('OK', [None])
('OK', ['2 (UID 16 FLAGS (\\Seen))'])
2

I cannot see the message in the INBOX. Can anyone give me a solution.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: copying or moving the mail message using imaplib

2005-02-21 Thread Raghul
Thanx I got some clear view about this. In the above program I used uid
method to copy thje mail to "Inbox".This shows the out put of my mail
messages and In the copy of messages I got the output
when printing the "dat"

('OK', [None])
('OK', ['2 (UID 16 FLAGS (\\Seen))'])
2

I cannot see the message in the INBOX. Can anyone give me a solution.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: copying or moving the mail message using imaplib

2005-02-21 Thread Grant Edwards
On 2005-02-22, Raghul <[EMAIL PROTECTED]> wrote:

> Thanks for ur message .How it is possible to copy the  messages betwwen
> folder ?I can't understand the copy function in python documentation.

Maybe you should take a look at the RFC for IMAP4:

http://www.faqs.org/rfcs/rfc2060.html

The UID command is documented in section 6.4.8.  It looks
fairly clear to me.

-- 
Grant Edwards   grante Yow!  Mr and Mrs PED, can
  at   I borrow 26.7
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: NOOB coding help....

2005-02-21 Thread Steven Bethard
Igorati wrote:
list = [ ] 
a = 1 
print 'Enter numbers to add to the list. (Enter 0 to quit.)'
while a != 0 :
a = input('Number? ')
list.append(a)
zero = list.index(0)
del list[zero]
list.sort() 
A simpler approach is to use the second form of the builtin iter 
function which takes a callable and a sentinel:

py> def getint():
... return int(raw_input('Number? '))
...
py> numbers = sorted(iter(getint, 0))
Number? 3
Number? 7
Number? 5
Number? 2
Number? 0
py> numbers
[2, 3, 5, 7]
Note that I've renamed 'list' to 'numbers' so as not to hide the builtin 
type 'list'.

variableMean = lambda x:sum(x)/len(x)
variableMedian =  lambda x: x.sort() or x[len(x)//2]
variableMode = lambda x: max([(x.count(y),y) for y in x])[1]
s = variableMean(list)
y = variableMedian(list)
t = variableMode (list)
See "Inappropriate use of Lambda" in 
http://www.python.org/moin/DubiousPython.

Lambdas aside, some alternate possibilities for these are:
def variable_median(x):
# don't modify original list
return sorted(x)[len(x)//2]
def variable_mode(x):
# only iterate through x once (instead of len(x) times)
counts = {}
for item in x:
counts[x] = counts.get(x, 0) + 1
# in Python 2.5 you'll be able to do
# return max(counts, key=counts.__getitem__)
return sorted(counts, key=counts.__getitem__, reverse=True)[0]
Note also that you probably want 'from __future__ import divsion' at the 
top of your file or variableMean will sometimes give you an int, not a 
float.

x = (s,y,t)
inp = open ("Wade_StoddardSLP3-2.py", "r")
outp = open ("avg.py", "w")
f = ("avg.py")
for x in inp:
outp.write(x)
import pickle
pickle.dump(x, f)
If you want to save s, y and t to a file, you probably want to do 
something like:

pickle.dump((s, y, t), file('avg.pickle', 'w'))
I don't know why you've opened Wade_StoddardSLP3-2.py, or why you write 
that to avg.py, but pickle.dump takes a file object as the second 
parameter, and you're passing it a string object, "avg.py".

f = open("avg.py","r")
avg.py = f.read()
print 'The Mean average is:', mean
print 'The Median is:', meadian
print 'The Mode is:', mode
mean, median, mode = pickle.load(file('avg.pickle'))
print 'The Mean average is:', mean
print 'The Median is:', meadian
print 'The Mode is:', mode
HTH,
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: copying or moving the mail message using imaplib

2005-02-21 Thread Raghul
Thanks for ur message .How it is possible to copy the  messages betwwen
folder ?I can't understand the copy function in python documentation.
Please Can u give me a sample example for this. And I also to copy
using uid but in vain. here is my program.

#!/usr/bin/env python
#Normal Library
import socket
import os
import re
import time
import sys
import getopt
import types
import traceback
import email
import mhlib,popen2


import string, random
import StringIO, rfc822

import email.Parser
from getpass import getpass
from email.Header import Header
from email.Utils import parsedate
from imaplib import IMAP4 as BaseIMAP
from email.Message import Message
from email.Header import Header
# Antispam database lib


class IMAPSession(BaseIMAP):

   def __init__(self, server, port, debug=0, do_expunge=False):

BaseIMAP.__init__(self, server, port)



   def getsizes(imap, msgs):
uidfetchbatchsize =25
res2=[]

# Python really needs do - while
while 1:
if len(msgs)==0: break
if len(msgs)>uidfetchbatchsize:
msgmore=msgs[uidfetchbatchsize:]
msgs=msgs[:uidfetchbatchsize]
else:
msgmore=[]
msgs=string.join(msgs, ',')
res=imap.uid("FETCH", msgs, "(UID RFC822.SIZE)")
assertok(res, "uid fetch", msgs, "(UID RFC822.SIZE)")
for i in res[1]:
mo=gsre.match(i)
if mo is None:
if verbose: print "getsize Eh?", i
else:
res2.append((mo.group(2), mo.group(1)))
msgs=msgmore
return res2




def run():
import getpass
#name = raw_input("Enter User name : ")
passwd = getpass.getpass ("Enter the password : ")
server ="mail.myhost.com"
port = 143
ss = IMAPSession(server,port)
sd = ss.login ("raghul",passwd)
uidfetchbatchsize =25
print ss.list()
print ss.select('Junk E-mail')
typ, data = ss.search(None,"ALL" )
for num in data[0].split():
  typ, data = ss.fetch(num, '(RFC822)')
  print 'Message %s\n%s\n' % (num, data[0][1])
  print "_"
  dat = ss.uid('copy',num,'INBOX')
  print "copied"
  print dat
  print num
  print "_"
ss.logout()











if __name__ == '__main__':
run()

-- 
http://mail.python.org/mailman/listinfo/python-list


which parser to use

2005-02-21 Thread a_nuther

I'm building something that requires parsing a rather complex
language. I'd like to do the whole application, including the
lex/parse phase, in Python (for development/debug speed), and only
move parts of it to a compiled language if execution speed absolutely
dictates. So, what i'm looking for in a Python parser is:

1) reliability (don't want to debug a parser)
1) flexibility (i do a lot of refactoring)
2) E/BNF friendliness (working from a spec)
3) speed (moderate speed will do; glacial won't)

Does anyone have any familiarity with some of the several Python
parsers out there? Any pointers to comparisons (as opposed to surveys)
of _several_ of the Python parsers would be much appereciated. (I've
seen the YAPPS/Spark comparison.) If none of the Python parsers really
fit the bill, any thoughts on ANTLR, Spirit, etc?

Thanks in advance,
E

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: NOOB coding help....

2005-02-21 Thread James Stroud
Could you phrase this in the form of a question, like Jeopardy?


On Monday 21 February 2005 08:08 pm, Igorati wrote:
> Ok, this is what I have so far:
>
> #This program will ask for a user to imput numbers. The numbers will then
> be calculated
> #to find the statistical mean, mode, and median. Finallly the user will be
> asked
> #if he would like to print out the answers.
> list = [ ]
> a = 1
> print 'Enter numbers to add to the list. (Enter 0 to quit.)'
> while a != 0 :
> a = input('Number? ')
> list.append(a)
> zero = list.index(0)
> del list[zero]
> list.sort()
>
> variableMean = lambda x:sum(x)/len(x)
> variableMedian =  lambda x: x.sort() or x[len(x)//2]
> variableMode = lambda x: max([(x.count(y),y) for y in x])[1]
> s = variableMean(list)
> y = variableMedian(list)
> t = variableMode (list)
>
> x = (s,y,t)
> inp = open ("Wade_StoddardSLP3-2.py", "r")
> outp = open ("avg.py", "w")
> f = ("avg.py")
> for x in inp:
> outp.write(x)
> import pickle
> pickle.dump(x, f)
>
>
> print 'Thank you! Would you like to see the results after calculating'
> print 'The mode, median, and mean? (Please enter Yes or No)'
> raw_input('Please enter Yes or No:')
> if raw_input == Yes:
>
> f = open("avg.py","r")
> avg.py = f.read()
> print 'The Mean average is:', mean
> print 'The Median is:', meadian
> print 'The Mode is:', mode
>
> I am attempting to make it so that I can save the mean, meadian, and mode
> and then if the user wants the data to give it to him. Thank you for any
> assistance you can provide!
>
> Wade

-- 
James Stroud, Ph.D.
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: copying or moving the mail message using imaplib

2005-02-21 Thread Tony Meyer
> My problem is I want to move the mail message to other folder in 
> the mail using imaplib (E.g) I want to move a message from 
> the inbox to the Draft folder in my account using python 
> code. Can any one help me by giving a sample code to do this?

IMAP is a terrible terrible protocol.  It is not possible to move messages,
whatever language you're using to interact with the IMAP server.

You can copy the message to the new folder (copy() function) and then mark
the old copy as deleted (store() function) but you then either have lots of
/Deleted messages in the original folder, or need to purge/expunge it and
remove any other messages that are /Deleted as well.

The python imaplib is a very thin wrapper over the IMAP protocol.  If you
want to use it, then I highly recommend that you do so with a copy of the
IMAP RFC handy (it's really just simple translation from the raw IMAP codes
to Python code).

=Tony.Meyer

-- 
http://mail.python.org/mailman/listinfo/python-list


NOOB coding help....

2005-02-21 Thread Igorati
Ok, this is what I have so far:

#This program will ask for a user to imput numbers. The numbers will then
be calculated
#to find the statistical mean, mode, and median. Finallly the user will be
asked
#if he would like to print out the answers.
list = [ ] 
a = 1 
print 'Enter numbers to add to the list. (Enter 0 to quit.)'
while a != 0 :
a = input('Number? ')
list.append(a)
zero = list.index(0)
del list[zero]
list.sort() 

variableMean = lambda x:sum(x)/len(x)
variableMedian =  lambda x: x.sort() or x[len(x)//2]
variableMode = lambda x: max([(x.count(y),y) for y in x])[1]
s = variableMean(list)
y = variableMedian(list)
t = variableMode (list)

x = (s,y,t)
inp = open ("Wade_StoddardSLP3-2.py", "r")
outp = open ("avg.py", "w")
f = ("avg.py")
for x in inp:
outp.write(x)
import pickle
pickle.dump(x, f)


print 'Thank you! Would you like to see the results after calculating'
print 'The mode, median, and mean? (Please enter Yes or No)'
raw_input('Please enter Yes or No:')
if raw_input == Yes:

f = open("avg.py","r")
avg.py = f.read()
print 'The Mean average is:', mean
print 'The Median is:', meadian
print 'The Mode is:', mode

I am attempting to make it so that I can save the mean, meadian, and mode
and then if the user wants the data to give it to him. Thank you for any
assistance you can provide!

Wade

-- 
http://mail.python.org/mailman/listinfo/python-list


about uid in imaplib

2005-02-21 Thread Raghul
Hi guys,
 How to use "uid" and copy a message to the other folders using
python.Please help in explainig with sample code.I think,imaplib uid
object need atleast a sample to understand clearly.

-- 
http://mail.python.org/mailman/listinfo/python-list


copying or moving the mail message using imaplib

2005-02-21 Thread Raghul
Hi Friends,

I am doing project in python.I am new to this. My problem
is I want to move the mail message to other folder in the mail using
imaplib (E.g) I want to move a message from the inbox to the Draft
folder in my account using python code. Can any one help me by giving a
sample code to do this?


Thanks in advance

-- 
http://mail.python.org/mailman/listinfo/python-list


pyrex just in time compilation

2005-02-21 Thread Simon Wittber
It occured to me that an import hook could be written for  pyrex
'.pyx' files, so that compilation can occur at runtime, if the source
file has changed since the last compile.

Before I try this myself, has anyone else already written any code to do this?

Sw.
-- 
http://mail.python.org/mailman/listinfo/python-list


PyGTA next meeting: Tuesday February 22, 7-9pm at offices of Frogware (not our usual location!)

2005-02-21 Thread Peter Hansen
We're announcing here in case anyone who doesn't subscribe to our
announcement mailing list was thinking of attending:
  NOTE the change in location from where we've been meeting for the
  last 12 months!!
The next meeting of PyGTA, the Toronto-area Python user group, will be
held at the offices of Frogware (http://www.frogware.com/) at:
  477 Richmond Street West,
  Suite 210, Toronto, Ontario
on Tuesday, February 22nd, 2005, 7pm to 9pm.
Here's a link using the Google Maps Beta:
http://maps.google.com/maps?q=477%20Richmond%20Street%20West%2C%20Toronto
Note also that as of this moment, we have no official speaker.  If
you would like to reserve time to talk about your own Python-related
project, please let us know!
-Ian and Peter, meeting organizers
P.S.:  We'd also like to take this opportunity to publicly
thank Givex (http://web.givex.com/) and D'Arcy Cain for generously
hosting our meetings for the last year.
--
http://mail.python.org/mailman/listinfo/python-list


pyGoogle is fun and easy to use, and thinks Python is the best programming language

2005-02-21 Thread rdsteph
I am having a lot of fun using the pyGoogle module (
http://pygoogle.sourceforge.net/ ) that uses the Google API. It is
about as easy to use as I can imagine, and it is a lot nicer than using
my old HTMl screen scraping habits.


My online CGI program Ask Merlin at www.awaretek.com/askmerlin.html is
an example. Currently, the program takes any user's question and picks
the best answer from amongst the possible answers given by the user.
The program uses an algorithm that uses an intelligent analysis of
search results from Google. OK, OK, I know already, that this is of
limited utility compared to answering any question without requiring
the user to give options to choose from; and, furthermore i know full
well that at this point Merlin is far from foolproof even when given
options to choose amongst. Still, if you play with it for a while you
will be amazed at how well it does do.


Moreover, I am hard at work on a version that will answer any question
without being given options, by choosing options from Google search
results that are most appropriate and then applying my "intelligent"
algorithm.


But hey, even as it stands, when queried "which is the best programming
language to use for ease of use," Merlin picks Python from amongst a
list of python, ruby, ADA and java. When queried "which language is the
best programming language to use for a large project requiring realtime
operation and involving life and death issues of human life", Merlin
picks ada out of the same list. And, when just plain asked "what is the
best programming language" Merlin wisely picks Python from the list.
And I assure you that none of this is "hard coded" but instead just
uses the regular algorithm applied to any other question ;-


OK, it's just a fun little hack by a very amateurish hacker; but that's
sort of the point. Just think what a good programmer could do with
pyGoogle ;-

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to write a ping client

2005-02-21 Thread Grant Edwards
On 2005-02-22, Harlin <[EMAIL PROTECTED]> wrote:

> Is there a way to write a ping client? 
[...]

http://www.google.com/search?q=python+icmp+ping

-- 
Grant Edwards   grante Yow!  I have the power
  at   to HALT PRODUCTION on all
   visi.comTEENAGE SEX COMEDIES!!
-- 
http://mail.python.org/mailman/listinfo/python-list


How to write a ping client

2005-02-21 Thread Harlin
Is there a way to write a ping client? I would like to be able to write
a small ping client so that I dont have to do os.system('ping args')
and thereby keep the resource overhead low. Does anyone know how this
can be done or can point me in the right direction?

thanks,

Harlin

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subclassing Decimal

2005-02-21 Thread [EMAIL PROTECTED]
STeVe,

Thanks for the response.  Very clear.

yea-though-I-walk-thru-the-valley-of-__new__-I-will-fear-no-super-ly
y'rs,

-Jeff

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MatPlotLib.MatLab troubles (how to install/run matplotlib.PyLab?)

2005-02-21 Thread John Hunter
> "Colombes" == Colombes  <[EMAIL PROTECTED]> writes:

Colombes> matplotlib.matlab deprecated, please import
Colombes> matplotlib.pylab or simply pylab instead.  See
Colombes> http://matplotlib.sf.net/matplotlib_to_pylab.py for a
Colombes> script which explains this change and will automatically
Colombes> convert your python scripts that use matplotlib.matlab.
Colombes> This change was made because we were concerned about
Colombes> trademark infringement on The Mathwork's trademark of
Colombes> matlab.

Colombes> Unfortunately, the above URL does not exist.

Oops -- that should be
http://matplotlib.sourceforge.net/matlab_to_pylab.py

In a nutshell, wherever you previously imported matplotlib.matlab you
can import matplotlib.pylab or equivalently, simply pylab

OLD:
from matplotlib.matlab import plot

NEW:
from pylab import plot

The script linked above will recursively search and replace these
strings for you in your scripts directory.

JDH
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A few q's on python files.

2005-02-21 Thread Larry Bates
On windows there's py2exe which packs a python program
so that it can be distributed "like" and .exe, but Python
is a bytecode language (a la Java) so it is never actually
compiled into machine language.  The .pyc files are the
bytecode that is actually executed.  For C programmers
this takes some getting accustomed to.

Larry Bates

Joseph Quigley wrote:
> hiya,
> i'm new to python (by a week) but am learning fast (that's what I like
> about python--it's simplicity). I got disgusted with C and C++ (i was
> learning) probably because of a bad copy of Visual C++ 6.0 that gave me
> errors.
> 
> I noticed that IDLE doesn't have an option to allow you to convert a .py
> or pyc. file into an executable. Why? Am i wrong? Where can I find one
> (if I'm right)?
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


UTF-8 / German, Scandinavian letters - is it really this difficult?? Linux & Windows XP

2005-02-21 Thread Mike Dee

   A very very basic UTF-8 question that's driving me nuts:

If I have this in the beginning of my Python script in Linux:

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

should I - or should I not - be able to use non-ASCII characters 
in strings and in Tk GUI button labels and GUI window titles and in 
raw_input data without Python returning wrong case in manipulated 
strings and/or gibberished characters in Tk GUI title? 



With non-ASCII characters I mean ( ISO-8859-1 ??) stuff like the 
German / Swedish / Finnish / etc "umlauted" letter A  (= a diaresis; 
that is an 'A' with two dots above it, or an O with two dots above.)

In Linux in the Tk(?) GUI of my 'program' I get an uppercase "A" 
with a tilde above - followed by a general currency symbol ['spider']. 
That is, two wrong characters where a small umlauted letter "a" 
should be. 

But in Windows XP exactly the *same* code (The initiating "#!/usr/bin
/env python" and all..) works just fine in the Tk GUI - non-ascii 
characters showing just as they should. (The code in both cases is 
without any u' prefixes in strings.)



I have UTF-8 set as the encoding of my Suse 9.2 / KDE localization, I 
have saved my 'source code' in UTF-8 format and I have tried to read
*a lot* of information about Unicode and I have heard it said many 
times that Python handles unicode very well -- so why can it be so 
bl**dy difficult to get an umlauted (two-dotted) letter a to be 
properly handled by Python 2.3? In Windows I have Python 2.4 - but the 
following case-insanity applies for Windows-Python as well:

For example, if I do this in my Linux konsole (no difference whether it 
be in KDE Konsole window or the non-gui one via CTRL-ALT-F2):

>>>aoumlautxyz="12xyz"   # number 1 = umlauted a, number 2 = uml o 
>>>print aoumlautxyz.(upper)

then the resulting string is NOT all upper case - it is a lowercase 
umlauted a, then a lowercase umlauted o then uppercase XYZ

And command:

>>> print aoumlautxyz.title()

..results in a string where a-umlaut, o-umlaut and yz are lowercase and 
only the Z in the middle is uppercase.  

this >>>print aoumlautxyz.lower()  

.. prints o.k. 


Am I missing something very basic here? Earlier there was a difference in 
my results between running the scripts in the CTRL ALT F2-konsole and the 
KDE-one, but I think running unicode_start & installing an unicode console
font at some point of time ironed that one out.

If this is due to some strange library, could someone please give me a 
push to a spot where to read about fixing it? Or am I just too stupid, 
and that's it. (I bet that really is what it boils down to..)




I cannot be the only (non-pro) person in Europe who might need to use non-
ASCII characters in GUI titles / button labels, in strings provided by the 
users of the software with raw_input (like person's name that begins with 
an umlauted letter or includes one or several of them) ..in comments, and 
so on.

How would you go about making a script where a) the user types in any text 
(that might or might not include umlauted characters) and b) that text then 
gets uppercased, lowercased or "titled" and c) printed? 

Isn't it enough to have that 'UTF-8 encoding declaration' in the beginning,
and then just like get the user's raw_input, mangle it about with .title() 
or some such tool, and then just spit it out with a print statement?

One can hardly expect the users to type characters like unicode('\xc3\
xa4\xc3\xb6\xc3\xbc', 'utf-8')u'\xe4\xf6\xfc' u"äöü".encode('utf-8') or 
whatnot, and encode & decode to and fro till the cows come home just to 
get a letter or two in their name to show up correctly. 

It's a shame that the Linux Cookbook, Learning Python 2nd ed, Absolute 
beginners guide to Python, Running Linux, Linux in a Nutshell, Suse 9.2 
Pro manuals and the online documentation I have bumped into with Google
(like in unicode.org or python.org or even the Python Programming Faq 
1.3.9 / Unicode error) do not contain enough - or simple enough - 
information for a Python/Linux newbie to get 'it'.

For what it's worth, in Kmail my encoding iso ISO8859-1. I tried that 
coding one in my KDE and my Python scripts, earlier too, but it was 
no better; actually that was why I started this Unicode sh..  ..thing. 


Am I beyond hope?




Mike d 


-- 
http://mail.python.org/mailman/listinfo/python-list


MatPlotLib.MatLab troubles (how to install/run matplotlib.PyLab?)

2005-02-21 Thread Dr. Colombes
On my home laptop computer, I'm trying to install the appropriate
modules so that  Python version 2.3.3 and IDLE version 1.0.2 (with an
"import matplotlib.matlab" statement) can produce nice MatLab-like
plots.

I have a matplotlib.matlab-capable Python set-up running OK on my
office desktop, which I obtained after downloading and installing a few
more modules (numarray and numeric, I think).

Now I get the following message about matplotlib.matlab being
deprecated:

-

matplotlib.matlab deprecated, please import matplotlib.pylab or simply
pylab instead.  See http://matplotlib.sf.net/matplotlib_to_pylab.py
for a script which explains this change and will automatically convert
your python scripts that use matplotlib.matlab.  This change was made
because we were concerned about trademark infringement on The
Mathwork's trademark of matlab.

---

Unfortunately, the above URL does not exist.

Thanks for suggestions, any help you can offer.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Accessing files installed with distutils

2005-02-21 Thread John Machin

Frans Englich wrote:
> This is silly. How do I access data files I've installed with
distutils? In a
> portable, generic way, I want to find out what is the following path
on most
> systems:
>
> /usr/local/lib/python2.4/lib/site-packages/foo/bar.txt

Most systems? A tad *nix-centric, yes/no?

>
> How do I figure out the rest, if I know foo/bar.txt? sys.prefix
doesn't get me
> far.

This hint may be useful:

>>> import sys
>>> sys.modules['readline'].__file__
'c:\\Python24\\lib\\site-packages\\readline\\__init__.pyc'

but it may not work if the caller does "from yourmodule import ."
or "import yourmodule as ym". Over to you.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: recommended way of generating HTML from Python

2005-02-21 Thread John J. Lee
Matt Goodall <[EMAIL PROTECTED]> writes:
[...]
> Agreed. Although I would go further and say that it's important to
> choose a templating system that allows the Python developer to annotate
> XHTML templates using **valid XML**, i.e. no "for x in y" loops, no "if
> foo" conditionals, no "i = 0" variable setting, no expression
> evaluations, etc.
[...]

Why does use of a templating system whose documemts are valid XML
imply no loops, conditionals, expression evaluation etc.?

Or are you just talking about particular (non-XML) syntaxes for these
constructs?


John
-- 
http://mail.python.org/mailman/listinfo/python-list


wxPython

2005-02-21 Thread GuyBrush Treepwood
I just compiled and installed wxWidgets and wxPython.
When I want to test this libraries, I get:


Python 2.4 (#1, Feb 19 2005, 19:24:31)
[GCC 3.3.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from wxPython.wx import *
Traceback (most recent call last):
  File "", line 1, in ?
  File 
"/usr/local/lib/python2.4/site-packages/wx-2.5.3-gtk2-ansi/wxPython/__init__.py",
 line 10, in ?
import _wx
  File 
"/usr/local/lib/python2.4/site-packages/wx-2.5.3-gtk2-ansi/wxPython/_wx.py", 
line 3, in ?
from _core import *
  File 
"/usr/local/lib/python2.4/site-packages/wx-2.5.3-gtk2-ansi/wxPython/_core.py", 
line 15, in ?
import wx._core
  File 
"/usr/local/lib/python2.4/site-packages/wx-2.5.3-gtk2-ansi/wx/__init__.py", 
line 42, in ?
from wx._core import *
  File "/usr/local/lib/python2.4/site-packages/wx-2.5.3-gtk2-ansi/wx/_core.py", 
line 4, in ?
import _core_
ImportError: libwx_gtk2_xrc-2.5.so.3: cannot open shared object file: No such 
file or directory

I installed wxWidgets in /opt/wx/2.5 as described in
http://www.wxpython.org/BUILD.html.

$ls /opt/wx/2.5/lib | grep wx
libwx_baseud-2.5.so@
libwx_baseud-2.5.so.3@
libwx_baseud-2.5.so.3.0.0*
libwx_baseud_net-2.5.so@
libwx_baseud_net-2.5.so.3@
libwx_baseud_net-2.5.so.3.0.0*
libwx_baseud_xml-2.5.so@
libwx_baseud_xml-2.5.so.3@
libwx_baseud_xml-2.5.so.3.0.0*
libwx_gtk2ud_adv-2.5.so@
libwx_gtk2ud_adv-2.5.so.3@
libwx_gtk2ud_adv-2.5.so.3.0.0*
libwx_gtk2ud_core-2.5.so@
libwx_gtk2ud_core-2.5.so.3@
libwx_gtk2ud_core-2.5.so.3.0.0*
libwx_gtk2ud_gizmos-2.5.so@
libwx_gtk2ud_gizmos-2.5.so.3@
libwx_gtk2ud_gizmos-2.5.so.3.0.0*
libwx_gtk2ud_gl-2.5.so@
libwx_gtk2ud_gl-2.5.so.3@
libwx_gtk2ud_gl-2.5.so.3.0.0*
libwx_gtk2ud_html-2.5.so@
libwx_gtk2ud_html-2.5.so.3@
libwx_gtk2ud_html-2.5.so.3.0.0*
libwx_gtk2ud_ogl-2.5.so@
libwx_gtk2ud_ogl-2.5.so.3@
libwx_gtk2ud_ogl-2.5.so.3.0.0*
libwx_gtk2ud_stc-2.5.so@
libwx_gtk2ud_stc-2.5.so.3@
libwx_gtk2ud_stc-2.5.so.3.0.0*
libwx_gtk2ud_xrc-2.5.so@
libwx_gtk2ud_xrc-2.5.so.3@
libwx_gtk2ud_xrc-2.5.so.3.0.0*
wx/

I seem to have the necessary libraries installed, but with a *ud* pattern
in their name.

Any advice here?

-- 
http://mail.python.org/mailman/listinfo/python-list


Mixing Txinter and Pygame

2005-02-21 Thread Tim Knauf
Hi everyone, I'm glad to have found this list.
I've written a small script for my own use which, amongst other things, 
captures mouse click information from a window containing an image. I 
used Pygame to manage the image window, as it was the easiest way to 
implement the functionality I needed. The surrounding interface windows 
(there are two) are constructed with Tkinter.

Despite their unholy union, Pygame and Tkinter seem, generally, to 
cooperate. I'm using this main loop to update one, then the other:

while 1:
   gameLoop() # This function pumps the Pygame events and checks for 
mouse and keyboard events
   pygame.time.wait(10)
   mainwin.update() # mainwin is an instance of Application class, 
which is a child of Tkinter.frame

I have my interface set up so that when *any* of the windows' close 
boxes are clicked, this function will be called:

# This portion of the Pygame loop calls doquit() when it gets a 'QUIT' 
event...
def gameLoop():
   pygame.event.pump()
   for event in pygame.event.get():
   if event.type == QUIT:
   doquit()
   # Etc.

   # And this portion of the Tkinter interface sets the 
WM_DELETE_WINDOW protocol to call doquit()
   def createWidgets(self):
   self.title("Region Management")
   self.geometry('+830+8')
   self.protocol("WM_DELETE_WINDOW", doquit)
   # Etc.

# A temporary file is removed, and both Pygame and Tkinter are 
instructed to quit
def doquit():
   if os.access('recalc.tmp', os.F_OK):
   os.remove('recalc.tmp')
   pygame.quit()
   mainwin.master.destroy()

Perhaps you've begun to see where I might be having problems. You see, 
if I close the script by closing the Pygame window, I get this exception:

Traceback (most recent call last):
 File "D:\Development\Python\sludge helpers\addScreenRegion 
helper.pyw", line 363, in ?
   mainwin.update()
 File "C:\Python24\lib\lib-tk\Tkinter.py", line 859, in update
   self.tk.call('update')
TclError: can't invoke "update" command:  application has been destroyed

Conversely, if I close the application by closing a Tkinter window, I 
get this exception:

Traceback (most recent call last):
 File "D:\Development\Python\sludge helpers\addScreenRegion 
helper.pyw", line 361, in ?
   gameLoop()
 File "D:\Development\Python\sludge helpers\addScreenRegion 
helper.pyw", line 203, in gameLoop
   pygame.event.pump()
error: video system not initialized

Obviously, Pygame doesn't like Tkinter telling it to quit (when it's 
trying to do something from its internal loop) and vice versa. Is there 
a simple way that I can avoid getting these exceptions on exit, or have 
I taken the wrong approach? Everything else appears to work fine. Please 
do excuse me if this seems a silly question, as I'm fairly new to Python 
and Pygame, and a total novice when it comes to Tkinter.

On a side note, has anyone else found the Tkinter documentation awfully 
obscure? I've found Python a joy to learn about, and Pygame's tutorials 
are a lot of fun. I can't say the same for Tkinter, and found myself 
having to do many Google searches before I uncovered information I could 
put to use. Has anyone found any high-quality (online) documentation 
that proves me wrong? :^)

Thanks in advance,
Tim Knauf
--
http://mail.python.org/mailman/listinfo/python-list


Re: [EVALUATION] - E02 - Support for MinGW Open Source Compiler

2005-02-21 Thread Ilias Lazaridis
George Sakkis wrote:
"Ilias Lazaridis" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
Nick Vargish wrote:
You can excuse yourself from this one and stop replying to comments,
but you don't get to unilaterally declare a discussion over.
[...]
The discussion is over.
At least the in-topic one.
Everything else is babbling, hairsplitting, playing an AI which does not
understand writings and all this unproductive garbage.
The Essence is this one, as stated before:
[huge copy paste of previous post]
The Essence is irrelevant.
It seems that this is true.
-
-
-
All your thread are belong to us.
This is true ["us" = a few off-topic-freaks]
-
-
-
George
[EVALUATION] - E02 - Support for MinGW Open Source Compiler
Essence:
http://groups-beta.google.com/group/comp.lang.python/msg/5ba2a0ba55d4c102
.
--
http://lazaridis.com
--
http://mail.python.org/mailman/listinfo/python-list


A few q's on python files.

2005-02-21 Thread Joseph Quigley
hiya,
i'm new to python (by a week) but am learning fast (that's what I like 
about python--it's simplicity). I got disgusted with C and C++ (i was 
learning) probably because of a bad copy of Visual C++ 6.0 that gave me errors.

I noticed that IDLE doesn't have an option to allow you to convert a .py or 
pyc. file into an executable. Why? Am i wrong? Where can I find one (if I'm 
right)?

--
http://mail.python.org/mailman/listinfo/python-list


Re: Tuple index

2005-02-21 Thread John Machin

Steve M wrote:
> John Machin wrote:
>
> >
> > Steve M wrote:
> >> I'm actually doing this as part of an exercise from a book. What
the
> > program
> >> is supposed to do is be a word guessing game. The program
automaticly
> >> randomly selects a word from a tuple.
> >
> > Care to tell us which book is using a tuple for this, but hasn't
got to
> > lists yet?
> >
> > Cheers,
> > John
>
> Python Programming for the absoulte beginner by Michael Dawson

In a review I found on the web:
http://www.skattabrain.com/css-books-plain/1592000738.html
"Dawson will take you by the hand and lead you down the garden path."

Malapropism? Intentional humour?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IDLE Problem: win98\Python2.4

2005-02-21 Thread "Martin v. Löwis"
kim kubik wrote:
A little knowledge is indeed a dangerous thing; forgive my
stupidity - it will happen again, so I'm apologizing in advance!
No need to apologize! This is a frequent mistake, and it might
be sensible to change Python to be more resistent against it.
For example, it might be possible to check whether TCL_LIBRARY
points to a "good" Tcl version if set, in lib-tk/FixTk.py.
Then, if it is somehow determined to be incorrect (i.e. by
containing an outdated tcldll, but no current one), TCL_LIBRARY
could be ignored, and the included library could be used.
Alternatively, a more detailed warning if import _tkinter
failed and TCL_LIBRARY is set could be produced (instead
of silently "fixing" the problem for the user).
Patches in this direction are welcome.
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: unicode encoding usablilty problem

2005-02-21 Thread "Martin v. Löwis"
aurora wrote:
What is the processing of getting a PEP work out? Does the work and  
discussion carry out in the python-dev mailing list? I would be glad to  
help out especially on this particular issue.
See PEP 1 for the PEP process. The main point is that discussion is
*not* carried out on any specific forum. But instead, the PEP serves
as a container for all possible considerations people come up with,
formally by writing to the PEP author. Of course, they will use
comp.lang.python and python-dev (and perhaps SIG mailing lists)
instead of writing to the PEP author, so the PEP author may need to
track these as well.
The process is triggered by the author posting revisions of the
PEP at a moderate rate, each time claiming "now I think it is
complete". Then, if nobody comes up with a reasoning that is
not yet covered in the PEP, it becomes ready for BDFL
pronouncement. It better also has an implementation at some point
in time.
For a dormant PEP, the prospective author should contact the
original author, and offer co-authoring. Perhaps the original
author even proposes that you can take over the entire thing
sometime.
Notice that, at some point, a patch implementing the PEP will
be needed. So you should indicate from the beginning whether you
are also willing to work on the implementation. If not, there is
a good chance that the PEP again goes dormant after the
specification is complete.
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Accessing files installed with distutils

2005-02-21 Thread Frans Englich

This is silly. How do I access data files I've installed with distutils? In a 
portable, generic way, I want to find out what is the following path on most 
systems:

/usr/local/lib/python2.4/lib/site-packages/foo/bar.txt

How do I figure out the rest, if I know foo/bar.txt? sys.prefix doesn't get me 
far.

I've googled, and looked in the python reference. I must be blind if the 
distutils section[1] covers this.


Cheers,

Frans

1.
http://www.python.org/doc/current/dist/dist.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: intersection of 2 list of pairs

2005-02-21 Thread John Machin

Pierre Quentel wrote:
> Another method is to build two sets of sets, one for E1 and one for
E2,
> then make the intersection of these sets
>
> - with Python 2.3
>
>  >>> E1=[('a','g'),('r','s')]
>  >>> E2=[('g','a'),('r','q'),('f','h')]
>  >>> from sets import Set,ImmutableSet
>  >>> f=Set([ImmutableSet(s) for s in E1])& Set([ImmutableSet(s) for s
in
> E2])
>  >>> [tuple(x) for x in f]
> [('a', 'g')]
>
> - with Python 2.4
>
>  >>> E1=[('a','g'),('r','s')]
>  >>> E2=[('g','a'),('r','q'),('f','h')]
>  >>> f=set([frozenset(s) for s in E1]) & set([frozenset(s) for s in
E2])
>  >>> [tuple(x) for x in f]
> [('a', 'g')]
>
> You must use ImmutableSet or frozenset to be able to create a set of
sets
>
> Pierre

The problem with using frozenset([x,y)) -- as compared to
(min(x,y),max(x,y))-- is that you don't get an *understandable*
canonical representation of the pair:

>>> frozenset(('a','b'))
frozenset(['a', 'b'])
>>> frozenset(('b','c'))
frozenset(['c', 'b'])

i.e. it depends on the Python hash function for the type/class being
used. Try explaining that to the first person you meet at the bus stop.
Exceptions prove the rule: if the OP regularly caught the same bus as
the timbot he wouldn't be asking questions like this :-)

In any case the OP still has a problem; when ('a','g') -- or ('g', 'a')
--pops out as the answer, he still doesn't know which list(s) the
duplicates are in, nor which way they are represented. To do something
useful, the output would have to be a list of lists, with the inner
list representing a cluster of duplicates. Each duplicate would be
represented by a unique identifier -- such as a tuple: (list_number,
index_in_that_list) -- so that it can be retrieved, inspected,
jettisoned, ...

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tuple index

2005-02-21 Thread Steve M
Steven Bethard wrote:

> Steve M wrote:
>> I'm actually doing this as part of an exercise from a book. What the
>> program is supposed to do is be a word guessing game. The program
>> automaticly randomly selects a word from a tuple. You then have the
>> oportunity to ask for a hint. I created another tuple of hints, where the
>> order of the hints correspond to the word order. I was thinking if I
>> could get the index position of the randomly selected word, I pass that
>> to the hints tuple to display the correct hint from the hints tuple. I'm
>> trying to do it this way as the book I'm using has not gotten to lists
>> yet.
> 
> I'm guessing it also hasn't gotten to dicts yet either?  Perhaps a
> somewhat more natural way of doing this would be something like:
> 
> py> hints = dict(word1="here's hint 1!",
> ...  word2="here's hint 2!",
> ...  word3="here's hint 3!")
> py> words = list(hints)
> py> import random
> py> selected_word = random.choice(words)
> py> selected_word
> 'word3'
> py> print hints[selected_word]
> here's hint 3!
> 
> That said, if you want to find the index of a word in a tuple without
> using list methods, here are a couple of possibilities, hopefully one of
> which matches the constructs you've seen so far:
> 
> py> t = ("fred", "barney", "foo")
> 
> py> for i, word in enumerate(t):
> ... if word == "barney":
> ... break
> ...
> py> i
> 1
> 
> py> for i in range(len(t)):
> ... if t[i] == "barney":
> ... break
> ...
> py> i
> 1
> 
> py> i = 0
> py> for word in t:
> ... if word == "barney":
> ... break
> ... i += 1
> ...
> py> i
> 1
> 
> HTH,
> 
> STeVe

Thanks Steve, I'll see if I can make that solution work for me.

Steve
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tuple index

2005-02-21 Thread Steve M
John Machin wrote:

> 
> Steve M wrote:
>> I'm actually doing this as part of an exercise from a book. What the
> program
>> is supposed to do is be a word guessing game. The program automaticly
>> randomly selects a word from a tuple.
> 
> Care to tell us which book is using a tuple for this, but hasn't got to
> lists yet?
> 
> Cheers,
> John

Python Programming for the absoulte beginner by Michael Dawson

Steve
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: high resolution time needed

2005-02-21 Thread Diez B. Roggisch
> I need a function returning a time value with a higher resolution that the
> standard 1sec unix timestamp. I found the clock() function in the time
> module, but that seems to return the same value (in the Python shell) each
> time I call it (Debian Linux speaking here).

Standard unix is a millisecond. And time.time() actually delivers a float
with sub-second precision. 



import time
t = time.time()
time.sleep(.25)
print time.time() - t


gives for me (also debian) 0.249767065048 secs.

-- 
Regards,

Diez B. Roggisch
-- 
http://mail.python.org/mailman/listinfo/python-list


high resolution time needed

2005-02-21 Thread Uwe Mayer
Hi,

I need a function returning a time value with a higher resolution that the
standard 1sec unix timestamp. I found the clock() function in the time
module, but that seems to return the same value (in the Python shell) each
time I call it (Debian Linux speaking here). 

Any ideas?

Thanks,
Uwe 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tuple index

2005-02-21 Thread Steven Bethard
Steve M wrote:
I'm actually doing this as part of an exercise from a book. What the program
is supposed to do is be a word guessing game. The program automaticly
randomly selects a word from a tuple. You then have the oportunity to ask
for a hint. I created another tuple of hints, where the order of the hints
correspond to the word order. I was thinking if I could get the index
position of the randomly selected word, I pass that to the hints tuple to
display the correct hint from the hints tuple. I'm trying to do it this way
as the book I'm using has not gotten to lists yet.
I'm guessing it also hasn't gotten to dicts yet either?  Perhaps a 
somewhat more natural way of doing this would be something like:

py> hints = dict(word1="here's hint 1!",
...  word2="here's hint 2!",
...  word3="here's hint 3!")
py> words = list(hints)
py> import random
py> selected_word = random.choice(words)
py> selected_word
'word3'
py> print hints[selected_word]
here's hint 3!
That said, if you want to find the index of a word in a tuple without 
using list methods, here are a couple of possibilities, hopefully one of 
which matches the constructs you've seen so far:

py> t = ("fred", "barney", "foo")
py> for i, word in enumerate(t):
... if word == "barney":
... break
...
py> i
1
py> for i in range(len(t)):
... if t[i] == "barney":
... break
...
py> i
1
py> i = 0
py> for word in t:
... if word == "barney":
... break
... i += 1
...
py> i
1
HTH,
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tuple index

2005-02-21 Thread John Machin

Steve M wrote:
> I'm actually doing this as part of an exercise from a book. What the
program
> is supposed to do is be a word guessing game. The program automaticly
> randomly selects a word from a tuple.

Care to tell us which book is using a tuple for this, but hasn't got to
lists yet?

Cheers,
John

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subclassing Decimal

2005-02-21 Thread Steven Bethard
[EMAIL PROTECTED] wrote:
I was interested in playing around with Decimal and
subclassing it.  For example, if I wanted a special
class to permit floats to be automatically converted
to strings.
from decimal import Decimal
class MyDecimal(Decimal):
def __init__(self, value):
if isinstance(value, float):
... initialize using str(float) ...
In the classic days, I would have added something
like this to MyDecimal __init__:
Decimal.__init__(self, str(value))
But I'm unfamiliar with the __new__ protocol.
__new__ is called to create a new instance of the class.  It is a 
staticmethod that gets passed as its first parameter the class to be 
created.  You should be able to do something like[1]:

py> import decimal
py> class MyDecimal(decimal.Decimal):
... def __new__(cls, value):
... if isinstance(value, float):
... value = str(value)
... return super(MyDecimal, cls).__new__(cls, value)
...
py> MyDecimal(3.0)
Decimal("3.0")
STeVe
[1] If you're really afraid of super for some reason, you can replace 
the line:
return super(MyDecimal, cls).__new__(cls, value)
with
return decimal.Decimal.__new__(cls, value)
--
http://mail.python.org/mailman/listinfo/python-list


Re: python2.4 generator expression > python2.3 list expression

2005-02-21 Thread Terry Reedy

"Christos TZOTZIOY Georgiou" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> On 21 Feb 2005 06:48:19 -0500, rumours say that Dan Sommers 
> <[EMAIL PROTECTED]>
>>for c in range( 128 ):
>>even_odd = 0
>>print '%3d' % c,
>>while c:
>>c &= c - 1
>>even_odd = not even_odd
>>print int( even_odd )
>
> Just for the sake of people who haven't messed with bit manipulation in C 
> or
> assembly, the effect of
> c &= c - 1
> is to reset the rightmost (less significant) '1' bit of a number (ie 
> change it
> to '0').

Cute.  I tried it a few times until I saw why it works.  But it is also 
dangerous (within a loop like the above) in a language like current Python 
(and unlike C/assembler) in which the binary representation of -1 is 
effectively a left infinite string of '1's: ...11

Terry J. Reedy



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tuple index

2005-02-21 Thread Steve M
Michael Hartl wrote:

> I actually find it strange that tuples don't have an index function,
> since finding the index doesn't involve any mutation.  Anyone know why
> Python doesn't allow a statement like t.index('foo')?
> 
> In any case, you can use the index method of list objects if you
> convert your tuple to a list first:
> 
 t = ("fred", "barney", "foo")
 list(t).index("foo")
> 2
 def index(a_tuple, element):
> ... return list(a_tuple).index(element)
> ...
 t[index(t, "foo")]
> 'foo'
> 
> (By the way, 'tuple' is a Python built-in type, so it's probably best
> to avoid using it as a variable name.)
> 
> 
> Michael
> 
> --
> Michael D. Hartl, Ph.D.
> CTO, Quark Sports LLC
> http://quarksports.com/

The book I'm using to learn Python with has not gotten to lists yet, maybe
next chapter.

I knew tuple is a built in type, I was just trying to be clear, I guess I
just muddied the water a bit. Thank you for your help.

Steve
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tuple index

2005-02-21 Thread Steve M
Steven Bethard wrote:

> Steve M wrote:
>> I guess I explained my problem incorrectly. Let me try again.
>> 
>> tuple = ("fred", "barney", "foo")
>> 
>> I know that foo is an element of tuple, but what I need to know is what
>> the index of foo is, tuple[?].
> 
> Larry Bates's solution is probably the best way to go here:
> 
> py> t = ("fred", "barney", "foo")
> py> list(t).index("foo")
> 2
> py> t[2]
> 'foo'
> 
> But note that if you're doing this often, you're probably using tuple
> for the wrong things.  Check out:
> 
> http://www.python.org/doc/faq
general.html#why-are-there-separate-tuple-and-list-data-types
> 
> If you're iterating over the items of something and the items are all of
>   the same type, you probably want a list, not a tuple.
> 
> What's the use case in which you want to do this?
> 
> STeVe

I'm actually doing this as part of an exercise from a book. What the program
is supposed to do is be a word guessing game. The program automaticly
randomly selects a word from a tuple. You then have the oportunity to ask
for a hint. I created another tuple of hints, where the order of the hints
correspond to the word order. I was thinking if I could get the index
position of the randomly selected word, I pass that to the hints tuple to
display the correct hint from the hints tuple. I'm trying to do it this way
as the book I'm using has not gotten to lists yet. As you may have guessed,
I'm just learning Python. I do appreciate your help, Thank you.

Steve
-- 
http://mail.python.org/mailman/listinfo/python-list


subclassing Decimal

2005-02-21 Thread [EMAIL PROTECTED]
I was interested in playing around with Decimal and
subclassing it.  For example, if I wanted a special
class to permit floats to be automatically converted
to strings.

from decimal import Decimal

class MyDecimal(Decimal):
def __init__(self, value):
if isinstance(value, float):
... initialize using str(float) ...

In the classic days, I would have added something
like this to MyDecimal __init__:

Decimal.__init__(self, str(value))

But I'm unfamiliar with the __new__ protocol.

Jeff Bauer
Rubicon, Inc.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tuple index

2005-02-21 Thread Steven Bethard
Michael Hartl wrote:
I actually find it strange that tuples don't have an index function,
since finding the index doesn't involve any mutation.  Anyone know why
Python doesn't allow a statement like t.index('foo')?
Tuples aren't really intended for this kind of use.  See:
http://www.python.org/doc/faq/general.html#why-are-there-separate-tuple-and-list-data-types
Tuples are supposed to be operated on as a group.  It's even been 
suggested occasionally on python-dev that in Python 3.0, tuples 
shouldn't support iteration at all...

STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tuple index

2005-02-21 Thread Steven Bethard
Steve M wrote:
I guess I explained my problem incorrectly. Let me try again.
tuple = ("fred", "barney", "foo")
I know that foo is an element of tuple, but what I need to know is what
the index of foo is, tuple[?].
Larry Bates's solution is probably the best way to go here:
py> t = ("fred", "barney", "foo")
py> list(t).index("foo")
2
py> t[2]
'foo'
But note that if you're doing this often, you're probably using tuple 
for the wrong things.  Check out:

http://www.python.org/doc/faq/general.html#why-are-there-separate-tuple-and-list-data-types
If you're iterating over the items of something and the items are all of 
 the same type, you probably want a list, not a tuple.

What's the use case in which you want to do this?
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tuple index

2005-02-21 Thread Michael Hartl
I actually find it strange that tuples don't have an index function,
since finding the index doesn't involve any mutation.  Anyone know why
Python doesn't allow a statement like t.index('foo')?

In any case, you can use the index method of list objects if you
convert your tuple to a list first:

>>> t = ("fred", "barney", "foo")
>>> list(t).index("foo")
2
>>> def index(a_tuple, element):
... return list(a_tuple).index(element)
...
>>> t[index(t, "foo")]
'foo'

(By the way, 'tuple' is a Python built-in type, so it's probably best
to avoid using it as a variable name.)


Michael

--
Michael D. Hartl, Ph.D.
CTO, Quark Sports LLC
http://quarksports.com/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: iterative lambda construction

2005-02-21 Thread Jack Diederich
On Mon, Feb 21, 2005 at 01:14:00PM -0800, Paul Rubin wrote:
> "markscottwright" <[EMAIL PROTECTED]> writes:
> > But when I try to do it iteratively, it just hangs when I try to
> > evaluate the results (for count > 1):
> > 
> > def repeated2(f, count):
> > newfun = f
> > for i in range(count-1):
> > newfun = lambda x: newfun(f(x))
> > return newfun
> > 
> > For the life of me, I can't figure out why.  It seems like for count =
> > 2, for example, the results from repeated2 should be lambda x: f(f(x)),
> > but it doesn't seem to be.
> 
> It's Python's scoping madness.  Try:
> 
>   def repeated2(f, count):
>  newfun = lambda x: x   # identity
>  for i in range(count):
>  newfun = lambda x, g=newfun: g(f(x))
>  return newfun

Ahh, but not sufficienty evil or pernicious.

def evil(f, count):
  def apply_evil(accum, func):
  return func(accum)
  def pernicious(x):
return reduce(apply_evil, [f]*count, x)
  return pernicious

def f(x):
return x+x

print evil(f, 3)(2)

More seriously I'd go without the recursion and just make a wrapper
that applies the function count times in a wrapper.

def benign(f, count):
  def wrap(x):
result = f(x)
for (i) in range(count-1):
  result = f(result)
return result
  return wrap

print benign(f, 3)(2)

-Jack
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: iterative lambda construction

2005-02-21 Thread Steven Bethard
markscottwright wrote:
Just for the hell of it, I've been going through the old Scheme-based
textbook "Structure and Interpretation of Computer Programs" and seeing
what I can and can't do with python.  I'm trying to create a function
that returns the function (not the results of the function, but a
function object) that results from applying function f to it's (single)
argument N times.  For example, if you have "def sq(x): return x*x",
then repeated(sq, 2)(2) = 16, repeated(sq, 3)(2) = 256, etc.
I can do it recursively, like this:
def repeated(f, count):
   if count == 1:
   return f
   else:
   return lambda x: f(repeated(f, count - 1)(x)
But when I try to do it iteratively, it just hangs when I try to
evaluate the results (for count > 1):
def repeated2(f, count):
newfun = f
for i in range(count-1):
newfun = lambda x: newfun(f(x))
return newfun
For the life of me, I can't figure out why.
Your problem is that lambdas (and defs) do late-binding.  Consider the 
following code:

py> newfun = (1).__add__
py> id(newfun)
18354384
py> newfun = lambda: sys.stdout.write('%s' % id(newfun))
py> id(newfun)
18217328
py> newfun()
18217328
Note that the id of 'newfun' is the same in the body of the lambda as 
the id of 'newfun' after the lambda is defined.  That is, if 'newfun' in 
the lambda were to be called, it would call the lambda function 
recursively, instead of calling the previous 'newfun'.  This is why 
you're getting infinite recursion.

The reason this happens is that, when a name is not bound by the 
argument list of a function, Python will look for that name in the 
enclosing scopes.  Since the lambda does not bind the name 'newfun', 
Python looks out to the enclosing scope to find 'newfun' (which, in this 
case, happens to be the funciton itself).

One solution to this problem is to bind the old function to a name in 
the argument list of your lambda[1]:

py> def repeated2(f, count):
... newfun = f
... for i in range(count - 1):
... def newfun(x, oldfun=newfun):
... return oldfun(f(x))
... return newfun
...
py> def square(x):
... return x**2
...
py> repeated2(square, 2)(2)
16
py> repeated2(square, 3)(2)
256
Another possibility would be to store the old function as part of a 
class instance:

py> class Composer(object):
... def __init__(self, outerfunc, innerfunc):
... self.outerfunc = outerfunc
... self.innerfunc = innerfunc
... def __call__(self, x):
... return self.outerfunc(self.innerfunc(x))
...
py> def repeated2(f, count):
... newfun = f
... for _ in range(count - 1):
... newfun = Composer(newfun, f)
... return newfun
...
py> repeated2(square, 2)(2)
16
py> repeated2(square, 3)(2)
256
Note that either way, you need some means to store the old value of 
newfunc.  In the first case, it's stored by binding it as a default 
value of one of the the function's arguments.  In the second case, it's 
stored as an instance attribute of a class.

STeVe
[1] I use def instead of lambda.  See "Inappropriate use of Lambda" in 
http://www.python.org/moin/DubiousPython
--
http://mail.python.org/mailman/listinfo/python-list


Re: Don't understand global variables between modules

2005-02-21 Thread Terry Reedy

"Bart" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> I don't understand globals between multiple modules in a python program.

Because there are not any.  All names are bound to objects in a module 
global namespace, a function local namespace, or an object attribute 
namespace.

The builtins seem like and act like intermodule 'globals', but their names 
are bound in a hidden module which is imported to all other modules and 
treated like an extension of each module's namespace.  Users can do 
something similar by defining a 'myglobals' module and importing it 
everywhere.

> I've narrowed it down to the following two very simple
> programs a.py and b.py. When I run a.py I get the following output:
>
> inc:  2
> A:  2
> inc:  3
> B:  3
> C:  1
> I don't understand the last line at all.

Don't feel too bad.  While I 'know' the answer -- running anyfile.py 
creates a module named '__main__' while importing it (in another module) 
creates a separate module named 'anyfile' -- it did not 'click' until 
reading Fredrik's hint.  You created a nice, memorable example that shows 
that __main__ is not anotherfile.anyfile (in this case, not b.a)!

Terry J. Reedy



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: iterative lambda construction

2005-02-21 Thread Andrew Koenig
"markscottwright" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Just for the hell of it, I've been going through the old Scheme-based
> textbook "Structure and Interpretation of Computer Programs" and seeing
> what I can and can't do with python.  I'm trying to create a function
> that returns the function (not the results of the function, but a
> function object) that results from applying function f to it's (single)
> argument N times.  For example, if you have "def sq(x): return x*x",
> then repeated(sq, 2)(2) = 16, repeated(sq, 3)(2) = 256, etc.
>
> I can do it recursively, like this:
>
> def repeated(f, count):
>   if count == 1:
>   return f
>   else:
>   return lambda x: f(repeated(f, count - 1)(x)
>
> But when I try to do it iteratively, it just hangs when I try to
> evaluate the results (for count > 1):
>
> def repeated2(f, count):
>newfun = f
>for i in range(count-1):
>newfun = lambda x: newfun(f(x))
>return newfun

The trouble is that Python's scoping rules are subtly different from 
Schemes, so you're binding to the wrong instance of newfun.  You should do 
this:

def repeated2(f, count):
newfun = f
for i in range(count-1):
newfun = lambda x, g=newfun: g(f(x))
return newfun

Alternatively, you could do it this way:

def repeated3(f, count):
def g(x):
for i in range(count):
x = f(x)
return x
return g


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: iterative lambda construction

2005-02-21 Thread Paul Rubin
"markscottwright" <[EMAIL PROTECTED]> writes:
> But when I try to do it iteratively, it just hangs when I try to
> evaluate the results (for count > 1):
> 
> def repeated2(f, count):
> newfun = f
> for i in range(count-1):
> newfun = lambda x: newfun(f(x))
> return newfun
> 
> For the life of me, I can't figure out why.  It seems like for count =
> 2, for example, the results from repeated2 should be lambda x: f(f(x)),
> but it doesn't seem to be.

It's Python's scoping madness.  Try:

  def repeated2(f, count):
 newfun = lambda x: x   # identity
 for i in range(count):
 newfun = lambda x, g=newfun: g(f(x))
 return newfun
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tuple index

2005-02-21 Thread Steve M
John Machin wrote:

> 
> Steve M wrote:
>> Hello,
>>
>> I'm trying to figure out the index position of a tuple
> member.
>> I know the member name, but I need to know the members index
> position.
> 
> Tuples, like lists, don't have members in the sense that they can be
> "named" like t.foo. The only way of referring to them is by index,
> t[4].
> 
>> I
>> know that if I use the statement print tuple[4] that it will print
> the
>> contents of that location. What I don't understand is if I know that
> foo is
>> a member of tuple, how do I get foo's index position.
> 
> You *can't* "know that foo is a member of tuple".
> 
> Consider this:
> 
 foo = 'carol'
 t = (123,456,789,'bob',foo,'ted')
 t[4]
> 'carol'
> 
> Is that what you mean by "foo is a member of t'? Well, it's not. foo is
> a reference to the string 'carol'. t[4] is also a reference to the
> string 'carol'.
> 
> Now read on ...
> 
 foo = 'alice'
 t
> (123, 456, 789, 'bob', 'carol', 'ted')
 t[4]
> 'carol'

> 
> Now foo is a reference to the string 'alice'. Nothing to do with t,
> either before or now.
> 
> Have you read the tutorial found at http://docs.python.org/tut/tut.html
> ?

I guess I explained my problem incorrectly. Let me try again.

tuple = ("fred", "barney", "foo")

I know that foo is an element of tuple, but what I need to know is what
the index of foo is, tuple[?]. Hopefully this explains what I'm trying 
do do better. Sorry about the earlier confusion.

Steve
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bug in email package?

2005-02-21 Thread Roman Suzi
On Sun, 20 Feb 2005, Steven Bethard wrote:
Erik Max Francis wrote:
Roman Suzi wrote:
I think that if any object (from standard library at least) doesn't support
iteration, it should clearly state so.
My guess is that 'for' causes the use of 'm[0]', which is (rightfully) an 
error...

Can this behaviour of email be considered a bug?
Is there a good case to iterate over something useful in a message
Why would it be a bug if the documentation never stated that the object was 
iterable?
I think the bug is not that an error is produced, but that the _wrong_ error 
is produced.  Trying to iterate over something that is not iterable should
Well, that was what I meant.
produce a TypeError saying so (not an Attribute error):
py> class C(object):
... pass
...
py> iter(C())
Traceback (most recent call last):
 File "", line 1, in ?
TypeError: iteration over non-sequence
I've actually seen something like this come up before (I think with 
email.Message even...)  I say call it a bug and submit a patch.
Ok. A bug minute on the next bug day ;-)
It's pretty 
easy to fix -- just add an __iter__ method to Message that raises a TypeError. 
That makes it clear that Message doesn't intend to support the getitem 
protocol -- it just does so accidentally because it provides __getitem__.

STeVe
Sincerely yours, Roman Suzi
--
[EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3
--
http://mail.python.org/mailman/listinfo/python-list


iterative lambda construction

2005-02-21 Thread markscottwright
Just for the hell of it, I've been going through the old Scheme-based
textbook "Structure and Interpretation of Computer Programs" and seeing
what I can and can't do with python.  I'm trying to create a function
that returns the function (not the results of the function, but a
function object) that results from applying function f to it's (single)
argument N times.  For example, if you have "def sq(x): return x*x",
then repeated(sq, 2)(2) = 16, repeated(sq, 3)(2) = 256, etc.

I can do it recursively, like this:

def repeated(f, count):
   if count == 1:
   return f
   else:
   return lambda x: f(repeated(f, count - 1)(x)

But when I try to do it iteratively, it just hangs when I try to
evaluate the results (for count > 1):

def repeated2(f, count):
newfun = f
for i in range(count-1):
newfun = lambda x: newfun(f(x))
return newfun

For the life of me, I can't figure out why.  It seems like for count =
2, for example, the results from repeated2 should be lambda x: f(f(x)),
but it doesn't seem to be.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Test for structure

2005-02-21 Thread Terry Reedy

"Steven Bethard" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> I don't like this idea much because it depends on str and unicode _not_ 
> having a particular function.  I haven't seen any guarantee anywhere that 
> str or unicode won't ever grow an __iter__ method.  So this code seems 
> dangerous as far as future compatibility goes.

When CPython's support for the old iteration protocol goes away, which I 
expects it will someday, strings will have to grow an __iter__ method. 
Even now, I think this difference between strings and lists is more of an 
accident than a logical design.  So the test is opaque and specific to 
current CPython.  The validity of something like a = a+'', however, is 
inherent to the nature of strings.

Terry J. Reedy



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyQt Python Bindings for Qt v3.14 Released

2005-02-21 Thread Jarek Zgoda
Phil Thompson napisał(a):
Riverbank Computing is pleased to announce the release of PyQt v3.14 available 
from http://www.riverbankcomputing.co.uk/.
Classes generated by puyic 3.13 are not compatible with PyQt 3.14 (some 
method signature incompatibilities). I cann't provide more details, as I 
regenerated all classes from *.ui files, but this may be reproductible.

--
Jarek Zgoda
http://jpa.berlios.de/ | http://www.zgodowie.org/
--
http://mail.python.org/mailman/listinfo/python-list


Re: - E02 - Support for MinGW Open Source Compiler

2005-02-21 Thread Nick Vargish
Grant Edwards <[EMAIL PROTECTED]> writes:

> I've never understood the problem with long URLs.  Many
> newsreaders let you click on them.  If not, you just cut/paste
> it into a browser (with a shellscript a couple lines long, you
> can start firefox with the URL on the X clipboard with a single
> command).

I use Gnus through a screen session, so when I select and copy a long
URL I get backslash characters in the copied text (as amusing as it
is, w3 is not a satisfying browsing experience for me :^). It's not
hard to manually pick out the backslashes, but it's time consuming and
kind of tedious. I use an open-source terminal app (iTerm under OS X),
so I guess I could hack the "open in browser" function to remove the
backslashes... Hmm...

Side projects aside, URLs less than 79 characters long are just easier
to handle in many ways.

Nick

-- 
#  sigmask  ||  0.2  ||  20030107  ||  public domain  ||  feed this to a python
print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?')
-- 
http://mail.python.org/mailman/listinfo/python-list


display VARCHAR(mysql) and special chars in html

2005-02-21 Thread Jonas Meurer
hello,

my script selects a comment saved as VARCHAR in MySQL and displays it
inside an html page.

the problem is, that the comment contains several special characters, as
mysterious utf-8 hyphens, german umlauts, etc.

i could write a function to parse the comment and substitute special
chars with the relevant html code, but maybe this already exists in some
module?

if not, it'll be hard work, as i've to consider many special chars, and
at least iso-8859-1* and utf-8 as charmaps.

bye
 jonas
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Test for structure

2005-02-21 Thread Steven Bethard
Martin Miller broke the order of reading again by top-posting:
However, to handle the more general problem of allow *any* argument to
be either a single item or a list seems to require a combination of
both EAPF and LBYL. This is the best solution I've been able to come up
with so far:
def asList(arg):
[snip]
if arg is None:
return []
elif isinstance(arg, basestring): # special case strings (to
  # avoid list())
return [arg]
else:
try:
return list(arg)
except TypeError:
return [arg]
[snip]
Can this be improved or is there anything wrong or overly limiting
about it?
I don't think you're going to do a whole lot better than that, though 
you can try something like the following if you're really afraid of the 
isinstance:

def aslist(arg):
# you don't need to test None; it will be caught by the list branch
try:
arg + ''
except TypeError:
return [arg]
try:
return list(arg)
except TypeError:
return [arg]
That said, I find that in most cases, the better option is to use *args 
in the original function though.  For example:

def f(arg):
args = aslist(arg)
...
f(42)
f(['spam', 'eggs', 'ham'])
could probably be more easily written as:
def f(*args):
...
f(42)
f('spam', 'eggs', 'ham')
Of course this won't work if you have multiple list arguments.
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: Real-Time Fluid Dynamics for Games...

2005-02-21 Thread Alberto Santini
You can find some screenshot in the Stam's original paper.
I didn't do any serious benchmark. I compared the speed
of C version with the Python one. It seems enough good.

I advice you to download from Stam's site paper and C code,
compile the C code and verify yourself the results.

I think the solver of Navier-Stokes equations is a piece
of cake(remember, it's patented): one page of code or less. :)

I don't like the use of global in the callback functions
of OpenGL.

-- 
Regards,
Alberto Santini


<[EMAIL PROTECTED]> ha scritto nel messaggio 
news:[EMAIL PROTECTED]
> Your two email addresses bouce emails back, so I post a shortened
> version of my comment here.
> I haven't installed:
> PyOpenGL-2.0.2.01.py2.4-numpy23
> glut-3.7.6
> Therefore at the moment I cannot try your interesting code.
> What's the speed of this Python code on your computer?
> I'd like to see a screenshoot of the running Python Program...
>
> Some people are doing in Python some things that require lots of
> computations, like:
> http://www.joachim-bauch.de/projects/python/pytrace
>
> Bye,
> Bearophile
> 


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: multimethod (or rather overloading) in Python

2005-02-21 Thread anton muhin
Nick Coghlan wrote:
anton muhin wrote:
anton muhin wrote:
Correction:
Of course, I can imagine some metaclasses magic that would allow to 
code:

class MyClass(WithOverloading):
  @overloadMethod(A)
  def someMetod(self, _): ...
But it would rather convoluted: the best idea I have so far is to 
mangle  methods name in the manner most of C++ compilers do.

PEAK has a fairly sophisticated implementation of method dispatch you 
may want to look at.

http://peak.telecommunity.com/Articles/WhatisPEAK.html
http://dirtsimple.org/2004/11/generic-functions-have-landed.html
http://peak.telecommunity.com/doc/src/dispatch/__init__.html
I'm compelled to point out that PEAK should still be considered a 'work 
in progress', but PJE's ideas should help you out :)

Cheers,
Nick.
Thank you very much, Nick!
anton.
--
http://mail.python.org/mailman/listinfo/python-list


Re: unicode encoding usablilty problem

2005-02-21 Thread Dieter Maurer
"Fredrik Lundh" <[EMAIL PROTECTED]> writes on Sat, 19 Feb 2005 18:44:27 +0100:
> "aurora" <[EMAIL PROTECTED]> wrote:
> 
> > I don't want to mix them. But how could I find them? How do I know this  
> > statement can be 
> > potential problem
> >
> >   if a==b:
> >
> > where a and b can be instantiated individually far away from this line of  
> > code that put them 
> > together?

I do understand aurora's problems very well.

Me, too, I had suffered from this occasionally:

   * some library decides to use unicode (without I had asked it to do so)

   * Python decides then to convert other strings to unicode
 and bum: "Unicode decode error".

I solve these issues with a "sys.setdefaultencoding(ourDefaultEncoding)"
in "sitecustomize.py".

I know that almost all the characters I have to handle
are encoded in "ourDefaultEncoding" and if something
converts to Unicode without being asked for, then this
is precisely the correct encoding.

I know that Unicode fanatists do not like "setdefaultencoding"
but until we will have completely converted to Unicode (which we probably
will do in the farer future), this is essential to keep sane...


Dieter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Test for structure

2005-02-21 Thread Martin Miller
Testing for the '__iter__' (or even '__getitem__') attribute doesn't
really address the problem, nor does trying to execute the statement
'itr = iter(a)'.

To use EAPF and answer the OP's original question, which was

> So how can I test if a variable 'a' is either a single character
> string or a list?

I think the best answer would be to use Robin Munn's suggestion (see
http://groups-beta.google.com/group/comp.lang.python/msg/c8befd4bed517bbc)
as mentioned in the link in Simon Brunning's post) namely:

try:
a + ''
except TypeError:
pass
else:
a = [a]

However, to handle the more general problem of allow *any* argument to
be either a single item or a list seems to require a combination of
both EAPF and LBYL. This is the best solution I've been able to come up
with so far:

def asList(arg):
"""Makes sure the argument it is passed is a Python list.
If it is, it is just returned, otherwise a (possibly empty)
list is created and returned with the single item in it.

asList() can used to create flexible interfaces which allow
arguments to be passed to them that are either single items or
lists of items. By applying this function before using the
values in arguments, single and multi-valued cases can be
handled by general list-handling code in the function or
method.

As a special case, a single argument with the value None is
converted into an empty list (instead of converted into the
list [None]).

asList(arg) ==> list
"""

if arg is None:
return []
elif isinstance(arg, basestring): # special case strings (to
  # avoid list())
return [arg]
else:
try:
return list(arg)
except TypeError:
return [arg]


if __name__ == "__main__":

def example(items=None):
"""Sample function that can be called with a single argument
that can be a single or list of items.
"""
itemList = asList(items)
if not itemList:
print "example() called with empty list or None argument"
else:
print "example() called with argument containing %d " \
  "thing%s" % \
  (len(itemList), ('','s')[len(itemList)>1])
for i, item in enumerate(itemList):
print "  items[%d] = %s" % (i, repr(item))

example(42)
example((1,2,3))
example([4,5,6,7])
example('abc')
example(u'def')
example(["aaa", 111, (4,5), 2.01])
example(None) #  Note that this will become an empty list
example() #  same in this case

Which produces the following output:

example() called with argument containing 1 thing
  items[0] = 42
example() called with argument containing 3 things
  items[0] = 1
  items[1] = 2
  items[2] = 3
example() called with argument containing 4 things
  items[0] = 4
  items[1] = 5
  items[2] = 6
  items[3] = 7
example() called with argument containing 1 thing
  items[0] = 'abc'
example() called with argument containing 1 thing
  items[0] = u'def'
example() called with argument containing 4 things
  items[0] = 'aaa'
  items[1] = 111
  items[2] = (4, 5)
  items[3] = 2.0098
example() called with empty list or None argument
example() called with empty list or None argument

Can this be improved or is there anything wrong or overly limiting
about it?

TIA,
Martin


=
Steven Bethard wrote:
> Terry Hancock wrote:
>  > But you probably shouldn't do that. You should probably just test
to
>  > see if the object is iterable --- does it have an __iter__ method?
>  >
>  > Which might look like this:
>  >
>  > if hasattr(a, '__iter__'):
>  > print "'a' quacks like a duck"
>
> Martin Miller top-posted:
> > I don't believe you can use the test for a __iter__ attribute in
this
> > case, for the following reason:
> >
> c1 = 'abc'
> c2 = ['de', 'fgh', 'ijkl']
> hasattr(c1, '__iter__')
> > False
> >
> hasattr(c2, '__iter__')
> > True
>
> Right.  str and unicode objects support iteration through the old
> __getitem__ protocol, not the __iter__ protocol.  If you want to use
> something as an iterable, just use it and catch the exception:
>
> try:
>  itr = iter(a)
> except TypeError:
>  # 'a' is not iterable
> else:
>  # 'a' is iterable
>
> Another lesson in why EAPF is often better than LBYL in Python[1].
> 
> STeVe
> 
> [1] http://www.python.org/moin/PythonGlossary

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python2.4 generator expression > python2.3 list expression

2005-02-21 Thread Bryan
Duncan Booth wrote:
Bryan wrote:

is to reset the rightmost (less significant) '1' bit of a number (ie
change it to '0').
i tried c &= c - 1 but i'm not getting the least significant or
rightmost bit reset to zero.  am i misunderstanding something?

2 & 1  # 2 = 0x10; reset right most would be 0x10
0
10 & 9 # 10 = 0x1010; reset right most would be 0x1010
8

The difference between the original "reset the rightmost '1' bit", and your 
interpretation: "reset the rightmost bit" is the "'1'".

The rightmost bit that is set is reset. So 0x10 -> 0, and 0x1010 -> 0x1000.
If you want to extract the least significant set bit from a number 'x' you 
can use (x&-x):


x = 0xab4
while x:
print hex(x&-x), hex(x)
x ^= (x&-x)

0x4 0xab4
0x10 0xab0
0x20 0xaa0
0x80 0xa80
0x200 0xa00
0x800 0x800
(but don't try this if x is negative: it works but never terminates).
thanks duncan... you're right, i did intrepret this as "reset the rightmost bit" 
instead of "reset the rightmost '1' bit".  and i must have read what christos 
wrote 100 times!!!

bryan
--
http://mail.python.org/mailman/listinfo/python-list


[OT] Re: lambda closure question

2005-02-21 Thread Steven Bethard
Antoon Pardon wrote:
def F():
...   l = []
...   def pop():
... return l.pop()
...   def push(e):
... l.append(e)
...   return pop, push
... 
Just a side note to point out that another way of writing this is:
py> def F():
... l = []
... return l.pop, l.append
...
You'll get the same behavior:
py> pop, push = F()
py> push(1)
py> pop()
1
py> push(2)
py> push(3)
py> pop()
3
py> pop()
2
Hooray for bound methods! ;)
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: combining several lambda equations

2005-02-21 Thread Steven Bethard
Antoon Pardon wrote:
So and if I have code like this:
f = lamda x:x 
for g in some_iter:
  f = compose(g,f)

Do you still think that one should use a named function in this case?
Yes.  If you really don't like taking two lines, Python still allows you 
to write this as:

def f(x): return x
for g in some_iter:
f = compose(g, f)
On the other hand, if you really love FP enough to write this kind of 
code, shouldn't you be using reduce istead? ;)  I'm horrible with 
reduce, but something like:

def identity(x):
return x
f = reduce(compose, some_iter, identity)
or if you want to use lambda (note that my complaint about making an 
named function with the anonymous function syntax doesn't apply here):

f = reduce(compose, some_iter, lambda x: x)
Not sure if the order of composition is right here, but you get the idea.
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: Test for structure

2005-02-21 Thread Steven Bethard
> Steven Bethard wrote:
>>
>>Right.  str and unicode objects support iteration through the old
>>__getitem__ protocol, not the __iter__ protocol.  If you want to use
>>something as an iterable, just use it and catch the exception:
>>
>>try:
>> itr = iter(a)
>>except TypeError:
>> # 'a' is not iterable
>>else:
>> # 'a' is iterable
Martin Miller broke the order of reading by top-posting:
In either case, you can't tell a string and list apart, which is what
the OP wanted to know, namely how to differentiate the two.
Yes, sorry, I should have marked my post OT.  It was an answer to Terry 
Hancock's post suggesting hasattr(x, '__iter__'), not the OP.

Perhaps the test for an __iter__ attribute *is* the way to go because
you can tell the difference between the two type.
I've seen this done before, e.g.:
try:
itr = iter(x)
except TypeError:
# is not iterable
else:
if hasattr(x, '__iter__'):
# is other iterable
else:
# is str or unicode
I don't like this idea much because it depends on str and unicode _not_ 
having a particular function.  I haven't seen any guarantee anywhere 
that str or unicode won't ever grow an __iter__ method.  So this code 
seems dangerous as far as future compatibility goes.

I think the technique suggested by Robin Munn nearly a year ago (and
referenced by the link in Simon Brunning's post):
http://groups-beta.google.com/group/comp.lang.python/msg/c8befd4bed517bbc
namely:
try:
a + ''
except TypeError:
pass
else:
a= [a]
would be a good usable solution, although it's not totally infallible.
Yup, if I had to do this kind of type-checking (which I don't think I 
ever do), I'd probably go with something along these lines.

STeVe
--
http://mail.python.org/mailman/listinfo/python-list


ANNOUNCE: SiGeFi v0.3

2005-02-21 Thread Batista, Facundo
Title: ANNOUNCE: SiGeFi v0.3






We're proud to announce the 0.3 version of SiGeFi, which you can find
at:


    http://sourceforge.net/projects/sigefi


    
What is SiGeFi?
---


SiGeFi is a Financial Management System, with focus in the needs of
the administration of the money in each personal life and house.


Always keeping the easy usage and concepts, SiGeFi has features of a 
complex Management system:


- Complies with Double Entry Accounting


- Has a Budget-based Money Distribution system


- Allow to make Loans between accounts (with associated financial
  costs)


And of course, it's completely written in Python (didn't decided the
GUI yet).



What is in this version?



Functionality change:
- Added the LoanChecker, a programmable asynchronous alert that verifies
  the loans due date.


Internal changes:
- Ended the docstrings, and generated the classes documentation using
  epydoc (that soon will be published in the web as part of its content).
- Translated all the code texts to English, and did the gettext integration,
  so now SiGeFi is multilanguage (so far we have English and Spanish only).
- Bugfixing.


Specified the SiGeFi graphic interface. In the manual-gui.html document we
described each window's functionality, and also we added an image for each
one, so if you want to have a preview of how the GUI will look, there you
have it).


See roadmap.txt to find out the milestone for each version.


Be aware that most of the documentation is not translated yet, it's only
in Spanish.



What can I expect for the next version?
---


To us to finish the GUI (with all that that implies) and some other
improvements:


- See if we replace the PersitentDict with a shelve.
- Study the consistency controls of Pickle, and implement some if
  necessary.
- Define the boot procedure and code it in config.py.
- Set up the web page.



How can I help?
---


In a thousand ways, there's a lot of things to do: documentation,
fixing code, translations, set up the web page, etc...


If you want to participate, send us a mail to the list 
([EMAIL PROTECTED]) or directly to us.



Thank you.


.    Facundo


Bitácora De Vuelo: http://www.taniquetil.com.ar/plog
PyAr - Python Argentina: http://pyar.decode.com.ar/



-- 
http://mail.python.org/mailman/listinfo/python-list

Re: recommended way of generating HTML from Python

2005-02-21 Thread has
Kent Johnson wrote:
> Michele Simionato wrote:
> > The problem is a problem of standardization, indeed. There plenty
of
> > recipes to
> > do the same job, I just would like to use a blessed one (I am
teaching
> > a Python
> > course and I do not know what to recommend to my students).
>
> Why not teach your students to use a template system?

Agreed. Don't use HTML generation simply for the sake of it. While it
has its niche, for most tasks templating is more appropriate. There
aren't any 'blessed' solutions, so just pick whichever third-party
system best fits your needs.

-- 
http://mail.python.org/mailman/listinfo/python-list


RE: recommended way of generating HTML from Python

2005-02-21 Thread Robert Brewer
Michele Simionato wrote:
> The problem is a problem of standardization, indeed.
> There are plenty of recipes to do the same job, I just
> would like to use a blessed one (I am teaching a Python
> course and I do not know what to recommend to my students).

Wouldn't we *all* like all of our problems worked out for us. ;)

> class HTMLTag(object):
> [wonderful code snipped]

That's a reasonable start, and you have some fun magic in there, but I think 
you're going to hit a wall of complexity Real Soon Now--elements without a 
separate closing tag, safe attribute quoting, and general usability pressures 
will start to bite you. I note also what Kent said about separation, and the 
desire to "hand things off to a web designer".

In my own work, I tried to meet both of these concerns with a single Assembly 
class, which you can see at http://www.aminus.org/rbre/cation/html/assembly.py. 
At its most basic, it is nothing more than a namespace plus a template. I think 
it solves the separation issue nicely by allowing the template to be loaded 
from a file, whether that file be HTML from a designer, HTML "bulding blocks" 
which a developer might supply, or even CSS, or an email template. But it also 
allows for useful subclassing, for code generation. Here's an example: the 
subclass for "hidden input" elements:

class HiddenElement(Assembly):
"""An Assembly for generating HTML  elements

Usage:
output = assembly.HiddenElement(app).assemble_all(key)
"""

templateText = u''

def assemble_all(self, name, value):
return self.assemble({u'name': html.quote(name),
  u'value': html.quote(value)})

The "assemble_all" method allows the developer to focus on the important bits 
(name and value) and forget the implementation details. Check out the TableRows 
class for a more complex example, whereby an HTML table can be built 
incrementally, inline with the data access logic.

Now, getting into usability concerns (that framework and library authors tend 
to obsess over ;) may be too advanced for your class at the moment. But that's 
why recipes are recipes, not standard library modules: they're often biased 
toward quick and dirty scripting, not usable, maintainable edifices.


Robert Brewer
MIS
Amor Ministries
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unittest - testing properties (read-only attributes)

2005-02-21 Thread Roy Smith
Paul Rubin  wrote:
>  The example I quoted used an assignment expression inside a
> lambda.  The person who posted it,

That was me.

> and the person who followed it up
> with the setattr alternative, both didn't notice that the assignment
> expression wasn't valid Python.

Ugh.  No, I hadn't noticed it.  Thanks for pointing it out.

I don't use lambdas much.  In fact, the only time I ever do use them is for 
an assertRaises unit test.  I've always thought that "assignment is  a 
statement not an expression" was one of Python's warts, and this is just 
another example of why it is.  Of course, "lambda isn't just a def body" is 
a wart too :-)

> However, my post came out sounding
> grumpier than I intended ;).

Actually, I hadn't noticed that either. :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IDLE Problem: win98\Python2.4

2005-02-21 Thread kim kubik

>   kim kubik wrote:
> > I installed Python2.4 in Win98
> > and IDLE doesn't work

> Are you also running Ruby? The Ruby bundle for MS Windows has caused
> problems with it's TCL package conflicting with Python's.
>
thanks, one of the first things I noted in the error msg
(not included for brevity) was that the ruby search
path in AUTOEXEC.BAT was ahead of the python path (and
ruby had tcl83.lib) so I REM'd all the tcl stuff out.
AND THEN (stupid me!) I put into AUTOEXEC.BAT
'set TCL_LIBRARY=c:\python23\tcl'  thinking that
would point python to the proper libs. What a mistake!
If I take that line out (and leave the ruby stuff REM'd
out as well) IDLE runs just fine. So thanks!

A little knowledge is indeed a dangerous thing; forgive my
stupidity - it will happen again, so I'm apologizing in advance!
\kim


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unittest - testing properties (read-only attributes)

2005-02-21 Thread Paul Rubin
Duncan Booth <[EMAIL PROTECTED]> writes:
> An assignment expression, if such a thing existed wouldn't help here.
> 
> The point being that the expression must be evaluated inside the exception 
> handler in assertRaises, so you either need to delay the evaluation with a 
> lambda, or by passing the function and arguments in separately. If you had 
> an assignment expression it would be roughly equivalent to:
> 
>self.assertRaises(AttributeError, setattr(self.combat, 'value', 1))
> 
> which will throw the AttributeError instead of passing the test.

Yes.  The example I quoted used an assignment expression inside a
lambda.  The person who posted it, and the person who followed it up
with the setattr alternative, both didn't notice that the assignment
expression wasn't valid Python.  However, my post came out sounding
grumpier than I intended ;).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python2.4 generator expression > python2.3 list expression

2005-02-21 Thread Brian Beck
Duncan Booth wrote:
The difference between the original "reset the rightmost '1' bit", and your 
interpretation: "reset the rightmost bit" is the "'1'".

The rightmost bit that is set is reset. So 0x10 -> 0, and 0x1010 -> 0x1000.
If you want to extract the least significant set bit from a number 'x' you 
can use (x&-x):
My interpretation of Bryan's (mis?)interpretation (heh) was that since 
in the numbers 2 and 10 (as in his examples), the least significant bit 
was already 0, performing an operation that set it to 0 should result in 
the number unchanged. As his tests show, this is not the case. This is 
because the operation works only if the least significant bit actually 
NEEDS to be unset. To zero the least significant bit unconditionally, we 
can use:

x &= ~1
--
Brian Beck
Adventurer of the First Order
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unittest - testing properties (read-only attributes)

2005-02-21 Thread Duncan Booth
Duncan Booth wrote:

> An assignment expression, if such a thing existed wouldn't help here.

Although of course it would help if still inside a lambda.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unittest - testing properties (read-only attributes)

2005-02-21 Thread Duncan Booth
Paul Rubin wrote:

> Peter Hansen <[EMAIL PROTECTED]> writes:
>> > You want something like
>> > self.assertRaises(AttributeError, lambda: self.combat.value = 1)
>> 
>> Or, combining the two responses and avoiding the lambda:
>> 
>>   self.assertRaises(AttributeError, setattr, self.combat, 'value', 1)
>> 
>> Hmm... this might be a case where the lambda form is actually the
>> more readable one...
> 
> Yes, assignment expressions could make code more readable, if Python
> supported them.
> 

An assignment expression, if such a thing existed wouldn't help here.

The point being that the expression must be evaluated inside the exception 
handler in assertRaises, so you either need to delay the evaluation with a 
lambda, or by passing the function and arguments in separately. If you had 
an assignment expression it would be roughly equivalent to:

   self.assertRaises(AttributeError, setattr(self.combat, 'value', 1))

which will throw the AttributeError instead of passing the test.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: exercise: partition a list by equivalence

2005-02-21 Thread Reinhold Birkenfeld
John Machin wrote:
> Reinhold Birkenfeld wrote:
>> Reinhold Birkenfeld wrote:
>>
>> > My solution (which may not be the fastest or most effective, but
> till
>> > now is the shortest  and it works):
> 
> [snip RB]
>>
>> A recursive solution (around twice as fast as the above, though very
>> slow still...)
>>
> [snip RB2]
>>
>> Another one:
>>
> 
> [snip RB3]
> 
> Dunno what data you are using for timing, but my tests suggest that RB
> is fast enough, RB3 is slightly faster, but RB2 is a real dog and
> appears to be quadratic [hint: it has that same for-for-for-update
> signature found in phase 2 of Xah's effort]. Not only that, but it
> seems to be somewhat irregular. Below are some results on trivial test
> data:
[snip]

Yes, I don't know exactly how I timed this, and I just posted the
solutions to show that there are very different solutions possible. They
are surely not using the best algorithms, as bearophile's function showed.

Reinhold

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unittest - testing properties (read-only attributes)

2005-02-21 Thread Paul Moore
Peter Hansen <[EMAIL PROTECTED]> writes:

> Roy Smith wrote:
>> You want something like
>> self.assertRaises(AttributeError, lambda: self.combat.value = 1)
>
> Or, combining the two responses and avoiding the lambda:
>
>  self.assertRaises(AttributeError, setattr, self.combat, 'value', 1)
>
> Hmm... this might be a case where the lambda form is actually the
> more readable one...

Thanks, I hadn't thought of setattr. I was bitten by the "assignment
is a statement, so can't be used in a lambda" issue, as well :-)

Paul.
-- 
It was a machine, and as such only understood one thing. Being clobbered
with big hammers was something it could relate to. -- Tom Holt
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: recommended way of generating HTML from Python

2005-02-21 Thread Michele Simionato
Kent Johnson:
>I've written web pages this way (using a pretty nice Java HTML
generation package) >and I don't
>recommend it. In my experience, this approach has several drawbacks:
>- as soon as the web page gets at all complex, the conceptual shift
from HTML to >code and back is
>difficult.
>- It is hard to work with a designer. The designer will give you
sample web pages >which then have to
>be hand-translated to code. Changes to the web page have to be located
in the code.
>- There is no separation of content and presentation

>IMO templating systems are a much better solution. They let you
express HTML in >HTML directly; you
>communicate with a designer in a language the designer understands;
you can >separate content and
>presentation

You make a series of good points I am well aware of; however, still
there are
places were direct HTML generation can be a reasonable approach (my use
case was the formatting of a SQL query): cases where the result will
never
ever touch a designer. Also, one could argue that the designer should
not
get in touch with the HTML, but just play with the CSS.
Finally, you can achieve separation between logic and presentation just
putting the
routines generating the HTML pages in a separate module, no need to use
a
different language.

Michele Simionato

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [EVALUATION] - E02 - Support for MinGW Open Source Compiler

2005-02-21 Thread George Sakkis
"Ilias Lazaridis" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]

> Nick Vargish wrote:
> > You can excuse yourself from this one and stop replying to comments,
> > but you don't get to unilaterally declare a discussion over.
> [...]
>
> The discussion is over.
>
> At least the in-topic one.
>
> Everything else is babbling, hairsplitting, playing an AI which does not
> understand writings and all this unproductive garbage.
>
> The Essence is this one, as stated before:
>
> [huge copy paste of previous post]


The Essence is irrelevant.
-
-
-
All your thread are belong to us.
-
-
-

George






-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python2.4 generator expression > python2.3 list expression

2005-02-21 Thread Duncan Booth
Bryan wrote:

>> is to reset the rightmost (less significant) '1' bit of a number (ie
>> change it to '0').
> 
> i tried c &= c - 1 but i'm not getting the least significant or
> rightmost bit reset to zero.  am i misunderstanding something?
> 
> >>> 2 & 1  # 2 = 0x10; reset right most would be 0x10
> 0
> >>> 10 & 9 # 10 = 0x1010; reset right most would be 0x1010
> 8

The difference between the original "reset the rightmost '1' bit", and your 
interpretation: "reset the rightmost bit" is the "'1'".

The rightmost bit that is set is reset. So 0x10 -> 0, and 0x1010 -> 0x1000.

If you want to extract the least significant set bit from a number 'x' you 
can use (x&-x):

>>> x = 0xab4
>>> while x:
print hex(x&-x), hex(x)
x ^= (x&-x)


0x4 0xab4
0x10 0xab0
0x20 0xaa0
0x80 0xa80
0x200 0xa00
0x800 0x800
>>> 

(but don't try this if x is negative: it works but never terminates).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unittest - testing properties (read-only attributes)

2005-02-21 Thread Paul Rubin
Peter Hansen <[EMAIL PROTECTED]> writes:
> > You want something like
> > self.assertRaises(AttributeError, lambda: self.combat.value = 1)
> 
> Or, combining the two responses and avoiding the lambda:
> 
>   self.assertRaises(AttributeError, setattr, self.combat, 'value', 1)
> 
> Hmm... this might be a case where the lambda form is actually the
> more readable one...

Yes, assignment expressions could make code more readable, if Python
supported them.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unittest - testing properties (read-only attributes)

2005-02-21 Thread Peter Hansen
Roy Smith wrote:
You want something like
self.assertRaises(AttributeError, lambda: self.combat.value = 1)
Or, combining the two responses and avoiding the lambda:
 self.assertRaises(AttributeError, setattr, self.combat, 'value', 1)
Hmm... this might be a case where the lambda form is actually the
more readable one...
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: detecting the change in desktop resolution - how?

2005-02-21 Thread Do Re Mi chel La Si Do
Hi !

On windows, and PyWin, this script give the H/V current resolution :



import win32com.client
oWMI = win32com.client.Dispatch("WbemScripting.SWbemLocator")
owbem = oWMI.ConnectServer(".","root\cimv2")
collec = owbem.ExecQuery("Select * from Win32_PrinterConfiguration")
print "Horizontal Resolution: ", collec[0].HorizontalResolution
print "Vertical Resolution: ", collec[0].VerticalResolution




@-salutations
-- 
Michel Claveau





-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unittest - testing properties (read-only attributes)

2005-02-21 Thread Roy Smith
In article <[EMAIL PROTECTED]>, Paul Moore <[EMAIL PROTECTED]> 
wrote:

> I have a class with a read-only attribute, and I want to add a unit
> test to ensure that it really *is* read-only. I can do this as
> 
> def test_readonly(self):
>   """Value and multiplier must be readonly"""
>   try:
>   self.combat.value = 1
>   self.fail("Value is not read only")
>   except AttributeError:
>   pass
> 
> That works, but it seems a bit clumsy. Is there a better way?
> 
> Thanks,
> Paul.

You want something like

self.assertRaises(AttributeError, lambda: self.combat.value = 1)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unittest - testing properties (read-only attributes)

2005-02-21 Thread Diez B. Roggisch
Paul Moore wrote:

> I have a class with a read-only attribute, and I want to add a unit
> test to ensure that it really *is* read-only. I can do this as
> 
> def test_readonly(self):
> """Value and multiplier must be readonly"""
> try:
> self.combat.value = 1
> self.fail("Value is not read only")
> except AttributeError:
> pass
> 
> That works, but it seems a bit clumsy. Is there a better way?


By using setattr, you could refactor the above code into a function. Looks
like this (untested):

def test_readonly(self, instance, attribute, value=1):
 """Value and multiplier must be readonly"""
 try:
setattr(instance, attribute, value)
self.fail("Value is not read only")
 except AttributeError:
pass


Then the testing becomes one line:

self.test_readonly(self.combat, "value")


-- 
Regards,

Diez B. Roggisch
-- 
http://mail.python.org/mailman/listinfo/python-list


Unittest - testing properties (read-only attributes)

2005-02-21 Thread Paul Moore
I have a class with a read-only attribute, and I want to add a unit
test to ensure that it really *is* read-only. I can do this as

def test_readonly(self):
"""Value and multiplier must be readonly"""
try:
self.combat.value = 1
self.fail("Value is not read only")
except AttributeError:
pass

That works, but it seems a bit clumsy. Is there a better way?

Thanks,
Paul.
-- 
XML with elementtree is what makes me never have think about XML
again. -- Istvan Albert
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IDLE Problem: win98\Python2.4

2005-02-21 Thread rmb25612

kim kubik wrote:
> This sure seems like it would have been
> brought up but I checked Google Groups
> (the dejanews replacement) and saw
> nothing:  I installed Python2.4 in Win98
> and IDLE doesn't work (neither does the
> online manual even tho a 3.6KB Python24.chm
> is there, but that's a story for another
> day) - that is, clicking on the IDLE icon
> in the Start menu just gives a brief hourglass
> cursor and then nothing . . .

Are you also running Ruby? The Ruby bundle for MS Windows has caused
problems with it's TCL package conflicting with Python's.

Search comp.lang.python on Google Groups for: Ruby TCL

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python2.4 generator expression > python2.3 list expression

2005-02-21 Thread Bryan
Christos TZOTZIOY Georgiou wrote:
On 21 Feb 2005 06:48:19 -0500, rumours say that Dan Sommers <[EMAIL PROTECTED]>
might have written:
[snip: snacktime posts code to count bits]

Seems to work, is there a better way to do this?

[Dan]
for c in range( 128 ):
  even_odd = 0
  print '%3d' % c,
  while c:
  c &= c - 1
  even_odd = not even_odd
  print int( even_odd )

Just for the sake of people who haven't messed with bit manipulation in C or
assembly, the effect of
c &= c - 1
is to reset the rightmost (less significant) '1' bit of a number (ie change it
to '0').
i tried c &= c - 1 but i'm not getting the least significant or rightmost bit 
reset to zero.  am i misunderstanding something?

>>> 2 & 1  # 2 = 0x10; reset right most would be 0x10
0
>>> 10 & 9 # 10 = 0x1010; reset right most would be 0x1010
8
bryan
--
http://mail.python.org/mailman/listinfo/python-list


detecting the change in desktop resolution - how?

2005-02-21 Thread Erik Bethke
Hello All,

I am trying to clean up some polish bugs with the Shanghai game I am
working on and I am currently stuck on trying to get the right event
for detecting when the user has changed the desktop resolution.

I have tried trapping the following events:

1) SDL_ACTIVEEVENT
2) SDL_VIDEOEXPOSE3) SDL_VIDEORESIZE

These are the events that are passed through to pygame as
pygame.ACTIVEEVENT and so on...

#3 - SDL_VIDEORESIZE  This is what I looked at first and I was wrong,
this is only for the WINDOW being resized... not the desktop resoltion

#2 - SDL_VIDEOEXPOSE  After watching the events in a debugger when I
change the desktop resolution I find out that this IS the event that is
generated from changing the desktop resolution.  Okay no problem right?
 Time to call:

self.screen = self.pygame.display.set_mode( size )

and draw() again right?

Well sure, now my game repaints properly when the desktop resolution
changes.  So What is the problem?  Well now EVERY TIME another window
draws on top of my game's window a SDL_VIDEOEXPOSE event is triggered.
There does not appear to be any flags associated with this event.  So I
am having trouble distinguishing from an overlapping window and
changing the desktop resolution.

So I tried this:

1) call pygame.display.Info() at the startup of my game and save off
this structure
2) call it again after getting a SDL_VIDEOEXPOSE event and comparing to
see if it has changed at all.

The problem with this is that apparantly the VidInfo structure DOES NOT
change when changing desktop resolution...

So then I tried using SDL_ACTIVEEVENT and simply leaving the display
black and unpainted after the user changes the resolution until the
user rolls the mouse over the game window and bringing it back to
focus.

This works.  However, it gets annoying watching the screen repaint
everytime the window gains focus

Do you guys have any leads for me to try?  This HAS to be a problem
solved many times before...

Thank you,
-Erik

-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >