Re: A new to Python question

2005-05-14 Thread Bernd Nawothnig
On 2005-05-14, M.E.Farmer wrote:

> I explained what i meant in previous post there was nothing more than
> just a discussion

No. You claimed


This will only create a tuple in memory


But we just learned that this is not the case.

> I have no real problem here just more of a sore point in style for
> me. I feel that parens are quite overloaded and it can be confusing
> to newbies. But if the parens are just fluff then get rid of them, it
> is clearer * at least to me * ;)

Reduced to this argument I have no objection.

> There are enough things wrapped in parens nowadays it is starting to
> look like lisp.

Lisp is far from being ugly ;-)




Bernd

-- 
Those who desire to give up freedom in order to gain security,
will not have, nor do they deserve, either one. [T. Jefferson]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: space saving retitle of thread

2005-05-14 Thread Mike Painter
Johnny Gentile wrote:
> aa.

I just added a second monitor and have over two feet of monitor as 1280 x 
1024.
Outlook expands this message and it still runs off the right side of the 
second monitor. 


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


Paranoider Deutschenmoerder kommt in Psychiatrie

2005-05-14 Thread zip . pritchard
Lese selbst:
http://brandenburg.rz.fhtw-berlin.de/poetschke.html
-- 
http://mail.python.org/mailman/listinfo/python-list


In search of prothon source

2005-05-14 Thread Alex
Since the DNS servers hosting prothon.org have stopped responding, the 
sole source of the source of prothon online that I can find has become 
inaccessable.  I was wondering if anyone subscribed has a copy of the 
source for the last C version of prothon, and would be kind enough to 
post a copy online.

Thanks,

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


Re: converting a set into a sorted list

2005-05-14 Thread MackS
Thank you for the pointer. I'll upgrade to 2.4.

Best,

Mack

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


Re: A new to Python question

2005-05-14 Thread Fredrik Lundh
Bernd Nawothnig wrote:

> > You're thinking you're passing the arguments as reference
>
> That is the way Fortran handles them:

which is one of the things you really love when you link against
underdocumented Fortran programs from C.  ("is that parameter
a scalar or an array? crash! oh, an array. how many values does
it expect? crash! oh, a few more, I suppose").





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


Re: pygame on win32, image.fromstring()

2005-05-14 Thread tlviewer
tlviewer wrote:

> Next I'm going to load all 53 card resources into a list (array) of
> strings, then write it out, pickled. That should smooth out loading the
>game when I use 4-6 decks (Blackjack-21).

# -*- coding: cp1252 -*-
"""
keywords: resource bitmap pickle
description: pickle resources from cards.dll 
requires: 
Pygame from www.pygame.org, 
PIL from www.pythonware.com/products/pil/ 

WinXP out:
63  ioerror
64  ioerror
66  resource skipped
saving pickled list
closing
debugging  

"""

# imports
import win32api as wi 
import string as st 
import pygame as gm 
import Image as im 
import StringIO
import win32con as wc 

import os, sys
import pickle as pkl

# OS independent path -- win32 only
sysroot = os.environ.get('SYSTEMROOT') 

# get module handle for cards DLL
hnd = wi.LoadLibrary(sysroot + '/system32/cards.dll')

"""
Loadresource returns the card image without a header! I dumped these
header strings from ResourceHacker. There are only 2 kinds: one for the
pictures, and one for Ace+numbers.
"""
# this header works for 71x96x1BPP image
pic_header = [ chr(0x42), chr(0x4D), chr(0xDE), chr(0x0D), chr(0x00), \
chr(0x00), chr(0x00), chr(0x00), chr(0x00), chr(0x00), chr(0x4A), \
chr(0x00), chr(0x00), chr(0x00)]
num_header = [ chr(0x42), chr(0x4D), chr(0xA0), chr(0x04), chr(0x00), \
chr(0x00), chr(0x00), chr(0x00), chr(0x00), chr(0x00), chr(0x20), \
chr(0x00), chr(0x00), chr(0x00)] 


fname = 'pkl_deck.dat'
fname = os.curdir + '/' + fname 
debugr=1 

#init main array to hold the cards as strings 
arr_cards=[]

def cards(fname):
#sheader = ''.join([ chr(header[x]) for x in range(len(header))]) 
if debugr!=0:
str = wi.LoadResource( hnd, 2, 1, 1033)   
str = st.join(num_header,'') + str
fp = open( os.curdir + '/aceclub.bmp', "wb")
fp.write( str)
fp.close ()

for i in range(1,68):
#default header (num)
#print "fetch ", i
header = num_header
if i % 13 > 10:
header = pic_header
try:
str = wi.LoadResource( hnd, wc.RT_BITMAP, i, 1033)
except:
print "%d" % i, " resource skipped"
continue
str = st.join(header,'') + str
try:
obj = im.open(StringIO.StringIO(str)) 
arr_cards.insert(i,obj.tostring())
except IOError:
print "%d" % i, " ioerror"
pass

wi.FreeLibrary(hnd)
#
# pickle out the list
print "saving pickled list"
fp = open(os.curdir + '/pkl_deck.dat', "wb")
try:
pkl.dump( arr_cards, fp, 1) #binary size Win2k:312kB WinXP:445kB
except:
print "errored, but still closing file"
fp.close()
else:
print "closing"
fp.close()
#fp = open("e:/batch/msdn/Bitmap_11.bmp", "rb") 

## main ##

# retrieve the deck from our pickled list, or repickle the list to file

if not os.path.exists(fname):
cards(fname)
else:
fp = open(os.curdir + '/pkl_deck.dat','rb')
val=fp.read()
print "pickled list len=",len(val)
fp.close 
arr_cards=pkl.loads(val)
 
if debugr!=0:  
img = gm.image.fromstring(arr_cards[11],(71,96),"P")   
print "debugging",img, img.get_rect() 
   


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


Re: A new to Python question

2005-05-14 Thread Fredrik Lundh
M.E.Farmer wrote:

> I said exactly what I meant, the parentheses around the values creates
> a tuple that you have no reference to!

repeating it doesn't make you right; no extra tuple is created, and the
parens are part of the syntax:

If the target is a target list enclosed in parentheses or in square
brackets: The object must be a sequence with the same number
of items as there are targets in the target list, and its items are
assigned, from left to right, to the corresponding targets.

http://docs.python.org/ref/assignment.html

(originally, you had to use [] to unpack lists, and () or no parens only
worked for tuples.  the ability to use an arbitrary sequence was added
in 1.5)

on the other hand, the function you're calling in this example *does*
create a tuple that you have no reference to after the assignment.
that doesn't matter, of course, since the tuple is removed by the
garbage collector immediately after it has been unpacked.





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


Re: Modifying a built-in function for logging purposes

2005-05-14 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> I wonder if it is possible to change (temporarily) a built-in function
> for logging purposes.
> Let me explain:
> I want to log all the 'open' operations, recording the file to be
> opened, the "mode" (r/w/a...) and (possibly) the module which made the
> call.

import sys
import __builtin__ # note: no plural s

old_open = __builtin__.open

def myopen(*args):
code = sys._getframe(1).f_code
print "OPEN", args, "FROM", code.co_name, "IN", code.co_filename
return old_open(*args)

__builtin__.open = myopen

this only handles file opens that goes via the "open" function, of course.
to handle all opens, including internal operations (e.g. imports), you're
probably better off using an external tool (e.g. strace, filemon, or some-
thing similar).





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


Re: Faster GUI text control

2005-05-14 Thread Fredrik Lundh
"none <"@bag.python.org> wrote:

> > no, it would mean writing some python code.  if all you need is a scrolling
> > text list, you can simply use the code on this page:
> >
> > http://effbot.org/zone/wck-4.htm
> >
> > (see "A scrollable list view, with scrollbar support" and, optionally,
> > the virtual data modifications under "Displaying Huge Data Sets")
> >
> > the resulting widget will update at constant speed, independent of the
> > data size.
> >
> > 
>
> Thanks for the suggestion.  I looked at that, but I need to be able to
> selectively change colors on parts of the text and I didn't think I
> could do that with a list box.  Am I misunderstanding that?

yes.  the list view isn't a listbox, it's a new widget.

with the list view, you control the drawing yourself, and can draw things
in whatever way you want.  (the section "Non-Standard Rendering" talks
about this; reading http://effbot.org/zone/wck-3.htm also helps).





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


Re: incorrect(?) shlex behaviour

2005-05-14 Thread M.E.Farmer
bill wrote:
> Consider:
> >>> import shlex
> >>> shlex.split('$(which sh)')
> ['$(which', 'sh)']
>
> Is this behavior correct?  It seems that I should
> either get one token, or the list
> ['$','(','which','sh',')'],
> but certainly breaking it the way it does is
> erroneous.
>
> Can anyone explain why the string is being split
> that way?
This may help.
http://www.python.org/dev/doc/devel/lib/module-shlex.html
This works on Python 2.4:
>>> import shlex
>>> sh = shlex.shlex('$(which sh)')
>>> sh.get_token()
'$'
>>> sh.get_token()
'('
>>> sh.get_token()
'which'
>>> sh.get_token()
'sh'
>>> sh.get_token()
')'
>>> sh.get_token()
etc...

Python 2.2 and maybe lower:
>>> import shlex
>>> import StringIO
>>> s = StringIO.StringIO('$(which sh)')
>>> sh = shlex.shlex(s)
>>> sh.get_token()
'$'
>>> sh.get_token()
'('
>>> sh.get_token()
'which'
>>> sh.get_token()
'sh'
>>> sh.get_token()
')'
>>> sh.get_token()
etc...

Hth,
M.E.Farmer

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


Re: Exception question

2005-05-14 Thread Steven Bethard
Ron Adam wrote:
> 
> Do exceptions that take place get stored in a stack or list someplace?
[snip]
> I know I can catch the error and store it myself with,
> 
> except Exception, exc:
> 
> or possibly,
> 
> errlist = []
> errlist.append(sys.exc_info())
> 
> But what I want to know is does the interpreter do that in any way?  And 
> if so, can I access it?

No, but there's been some recent talk about having it do so:

http://mail.python.org/pipermail/python-dev/2005-May/053672.html

If that happens though, it's not likely to show up before Python 3.0. 
Too backwards incompatible to do now.  It also seems that the exact 
semantics haven't yet been agreed upon.

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


stop

2005-05-14 Thread Johnny Gentile

Enough salvation for one day.

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


Massenhafter Steuerbetrug durch auslaendische Arbeitnehmer

2005-05-14 Thread mal
Lese selbst:
http://www.rp-online.de/public/article/nachrichten/wirtschaft/finanzen/deutschland/85815
-- 
http://mail.python.org/mailman/listinfo/python-list


Transparenz ist das Mindeste

2005-05-14 Thread dstamsta
Lese selbst:
http://www.npd.de/npd_info/deutschland/2005/d0405-39.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Jesus said, "I am the way, the truth and the life: no one can come to the Father(God)(in Heaven), but by me." (John 14:6) This means that if you die without trusting in Jesus Christ as your Lord and Saviour you will die in your sins and be forever sepa

2005-05-14 Thread Bubba
I'm so glad you've decided what everyone believes

"don freeman" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
>
>
> > http://www.gotquestions.org/sinners-prayer.html << I saw this site on a
> > search directory. Great Resource!
> >
>
>
> C'mon, this is the 21st century. Nobody believes that silly story about
> God having a son anymore.
>
> Think about it. The original story is always the best. The sequel is
> always a commercial rip-off. Frankenstein was literature. Son of
> Frankenstein was silly.
>
> God impregnates a virgin woman and gives birth to a half man/half god,
> who can walk on water and turn water into wine, but who can't defend
> himself very well at all from the Romans. This story may have sold in
> the past, but not now. We've become too sophisticated for this kind of
> fantasy.
>


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


Re: converting a set into a sorted list

2005-05-14 Thread Brian Beck
Robert Kern wrote:
> MackS wrote:
> 
>> Dear all,
>>
>> I've got several large sets in my program. After performing several
>> operations on these I wish to present one set to the user [as a list]
>> sorted according to a certain criterion. Is there any direct way to do
>> so? Or must I
>>
>> list = []
>>
>> for item in set1:
>>list.append(item)
>>
>> list.sort()

So, for this example, just do:

sorted(set1)


-- 
Brian Beck
Adventurer of the First Order
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: converting a set into a sorted list

2005-05-14 Thread Terry Reedy

"MackS" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Can I somehow avoid doing this in two stages? Can I somehow avoid first
> creating a long list only to immediately sort it afterwards?

Yes, you could interatively extract and append the min of the set 
(selection sort), but this would be O(n**2), like bubble or insert sort, 
instead of the O(n*logn) of make list and sort.  You can do the latter in 
two statements without append:
 display = list(big_set)
 display.sort().

As Robert noted, this can be condensed to one using sorted, but that will 
do the same as the two lines above.

Terry J. Reedy



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


Exception question

2005-05-14 Thread Ron Adam

I'm trying to understand exception handling better and have a question I 
haven't been able to find an answer too.  Which probably means It won't 
work, but...

Do exceptions that take place get stored in a stack or list someplace?

For example in:

try:
 try:
 try:
 riskyfunc()
 # error 1
 except:
 pass
 crazyclass()
 # error 2
 except:
 pass
 iffycalc()
 # error 3
except:
 pass

# print any errors that occurred here.


If errors 1,2,and 3 are possible errors, can I get
a list of them, or can I only see the last one?

I know I can catch the error and store it myself with,

 except Exception, exc:

or possibly,

 errlist = []
 errlist.append(sys.exc_info())

But what I want to know is does the interpreter do that in any way?  And 
if so, can I access it?

Cheers,
_Ron_Adam



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


Please confirm (conf#8d26af0fb789e6023d272db682e0f9b4)

2005-05-14 Thread MQ Feedback

Thank you for your feedback.

Due to high levels of spam and virus activity on this mailing list the 
message you sent (attached below) requires confirmation before it can be
delivered. To confirm that you sent the message below, simply reply to this
message, leaving the Subject line unchanged (you don't need to edit anything).
Once this is done your original message will be delivered and no more
confirmations will be necessary.

We apologize for the inconvenience and thank you for your patience,

The Message Queue Team



This email account is protected by:
Active Spam Killer (ASK) V2.4.1 - (C) 2001-2002 by Marco Paganini
For more information visit http://www.paganini.net/ask

--- Original Message Follows ---

From: python-list@python.org
To: [EMAIL PROTECTED]
Date: Sun, 15 May 2005 02:58:54 UTC
Subject: Dresden Bombing Is To Be Regretted Enormously

Full Article:
http://service.spiegel.de/cache/international/0,1518,341239,00.html



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


Re: converting a set into a sorted list

2005-05-14 Thread Robert Kern
MackS wrote:
> Dear all,
> 
> I've got several large sets in my program. After performing several
> operations on these I wish to present one set to the user [as a list]
> sorted according to a certain criterion. Is there any direct way to do
> so? Or must I
> 
> list = []
> 
> for item in set1:
>list.append(item)
> 
> list.sort()
> 
> Can I somehow avoid doing this in two stages? Can I somehow avoid first
> creating a long list only to immediately sort it afterwards?

In Python 2.4,

In [1]:sorted?
Type:   builtin_function_or_method
Base Class: 
String Form:
Namespace:  Python builtin
Docstring:
 sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter

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


Re: Modifying a built-in function for logging purposes

2005-05-14 Thread Robert Kern
[EMAIL PROTECTED] wrote:
> Hi Greg,
> thank for your replay, but I didn't succeed in any way. You must
> consider however that I'm not a Python "expert"...
> IMHO, it must be a script that change part of the interpreter, and
> substitute a new module (py) in the place of the standard one (py or
> pyc). The standard module must be saved in order to be able to undo the
> changes and go back to the normal behaviour.
> The problem is that I don't know if the built-in functions like open
> (or file) are written in Python or in C and, besides that, if they can
> be modified.

Short answer: if you don't know stuff like this, then you probably 
shouldn't mess around with the builtins in production code.

Depending on your operating system, there are probably programs that let 
you list all of the files that have been opened on your system. For 
example, on OS X, lsof(1) does the trick.

> Other solutions which modify the source to be logged, are not
> solutions, because it is far simpler to introduce here and there print
> statements... 

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter

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


Paranoider Deutschenmoerder kommt in Psychiatrie

2005-05-14 Thread admin
Lese selbst:
http://brandenburg.rz.fhtw-berlin.de/poetschke.html
-- 
http://mail.python.org/mailman/listinfo/python-list


converting a set into a sorted list

2005-05-14 Thread MackS
Dear all,

I've got several large sets in my program. After performing several
operations on these I wish to present one set to the user [as a list]
sorted according to a certain criterion. Is there any direct way to do
so? Or must I

list = []

for item in set1:
   list.append(item)

list.sort()

Can I somehow avoid doing this in two stages? Can I somehow avoid first
creating a long list only to immediately sort it afterwards?

Thanks for any guidance,

Mack

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


Re: A new to Python question

2005-05-14 Thread Terry Reedy

"M.E.Farmer" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> But if the parens are just fluff then get rid of them, it is clearer *
> at least to me * ;)

While I find unnecessary parens on the right of '=' tolerable, I agree as 
to the style preference.

Terry J. Reedy



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


Re: Multiple "cmp"s chained one after another

2005-05-14 Thread Peter Hansen
Volker Grabsch wrote:
> Peter Hansen wrote:
> 
>>Or just use the .timetuple() method on datetime objects and sort on the 
>>8th element of the 9-element tuple, which is the day-of-the-year.
> 
> An interesting idea. But wouldn't sorting by (dd.month,dd.day) be more
> effective?

Depending on the meaning of "effective", I suppose so.

> In other words: Does .timetuple() create a tuple, or does it just return
> a tuple which is present anyway?

I don't know what it does.  Normally one shouldn't care about that kind 
of thing.  In this case, you seem to be assuming that .month and .day 
are values that are "present anyway", but we don't really know that 
either, since they could just as well be properties.  If someone who 
knows or someone who checks the source (for a given implementation of 
course... it could change) cares to share, we'd know more.  What good 
that would do us is still a mystery to me. ;-)

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


space saving retitle of thread

2005-05-14 Thread Johnny Gentile
aa.

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


Re: A new to Python question

2005-05-14 Thread M.E.Farmer
Ok I give up you have convinced me. Of what I am not sure ;)
Anyway I have always viewed :
a,b,c= (1,2,3)
as unpacking a tuple
and :
(a,b,c) = (1,2,3)
as creation of a tuple
It was a false assumption, I have used Python for years and have never
written an unpacking as:
(a,b,c) = (1,2,3)
I have always put parens around my tuples I always thought that a tuple
was a parens with at least one comma ;)
It is just not something I have done, it seems counter to my thinking ,
till I read from Bengt it is the commas that make the tuple not the
parens.
It all makes sense now, but if they are not needed I think they that
should be avoided for clarity.
Steve thanks for your time. I always learn a little from you ;)
M.E.Farmer

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


Re: Jesus said, "I am the way, the truth and the life: no one can come to the Father(God)(in Heaven), but by me." (John 14:6) This means that if you die without trusting in Jesus Christ as your Lord and Saviour you will die in your sins and be forever separated from the love of God in a place called Hell. The Holy Bible descibes Hell as a place of eternal torment, suffering, pain and agony for all those who have rejected Jesus Christ. The good news is that you can be sure you are going to Heaven when this life is over if you allow Jesus Christ to save you today. Do not wait until later to be saved because you do not know exactly when you will die. [ Posted by: RonaldGrossi3848@yahoo.com on May 14, 2005 ] [ 2:52:09 pm ]

2005-05-14 Thread don freeman


> http://www.gotquestions.org/sinners-prayer.html << I saw this site on a
> search directory. Great Resource!
> 


C'mon, this is the 21st century. Nobody believes that silly story about 
God having a son anymore.

Think about it. The original story is always the best. The sequel is 
always a commercial rip-off. Frankenstein was literature. Son of 
Frankenstein was silly.

God impregnates a virgin woman and gives birth to a half man/half god, 
who can walk on water and turn water into wine, but who can't defend 
himself very well at all from the Romans. This story may have sold in 
the past, but not now. We've become too sophisticated for this kind of 
fantasy.

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


Re: Multiple "cmp"s chained one after another

2005-05-14 Thread Volker Grabsch
vincent wehren wrote:
> 
>| > If you don't care about the year, why not just "normalize" the year
>| > to all be the same using the replace method of the date instance?
>|
>| That's a very bad idea. In my example, this would work, but in "reality"
>| I don't sort datetime objects, of course! (Is there any real application
>| where you want to do that?)
>|
>| Instead, I'm sorting "Person" objects using a "birthday" attribute.
>| Since I use these Person objects also in other places, they should never
>| be modified without just to be sorted. In general, the number side effects
>| should always be minimized.
> 
> Can you explain where you see a modification to the orginal object 
> happening?
> (or in any of the other solutions proposed for that matter...)

Sorry, my fault. I didn't read carefully enough.  X-)

> Not here I hope:
> 
>| > datesNorm = [obj.replace(year=1900) for obj in (dates)]
>| > datesNorm.sort()

While you don't change the original objects, there's still a problem since
you're sorting the normalized values. However, I want to sort the original
list (i.e. the list of "Person" objects).

But that's not a real problem if one normalizes in a key function:

def key_birthday(d):
return d.replace(year=1900)
...
dates.sort(key=key_birthday)

..as suggested in other followups of my posting.

>| Nevertheless, I think you idea is very interesting. Is there any "real"
>| application where normalizing just for sorting would be reasonable?
> 
> How about a case-insensitive sort of strings? (uppering being the 
> normalization step)
> Or getting rid of accented / special characters before sorting.
> These sound like fairly straight-forward use cases to me ;)

For your solution these are good examples. But my question was, whether
normalizing first, and just sorting the normalized values (not the original
values) is reasonable.

I.e., when I sort some strings case-insensitive, I don't want my resulting
(sorted) list to contain only lowercase string. But that's what I would
get if I used the algorithm you described above.


Greets,

-- 
Volker Grabsch
---<<(())>>---
\frac{\left|\vartheta_0\times\{\ell,\kappa\in\Re\}\right|}{\sqrt
[G]{-\Gamma(\alpha)\cdot\mathcal{B}^{\left[\oint\!c_\hbar\right]}}}
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A new to Python question

2005-05-14 Thread M.E.Farmer
I explained what i meant in previous post there was nothing more than
just a discussion I have no real problem here just more of a sore point
in style for me. I feel that parens are quite overloaded and it can be
confusing to newbies.
But if the parens are just fluff then get rid of them, it is clearer *
at least to me * ;)
There are enough things wrapped in parens nowadays it is starting to
look like lisp.
> BTW, UIAM it is the commas that define tuples, so the outermost
parens are really >expression
>parens more than tuple syntax.
Hadn't really thought of that way but it makes sense
>>> w = 1,2,3
>>> w.__doc__
"""tuple() -> an empty tuple
 tuple(sequence) -> tuple initialized from sequence's items

 If the argument is a tuple, the return value is the same object."""
Thanks for your time Bengt!
M.E.Farmer

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


Re: A new to Python question

2005-05-14 Thread Steven Bethard
M.E.Farmer wrote:
>>They're both an UNPACK_SEQUENCE byte-code.
> 
> I have dissed it myself ;)
> My argument, if you can call it that, is that it is not clear that
> Python is going to do a tuple unpacking here or not !

Hmm...  Well, I wouldn't say that.  I think it's quite clear that 
Python's doing a tuple unpacking.  Just like it always does anytime 
there's a comma on the left-hand side of an assignment statement.

Note that there's nothing that forces you to write the unpack sequence 
like a tuple display.  You can write it like a list display too, and 
Python will treat it identically:

py> def unpack_tuple(t):
... [x, y] = t
...
py> dis.dis(unpack_tuple)
   2   0 LOAD_FAST0 (t)
   3 UNPACK_SEQUENCE  2
   6 STORE_FAST   2 (x)
   9 STORE_FAST   1 (y)
  12 LOAD_CONST   0 (None)
  15 RETURN_VALUE

I don't know how UNPACK_SEQUENCE is implemented, but at least on the 
Python level, no tuple or list is created in the unpacking process.

> Seems weird, non-intuitive that a tuple unpacking and tuple creation
> have the same bytecode.

Sorry, I don't understand.  Why do you think this?

py> def create_tuple(x, y):
... (x, y)
...
py> dis.dis(create_tuple)
   2   0 LOAD_FAST0 (x)
   3 LOAD_FAST1 (y)
   6 BUILD_TUPLE  2
   9 POP_TOP
  10 LOAD_CONST   0 (None)
  13 RETURN_VALUE
py> def unpack_tuple(t):
... x, y = t
...
py> dis.dis(unpack_tuple)
   2   0 LOAD_FAST0 (t)
   3 UNPACK_SEQUENCE  2
   6 STORE_FAST   2 (x)
   9 STORE_FAST   1 (y)
  12 LOAD_CONST   0 (None)
  15 RETURN_VALUE

To me, it looks like tuple creation uses the BUILD_TUPLE op-code, and 
tuple unpacking uses the UNPACK_SEQUENCE op-code.  Could you explain 
what you meant by "a tuple unpacking and tuple creation have the same 
bytecode"?

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


Re: Modifying a built-in function for logging purposes

2005-05-14 Thread qwweeeit
Hi Greg,
thank for your replay, but I didn't succeed in any way. You must
consider however that I'm not a Python "expert"...
IMHO, it must be a script that change part of the interpreter, and
substitute a new module (py) in the place of the standard one (py or
pyc). The standard module must be saved in order to be able to undo the
changes and go back to the normal behaviour.
The problem is that I don't know if the built-in functions like open
(or file) are written in Python or in C and, besides that, if they can
be modified.
Other solutions which modify the source to be logged, are not
solutions, because it is far simpler to introduce here and there print
statements... 
Bye.

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


Re: A new to Python question

2005-05-14 Thread M.E.Farmer
>It actually is the same, and I don't think implicit or explicit is the
>difference you should be citing here.
Why not it is relevant and true that Python is doing an implicit
unpacking of the values in that unnamed tuple.
Quoting myself """It might be the "same" as
no parens but it isn't very clear. If you want a tuple make it
explicit, if you want individual names make it explicit."""
So as you say, maybe it is is fully a matter of style and apparently I
don't like that style!

>They're both an UNPACK_SEQUENCE byte-code.
I have dissed it myself ;)
My argument, if you can call it that, is that it is not clear that
Python is going to do a tuple unpacking here or not !
You had to dis it to find out and you are not a newbie.
# extra fluff from pyshell
>>> import dis
>>> dis.dis(compile('(x,y,dotp,sumx,maxv) =
abc(x,y,dotp,sumx,maxv)','','exec'))
  0 SET_LINENO   0

  3 SET_LINENO   1
  6 LOAD_NAME0 (abc)
  9 LOAD_NAME1 (x)
 12 LOAD_NAME2 (y)
 15 LOAD_NAME3 (dotp)
 18 LOAD_NAME4 (sumx)
 21 LOAD_NAME5 (maxv)
 24 CALL_FUNCTION5
 27 UNPACK_SEQUENCE  5
 30 STORE_NAME   1 (x)
 33 STORE_NAME   2 (y)
 36 STORE_NAME   3 (dotp)
 39 STORE_NAME   4 (sumx)
 42 STORE_NAME   5 (maxv)
 45 LOAD_CONST   0 (None)
 48 RETURN_VALUE
>>> dis.dis(compile('x,y,dotp,sumx,maxv =
abc(x,y,dotp,sumx,maxv)','','exec'))
  0 SET_LINENO   0

  3 SET_LINENO   1
  6 LOAD_NAME0 (abc)
  9 LOAD_NAME1 (x)
 12 LOAD_NAME2 (y)
 15 LOAD_NAME3 (dotp)
 18 LOAD_NAME4 (sumx)
 21 LOAD_NAME5 (maxv)
 24 CALL_FUNCTION5
 27 UNPACK_SEQUENCE  5
 30 STORE_NAME   1 (x)
 33 STORE_NAME   2 (y)
 36 STORE_NAME   3 (dotp)
 39 STORE_NAME   4 (sumx)
 42 STORE_NAME   5 (maxv)
 45 LOAD_CONST   0 (None)
 48 RETURN_VALUE
>>> dis.dis(compile('tup = abc(x,y,dotp,sumx,maxv)','','exec'))
  0 SET_LINENO   0

  3 SET_LINENO   1
  6 LOAD_NAME0 (abc)
  9 LOAD_NAME1 (x)
 12 LOAD_NAME2 (y)
 15 LOAD_NAME3 (dotp)
 18 LOAD_NAME4 (sumx)
 21 LOAD_NAME5 (maxv)
 24 CALL_FUNCTION5
 27 STORE_NAME   6 (tup)
 30 LOAD_CONST   0 (None)
 33 RETURN_VALUE
>>>
You may notice that the act of assigning the return values to a unnamed
tuple and a name have different semantics and that was the real point.
The problem is why should this be the same:

a,b,c=(1,2,3)

(a,b,c)=(1,2,3)

Seems weird, non-intuitive that a tuple unpacking and tuple creation
have the same bytecode.
So why is this done? What is the reason, I am sure there are a few ;)

p.s. I am leaving out for a while and will read/followup later if
needed. Thank you all for your time. 
M.E.Farmer

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


Re: A new to Python question

2005-05-14 Thread Bengt Richter
On 14 May 2005 13:25:55 -0700, "M.E.Farmer" <[EMAIL PROTECTED]> wrote:

>I said exactly what I meant, the parentheses around the values creates
>a tuple that you have no reference to! It also has a side effect of
I don't understand what you are saying, or meaning ;-)
BTW, the function call has nothing to do with what happens on the left hand side
of the assignment. It is only the result of the function call that counts, so we
could as well use a literal or other expression. This is a matter of unpacking
a sequence according to the left hand target. E.g.,

 >>> iter([1,2,3])
 
 >>> a,b,c = iter([1,2,3])
 >>> d,e,f = [1,2,3]
 >>> g,h,i = 'GHI'
 >>> [a,b,c,d,e,f,g,h,i]
 [1, 2, 3, 1, 2, 3, 'G', 'H', 'I']

Ok, now looking at the code for the assignment to a,b,c vs to (a,b,c):

 >>> import dis
 >>> dis.dis(compile('(a,b,c) = iter([1,2,3])','','exec'))
   1   0 LOAD_NAME0 (iter)
   3 LOAD_CONST   0 (1)
   6 LOAD_CONST   1 (2)
   9 LOAD_CONST   2 (3)
  12 BUILD_LIST   3
  15 CALL_FUNCTION1
  18 UNPACK_SEQUENCE  3
  21 STORE_NAME   1 (a)
  24 STORE_NAME   2 (b)
  27 STORE_NAME   3 (c)
  30 LOAD_CONST   3 (None)
  33 RETURN_VALUE
 >>> dis.dis(compile('a,b,c = iter([1,2,3])','','exec'))
   1   0 LOAD_NAME0 (iter)
   3 LOAD_CONST   0 (1)
   6 LOAD_CONST   1 (2)
   9 LOAD_CONST   2 (3)
  12 BUILD_LIST   3
  15 CALL_FUNCTION1
  18 UNPACK_SEQUENCE  3
  21 STORE_NAME   1 (a)
  24 STORE_NAME   2 (b)
  27 STORE_NAME   3 (c)
  30 LOAD_CONST   3 (None)
  33 RETURN_VALUE
 
I don't see anything in the code about creating a tuple that you have no 
reference to.
To see the unpacking of "GHI" so as to get rid of the function call red herring:

 >>> dis.dis(compile('a,b,c = "GHI"','','exec'))
   1   0 LOAD_CONST   0 ('GHI')
   3 UNPACK_SEQUENCE  3
   6 STORE_NAME   0 (a)
   9 STORE_NAME   1 (b)
  12 STORE_NAME   2 (c)
  15 LOAD_CONST   1 (None)
  18 RETURN_VALUE
 >>> dis.dis(compile('(a,b,c) = "GHI"','','exec'))
   1   0 LOAD_CONST   0 ('GHI')
   3 UNPACK_SEQUENCE  3
   6 STORE_NAME   0 (a)
   9 STORE_NAME   1 (b)
  12 STORE_NAME   2 (c)
  15 LOAD_CONST   1 (None)
  18 RETURN_VALUE

ISTM the assignment part starts with UNPACK_SEQUENCE and all the code looks the 
same.
BTW, UIAM it is the commas that define tuples, so the outermost parens are 
really expression
parens more than tuple syntax. But note that you can have nested tuple 
structure as target,
and that does change the unpacking code (and what it expects to have available 
to unpack):

 >>> (x,(y,z)) = 'XYZ'
 Traceback (most recent call last):
   File "", line 1, in ?
 ValueError: too many values to unpack
 >>> (x,(y,z)) = 'X','YZ'
 >>> x
 'X'
 >>> y
 'Y'
 >>> z
 'Z'
 >>> (x,(y,z)) = [1, [2,3]]
 >>> x
 1
 >>> y
 2
 >>> z
 3
 >>> dis.dis(compile('(x,(y,z)) = 0','','exec'))
   1   0 LOAD_CONST   0 (0)
   3 UNPACK_SEQUENCE  2
   6 STORE_NAME   0 (x)
   9 UNPACK_SEQUENCE  2
  12 STORE_NAME   1 (y)
  15 STORE_NAME   2 (z)
  18 LOAD_CONST   1 (None)
  21 RETURN_VALUE

Obviously we can't unpack the zero, but the code doesn't know
that until it tries it, so we can look at what the left hand side code is
independent of the right hand side.


>binding the names inside the tuple to a value and placing them in the
>local namespace( implicit tuple unpacking ). It might be the "same" as
>no parens but it isn't very clear. If you want a tuple make it
>explicit, if you want individual names make it explicit.
OTOH, you might want a mix:

 >>> a, tup, (b,c), d = ['A', ('a', 'tuple'), 'BC', 'Sandra']
 >>> a
 'A'
 >>> tup
 ('a', 'tuple')
 >>> b
 'B'
 >>> c
 'C'
 >>> d
 'Sandra'

Or with gratuitous _outer_ parens:

 >>> (a, tup, (b,c), d) = ['A', ('a', 'tuple'), 'BC', 'Sandra']
 >>> a
 'A'
 >>> tup
 ('a', 'tuple')
 >>> b
 'B'
 >>> c
 'C'
 >>> d
 'Sandra'

 >>> dis.dis(compile("a, tup, (b,c), d = ['A', ('a', 'tuple'), 'BC', 
 >>> 'Sandra']",'','exec'))
   1   0 LOAD_CONST   0 ('A')
   3 LOAD_CONST   6 (('a', 'tuple'))
   6 LOAD_CONST   3 ('B

Re: A new to Python question

2005-05-14 Thread Bengt Richter
On 14 May 2005 10:44:30 -0700, "M.E.Farmer" <[EMAIL PROTECTED]> wrote:
[...]
>Be sure to study up on namespaces, it will ease your Python woes.
>Namespaces are the most fundamental part of Python that new users don't
>understand. Namespace mastery will take you far.
>Just remember there are only two scopes local and global ;)
And don't jump to conclusions when you read a line like the last above ;-)
I.e., there can be many different local and global scopes, not just one of each,
and since Python is a very dynamic language, existence of things can vary with
execution time and logic, so those scopes don't all have to exist at the same 
time,
or at all, nor persist until the program runs to its end. Also, ISTM "local" is 
probably
being stretched a little above to include nested scopes, which are a bit 
different
from either plain local or global in how you can access them.

I would second the advice to explore namespaces, and particularly attribute 
name spaces
such as are defined by classes. Attribute access and descriptors conspire to 
enable much
of the magic you can cook up with Python, as well as stuff that happens 
automatically.

In short, a whole unopened deluxe set of programming Legos is at your elbow, 
besides the
pieces you have encountered so far. Have fun ;-)

Regards,
Bengt Richter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A new to Python question

2005-05-14 Thread Steven Bethard
Steven Bethard wrote:
> 
> I don't know the implementation enough to know whether or not a tuple is 
> actually created when "b" and "c" are bound to their values, but I'd be 
> willing to bet that whatever happens to "(b, c)" is exactly the same as 
> what happens to "b, c".

Some corroborating evidence:

py> def f(t):
... (b, c) = t
...
py> def g(t):
... b, c = t
...
py> import dis
py> dis.dis(f)
   2   0 LOAD_FAST0 (t)
   3 UNPACK_SEQUENCE  2
   6 STORE_FAST   2 (b)
   9 STORE_FAST   1 (c)
  12 LOAD_CONST   0 (None)
  15 RETURN_VALUE
py> dis.dis(g)
   2   0 LOAD_FAST0 (t)
   3 UNPACK_SEQUENCE  2
   6 STORE_FAST   2 (b)
   9 STORE_FAST   1 (c)
  12 LOAD_CONST   0 (None)
  15 RETURN_VALUE

They're both an UNPACK_SEQUENCE byte-code.

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


Re: A new to Python question

2005-05-14 Thread Steven Bethard
M.E.Farmer wrote:
> I said exactly what I meant, the parentheses around the values creates
> a tuple that you have no reference to! It also has a side effect of
> binding the names inside the tuple to a value and placing them in the
> local namespace( implicit tuple unpacking ). It might be the "same" as
> no parens but it isn't very clear. If you want a tuple make it
> explicit, if you want individual names make it explicit.

It actually is the same, and I don't think implicit or explicit is the 
difference you should be citing here.  The parentheses are fully 
optional -- they don't change the semantics at all:

py> t = (4, 5)
py> a = t
py> a is t
True
py> a = (b, c) = t
py> a is t
True
py> a = b, c = t
py> a is t
True

In all cases, "a" still gets assigned the tuple (4, 5).  Whether or not 
you put the parentheses around "b, c" is fully a matter of style.

I don't know the implementation enough to know whether or not a tuple is 
actually created when "b" and "c" are bound to their values, but I'd be 
willing to bet that whatever happens to "(b, c)" is exactly the same as 
what happens to "b, c".

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


Re: tkinter puzzler

2005-05-14 Thread Paul Rubin
Martin Franklin <[EMAIL PROTECTED]> writes:
> I suspect you need to look at the columnconfigure / rowconfigure methods
> of the container (toplevel or frame)

Thanks, columnconfigure turned out to be the answer and Peter Otten's
post showing how to use it was very informative.  For some reason
columnconfigure is not documented in the otherwise excellent tkinter
reference manual from New Mexico Tech.

I'm having sort of a different prob now, which is I want to make a
pulldown menu as commonly seen on web pages.  The NMT reference
suggests using the MenuButton widget, which sort of works, though the
entrycget and entryconfigure methods that are supposedly on the menu
items aren't really there.  The toolkit itself says that MenuButton is
now considered obsolete and Frederik Lundh's manual seems to say
to use Menu somehow instead, but I haven't quite figured out how.

Is there a preferred and normal way to do this?  One thing I need is
to be able to disable individual menu choices based on stuff happening
in the application, which is why I wanted to use entryconfigure.

Also, I don't see how to get the little horizontal bar marker on the
button (as seen in IDLE) indicating that the button is a pulldown.  A
minute examining the IDLE source code didn't show it either, though I
can probably find it there with more effort.

Thanks as usual.
-- 
http://mail.python.org/mailman/listinfo/python-list


incorrect(?) shlex behaviour

2005-05-14 Thread bill
Consider:
>>> import shlex
>>> shlex.split('$(which sh)')
['$(which', 'sh)']

Is this behavior correct?  It seems that I should
either get one token, or the list
['$','(','which','sh',')'],
but certainly breaking it the way it does is
erroneous.  

Can anyone explain why the string is being split
that way?

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


Re: Modifying a built-in function for logging purposes

2005-05-14 Thread Greg Krohn
[EMAIL PROTECTED] wrote:
> Hi all,
> I wonder if it is possible to change (temporarily) a built-in function
> for logging purposes.
> Let me explain:
> I want to log all the 'open' operations, recording the file to be
> opened, the "mode" (r/w/a...) and (possibly) the module which made the
> call.
> After that the 'open' can carry on following the standard built-in
> path.
> Possibly I don't want to have to modify the source of the application
> to be logged.
> If there is another solution, I am open to any suggestion...
> 
> Bye.
> 

Would this work?

_file = file
def file(path, mode):
 print path, mode
 return _file(path, mode)

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


Re: A new to Python question

2005-05-14 Thread M.E.Farmer
I said exactly what I meant, the parantheses around the values creates
a tuple that you have no reference to! It also has a side effect of
binding the names inside the tuple to a value and placing them in the
local namespace. It might be the "same" but it isn't very clear. If you
want a tuple make it explicit, if you want individual names make it
explicit.
>>> def f(q,w,e,r):
... return q,w,e,r
...
>>> # diff names
>>> a,b,c,d= f(1,2,3,4)# explicit tuple unpacking
>>> dir()
['__builtins__', '__doc__', '__name__', 'a', 'b', 'c', 'd', 'f',
'shell']
>>> del a,b,c,d
>>> # where is the tuple
>>> (a,b,c,d)= f(1,2,3,4)# implicit tuple unpacking !?
>>> dir()
['__builtins__', '__doc__', '__name__', 'a', 'b', 'c', 'd', 'f',
'shell']
>>> del a,b,c,d
>>> # Where is the tuple (a,b,c,d)? There isn't one.
>>> # assign to a single name ( don't do tuple unpacking )
>>> tup=f(1,2,3,4)
>>> dir()
['__builtins__', '__doc__', '__name__', 'f', 'shell', 'tup']
Now there is.
Steve since you are closer to expert than novice you understand the
difference.
I feel this can be confusing to newbies, maybe you disagree.
M.E.Farmer

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


Re: A new to Python question

2005-05-14 Thread M.E.Farmer
I said exactly what I meant, the parentheses around the values creates
a tuple that you have no reference to! It also has a side effect of
binding the names inside the tuple to a value and placing them in the
local namespace( implicit tuple unpacking ). It might be the "same" as
no parens but it isn't very clear. If you want a tuple make it
explicit, if you want individual names make it explicit.
>>> def f(q,w,e,r):
... return q,w,e,r
...
>>> # diff names
>>> a,b,c,d= f(1,2,3,4)# explicit tuple unpacking
>>> dir()
['__builtins__', '__doc__', '__name__', 'a', 'b', 'c', 'd', 'f',
'shell']
>>> del a,b,c,d
>>> # where is the tuple
>>> (a,b,c,d)= f(1,2,3,4)# implicit tuple unpacking !?
>>> dir()
['__builtins__', '__doc__', '__name__', 'a', 'b', 'c', 'd', 'f',
'shell']
>>> del a,b,c,d
>>> # Where is the tuple (a,s,d,f)? There isn't one.
>>> # assign to a single name ( don't do tuple unpacking )
>>> tup=f(1,2,3,4)
>>> dir()
['__builtins__', '__doc__', '__name__', 'f', 'shell', 'tup']
Now there is.
Steve since you are closer to expert than novice you understand the
difference.
I feel this can be confusing to newbies, maybe you disagree.
M.E.Farmer

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


Re: A new to Python question

2005-05-14 Thread Bengt Richter
On Sat, 14 May 2005 20:38:26 +0200, Bernd Nawothnig <[EMAIL PROTECTED]> wrote:

>
>> On 2005-05-14, M.E.Farmer wrote:
>
>> (x,y,dotp,sumx,maxv) = abc(x,y,dotp,sumx,maxv)
>> This will only create a tuple in memory that has no name to reference
>> it by!
>
>Maybe. But it does not seem to hurt. And I am not sure the tupel _is_
>really created in that situation.
>
One way to get insight into what a statement does is to disassemble its code, 
e.g.,

 >>> import dis
 >>> dis.dis(compile('(x,y,dotp,sumx,maxv) = 
 >>> abc(x,y,dotp,sumx,maxv)','','exec'))
   1   0 LOAD_NAME0 (abc)
   3 LOAD_NAME1 (x)
   6 LOAD_NAME2 (y)
   9 LOAD_NAME3 (dotp)
  12 LOAD_NAME4 (sumx)
  15 LOAD_NAME5 (maxv)
  18 CALL_FUNCTION5
  21 UNPACK_SEQUENCE  5
  24 STORE_NAME   1 (x)
  27 STORE_NAME   2 (y)
  30 STORE_NAME   3 (dotp)
  33 STORE_NAME   4 (sumx)
  36 STORE_NAME   5 (maxv)
  39 LOAD_CONST   0 (None)
  42 RETURN_VALUE

In the context of a function or module scope, those loads and stores will change
to optimized byte code ops like LOAD_FAST and STORE_FAST etc, but you can see 
what's
happening above. I.e., on return from the function call, the returned sequence 
(we know it's
a tuple in your example, but it could be some other sequence thing) is upacked 
and its elements
are bound to the individual names, just as individual "assignments" would do.

Regards,
Bengt Richter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Multiple "cmp"s chained one after another

2005-05-14 Thread vincent wehren

"Volker Grabsch" <[EMAIL PROTECTED]> schrieb im 
Newsbeitrag news:[EMAIL PROTECTED]
| vincent wehren wrote:
| >
| > If you don't care about the year, why not just "normalize" the year
| > to all be the same using the replace method of the date instance?
|
| That's a very bad idea. In my example, this would work, but in "reality"
| I don't sort datetime objects, of course! (Is there any real application
| where you want to do that?)
|
| Instead, I'm sorting "Person" objects using a "birthday" attribute.
| Since I use these Person objects also in other places, they should never
| be modified without just to be sorted. In general, the number side effects
| should always be minimized.

Can you explain where you see a modification to the orginal object 
happening?
(or in any of the other solutions proposed for that matter...)

Not here I hope:

|
| > datesNorm = [obj.replace(year=1900) for obj in (dates)]
| > datesNorm.sort()

If you print datesNorm, you'll see:

[datetime.date(1900, 12, 2), datetime.date(1900, 12, 3), datetime.date(1900, 
12, 6), datetime.date(1900, 12, 7)]

However, dates is still the same:

[datetime.date(2004, 12, 2), datetime.date(2001, 12, 3), datetime.date(2002, 
12, 6), datetime.date(1977, 12, 7)]

|
| This code would go bad especially in my situation, where my "Person"
| objects are SQLObjects, thus the "normalisation" would be written into
| the database. Okay, one could use transactions and rollback", but I
| think, my point is clear now.

Since you wouldn't need to change the attribute object to
perform a sort (on the instances) using it (or portions of it) as key, it's 
not.
Or is there something fundamental I am missing about your particular use 
case?

| Nevertheless, I think you idea is very interesting. Is there any "real"
| application where normalizing just for sorting would be reasonable?

How about a case-insensitive sort of strings? (uppering being the 
normalization step)
Or getting rid of accented / special characters before sorting.
These sound like fairly straight-forward use cases to me ;)

Anyway, I was doing some SQL this morning where getting rid of portions of 
'datetime' fields in
a WHERE clause is sometimes just the ticket - hence the connection.


--

Vincent


|
| -- 
| Volker Grabsch
| ---<<(())>>---
| \frac{\left|\vartheta_0\times\{\ell,\kappa\in\Re\}\right|}{\sqrt
| [G]{-\Gamma(\alpha)\cdot\mathcal{B}^{\left[\oint\!c_\hbar\right]}}} 


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


Re: Faster GUI text control

2005-05-14 Thread none
   That's a good point about the amount of text available at once.  As 
long as I could swap the visible section fast enough that might be a 
good solution.
   This will run mostly on Windows, but I'd like for it to be equally 
usable on Linux.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Faster GUI text control

2005-05-14 Thread none
> 
> no, it would mean writing some python code.  if all you need is a scrolling
> text list, you can simply use the code on this page:
> 
> http://effbot.org/zone/wck-4.htm
> 
> (see "A scrollable list view, with scrollbar support" and, optionally,
> the virtual data modifications under "Displaying Huge Data Sets")
> 
> the resulting widget will update at constant speed, independent of the
> data size.
> 
> 
> 

Thanks for the suggestion.  I looked at that, but I need to be able to 
selectively change colors on parts of the text and I didn't think I 
could do that with a list box.  Am I misunderstanding that?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A new to Python question

2005-05-14 Thread Robert Kern
David wrote:
> Thank you very much.  Tulpes are really neat now that I've looked at
> them.  So after just fixing it, I changed it up and I would like to
> show it off now.
> 
> #! /usr/bin/python
> #This program takes two vectors and multiplies them
> #against a 10X10 array.  It also then gives the dot product,
> #sum, and max value of the array.
> 
> import Numeric
> def abc(package):
> """Takes two arrays and performs predetermined calculations,
>Then returns the solutions back as the same array, along
>with the dot product, sum, and max value of the array.
> 
>Data slots:
>0 - First Array
>1 - Second Array
>2 - Dot product
>3 - Sum
>4 - Max Value"""
> f = Numeric.zeros((10,10))
> for i in range(10):
> for j in range(10):
> f[i,j] = (i+1)+(j+1)
> 
> e = Numeric.matrixmultiply(f, package[0])
> g = Numeric.matrixmultiply(Numeric.transpose(f),package[1])
> package[0] = e
> package[1] = g
> package[2] = Numeric.dot(package[0],package[1])
> package[3] = Numeric.sum(package[0])
> package[4] = package[1][Numeric.argmax(package[1])]
> return package
> 
> data = [Numeric.arange(1,11),Numeric.arange(1,11)*2,0,0,0]
> #data = [Array X, Array Y, Dot product, Sum, Max Value]
> 
> print 'Array X:',data[0]
> print 'Array Y:',data[1]
> 
> data = abc(data)
> 
> print 'Calling function abc'
> print 'Array X:',data[0]
> print 'Array Y:',data[1]
> print 'Dot Product of X and Y:',data[2]
> print 'Sum of array X:',data[3]
> print 'Max value of array Y:',data[4]
> 
> I think its just wonderful now, but if you got any other suggestions,
> Please do tell.  Thanks everyone.

It's still not very Pythonic. Don't bother putting outputs in the 
argument list. There are some good use cases for doing so, but until 
you've been writing Python code for a while and the Pythonic idioms come 
naturally to you, you should probably resist the urge. Python is not 
Fortran.

def abc(x, y):
...
e = Numeric.matrixmultiply(f, x)
g = Numeric.matrixmultiply(Numeric.transpose(f), y)
dotp = Numeric.dot(x, y)
sumx = Numeric.sum(x)
maxy = Numeric.maximum.reduce(y)
return e, g, dotp, sumx, maxy

x = Numeric.arange(1,11)
y = x*2

x, y, dotp, sumx, maxy = abc(x, y)

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter

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


Re: Returning Date As String ?

2005-05-14 Thread Brian Beck
Peter Moscatt wrote:
> I am wanting to return the system date using the following:
> 
>   date.today()
> 
> How would I then convert this to a string ?

Use the strftime method. The formatting directives are documented here:
http://docs.python.org/lib/module-time.html

Example: date.today().strftime("%B %d, %Y")

-- 
Brian Beck
Adventurer of the First Order
-- 
http://mail.python.org/mailman/listinfo/python-list


Modifying a built-in function for logging purposes

2005-05-14 Thread qwweeeit
Hi all,
I wonder if it is possible to change (temporarily) a built-in function
for logging purposes.
Let me explain:
I want to log all the 'open' operations, recording the file to be
opened, the "mode" (r/w/a...) and (possibly) the module which made the
call.
After that the 'open' can carry on following the standard built-in
path.
Possibly I don't want to have to modify the source of the application
to be logged.
If there is another solution, I am open to any suggestion...

Bye.

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


Re: Jesus said, "I am the way, the truth and the life: no one can come to the Father(God)(in Heaven), but by me." (John 14:6) This means that if you die without trusting in Jesus Christ as your Lord and Saviour you will die in your sins and be forever separated from the love of God in a place called Hell. The Holy Bible descibes Hell as a place of eternal torment, suffering, pain and agony for all those who have rejected Jesus Christ. The good news is that you can be sure you are going to Heaven when this life is over if you allow Jesus Christ to save you today. Do not wait until later to be saved because you do not know exactly when you will die. [ Posted by: RonaldGrossi3848@yahoo.com on May 14, 2005 ] [ 2:52:09 pm ]

2005-05-14 Thread Do
Abuse reports to
[EMAIL PROTECTED],[EMAIL PROTECTED],[EMAIL PROTECTED],[EMAIL PROTECTED],[EMAIL 
PROTECTED],[EMAIL PROTECTED],[EMAIL PROTECTED],[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Multiple "cmp"s chained one after another

2005-05-14 Thread Volker Grabsch
Peter Hansen wrote:
> 
> Or just use the .timetuple() method on datetime objects and sort on the 
> 8th element of the 9-element tuple, which is the day-of-the-year.

An interesting idea. But wouldn't sorting by (dd.month,dd.day) be more
effective?

In other words: Does .timetuple() create a tuple, or does it just return
a tuple which is present anyway?


Greets,

-- 
Volker Grabsch
---<<(())>>---
\frac{\left|\vartheta_0\times\{\ell,\kappa\in\Re\}\right|}{\sqrt
[G]{-\Gamma(\alpha)\cdot\mathcal{B}^{\left[\oint\!c_\hbar\right]}}}
-- 
http://mail.python.org/mailman/listinfo/python-list


Jesus said, "I am the way, the truth and the life: no one can come to the Father(God)(in Heaven), but by me." (John 14:6) This means that if you die without trusting in Jesus Christ as your Lord and Saviour you will die in your sins and be forever separated from the love of God in a place called Hell. The Holy Bible descibes Hell as a place of eternal torment, suffering, pain and agony for all those who have rejected Jesus Christ. The good news is that you can be sure you are going to Heaven when this life is over if you allow Jesus Christ to save you today. Do not wait until later to be saved because you do not know exactly when you will die. [ Posted by: RonaldGrossi3848@yahoo.com on May 14, 2005 ] [ 2:52:09 pm ]

2005-05-14 Thread RonaldGrossi3848
http://www.gotquestions.org/sinners-prayer.html << I saw this site on a
search directory. Great Resource!

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


Re: Multiple "cmp"s chained one after another

2005-05-14 Thread Volker Grabsch
vincent wehren wrote:
> 
> If you don't care about the year, why not just "normalize" the year
> to all be the same using the replace method of the date instance?

That's a very bad idea. In my example, this would work, but in "reality"
I don't sort datetime objects, of course! (Is there any real application
where you want to do that?)

Instead, I'm sorting "Person" objects using a "birthday" attribute.
Since I use these Person objects also in other places, they should never
be modified without just to be sorted. In general, the number side effects
should always be minimized.

> datesNorm = [obj.replace(year=1900) for obj in (dates)]
> datesNorm.sort()

This code would go bad especially in my situation, where my "Person"
objects are SQLObjects, thus the "normalisation" would be written into
the database. Okay, one could use transactions and rollback", but I
think, my point is clear now.

Nevertheless, I think you idea is very interesting. Is there any "real"
application where normalizing just for sorting would be reasonable?


Greets,

-- 
Volker Grabsch
---<<(())>>---
\frac{\left|\vartheta_0\times\{\ell,\kappa\in\Re\}\right|}{\sqrt
[G]{-\Gamma(\alpha)\cdot\mathcal{B}^{\left[\oint\!c_\hbar\right]}}}
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A new to Python question

2005-05-14 Thread Philippe C. Martin
Yes, I gathered.

We all get our habits from somewhere :-)

Regards,

Philippe

Bernd Nawothnig wrote:

> On 2005-05-14, Philippe C. Martin wrote:
> 
>> You're thinking you're passing the arguments as reference
> 
> That is the way Fortran handles them:
> 
> [...]
> 
>>> Right now I'm taking a simple program I wrote in Fortran
> 
> 
> 
> 
> Bernd
> 

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


Re: sockets don't play nice with new style classes :(

2005-05-14 Thread Skip Montanaro

Paul> It seems to me that the socket module itself should be rewritten
Paul> to use new style classes, so that socket.socket objects can extend
Paul> _socket.socket instead of wrapping them.

Paul> Am I missing something?

Probably not.  The socket module could use some attention.

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


Re: Multiple "cmp"s chained one after another

2005-05-14 Thread Volker Grabsch
Steven Bethard wrote:
> Robert Kern wrote:
>  def mykey(d):
>  return (d.month, d.day)
> 
> The point here is that rather than chaining cmp() calls with ors, you 
> should just use a tuple -- the standard comparison order in tuples is 
> exactly what you're looking for.

That's an excellent idea! Thanks a lot. I really didn't think of the "key="
argument.


Greets,

-- 
Volker Grabsch
---<<(())>>---
\frac{\left|\vartheta_0\times\{\ell,\kappa\in\Re\}\right|}{\sqrt
[G]{-\Gamma(\alpha)\cdot\mathcal{B}^{\left[\oint\!c_\hbar\right]}}}
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A new to Python question

2005-05-14 Thread Bernd Nawothnig

> On 2005-05-14, M.E.Farmer wrote:

> (x,y,dotp,sumx,maxv) = abc(x,y,dotp,sumx,maxv)
> This will only create a tuple in memory that has no name to reference
> it by!

Maybe. But it does not seem to hurt. And I am not sure the tupel _is_
really created in that situation.

> How would you access the returned value?
> If you want a tuple you need to assign all the return vales to a single
> name.

We do not want the tuple.


Python 2.3.5 (#1, Apr 28 2005, 12:14:04)
[GCC 3.4.3-20050110 (Gentoo Linux 3.4.3.20050110-r2,
ssp-3.4.3.20050110-0, pie-
on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def foo():
>>> ... return 1,2,3
>>> ...
>>> (a,b,c)=foo()
>>> print a,b,c
1 2 3
>>>

works.

Of course, you can omit the ():

>>> a,b,c=foo()
>>> print a,b,c
1 2 3

That makes no difference.




Bernd

-- 
Those who desire to give up freedom in order to gain security,
will not have, nor do they deserve, either one. [T. Jefferson]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A new to Python question

2005-05-14 Thread David
Hmm don't know what happened.  I guess the formatting got all chewed up.

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


Re: A new to Python question

2005-05-14 Thread David
Thank you very much.  Tulpes are really neat now that I've looked at
them.  So after just fixing it, I changed it up and I would like to
show it off now.

#! /usr/bin/python
#This program takes two vectors and multiplies them
#against a 10X10 array.  It also then gives the dot product,
#sum, and max value of the array.

import Numeric
def abc(package):
"""Takes two arrays and performs predetermined calculations,
   Then returns the solutions back as the same array, along
   with the dot product, sum, and max value of the array.

   Data slots:
   0 - First Array
   1 - Second Array
   2 - Dot product
   3 - Sum
   4 - Max Value"""
f = Numeric.zeros((10,10))
for i in range(10):
for j in range(10):
f[i,j] = (i+1)+(j+1)

e = Numeric.matrixmultiply(f, package[0])
g = Numeric.matrixmultiply(Numeric.transpose(f),package[1])
package[0] = e
package[1] = g
package[2] = Numeric.dot(package[0],package[1])
package[3] = Numeric.sum(package[0])
package[4] = package[1][Numeric.argmax(package[1])]
return package

data = [Numeric.arange(1,11),Numeric.arange(1,11)*2,0,0,0]
#data = [Array X, Array Y, Dot product, Sum, Max Value]

print 'Array X:',data[0]
print 'Array Y:',data[1]

data = abc(data)

print 'Calling function abc'
print 'Array X:',data[0]
print 'Array Y:',data[1]
print 'Dot Product of X and Y:',data[2]
print 'Sum of array X:',data[3]
print 'Max value of array Y:',data[4]

I think its just wonderful now, but if you got any other suggestions,
Please do tell.  Thanks everyone.

David

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


Re: A new to Python question

2005-05-14 Thread Steven Bethard
M.E.Farmer wrote:
> (x,y,dotp,sumx,maxv) = abc(x,y,dotp,sumx,maxv)
> This will only create a tuple in memory that has no name to reference
> it by!

Huh?  This binds the names "x", "y", "dotp", "sumx" and "maxv" to the 
values returned by abc:

py> def abc(*args):
... return args
...
py> (x,y,dotp,sumx,maxv) = abc(2,3,5,7,11)
py> x
2
py> y
3
py> dotp
5
py> sumx
7
py> maxv
11

Of course, the parentheses around x,y,dotp,sumx,maxv are unnecessary.

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


Re: A new to Python question

2005-05-14 Thread M.E.Farmer
(x,y,dotp,sumx,maxv) = abc(x,y,dotp,sumx,maxv)
This will only create a tuple in memory that has no name to reference
it by!
How would you access the returned value?
If you want a tuple you need to assign all the return vales to a single
name.
mytup = abc(x,y,dotp,sumx,maxv)
M.E.Farmer

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


Re: A new to Python question

2005-05-14 Thread M.E.Farmer
David wrote:
> Hi I'm trying to teach myself python and so far to good, but I'm
having
> a bit of trouble getting a function to work the way I think it should
> work.  Right now I'm taking a simple program I wrote in Fortran and
> trying to do it in Python.  I got it to work, but now I'm trying to
> modularize it.  My fortran program uses a subroutine and I was trying
> to do the same thing in Python.  But I'm still new so I'm having
> trouble understanding what I'm doing wrong.  Here is my code:
>
> #! /usr/bin/python
> #This program takes two vectors and multiplies them
> #against a 10X10 array.  It also then gives the dot product,
> #sum, and max value of the array.
>
> import Numeric
> def abc(array1,array2,dotprod,sum,maxvalue):
> """Takes two arrays and performs predetermined calculations,
>Then returns the solutions back as the same array, along
>with the dot product, sum, and max value of the array."""
> #TODO: Get this damn thing working!!
> print "Array 1 in:",array1 #Debug
> data = Numeric.zeros((10,10))
> for i in range(10):
> for j in range(10):
> data[i,j] = (i+1)+(j+1)
>
> e = Numeric.matrixmultiply(data, array1)
> g = Numeric.matrixmultiply(Numeric.transpose(data),array2)
> array1 = e
> array2 = g
> dotprod = Numeric.dot(array1,array2)
> sum = Numeric.sum(array1)
> maxvalue = array2[Numeric.argmax(array2)]
> print "Array 1 out:",array1 #Debug
>
> return array1,array2,dotprod,sum,maxvalue #<<-- Not working as I
> thought it would.
>
> x = Numeric.arange(1,11)
> y = Numeric.arange(1,11)*2
> dotp,sumx,maxv = 0,0,0  #Is this the only way to declare a variable?
>
> print 'Array X:',x
> print 'Array Y:',y
> abc(x,y,dotp,sumx,maxv)
> print 'Calling function abc'
> print 'Array X:',x
> print 'Array Y:',y
> print 'Dot Product of X and Y:',dotp
> print 'Sum of array X:',sumx
> print 'Max value of array Y:',maxv
>
> If you run it the data gets passed to the function just fine and it
> finds the right numbers.  Its just getting it to pass them back thats
> not working.  I put some print statements inside the function just to
> see how the data gets passed.  So any ideas that would help me? If
you
> want to see the fortran code just email me.
>
> David

Hello David,
   welcome to Python!
Python always returns 'something' from a function or method if nothing
is specified or there is no return you get an implicit None.
You have created a function that accepts a few arguments and processes
them then returns there value.
The problem is that you **have not** used the return values ;)
example:

def funk(first,second,third):
return first,second,third

This can be like this:
print funk("theses three args can be anything",2,"three")

If you need to use the return values you need to assign them to a
"name" so you have a handle on them.
Variables are don't exist in Python there are only objects and names(
hence namespaces ), but not everyone is so strict and you still see
mention of 'variables' when they mean 'names'.
> ##dotp,sumx,maxv = 0,0,0  # not needed here
> print 'Array X:',x
> print 'Array Y:',y
> ## Notice we assign the return values to names so we can access it
later
> arr1,arr2,dotp,sumx,maxv = abc(x,y,0,0,0)
> print 'Calling function abc'
> print 'Array X:',arr1
> print 'Array Y:',arr2
> print 'Dot Product of X and Y:',dotp
> print 'Sum of array X:',sumx
> print 'Max value of array Y:',maxv

Or you could pack all return values into a tuple and access it thru
slices.
> ##dotp,sumx,maxv = 0,0,0  # not needed here
> print 'Array X:',x
> print 'Array Y:',y
> abcinfo = abc(x,y,0,0,0)
> print 'Calling function abc'
> print 'Array X:',abcinfo[0]
> print 'Array Y:',abcinfo[1]
> print 'Dot Product of X and Y:',abcinfo[2]
> print 'Sum of array X:',abcinfo[3]
> print 'Max value of array Y:',abcinfo[4]

Or you could use a dictionary, or etc...
The possibilities are endless.
Be sure to study up on namespaces, it will ease your Python woes.
Namespaces are the most fundamental part of Python that new users don't
understand. Namespace mastery will take you far.
Just remember there are only two scopes local and global ;)
http://docs.python.org
hth,
M.E.Farmer

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


Re: pygame on win32, image.fromstring()

2005-05-14 Thread tlviewer

"Greg Krohn" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> tlviewer wrote:
> > hello,
>
> hi
>
> > fp = open( "e:/batch/python/aceclub.bmp", "wt")
>
> wt? Should this be wb?
>
> > # gives: ValueError: String length does not equal format and resolution
size
> > img = gm.image.fromstring(str,(71,96),"P")
>
> The pygame docs say "P" is for 8bit pallete indices. When I look at the
> properties of aceclub.bmp, Windows says it's Bit Depth is 4. I'm not sure
if
> they're talking about the same thing, though. If so, you could probably
use PIL
> to convert the depth.

Yes, that was the trouble. Based on your suggestion, I now massage the
image string with PIL, then fromstring() works!

obj =Image.open(StringIO.StringIO(str))

#obj.convert( mode='P')
# conversion is implicit, mode is 'P' already
img = gm.image.fromstring(obj.tostring(),(71,96),"P")

Next I'm going to load all 53 card resources into a list (array) of strings,
then
write it out, pickled. That should smooth out loading the game when I use
4-6 decks (Blackjack-21).

thanks for getting to my post so quickly,
tlviewer
--


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


Re: A new to Python question

2005-05-14 Thread Bernd Nawothnig
On 2005-05-14, Philippe C. Martin wrote:

> You're thinking you're passing the arguments as reference

That is the way Fortran handles them:

[...]

>> Right now I'm taking a simple program I wrote in Fortran




Bernd

-- 
Those who desire to give up freedom in order to gain security,
will not have, nor do they deserve, either one. [T. Jefferson]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Documentation (should be better?)

2005-05-14 Thread kaerbuhez
bruno modulix a écrit :

> 
> I fail to see why would it would be better to have to open a browser, go 
> to python.org, go to the doc, find the right link etc instead of just 
> typing dir(xxx) and/or help(xxx).
> 

I fully agree with you. I just suspect that you are not more than me a 
web developper. I suppose that for this kind of guys, using a browser 
connected to the web is the more natural way to go ... and PHP 
developers are those kind of guys. This is to say that comparing the doc 
of PHP to the one of Python is somewhat not more relevant that comparing 
PHP to Python as languages. Probably even less because:
- PHP developers are "naturally" presentation oriented.
- it's easier to give "good" exemples when everybody is working in about
the same area.

Python is a very flexible tool and that makes things sometimes more
difficult ... but worthy anyway.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A new to Python question

2005-05-14 Thread Philippe C. Martin
Hi,

You're thinking you're passing the arguments as reference (look at mutable
vs non-mutable)

Your function returns the values in a tupple (x,y,...); you need to fetch
the values from that tupple

Regards,

Philippe





David wrote:

> Hi I'm trying to teach myself python and so far to good, but I'm having
> a bit of trouble getting a function to work the way I think it should
> work.  Right now I'm taking a simple program I wrote in Fortran and
> trying to do it in Python.  I got it to work, but now I'm trying to
> modularize it.  My fortran program uses a subroutine and I was trying
> to do the same thing in Python.  But I'm still new so I'm having
> trouble understanding what I'm doing wrong.  Here is my code:
> 
> #! /usr/bin/python
> #This program takes two vectors and multiplies them
> #against a 10X10 array.  It also then gives the dot product,
> #sum, and max value of the array.
> 
> import Numeric
> def abc(array1,array2,dotprod,sum,maxvalue):
> """Takes two arrays and performs predetermined calculations,
>Then returns the solutions back as the same array, along
>with the dot product, sum, and max value of the array."""
> #TODO: Get this damn thing working!!
> print "Array 1 in:",array1 #Debug
> data = Numeric.zeros((10,10))
> for i in range(10):
> for j in range(10):
> data[i,j] = (i+1)+(j+1)
> 
> e = Numeric.matrixmultiply(data, array1)
> g = Numeric.matrixmultiply(Numeric.transpose(data),array2)
> array1 = e
> array2 = g
> dotprod = Numeric.dot(array1,array2)
> sum = Numeric.sum(array1)
> maxvalue = array2[Numeric.argmax(array2)]
> print "Array 1 out:",array1 #Debug
> 
> return array1,array2,dotprod,sum,maxvalue #<<-- Not working as I
> thought it would.
> 
> x = Numeric.arange(1,11)
> y = Numeric.arange(1,11)*2
> dotp,sumx,maxv = 0,0,0  #Is this the only way to declare a variable?
> 
> print 'Array X:',x
> print 'Array Y:',y
> abc(x,y,dotp,sumx,maxv)
> print 'Calling function abc'
> print 'Array X:',x
> print 'Array Y:',y
> print 'Dot Product of X and Y:',dotp
> print 'Sum of array X:',sumx
> print 'Max value of array Y:',maxv
> 
> If you run it the data gets passed to the function just fine and it
> finds the right numbers.  Its just getting it to pass them back thats
> not working.  I put some print statements inside the function just to
> see how the data gets passed.  So any ideas that would help me? If you
> want to see the fortran code just email me.
> 
> David

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


Re: A new to Python question

2005-05-14 Thread Bernd Nawothnig
On 2005-05-14, David wrote:

> abc(x,y,dotp,sumx,maxv)

(x,y,dotp,sumx,maxv) = abc(x,y,dotp,sumx,maxv)




Bernd

-- 
Those who desire to give up freedom in order to gain security,
will not have, nor do they deserve, either one. [T. Jefferson]
-- 
http://mail.python.org/mailman/listinfo/python-list


A new to Python question

2005-05-14 Thread David
Hi I'm trying to teach myself python and so far to good, but I'm having
a bit of trouble getting a function to work the way I think it should
work.  Right now I'm taking a simple program I wrote in Fortran and
trying to do it in Python.  I got it to work, but now I'm trying to
modularize it.  My fortran program uses a subroutine and I was trying
to do the same thing in Python.  But I'm still new so I'm having
trouble understanding what I'm doing wrong.  Here is my code:

#! /usr/bin/python
#This program takes two vectors and multiplies them
#against a 10X10 array.  It also then gives the dot product,
#sum, and max value of the array.

import Numeric
def abc(array1,array2,dotprod,sum,maxvalue):
"""Takes two arrays and performs predetermined calculations,
   Then returns the solutions back as the same array, along
   with the dot product, sum, and max value of the array."""
#TODO: Get this damn thing working!!
print "Array 1 in:",array1 #Debug
data = Numeric.zeros((10,10))
for i in range(10):
for j in range(10):
data[i,j] = (i+1)+(j+1)

e = Numeric.matrixmultiply(data, array1)
g = Numeric.matrixmultiply(Numeric.transpose(data),array2)
array1 = e
array2 = g
dotprod = Numeric.dot(array1,array2)
sum = Numeric.sum(array1)
maxvalue = array2[Numeric.argmax(array2)]
print "Array 1 out:",array1 #Debug

return array1,array2,dotprod,sum,maxvalue #<<-- Not working as I
thought it would.

x = Numeric.arange(1,11)
y = Numeric.arange(1,11)*2
dotp,sumx,maxv = 0,0,0  #Is this the only way to declare a variable?

print 'Array X:',x
print 'Array Y:',y
abc(x,y,dotp,sumx,maxv)
print 'Calling function abc'
print 'Array X:',x
print 'Array Y:',y
print 'Dot Product of X and Y:',dotp
print 'Sum of array X:',sumx
print 'Max value of array Y:',maxv

If you run it the data gets passed to the function just fine and it
finds the right numbers.  Its just getting it to pass them back thats
not working.  I put some print statements inside the function just to
see how the data gets passed.  So any ideas that would help me? If you
want to see the fortran code just email me.

David

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


Anyway to designating the encoding of the "source" for compile?

2005-05-14 Thread janeaustine50
Python's InteractiveInterpreter uses the built-in compile function.

According to the ref. manual, it doesn't seem to concern about the
encoding of the source string.

When I hand in an unicode object, it is encoded in utf-8 automatically.
It can be a problem when I'm building an interactive environment using
"compile", with a different encoding from utf-8. IDLE itself has the
same problem. ( '' is treated okay
but u'' is treated wrong.)

Any suggestions or any plans in future python versions?

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


Quick Reference from module doc strings.

2005-05-14 Thread Ron Adam

Does anyone have suggestions on how to improve this further?


Cheers,
Ron_Adam



def getobjs(object, dlist=[], lvl=0, maxlevel=1):
 """ Retrieve a list of sub objects from an object. """
 if object not in dlist:
 dlist.append(object)
 if lvl200:
 s = object[0:200]+".."
 else:
 s = object
 outtext.append(obj+'=')
 if '\n' in s: quotes='"""'
 else: quotes ='"'
 if len(s)>60: print
 outtext.append(quotes+s+quotes+'\n\n')
 elif (isinstance(object,str)
 or isinstance(object,int)
 or isinstance(object,bool)
 or isinstance(object,tuple)
 or isinstance(object,list)
 or isinstance(object,dict)):
 s = str(object)
 if len(s)<200:
 outtext.append(obj+'='+s+'\n\n')
 else:
 outtext.append(obj+'='+s[0:200]+'..\n\n')
 if hasattr(object,'__doc__'):
 if object.__doc__ != type(object).__doc__:
 outtext.append(str(object.__doc__)+'\n\n')
 return ''.join(outtext)

def quick_ref(name):
 """
 quick_ref(module_name) -> printable string

 Generate a sorted quick reference guide from an objects
 doc strings.  The module_name is a string with the name of
 the module or class to get documents string from.

 Example:
 import os
 print quick_ref('os')
 """
 objlist = getobjs(name)
 return printdoc(objlist)

if __name__ == "__main__":
 #import module before calling in most cases.
 print quick_ref('__builtins__')





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


Re: Python 2.4 & BLT ?

2005-05-14 Thread Ron Adam
StepH wrote:

>>
>> A little googling found the following which may give you a clue or 
>> ideas of further searches.  Also run a virus scanner on the file 
>> before hand.
>>
>> http://www.noteworthysoftware.com/composer/faq/90.htm
> 
> 
> Argg...  I always find me stupid when i don't have find myself a such 
> easy solution.  Running the .exe from C:\temp works, but now, even if 
> the installation succes, i'm not able to run the pmw sample based on 
> it...  Looks like i've now to re-install pmw or somethings like that.
> 
> I'll find it...
> 
> Thanks a lot for your help.
> StepH.
> 

Glad I could help. It's a shame BLT has the installation issues it does 
on windows.  It really needs to be repackaged correctly.  Also you will 
probably also need to do the following which I posted earlier on the 
group, but will recopy it here as well.  (That way it will be easier for 
me to find it next time I need it. ;-)


BLT doesn't install in the correct directories on Windows. I found this
helpful.

 1.  Install BLT 2.4u into C:/Python23/tcl, using BLT's installer
(the one for Tcl/Tk 8.3). This gives you bin, include, and lib
subdirectories of C:/Python23/tcl, with all the BLT stuff in them.
 2. Copy C:/Python23/tcl/lib/blt2.4 into C:/Python23/tcl/tcl8.3.
 3. Put the BLT DLLs in a directory on your PATH (not necessarily a
system directory, it just has to be on your PATH)

Clipped from: http://heim.ifi.uio.no/~hpl/scripting/software.html


Cheers,
Ron_Adam

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


Re: Multiple "cmp"s chained one after another

2005-05-14 Thread Steven Bethard
Robert Kern wrote:
> I find that using the "key" argument to sort is much nicer than "cmp" 
> for these tasks.
> 
> In [5]:L = [datetime.date(2005,5,2), datetime.date(1984,12,15), 
> datetime.date(1954,1,1)]
> 
> In [7]:L.sort(key=lambda x: (x.month, x.day))
> 
> In [8]:L
> Out[8]:
> [datetime.date(1954, 1, 1),
>  datetime.date(2005, 5, 2),
>  datetime.date(1984, 12, 15)]

Yes, definitely.  Also worth noting in Robert Kern's solution is that 
instead of writing:

 def mycmp(d1, d2):
 return cmp(d1.month,d2.month) or cmp(d1.day,d2.day)

you can write:

 def mycmp(d1, d2):
 return cmp((d1.month, d1.day), (d2.month, d2.day))

or if you're using the key= argument (like you probably should):

 def mykey(d):
 return (d.month, d.day)

The point here is that rather than chaining cmp() calls with ors, you 
should just use a tuple -- the standard comparison order in tuples is 
exactly what you're looking for.

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


Re: Encryption with Python?

2005-05-14 Thread Philippe C. Martin
Hi,

I am a very happy user of http://www.amk.ca/python/code/crypto.html

Regards,

Philippe



Blake T. Garretson wrote:

> I want to save some sensitive data (passwords, PIN numbers, etc.) to
> disk in a secure manner in one of my programs.  What is the
> easiest/best way to accomplish strong file encryption in Python?  Any
> modern block cipher will do: AES, Blowfish, etc.  I'm not looking for
> public key stuff; I just want to provide a pass-phrase.
> 
> I found a few modules out there, but they seem to be all but abandoned.
>  Most seem to have died several years ago.  The most promising package
> is A.M. Kuchling's Python Cryptography Toolkit
> (http://www.amk.ca/python/code/crypto.html).
> 
> Is this the defacto Python encryption solution?  What does everyone
> else use?  Any other suggestions?  The SSLCrypto package
> (http://www.freenet.org.nz/python/SSLCrypto/) may be a good alternative
> too, but I am not sure if it is actively maintained.
> 
> Thanks,
> Blake

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


Re: Build-in or user-defined exceptions?

2005-05-14 Thread Peter Hansen
Torsten Bronger wrote:
> I write a module, and so I must raise exceptions at several points.
> The PEP 8 says that a module should define their own exceptions base
> class, derived from "Exception", and derivatives of that.
> 
> However, the build-in exceptions cover most of the error types that
> occur in a standard program.  For example, my module communicates
> with measurement instruments, so any communication error would fit
> perfectly to the build-in "IOError", wouldn't it?  

No... *any* communication error?  What if it's an error in the serial 
port layer, or the protocol layer, or the application layer handling 
that communication?  Wouldn't SerialError, ProtocolError, or 
UnrecognizedResponseError (or things like that) be much more readable. 
I find fine-grained app-specific exceptions to be very helpful in 
writing code that talks to machines.

> Invalid arguments
> can raise "TypeError"s, and so on and so forth.

Likewise, RangeError, InvalidAddressError, and the like seem more 
helpful to me, most of the time.

I guess I pretty much follow PEP8 (though I don't recall its details 
right now) since I derive from Exception things like DriverError and 
then derive more specific exceptions from that as needed (in the case of 
a driver module), or ProtocolError and children, etc..

> Is it considered good style to raise build-in exceptions whereever
> one thinks it's appropriate?  Is the definition of module exceptions
> derived from "IOError", "TypeError" etc. a good idea?  Is there some
> sort of style guide for recommended exceptions design in Python?

As Fredrik recommends, use your own judgment, but I believe that one 
should use a very narrow definition for those exceptions.  For example, 
TypeError should be used specifically when the code involved has 
received an object of the wrong type and *not* (for example) when a 
driver receives the wrong "type" of command from another device.

I sometimes derive from things like ValueError (rather than just 
Exception) when it seems appropriate, but that's pretty rare, and it's 
also not what the docs themselves recommend.

Be guided by the descriptions of those exceptions in the docs and not by 
their names alone.  See 
http://docs.python.org/lib/module-exceptions.html for more and be sure 
to read the descriptions of the base classes, not just the subclasses.

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


Re: Multiple "cmp"s chained one after another

2005-05-14 Thread Peter Hansen
vincent wehren wrote:
> "Volker Grabsch" <[EMAIL PROTECTED]> schrieb im 
> Newsbeitrag news:[EMAIL PROTECTED]
> | However, I don't want to sort them the default way. These are birthdays,
> | so only the month and day do matter, not the year. E.g.:
> |
...
> If you don't care about the year, why not just "normalize" the year
> to all be the same using the replace method of the date instance?
> Something like:
> 
> d1 = datetime.date(2004, 12, 2)
> d2 = datetime.date(2001, 12, 3)
> d3 = datetime.date(2002, 12, 6)
> d4 = datetime.date(1977, 12, 7)
> dates =[d1,d2,d3,d4]
> datesNorm = [obj.replace(year=1900) for obj in (dates)]
> datesNorm.sort()
> print datesNorm # etcetera

Or just use the .timetuple() method on datetime objects and sort on the 
8th element of the 9-element tuple, which is the day-of-the-year.

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


Re: Build-in or user-defined exceptions?

2005-05-14 Thread Fredrik Lundh
Torsten Bronger wrote:

> Is it considered good style to raise build-in exceptions whereever
> one thinks it's appropriate?

yes.

> Is the definition of module exceptions derived from "IOError", "TypeError"
> etc. a good idea?

sure (when absolutely necessary).

> Is there some sort of style guide for recommended exceptions design in
> Python?

just use your intuition.





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


Re: function with variable arguments

2005-05-14 Thread Harald Schmidt
Xah Lee wrote:

> I think it would be a improvement for the built-in range() so that step
> needs not be an integer. [...]
>
> Range( 5, 7, 0.3); # returns [5, 5.3, 5.6, 5.9, 6.2, 6.5, 6.8]

This may not return what you expect it to return.

For example let's use a naive implementation like this:

def Range(start, stop, step):
  values = []
  while start < stop:
values.append(start)
start += step
  return values

The result is:
>>> Range(5, 7, 0.3)
[5, 5.2998, 5.5996, 5.8995,
6.1993, 6.4991, 6.7989]

Worse: Range(5, 7.1, 0.3) would return 8 values, not 7 as expected from e.g.
range(50, 71, 3).

Welcome to the interesting world of floating point numbers.

 Harald

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


Re: A question about inheritance

2005-05-14 Thread arserlom
Ok, thanks. I didn't know about new-style classes (I had learned python
from a book prior to them).

After reading about new-style classes, I find that your solution is
better because, using super (in general) avoids cl2 from having to know
the implementation details of cl1. This is  clearly explained in:

http://www.python.org/2.2.3/descrintro.html#cooperation

Also, when using new-style classes with IDLE, I found some problems
which I talk about in "Modifying CallTips.py to work with with
new-style classes in IDLE.", which I posted in this group.

Steven Bethard wrote:
> [EMAIL PROTECTED] wrote:
> > Hello I have a question about inheritance in Python. I'd like to do
> > something like this:
> >
> >  class cl1:
> >   def __init__(self):
> >self.a = 1
> >
> >  class cl2(cl1):
> >   def __init__(self):
> >self.b = 2
> >
> > But in such a way that cl2 instances have atributes 'b' AND 'a'.
> > Obviously, this is not the way of doing it, because the __init__
> > definition in cl2 overrides cl1's __init__.
> >
> > Is there a 'pythonic' way of achieving this?
>
> If there's a chance you might have multiple inheritance at some point
in
> this hierarchy, you might also try using super:
>
> class cl1(object): # note it's a new-style class
>  def __init__(self):
>  self.a = 1
>
> class cl2(cl1):
>  def __init__(self):
>  super(cl2, self).__init__()
>  self.b = 2
>
> Note that you probably want a new-style class even if you chose not
to
> use super in favor of Jp Calderone's suggestion.  There are very few
> cases for using old-style classes these days.
> 
> STeVe

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


Re: replace text in unicode string

2005-05-14 Thread John Machin
On 14 May 2005 02:23:55 -0700, "Dan Bishop" <[EMAIL PROTECTED]> wrote:

>Svennglenn wrote:
>> I'm having problems replacing text in a
>> unicode string.
>> Here's the code:
>>
>> # -*- coding: cp1252 -*-
>>
>> titel = unicode("ä", "iso-8859-1")

To the OP:
This is not causing the later problem, but it's evidence of the wrong
mindset for a start. You have just lied to the interpreter. You said
that your script was encoded using cp1252, but then you tried to pass
off a string constant as iso-8859-1!!! They are not exactly the same
repertoire. You need to make up your mind what character repertoire
your application should be confined to, and then apply that
restriction rigorously.

To get over the error message, all you need to do is this:

titel = u"ä"

... and didn't I (and/or somebody else) tell you this only a few days
ago?


>> print titel
>> print type(titel)
>>
>> titel.replace("ä", "a")
>>
>> When i run this program I get this error:
>>
>> titel.replace("ä", "a")
>> UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position
>0:
>> ordinal not in range(128)
>>
>> How can i replace text in the Unicode string?
>
>titel = titel.replace(u"ä", "a")

To Dan:
Fortuitously this works but if the OP wanted to change it to (say) an
umlauted-u then it would have thrown another UnicodeDecodeError.

Everybody please get into the habit of using u"blah blah" when you're
working with Unicode.

Like this:

titel = titel.replace(u"ä", u"a")

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


Build-in or user-defined exceptions?

2005-05-14 Thread Torsten Bronger
HallÃchen!

I write a module, and so I must raise exceptions at several points.
The PEP 8 says that a module should define their own exceptions base
class, derived from "Exception", and derivatives of that.

However, the build-in exceptions cover most of the error types that
occur in a standard program.  For example, my module communicates
with measurement instruments, so any communication error would fit
perfectly to the build-in "IOError", wouldn't it?  Invalid arguments
can raise "TypeError"s, and so on and so forth.

Is it considered good style to raise build-in exceptions whereever
one thinks it's appropriate?  Is the definition of module exceptions
derived from "IOError", "TypeError" etc. a good idea?  Is there some
sort of style guide for recommended exceptions design in Python?

Thank you!

TschÃ,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: win32com and apache and permissions

2005-05-14 Thread Chris Curvey
found the answer five minutes after posting the question.  Isn't that
always the way?

I had not granted the Apache user permission to launch IE.  To do so:

* launch DCOMCNFG.exe
* choose "internet explorer" and click "properties"
* choose the "security" tab and and "custom launch permissions"
* "edit  permissions", then "add"
* choose "Users", then click "show users"
* choose the "apache" user and click "add"
* "OK" your way out of there.

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


problem uploading ZIP file tp PyPI

2005-05-14 Thread John Machin

Sorry in advance if this is not the correct forum ...

I'm trying to upload what appears to be a perfectly OK zip file as a
"source" file type to PyPI, and am getting this response:

Error...
There's been a problem with your request
exceptions.ValueError: invalid distribution file

I have managed to upload a Windows installer, and downloaded it again
[but the download count is still stuck on zero].

Any clues?

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


win32com and apache and permissions

2005-05-14 Thread Chris Curvey
I'm trying to have a Python script (which is being launched by Apache
as a CGI) control Internet Explorer.  I have this working on my
development box, but when I moved the code to my integration test box,
I get "Access Denied" when trying to launch IE.  This only seems to
happen when running Apache as a service.  If I run apache as a console
app, everything works fine.  In summary:

User Method   Dev Box   Integration Box
AdministratorConsole  Works Works
AdministratorService  Works "Access Denied"
Apache   Console  Works Works
Apache   Service  Not permitted Not permitted

So somewhere, somehow, I think I've granted some permission on the dev
box that I have not granted on the integration box.  Can anyone think
of what it might be?

-Chris

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


Re: Multiple "cmp"s chained one after another

2005-05-14 Thread Robert Kern
Volker Grabsch wrote:
> Hello!
> 
> Ich just found a very nice 'pythonic' solution for an often appearing
> problem. I didn't find it documented anywhere, so I'm posting it here.
> If this isn't new in any way, I'd really like to get to know it.
> 
> Example problem:
> I have some "datetime" objects and want to sort them, as here:
> 
>   birthdays = [d1,d2,d3,d4]
>   birthdays.sort()
> 
> However, I don't want to sort them the default way. These are birthdays,
> so only the month and day do matter, not the year. E.g.:
> 
>   2003-01-01  should be smaller than  1984-05-01
[snip]
> Any opinions?

I find that using the "key" argument to sort is much nicer than "cmp" 
for these tasks.

In [5]:L = [datetime.date(2005,5,2), datetime.date(1984,12,15), 
datetime.date(1954,1,1)]

In [7]:L.sort(key=lambda x: (x.month, x.day))

In [8]:L
Out[8]:
[datetime.date(1954, 1, 1),
  datetime.date(2005, 5, 2),
  datetime.date(1984, 12, 15)]

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter

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


Re: function with variable arguments

2005-05-14 Thread tiissa
Xah Lee wrote:
> on a related topic,
> I think it would be a improvement for the built-in range() so that step
> needs not be an integer.

There are easy workarounds but I'd find it useful as well.

> Further, it'd be better to support decreasing range. e.g.
> 
> Range( 5, 7, 0.3); # returns [5, 5.3, 5.6, 5.9, 6.2, 6.5, 6.8]
> Range( 5, -4, -2); # returns [5,3,1,-1,-3]

The last one already works:
  >>> range(5,-4,-2)
  [5, 3, 1, -1, -3]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wxTimer problem

2005-05-14 Thread F. GEIGER
As Jp asked already: "indepenedent" from what?

I do such things all the time in a wx-App that controls a 6-axes robot. For
example, there I have a LED-Widget for displaying the actual pos. and
orient. of the tool. In a wxTimer handler I read OPC variables, whose values
are displayed in the LED-Widgets (the 6 LED-widgets make up a compound
widget that does the data retreival in a wxTimer handler).  My app is full
of widgets that own a timer to display current values.

As for "independent": If you wrote a GUI app in wx you'll want to display
those values coming from some COM objects. So simply tie a timer to the
widget that should display it and - do it. Or tie it to the frame containing
your widget. It's up to you - plenty of possibilities in wx/Python, and
total freedom (I know what I'm speakin' of, I started that app in VB...).

Kind regards
Franz GEIGER

"Jp Calderone" <[EMAIL PROTECTED]> schrieb im Newsbeitrag
news:[EMAIL PROTECTED]
> On Fri, 13 May 2005 14:57:26 +0800, Austin <[EMAIL PROTECTED]> wrote:
> >I wrote a GUI program on windows. (python & wxPython)
> >One function is to refresh the data from the COM Object continously.
> >In the beginning, I used the thread.start_new_thread(xxx,())
> >But no matter how i try, it will cause the win32com error.
> >
> >After that, i use the wx.Timer to do the refresh function.
> >It works fine, but i find one problem.
> >I think timer should be independant, just like thread, but wxTimer
doesn't.
> >
> >1. Does python have timer function( not included by thread)?
> >2. About the wxTimer, does any parameter to let it be independent?
> >
>
>   What does "independent" mean?
>
>   Jp


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


Re: Importing modules

2005-05-14 Thread jmdeschamps
CONTEXT:
Trying to modularize (is this english?) application development : MVC
style, team distributed so that a visual component can be in one module
imported and used  by the __main__, and connected (read packed) at
runtime to other components coming from the main or other modules.

PROBLEM:
After reading the above reference (and the Nutshell chapter) and trying
different importing variations I still have a very difficult time
understanding this situation.
1-importing Tkinter in main,
2-importing module that uses Tkinter, without importing Tkinter in that
module (DOES NOT WORK)
KLUDGED SOLUTION:
import Tkinter in module (but don't understand why it has to be this
way)

MODEL (I taught would work):
## importTestMain module
from Tkinter import *
import testModule

tata = testModule.toto() ## this works
myWidget = tata.createNewFrame() ## this gets the exception (see below)
...

## testModule
class toto(object):
def __init__(self):
self.someAttribute= 2
def createNewFrame(self):
self.myFrame = Frame()## culprit line in exception
return f

if __main__=='__name__':  ## team member tests is work here (does
work!)
from Tkinter import *
myInstance = otherModule.toto()
myWidget = myInstance.createNewFrame()
root=Tk()
myWidget.pack(in_=root)
root.mainloop()

The exception says :
Traceback (most recent call last):
  File
"C:\Python23\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py",
line 310, in RunScript
exec codeObject in __main__.__dict__
  File
"C:\jean_marc\exemples_code_source\modules_packages\import_test\importTestMain.py",
line 18, in ?
tata=toto()
  File
"C:\jean_marc\exemples_code_source\modules_packages\import_test\importTestMain.py",
line 10, in __init__
self.myNewFrame =
self.myTestModuleObject.createNewFrame(self.myInterModuleTestCommand)
  File
"C:\jean_marc\exemples_code_source\modules_packages\import_test\testModule.py",
line 8, in createNewFrame
self.myFrame = Frame()
NameError: global name 'Frame' is not defined
>>>

VARIATION
Imported testModule AFTER using Tkinter in main... same error :(

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


Re: Multiple "cmp"s chained one after another

2005-05-14 Thread vincent wehren

"Volker Grabsch" <[EMAIL PROTECTED]> schrieb im 
Newsbeitrag news:[EMAIL PROTECTED]
| Hello!
|
| Ich just found a very nice 'pythonic' solution for an often appearing
| problem. I didn't find it documented anywhere, so I'm posting it here.
| If this isn't new in any way, I'd really like to get to know it.
|
| Example problem:
| I have some "datetime" objects and want to sort them, as here:
|
| birthdays = [d1,d2,d3,d4]
| birthdays.sort()
|
| However, I don't want to sort them the default way. These are birthdays,
| so only the month and day do matter, not the year. E.g.:
|
| 2003-01-01  should be smaller than  1984-05-01
|
| So I have to write the comparison on my own, e.g.
|
| def cmp_birthdays(d1,d2):
| if d1.month > d2.month: return 1
| if d1.month < d2.month: return -1
| if d1.day > d2.day: return 1
| if d1.day < d2.day: return -1
| return 0
|
| ...
| birthdays.sort(cmp_birthdays)


If you don't care about the year, why not just "normalize" the year
to all be the same using the replace method of the date instance?
Something like:

d1 = datetime.date(2004, 12, 2)
d2 = datetime.date(2001, 12, 3)
d3 = datetime.date(2002, 12, 6)
d4 = datetime.date(1977, 12, 7)
dates =[d1,d2,d3,d4]
datesNorm = [obj.replace(year=1900) for obj in (dates)]
datesNorm.sort()
print datesNorm # etcetera


HTH,

---
Vincent




|
| This implementation of cmp_birthdays is very ugly. Image you want to
| chain more than 2 values in that "cmp_birthdays". I also want to use the
| builtin "cmp" function, not ">" and "<".
|
| After thinking some minutes about it, I found a very nice solution:
| I have some "cmp"s one aftter another. If one if them return 1 oder -1,
| it sould be returned. If it returns 0, the next "cmp" is used. In other
| words: I have a sequence of numbers, and want to get the first one that
| is not 0. (or return 0, if all numbers were 0)
|
| But this is exactly what the "or" operator does, due to short-circuit
| evaluation. In this example, that means:
|
| def cmp_bithdays(d1,d2):
| return cmp(d1.month,d2.month) or cmp(d1.day,d2.day)
|
| The generic pattern is:
|
| return cmp(...) or cmp (...) or cmp(...) or ...
|
| I'm not sure whether this pattern is already a "common recipe", but
| I found it to be a very nice idea. :-)
|
| Any opinions?
|
|
| Greets,
|
| Volker
|
| -- 
| Volker Grabsch
| ---<<(())>>---
| \frac{\left|\vartheta_0\times\{\ell,\kappa\in\Re\}\right|}{\sqrt
| [G]{-\Gamma(\alpha)\cdot\mathcal{B}^{\left[\oint\!c_\hbar\right]}}} 


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


Modifying CallTips.py to work with with new-style classes in IDLE.

2005-05-14 Thread arserlom
When using Idle, Call Tips are floating windows which display function,
class, and method parameter and docstring information when you type an
opening parenthesis, and which disappear when you type a closing
parenthesis.

But when you use new-style classes, they don't work fine and don't show
the arguments of the __init__ method.

There is a topic in this newsgroup (new style classes and an IDLE
"grump"), where a solution was given to the problem (in Mar 27 2002):

> The solution seems to be simply changing line 115 in CallTips.py (in
the
> Tools/Idle/ directory) as folows:
>
> if type(ob)==types.ClassType:
>
>   to
>
> if type(ob)==types.ClassType or type(ob) == types.TypeType:

I've tried it (Python 2.4.1 - IDLE 1.1.1) and it works fine (CallTips
was in the \Lib\idlelib directory for me).

Why isn't this the default behaviour? Is this the right place to post
this?

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


Re: 80 bit precision ?

2005-05-14 Thread chris

"km" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Hi all,
>
> does python currently support 80 bit precision  Floating Point Unit ?
>
> regards,
> KM

I've just been using the decimal module for Python 2.3 (native in Python
2.4) at 100 digit precision to solve some very high order polynomials. Slow
but worked well for me. Also used a rational.py module ported to Py 2.3.
Perhaps you can do your calcs to the precision you want with a combination
of decimal and rational arithmetic.

bwaha


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


Re: Returning Date As String ?

2005-05-14 Thread Roy Smith
Peter Moscatt <[EMAIL PROTECTED]> wrote:

> I am wanting to return the system date using the following:
> 
>   date.today()
> 
> How would I then convert this to a string ?
> 
> Pete

datetime.data objects have a __str__() method.  To convert one to a string, 
you just have to cause its __str__() to be invoked.  The most common ways 
of doing that are str(), %s, or print:

>>> import datetime
>>> d = datetime.date.today()
>>> d
datetime.date(2005, 5, 14)   # this is the repr() of the object
>>> print d
2005-05-14
>>> str(d)
'2005-05-14'
>>> '%s' % d
'2005-05-14'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.4 & BLT ?

2005-05-14 Thread StepH
Ron Adam a écrit :
> StepH wrote:
> 
>> Ron Adam a écrit :
>>
>>> StepH wrote:
>>>
>>>
 Ron Adam a écrit :


> StepH wrote:
>
>
>
>> Hi,
>>
>> I'm not able to install BLT on my Python 2.4 (upgraded to 2.4.1) 
>> distibution...
>>
>> I'v try to download btlz-for-8.3.exe, but when i try to install 
>> it, i've a msgbox saying to the file is corrupt...
>>
>> Any idea ?
>>
>> Thanks.
>>
>> StepH.
>
>
>
>
> Have you tried blt2.4z-for-8.4exe?
>
> http://blt.sourceforge.net




 yes.  When i try to execute it, a small msgbox apprea with the msg:
 Corrupt installation detected!

 Any idea ?
>>>
>>>
>>>
>>> Sounds like it might not be a corrupted install exe file, but a 
>>> previously installed version that is corrupted.
>>>
>>
>>
>> Hum, i've try to re-install all from scratch without success...
>>
>>
>>> Does the message box say anything else?  With just "Corrupt 
>>> installation detected!", it could also be a support file or missing 
>>> dll that the installer needs.
>>
>>
>>
>> Yes.  It's the only message that is displayed.
>> I've to go ahead...  so for now i'll use tk.Canvas for my display...
>>
>> If you have idea ?
> 
> 
> A little googling found the following which may give you a clue or ideas 
> of further searches.  Also run a virus scanner on the file before hand.
> 
> http://www.noteworthysoftware.com/composer/faq/90.htm

Argg...  I always find me stupid when i don't have find myself a such 
easy solution.  Running the .exe from C:\temp works, but now, even if 
the installation succes, i'm not able to run the pmw sample based on 
it...  Looks like i've now to re-install pmw or somethings like that.

I'll find it...

Thanks a lot for your help.
StepH.

> http://www.transcender.com/faqs/detail.aspx?pn=tradwnldinstallarticle00900&full=True&tree=True
>  
> 
> http://www.visagesoft.com/help/index.php?_a=knowledgebase&_j=questiondetails&_i=5
>  
> 
> http://www.wise.com/KBArticle.aspx?articleno=1034
> 
> As a last resort, you may also be able to check the exe file by using a 
> zip file reader such as winzip or powerarchiver.  You should be able to 
> extract the individual files that way, but it may be a bit of a task to 
> figure out where to put them.
> 
> Hope this helps,
> 
> _Ron

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


Python on a public library computer

2005-05-14 Thread [EMAIL PROTECTED]
Here's my situation:

I'm typing this in a public library on a computer with OS windows 2000
server. I can run Internet explorer, word, excel and powerpoint, that's
it. Maybe java, but it seems to be flaky.

I want to run python scripts from this computer. At home I have a
multi-computer network (from better times) but no internet access
anymore, I could use this to try out solutions. I also have access to a
friends computer which has internet connection, but I can't visit his
place all the time. He's away often but he's got a life of his own :-)

So I'm thinking of running some kind of python webserver from a
dedicated computer over there (visualizing some cherrypy webpage based
interpreter at the moment) but I would like to know other options.
However it would have to run from a webpage here ...

For example I would like to run a python script over there (e.g.
getting news from a usenet server) which puts the output in a zipfile
on another webpage so that I can fetch it here with the Internet
Explorer.

There seems to be no traffic load problem since there would be only a
few users (but it could become popular fast?). Also I'm worried about
security issues, but not so much that I would consider installing some
large scale payware professional solution.

Let me know what you think, unless it costs money. On the other hand
money would solve this problem so if I can do something to get that it
would be even better.

Anton

[the things they make you go through ...]

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


Re: Returning Date As String ?

2005-05-14 Thread [EMAIL PROTECTED]
if you're using date.today():
x=date.today()

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


Returning Date As String ?

2005-05-14 Thread Peter Moscatt
I am wanting to return the system date using the following:

date.today()

How would I then convert this to a string ?

Pete

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


Re: function with variable arguments

2005-05-14 Thread Xah Lee
Thanks to all for the reply. (i should've known better)

on a related topic,
I think it would be a improvement for the built-in range() so that step
needs not be an integer.
Further, it'd be better to support decreasing range. e.g.

Range( 5, 7, 0.3); # returns [5, 5.3, 5.6, 5.9, 6.2, 6.5, 6.8]
Range( 5, -4, -2); # returns [5,3,1,-1,-3]

 Xah
 [EMAIL PROTECTED]
â http://xahlee.org/

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

Multiple "cmp"s chained one after another

2005-05-14 Thread Volker Grabsch
Hello!

Ich just found a very nice 'pythonic' solution for an often appearing
problem. I didn't find it documented anywhere, so I'm posting it here.
If this isn't new in any way, I'd really like to get to know it.

Example problem:
I have some "datetime" objects and want to sort them, as here:

birthdays = [d1,d2,d3,d4]
birthdays.sort()

However, I don't want to sort them the default way. These are birthdays,
so only the month and day do matter, not the year. E.g.:

2003-01-01  should be smaller than  1984-05-01

So I have to write the comparison on my own, e.g.

def cmp_birthdays(d1,d2):
if d1.month > d2.month: return 1
if d1.month < d2.month: return -1
if d1.day > d2.day: return 1
if d1.day < d2.day: return -1
return 0

...
birthdays.sort(cmp_birthdays)

This implementation of cmp_birthdays is very ugly. Image you want to
chain more than 2 values in that "cmp_birthdays". I also want to use the
builtin "cmp" function, not ">" and "<".

After thinking some minutes about it, I found a very nice solution:
I have some "cmp"s one aftter another. If one if them return 1 oder -1,
it sould be returned. If it returns 0, the next "cmp" is used. In other
words: I have a sequence of numbers, and want to get the first one that
is not 0. (or return 0, if all numbers were 0)

But this is exactly what the "or" operator does, due to short-circuit
evaluation. In this example, that means:

def cmp_bithdays(d1,d2):
return cmp(d1.month,d2.month) or cmp(d1.day,d2.day)

The generic pattern is:

return cmp(...) or cmp (...) or cmp(...) or ...

I'm not sure whether this pattern is already a "common recipe", but
I found it to be a very nice idea. :-)

Any opinions?


Greets,

Volker

-- 
Volker Grabsch
---<<(())>>---
\frac{\left|\vartheta_0\times\{\ell,\kappa\in\Re\}\right|}{\sqrt
[G]{-\Gamma(\alpha)\cdot\mathcal{B}^{\left[\oint\!c_\hbar\right]}}}
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 80 bit precision ?

2005-05-14 Thread Sébastien Boisgérault
Terry Reedy a écrit :
> [...]
> Last I read, in CPython, the float type encapsulates a C double.
> So, does any C compiler implements doubles as 80 bit floats?

I seriously doubt it.

> Or, if it has 64 bit
> doubles and 80 bit long doubles, are the latter transparently
> substitutible for the former, so that you could change Python's
> float declaration and have everything work as expected?  (I an
> not sure of either.)

Mm ... the python C code implementing the math module is
probably not that polymorphic . Even a call to "sqrt"
does not work as expected if the argument is a long double.
"sqrtl" should be use instead.

Cheers,

SB

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


Re: replace text in unicode string

2005-05-14 Thread Dan Bishop
Svennglenn wrote:
> I'm having problems replacing text in a
> unicode string.
> Here's the code:
>
> # -*- coding: cp1252 -*-
>
> titel = unicode("ä", "iso-8859-1")
> print titel
> print type(titel)
>
> titel.replace("ä", "a")
>
> When i run this program I get this error:
>
> titel.replace("ä", "a")
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position
0:
> ordinal not in range(128)
>
> How can i replace text in the Unicode string?

titel = titel.replace(u"ä", "a")

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


  1   2   >