ANN: Python Ireland Meeting and Presentations

2006-10-17 Thread Michael Twomey
The Python Ireland group will be meeting on Thursday, 19th October at
Trinity College Arts Block, room 2041B from 19:00 - 20:00.

The following presentations are lined up:

* What's new in python 2.5
* Introduction to web.py

This will be followed by a drink or two in the nearest pub.

For more information and directions see
http://wiki.python.ie/moin.cgi/PythonMeetup/October2006

For more information on the Python Ireland group see http://python.ie/

cheers,
  Michael
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


OSDC 2006's fabulous keynotes

2006-10-17 Thread Richard Jones
Book before 31st October to save $50 and get a free conference t-shirt!

Registrations are open for the Open Source Developers' Conference 2006:
http://www.osdc.com.au/registration/index.html   The conference is running
in Melbourne from the 6th - 8th December, with a day of tutorials on the
5th.

Keynote talks this year include:

Anthony Baxter: futurepython

import __future__

What does the future hold for the Python language? In this talk, we'll look
at Microsoft's (Open Sourced!) IronPython and show some of the massive fun
coming down the track for scripting languages thanks to .Net and Mono.
We'll also cover Python 3.0 (now under development) and the PyPy (Python,
in Python) project.


Damian Conway:  The Da Vinci Codebase

When a dying operating system scrawls his name across its corrupted boot
volume, Dr. Damian Conway, an unassuming college professor, is plunged into
a deadly race against time to solve a series of impossible riddles. What is
the mysterious Priory of Bios? And who are their deadly nemeses Opus
Arai? On the run from the law and stalked by a ghostly pale killer, will
he unravel the subtle clues hidden in Leonardo's most famous source code
and reveal to the world the incredible secret encrypted in...the Da Vinci
Codebase?


Randal L. Schwartz: Free software - A look back, a look ahead

A twenty year history of the free/open software movement, from my
perspective of how to contribute (in many ways!) and how to make money as
well.


Richard Farnsworth: Open Source Synchrotron

What is a Synchrotron anyway?  What software needs does it has?  How can
Open Source help solve these?  The Australian Synchrotron achieved first
light in July 2005 almost exclusively filling its software needs through
open source.  The code base has been refined to suit local conditions, and
shared with the rest of the Synchrotron open source community.  By sharing
information, experience and software freely between scientists and
engineers, great design efficiencies have been made further aiding the
development of experimental beamlines.


Be a part of this fantastic conference and help it be the best developers'
conference this year!  If your business would like to benefit from exposure
to many of Australia's best open source developers then perhaps you should
consider sponsorship.  We have a wide range of sponsorship options, to find
out more information please visit:
http://www.osdc.com.au/sponsors/index.html

We look forward to sharing this great conference with you!  Don't forget to
register before 31st October to get a free conference t-shirt.

http://www.osdc.com.au/registration/index.html


-- 
Richard Jones, OSDC 2006 Programme Chair
http://www.osdc.com.au/
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


Re: A friendlier, sugarier lambda -- a proposal for Ruby-like blocksin python

2006-10-17 Thread Hendrik van Rooyen
 Bruno Desthuilliers [EMAIL PROTECTED] wrote:
 Kay Schluehr wrote:
  Bruno Desthuilliers wrote:
 
  Just for the record : Ruby's code-blocks (closures, really) come from
  Smalltalk, which is still the OneTrueObjectLanguage(tm).
 
  IsTheOneTrueObjectLanguage(tm)ReallyCamelCased?
 
 ThatsAGoodQuestion.


DoYouMeanIsTheIdentifierTheOneTrueObjectLanguage(tm)CamelCasedOrIsTheObjectObjec
tBoundToIdentifierTheOneTrueObjectLanguage(tm)CamelCasedOrYetSomethingElse?

IAmGladToSeeThisSterlingAttemptAtMinimisingTheEncodingSpaceAsTheSpaceCharacterNe
verImpartedAnyInformationAnywayHendrik

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


Re: COM Error -- Urgent help

2006-10-17 Thread M�ta-MCI
Hi!


.func(  is not defined...


@-salutations
-- 
Michel Claveau



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


a question about s[i:j] when i is negative

2006-10-17 Thread dracula571
s[i:j] slice of s from i to j (3), (4)

(3)
If i or j is negative, the index is relative to the end of the string:
len(s) + i or len(s) + j is substituted. But note that -0 is still 0.


(4)
The slice of s from i to j is defined as the sequence of items with
index k such that i = k  j. If i or j is greater than len(s), use
len(s). If i is omitted or None, use 0. If j is omitted or None, use
len(s). If i is greater than or equal to j, the slice is empty.

i can't follow (3) very well.
for example:k = [1,2,3,4,5]
k[-1:2]=[]
k[-5:2]=[1,2]
but k[-6:2] = [1,2]
why k[-6:2] is [1,2]not [].i do follow (3),to make i positive by
plusing len(k) twice.But the result is not what i expect.why,or did i
misunderstand the rule of (3).

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


Re: a question about s[i:j] when i is negative

2006-10-17 Thread Fredrik Lundh
dracula571 wrote:

 but k[-6:2] = [1,2]
 why k[-6:2] is [1,2]not [].i do follow (3),to make i positive by
 plusing len(k) twice.

twice?

/F

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


Re: Python component model

2006-10-17 Thread Ilias Lazaridis
Terry Reedy wrote:
 Ilias Lazaridis [EMAIL PROTECTED] wrote in message
 news:[EMAIL PROTECTED]
  I share the infrastructure which I use:
 
  http://dev.lazaridis.com/base

 But not quite yet, it appears. A public release is planned shortly

Thank you for you comment.

You are right.

I've not yet selected the license yet (this case is quite complex):

http://case.lazaridis.com/wiki/License

But I've placed a BSD2 license to the existent files:

http://dev.lazaridis.com/base/browser/infra

.

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


Scope of decorator argument

2006-10-17 Thread Gregor Horvath
Hi,

this:

class base(object):
@adecorator(xy)
def edit(self):
print edit

class child(base):
xy = 3


obviously fails because xy is not bound at class creation time of the
base object.

One solution could be delegation:

class base(object):
@classmethod
def edit(self):
print do the real work here

class child(object):
xy = 3
mybase = base

@adecorator(xy)
def edit(self, *args, **kwargs):
self.mybase.edit(*args, **kwargs)

But then I have the ugly boiler plate delegation code in child.

Is there any other solution, probably with metaclasses ?

-- 
  Servus, Gregor
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python component model

2006-10-17 Thread Ilias Lazaridis

Peter  Wang wrote:
 Ilias Lazaridis wrote:
  looks interesting.

 Thanks!

  what about persistency?

 Um... what about it?


As far as I can see, there's no persistency binding available.

Is one planned?

http://groups.google.com/group/comp.lang.python/msg/dbdaedc68eee653a

.

--
http://lazaridis.com

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


Re: a question about s[i:j] when i is negative

2006-10-17 Thread [EMAIL PROTECTED]

dracula571 wrote:
 s[i:j] slice of s from i to j (3), (4)

 (3)
 If i or j is negative, the index is relative to the end of the string:
 len(s) + i or len(s) + j is substituted. But note that -0 is still 0.


 (4)
 The slice of s from i to j is defined as the sequence of items with
 index k such that i = k  j. If i or j is greater than len(s), use
 len(s). If i is omitted or None, use 0. If j is omitted or None, use
 len(s). If i is greater than or equal to j, the slice is empty.

 i can't follow (3) very well.
 for example:k = [1,2,3,4,5]
 k[-1:2]=[]
 k[-5:2]=[1,2]
 but k[-6:2] = [1,2]
 why k[-6:2] is [1,2]not [].

Because 6 is greater then len(k), so when you ask
for i=-6, you get i=-5 instead. And relative -5 is actually
absolute 0 which is less than 2, so you do not get an
empty slice.

 i do follow (3),to make i positive by
 plusing len(k) twice.But the result is not what i expect.why,or did i
 misunderstand the rule of (3).

See (4).

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


Re: Best IDE?

2006-10-17 Thread limodou
On 10/14/06, Fulvio [EMAIL PROTECTED] wrote:
 ***
 Your mail has been scanned by InterScan MSS.
 ***


 On Friday 13 October 2006 23:17, limodou wrote:
  hope you try it.

 If you'll manage for macro recording, playing back and from file then I'll be
 yours :)

 F

I'll add this funcationality at 3.6 version. And I want to release 3.5
as soon as I can.

-- 
I like python!
UliPad The Python Editor: http://wiki.woodpecker.org.cn/moin/UliPad
My Blog: http://www.donews.net/limodou
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Thread termination

2006-10-17 Thread Stefan Schukat



Hello

you are using the module variable ie inside the Generic 
Function, but you have to use "d" since this is the Python object 

which is allowed to access the COM object in the 
separate thread.

 Stefan

  
  
  From: Tejovathi P 
  [mailto:[EMAIL PROTECTED] Sent: Monday, October 16, 2006 9:47 
  AMTo: Stefan SchukatSubject: Re: Thread 
  termination
  
  HI all, 
  I have a problem in accesing COM objects in threads. To be precise, lets 
  assume that I have a class GenericFunctions which is defined as follows:
  import win32com.client, pythoncom, thread 
  ie=win32com.client.Dispatch('internetexplorer.application') 
  ie.Visible=1 
  class GenericFunctions: 
   def 
  __init__(self): 
  print "In Constructor of Generic 
  Functions" 
   def 
  MyNavigate(self,dest): 
  ie.Navigate(dest) 
  Now there is another file Main.py which is defined as 
follows:
  import win32com.client, pythoncom, thread from GenericFunctions import 
  *obj = GenericFunctions()
  class Mainclass: def 
  __init__(self); 
  print "In Constructor of Main class"
   def 
  threadFunction(self,dest): 
  pythoncom.CoInitialize() 
  d=pythoncom.CoGetInterfaceAndReleaseStream(s, 
  pythoncom.IID_IDispatch) 
  my_ie=win32com.client.Dispatch(d) 
  obj.func(dest) # this is 
  gving an 
  error. 
  pythoncom.CoUninitialize()
  if __name__ == "__main__": 
  s=pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch,ie) 
  thread.start_new_thread(self.nav, (s,'www.google.com ')
  Basically, I want to access object of GenericFunctions class inside 
  threadFunction(). However I was able to execute my_ie.Navigate("google.com"). But that was not I wanted. I am not 
  knowing where the error is Please let me know the solution ASAP...
  Teja.P
  
  On 10/13/06, Stefan 
  Schukat [EMAIL PROTECTED] 
  wrote: 
  Reading 
from your last posts you are using COM objects. Therefore youshould not 
"kill" the thread since this would lead to reference leaks. So there are 
only two ways left:1. Program a specific interpreter and not use 
python.exe whichimplements an access to PyThreadState_SetAsyncExc2. 
Check in the separate thread at specific times a variable which is set 
in the main thread.Both need the try finally construct in the 
threadfunction to release COMobjects in the right way.I.e., (taking 
the source from Roger):def ThreadFunction(istream, dest): 
 pythoncom.CoInitialize() // Initialize COM 
Runtime for this thread 
try: 
d=pythoncom.CoGetInterfaceAndReleaseStream(istream,pythoncom.IID_IDispatch) 
my_ie=win32com.client.Dispatch 
(d) 
my_ie.Navigate(dest) 
finally: 
my_ie = None// Release COM 
object 
pythoncom.CoUninitialize() // Release COM Runtime for 
thisthread Stefan 
  
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Max-plus library

2006-10-17 Thread Sébastien Boisgérault
Robert Kern wrote:
 Martin Manns wrote:
  Hello,
 
  Is there any library that allows employing max-plus dioids in
  python (e.g. based on numpy/scipy)?

 Google says no and I haven't heard of any, so I imagine that there aren't.
 There might be something buried in some of the control theory packages, but 
 as I
 neither know what max-plus dioids are, nor have I any current interest in 
 them,
 I can't give you any better pointers.

See http://cermics.enpc.fr/~cohen-g//SED/index-e.html for a two-page
introduction to the field and its applications. Definitely worth a look
IMHO.

The second software you refer to
(http://www-rocq.inria.fr/MaxplusOrg/soft.html) is a Scilab package but
essentially made of C and Fortran files. Getting a working binding for
Python may not be that hard ...

Cheers,

SB


 --
 Robert Kern

 I have come to believe that the whole world is an enigma, a harmless enigma
   that is made terrible by our own mad attempt to interpret it as though it 
 had
   an underlying truth.
-- Umberto Eco

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


How to paras such echo string effection?

2006-10-17 Thread Kevien Lee
Hi everyone,

When i decide to paras a string,which return from running a CVS command,it's amaze that i want to get some file of the echo string ,how to make paras process more effect?

the problem detail as follow that:

run command:cvs status -r it will return all the file list in as follow?


===File: file01.xlsStatus: Up-to-date
 Working revision:1.1 Repository revision:1.1/msg/file01.xls,v Sticky Tag:(none) Sticky Date:(none) Sticky Options:-kb
cvs status: Examining 20060815===File: file02.xlsStatus: Up-to-date
 Working revision:1.1 Repository revision:/msg/file02.xls ,v Sticky Tag:(none) Sticky Date:(none) Sticky Options:-kb
cvs status: Examining 20060816===
Now ,i just what to know the file of Status,if paras all should be
coast expenses,is there any effect way?
PS:is there any python lib for CVS ?

Thanks 
Best regards
Kevin Lee
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: COM Error -- Urgent help

2006-10-17 Thread Teja
Méta-MCI wrote:
 Hi!


 .func(  is not defined...


 @-salutations
 --
 Michel Claveau

I am sorry. By func(dest) I meant MyNavigate(dest). Can u please help
me out...

Thnks, 
Teja.P

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


Re: Scope of decorator argument

2006-10-17 Thread Gregor Horvath
Gregor Horvath schrieb:
 
 Is there any other solution, probably with metaclasses ?
 

I've found this one:

class mymeta(type):
def __new__(meta, class_name, bases, new_attrs):
new_attrs[edit] = adecorator(new_attrs['xy'])(bases[0].edit))
return type.__new__(meta, class_name, bases, new_attrs)

class base(object):
def edit(self):
print %s edit % self

class child(base):
__metaclass__ = mymeta
xy = 3


Don't know if it's the best solution but it seems to work.

-- 
  Servus, Gregor

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


Re: How to paras such echo string effection?

2006-10-17 Thread limodou
On 10/17/06, Kevien Lee [EMAIL PROTECTED] wrote:
 Hi everyone,

 When i decide to paras a string,which return from running a CVS command,it's
 amaze that i want to get some file of the echo string ,how to make paras
 process more effect?

 the problem detail as follow that:

 run command:cvs  status -r it will return all the file list in as follow?



 ===
 File: file01.xls Status: Up-to-date

Working revision: 1.1
Repository revision: 1.1 /msg/file01.xls,v
Sticky Tag:  (none)
Sticky Date:  (none)
Sticky Options: -kb

 cvs status: Examining 20060815
 ===
 File: file02.xls Status: Up-to-date

Working revision: 1.1
Repository revision:/msg/file02.xls ,v
Sticky Tag:  (none)
Sticky Date:  (none)
Sticky Options: -kb

 cvs status: Examining 20060816
 ===


 Now ,i just what to know the file of Status,if paras all should be

 coast expenses,is there any effect way?

 PS:is there any python lib for CVS ?


I think you can use regular expression to match the Status. Or simple
find 'File' and 'Status' substring, and get the result.

-- 
I like python!
UliPad The Python Editor: http://wiki.woodpecker.org.cn/moin/UliPad
My Blog: http://www.donews.net/limodou
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to paras such echo string effection?

2006-10-17 Thread Theerasak Photha
On 10/17/06, Kevien Lee [EMAIL PROTECTED] wrote:

 PS:is there any python lib for CVS ?

Doubt it, but there is a Python library for Subversion (SVN  CVS anyway).

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


Re: COM Error -- Urgent help

2006-10-17 Thread Fredrik Lundh
Teja wrote:

 I am sorry. By func(dest) I meant MyNavigate(dest). Can u please help
 me out...

nobody here can read your mind.  please post the code you're actually 
using, *and* the error you're getting.

/F

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


Re: How to paras such echo string effection?

2006-10-17 Thread Fredrik Lundh
Kevien Lee wrote:

 PS:is there any python lib for CVS ?

there's some stuff in Demo/pdist in the Python source distribution, 
including a module called cvslib.

/F

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


Re: How to paras such echo string effection?

2006-10-17 Thread Theerasak Photha
On 10/17/06, Fredrik Lundh [EMAIL PROTECTED] wrote:
 Kevien Lee wrote:

  PS:is there any python lib for CVS ?

 there's some stuff in Demo/pdist in the Python source distribution,
 including a module called cvslib.

then I stand corrected...

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


Re: A friendlier, sugarier lambda -- a proposal for Ruby-like blocksin python

2006-10-17 Thread Theerasak Photha
On 10/17/06, Hendrik van Rooyen [EMAIL PROTECTED] wrote:
  Bruno Desthuilliers [EMAIL PROTECTED] wrote:
  Kay Schluehr wrote:
   Bruno Desthuilliers wrote:
  
   Just for the record : Ruby's code-blocks (closures, really) come from
   Smalltalk, which is still the OneTrueObjectLanguage(tm).
  
   IsTheOneTrueObjectLanguage(tm)ReallyCamelCased?
  
  ThatsAGoodQuestion.
 
 
 DoYouMeanIsTheIdentifierTheOneTrueObjectLanguage(tm)CamelCasedOrIsTheObjectObjec
 tBoundToIdentifierTheOneTrueObjectLanguage(tm)CamelCasedOrYetSomethingElse?

 IAmGladToSeeThisSterlingAttemptAtMinimisingTheEncodingSpaceAsTheSpaceCharacterNe
 verImpartedAnyInformationAnywayHendrik

BurnMeIfThisIsntTurningIntoCeeTwoWiki

-- http://www.c2.com/cgi/wiki?TheerasakPhotha
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: COM Error -- Urgent help

2006-10-17 Thread Teja

Fredrik Lundh wrote:
 Teja wrote:

  I am sorry. By func(dest) I meant MyNavigate(dest). Can u please help
  me out...

 nobody here can read your mind.  please post the code you're actually
 using, *and* the error you're getting.

 /F

Thnks for your immediate reply.

Here is the code:

I have a class GenericFunctions which is defined as
follows:

import win32com.client, pythoncom, thread
ie=win32com.client.Dispatch('internetexplorer.application')
ie.Visible=1

class GenericFunctions:

   def __init__(self):
 print In Constructor of Generic Functions

   def MyNavigate(self,dest):
 ie.Navigate(dest)


Now there  is another file Main.py which is defined as follows:

import win32com.client, pythoncom, thread
from GenericFunctions import *
obj = GenericFunctions()

def threadFunction(self,dest):
pythoncom.CoInitialize()
d=pythoncom.CoGetInterfaceAndReleaseStream(s,
pythoncom.IID_IDispatch)
my_ie=win32com.client.Dispatch(d)
obj.MyNavigate(dest)  # this is gving an error.
pythoncom.CoUninitialize()

if __name__ == __main__:

s=pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch,i­­e)

   thread.start_new_thread(self.nav, (s,'www.google.com')

I am getting an attribute error

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


Re: A friendlier, sugarier lambda -- a proposal for Ruby-like blocks in python

2006-10-17 Thread Theerasak Photha
On 14 Oct 2006 09:25:00 -0700, Paul Boddie [EMAIL PROTECTED] wrote:

 Unlike Java, Python's first class functions and
 methods are already highly useful for callback-based systems

Curious: how well does the use of returning inner functions work as a
strategy for providing effectively 'anonymous' callbacks? e.g.

def outer(x):
  def inner(y):
...
  return inner

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


Any idea how to do this in Python?

2006-10-17 Thread Lad
In a web application users can post some information. I would like to
link each posting with a weight of importance for a user, depending
on a keywords in the posting.
For example, I know that a user A is interested in Nokia mobiles while
user B in Siemens mobiles.
So, if a user A is signed, he would see postings with more Nokia
information FIRST, while B user will see  FIRST  information about
Siemens mobiles
How can be that done in Python?
Thank you for any idea.
L.

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


Re: a question about s[i:j] when i is negative

2006-10-17 Thread dracula571

Fredrik Lundh 写道:

 dracula571 wrote:

  but k[-6:2] = [1,2]
  why k[-6:2] is [1,2]not [].i do follow (3),to make i positive by
  plusing len(k) twice.
 
 twice?
 
 /F
that is -6 + len(k) + len(k) =4

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

Numpy-f2py troubles

2006-10-17 Thread Andrea Gavana
Hello NG,

I am using the latest Numpy release 1.0rc2 which includes F2PY. I
have switched to Python 2.5 so this is the only alternative I have
(IIUC). With Python 2.4, I was able to build a very simple fortran
extension without problems.

My extension contains 4 subroutines that scan a file and do simple operations.
Now, attempting to run the second subroutine as:

dprops, dwgnames, dunits = readsmspec.readsmspec(smspec, dimens)

Prompt a ValueError from Python:

  File D:\MyProjects\Carolina\MainPanel.py, line 894, in ReadSMSPECFile
dprops, dwgnames, dunits = readsmspec.readsmspec(smspec, dimens)
ValueError: data type must provide an itemsize

?!? I have never seen anything like that and googling around didn't
give me any answer. The function accepts two inputs:

- smspec: a filename, maximum 1000 characters long
- dimens: an integer

and returns 3 array of chars, each of them with size (8, dimens). Does
anyone know what I may be doing wrong?

Thank you very much for every pointer.


-- 
Andrea.

Imagination Is The Only Weapon In The War Against Reality.
http://xoomer.virgilio.it/infinity77/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a question about s[i:j] when i is negative

2006-10-17 Thread dracula571

[EMAIL PROTECTED] 写道:

 dracula571 wrote:
  s[i:j] slice of s from i to j (3), (4)
 
  (3)
  If i or j is negative, the index is relative to the end of the string:
  len(s) + i or len(s) + j is substituted. But note that -0 is still 0.
 
 
  (4)
  The slice of s from i to j is defined as the sequence of items with
  index k such that i = k  j. If i or j is greater than len(s), use
  len(s). If i is omitted or None, use 0. If j is omitted or None, use
  len(s). If i is greater than or equal to j, the slice is empty.
 
  i can't follow (3) very well.
  for example:k = [1,2,3,4,5]
  k[-1:2]=[]
  k[-5:2]=[1,2]
  but k[-6:2] = [1,2]
  why k[-6:2] is [1,2]not [].

 Because 6 is greater then len(k), so when you ask
 for i=-6, you get i=-5 instead. And relative -5 is actually
 absolute 0 which is less than 2, so you do not get an
 empty slice.

  i do follow (3),to make i positive by
  plusing len(k) twice.But the result is not what i expect.why,or did i
  misunderstand the rule of (3).

 See (4).
when compared with len(k), the value of i is a absolute value?
in this example,i used -6 to compare with len(k).
I misunstood the rule (4),and used (3) wrong by plusing len(k) twice to
make it positive ,that is -6 + len(k) + len(k) = 4.
Thanks

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

Re: A Universe Set

2006-10-17 Thread Jorgen Grahn
On Mon, 16 Oct 2006 09:21:11 -0500, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:


  [me]
  - the wildcard object, which compares equal to everything else

  [Paul]
 Paul class MatchAny(object):
 Paul def __cmp__(self,other):
 Paul return 0

 Paul wild = MatchAny()

FWIW, I define __eq__ in the one I (infrequently) use.

 ...

 You're at the mercy of the comparison machinery implemented by individual
 classes.  Executing this script (using any of Python 2.3 through what's
 currently in the SVN repository):
...

Oh. /Is/ there a way of making it work, then?  If we ignore the problems
with having such objects in the first place, that is. 

/Jorgen

-- 
  // Jorgen Grahn grahn@Ph'nglui mglw'nafh Cthulhu
\X/ snipabacken.dyndns.org  R'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a question about s[i:j] when i is negative

2006-10-17 Thread Fredrik Lundh
dracula571 wrote:

 dracula571 wrote:

  but k[-6:2] = [1,2]
  why k[-6:2] is [1,2]not [].i do follow (3),to make i positive by
  plusing len(k) twice.

 twice?

 that is -6 + len(k) + len(k) =4

sure, but what makes you think you should add the length twice?

/F 



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


Re: COM Error -- Urgent help

2006-10-17 Thread Teja

Dennis Lee Bieber wrote:
 On 17 Oct 2006 00:58:59 -0700, Teja [EMAIL PROTECTED] declaimed
 the following in comp.lang.python:

 thread.start_new_thread(self.nav, (s,'www.google.com')
 
  I am getting an attribute error

   That can not be the REAL code... I'd expect a syntax error... You
 have mismatched parens on that line!
 --
   WulfraedDennis Lee Bieber   KD6MOG
   [EMAIL PROTECTED]   [EMAIL PROTECTED]
   HTTP://wlfraed.home.netcom.com/
   (Bestiaria Support Staff:   [EMAIL PROTECTED])
   HTTP://www.bestiaria.com/

Hi,

Ya its a copy paste error... But can u please let me know what is the
reason for attribute error and how to rectify it??

Thnks, 
Regards
Teja.P

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


Re: COM Error -- Urgent help

2006-10-17 Thread Fredrik Lundh
Teja wrote:

 s=pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch,i­­e)

thread.start_new_thread(self.nav, (s,'www.google.com')

 I am getting an attribute error

the traceback tells you what attribute Python was looking for, and may also 
provide
additional clues.  can you post the traceback too?  make sure you include all 
of it.

/F 



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

Re: COM Error -- Urgent help

2006-10-17 Thread Diez B. Roggisch
Teja wrote:

 
 Dennis Lee Bieber wrote:
 On 17 Oct 2006 00:58:59 -0700, Teja [EMAIL PROTECTED] declaimed
 the following in comp.lang.python:

 thread.start_new_thread(self.nav, (s,'www.google.com')
 
  I am getting an attribute error

 That can not be the REAL code... I'd expect a syntax error... You
 have mismatched parens on that line!
 --
 Wulfraed Dennis Lee Bieber   KD6MOG
 [EMAIL PROTECTED][EMAIL PROTECTED]
 HTTP://wlfraed.home.netcom.com/
 (Bestiaria Support Staff:[EMAIL PROTECTED])
 HTTP://www.bestiaria.com/
 
 Hi,
 
 Ya its a copy paste error... But can u please let me know what is the
 reason for attribute error and how to rectify it??

How many times need you a beating with a clue-stick? 

Post the _actual_ code, not something that closely resembles it - in _your_
opinion

Post the error message

And before you do all this, read:

http://www.catb.org/~esr/faqs/smart-questions.html

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


Re: COM Error -- Urgent help

2006-10-17 Thread Teja

Diez B. Roggisch wrote:
 Teja wrote:

 
  Dennis Lee Bieber wrote:
  On 17 Oct 2006 00:58:59 -0700, Teja [EMAIL PROTECTED] declaimed
  the following in comp.lang.python:
 
  thread.start_new_thread(self.nav, (s,'www.google.com')
  
   I am getting an attribute error
 
  That can not be the REAL code... I'd expect a syntax error... You
  have mismatched parens on that line!
  --
  Wulfraed Dennis Lee Bieber   KD6MOG
  [EMAIL PROTECTED][EMAIL PROTECTED]
  HTTP://wlfraed.home.netcom.com/
  (Bestiaria Support Staff:[EMAIL PROTECTED])
  HTTP://www.bestiaria.com/
 
  Hi,
 
  Ya its a copy paste error... But can u please let me know what is the
  reason for attribute error and how to rectify it??

 How many times need you a beating with a clue-stick?

 Post the _actual_ code, not something that closely resembles it - in _your_
 opinion

 Post the error message

 And before you do all this, read:

 http://www.catb.org/~esr/faqs/smart-questions.html

 Diez


OK Ok .. Here is the final code thats giving an error:

GenericFunctions.py
--

import win32com.client, pythoncom, thread
ie=win32com.client.Dispatch('internetexplorer.application')
ie.Visible=1

class GenericFunctions:
def __init__(self):
print In Constructor of Generic Functions
def MyNavigate(self,dest):
ie.Navigate(dest)
---
MainThread.py
--

import win32com.client, pythoncom, thread
from GenericFunctions import *
obj = GenericFunctions()
import sys,traceback


def threadFunction(s,dest):
pythoncom.CoInitialize()
try:
d=pythoncom.CoGetInterfaceAndReleaseStream(s,
pythoncom.IID_IDispatch)
my_ie=win32com.client.Dispatch(d)
#d.MyNavigate(dest)
obj.MyNavigate(dest)  # this is gving an error.
except:
my_ie = None
print traceback.print_exc(file= sys.stdout)
pythoncom.CoUninitialize()

if __name__ == __main__:

s=pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch,ie)

thread.start_new_thread(threadFunction, (s,'www.google.com'))


-
And here is the error:

Traceback (most recent call last):
  File C:\Documents and Settings\dzxbrn\Desktop\Stop Test\13
Oct\MainThread.py, line 13, in threadFunction
obj.MyNavigate(dest)  # this is gving an error.
  File C:\Documents and Settings\dzxbrn\Desktop\Stop Test\13
Oct\GenericFunctions.py, line 9, in MyNavigate
ie.Navigate(dest)
  File C:\Python24\Lib\site-packages\win32com\client\dynamic.py, line
489, in __getattr__
raise AttributeError, %s.%s % (self._username_, attr)
AttributeError: internetexplorer.application.Navigate
None


This is highly urgent and important... Please help me out

Thnks  Regards,
Tejovathi.P

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


Re: python's OOP question

2006-10-17 Thread Bruno Desthuilliers
neoedmund wrote:
(snip)
 So I can reuse a method freely only if it's worth reusing.
 For the word inheritance, in some aspect, meanings reuse the super
 class, with the condition: must reuse everything from super class.

Not really. In fact, inheritance *is* a special case of
composition/delegation. A 'child' class is a class that has references
to other classes - it's 'parents' -, and  then attributes that are not
found in the instance or child class are looked up in the parents
(according to mro rules in case of multiple inheritance). And that's all
there is.

 It's lack of a option to select which methods are to be reused.

Methods not redefined in the 'child' class or it's instance are
'reusable'. Now they are only effectively 'reused' if and when called by
client code. So the 'option to select which methods are to be reused' is
mostly up to both the 'child' class and code using it.

 this is something should be improved for general OOP i think.
 So to answer  What is your problem with having the other extra methods
 too ?,
 in real life, a class is not defined so well that any method is needed
 by sub-class. 

Then perhaps is it time to refactor. A class should be a highly cohesive
unit. If you find yourself needing only a specific subset of a class, it
may be time to extract this subset in it's own class. Given Python's
support for both multiple inheritance and composition/delegation, it's
usually a trivial task (unless you already mixed up too many orthogonal
concerns in your base class...).

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A Universe Set

2006-10-17 Thread Duncan Booth
Jorgen Grahn [EMAIL PROTECTED] wrote:

  - the wildcard object, which compares equal to everything else

   [Paul]
 Paul class MatchAny(object):
 Paul def __cmp__(self,other):
 Paul return 0

 Paul wild = MatchAny()
 
 FWIW, I define __eq__ in the one I (infrequently) use.

The advantage to using __eq__ is that it fails to work correctly less often 
than __cmp__. Compare skip's example where comparison against datetime give 
the wrong answer 100% of the time with __cmp__ and 50% of the time with 
__eq__/__ne__:

 import datetime
 class MatchAny(object):
def __cmp__(self,other):
return 0


 wild = MatchAny()
 print wild == datetime.datetime.now()
False
 print datetime.datetime.now() == wild
False
 print wild != datetime.datetime.now()
True
 print datetime.datetime.now() != wild
True
 class MatchAny(object):
def __eq__(self,other):
return True
def __ne__(self,other):
return False


 wild = MatchAny()
 print wild == datetime.datetime.now()
True
 print datetime.datetime.now() == wild
False
 print wild != datetime.datetime.now()
False
 print datetime.datetime.now() != wild
True


 
 ...

 You're at the mercy of the comparison machinery implemented by
 individual classes.  Executing this script (using any of Python 2.3
 through what's currently in the SVN repository):
 ...
 
 Oh. /Is/ there a way of making it work, then?  If we ignore the
 problems with having such objects in the first place, that is. 
 
In a contained environment, it can be made to work 'well enough'. So if you 
are writing unit tests and want a wildcard element to include inside data 
structures, AND you can guarantee that you always assert in the order 
expected,actual, then you can probably get away with it. That's assuming 
you remembered to use __eq__/__ne__ rather than __cmp__.

For an object safe to let out in the wild though there isn't any way to 
implement it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cannot import a module from a variable

2006-10-17 Thread Tim Williams
On 16/10/06, Bruno Desthuilliers [EMAIL PROTECTED] wrote:
 Jia Lu wrote:
  Hi all:
 
  I try to do things below:
  import sys
  for i in sys.modules.keys():
import i
  Traceback (most recent call last):
File pyshell#67, line 2, in module
  import i
  ImportError: No module named i
 
  But it seems that import donot know what is i ?

 The import statement expects a name (a symbol), not a string.


eval( 'import %s' % modname)

and

eval( 'reload(%s)' % modname)

Usual warnings about eval apply,  but in this case it is usable.

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


Re: Any idea how to do this in Python?

2006-10-17 Thread Lad

Dennis,
Thank you for your reply
You say:
Pretend you are the computer/application/etc.  How would YOU
 perform such a ranking?
That is what I do not know , how to perform such ranking.
Do you have any idea?

Regards,
Lad.

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


Re: Book about database application development?

2006-10-17 Thread Bruno Desthuilliers
Wolfgang Keller wrote:
 Developping quality SQLDBMS-based applications requires more than a
 bit of SQL knowledge.
 
 No doubt. :-) But my bit is enough to get me going and to know where to 
 look for further information if I hit a wall. Especially the people on the 
 Postgres mailinglists (as well as the excellent documentation of Postgres) 
 tend to be very helpful here. :-)

Well, this was intended as a general observation !-)

 What I'm interested in is rather how to connect a GUI to a database, with 
 quite a bit of application logic in between. And how to do it well.
 This is more a general design question than a database-related (or even
 Python-related) one.
 
 The question is specific to database applications in so far as these are 
 typically client-server aplications (multiple users working with the same 
 data with all the resulting concurrency nightmares), and as the volumes and 
 the complexity of the data to be handled are non-trivial.

This can be true for non database-applications (well... non SQL DBMS
based applications would be better here I think) as well.

 The answer starts with forgetting about connect(ing) a GUI to a database 
 IMHO 
 
 Well, _somehow_ the GUI _has_ to be connected to the database. ;-)

The GUI has to be connected to the application, which uses the database.
There's no need for the GUI code itself to know anything about the SQL DBMS.

 I didn't say that this would be through a spaghetti-heap of SQL queries 
 hard-coded into the GUI event handlers.

Hopefully not !-)

 and experience. Might be time to google for MVC... 
 
 I know about the existence of MVC. But what I'm actually missing is a nice 
 textbook that teaches how to actually implement it 

Yes, this can be another problem. But FWIW, most modern GUI toolkits
already do a big part of the job.

 (and other design patterns 
 which are useful for database applications) in a real-world application in a 
 way that leads to non-ridiculous behaviour of the resulting application when 
 it gets actually used.

There are some known anti-patterns at least. Like selecting a whole
table (preferably with all attributes) then looping thru the result set
just to count the number of records in the table (don't laugh, I've
actually seens this (and even worse) in production code).

But given your concerns, I don't think you'd do such a thing anyway !-)



-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.4 online certification - new items available for Beta testing

2006-10-17 Thread NickC
[EMAIL PROTECTED] wrote:
 Randy There is a free Beta test of a Python 2.4 Certification test
 Randy available at Brainbench.com. They are a provider of skills-based
 Randy certification exams.  Go to the link below to find the test. It
 Randy is free to take the test.

 Randy http://www.brainbench.com/xml/bb/common/testcenter/betatests.xml

 I've given up on Brainbench.  Ignoring the possibility that their
 certification tests may not be all that useful, they never stopped spamming
 me, so I refuse to help them with anything.

 Skip

I went through their first test module (although using a mailinator
address after this testimonial from Skip) and I think Beta is
generous. Try pre-alpha - i marked nearly half (maybe more than half)
of the 20 questions as no correct answer, and a number of the others
included sample code that stank to high heaven.

I also pointed out that what does this code do? type questions are
pretty pointless for a language that comes with an interactive
interpreter (I would actually be somewhat disappointed with any Python
programmer whose automatic reaction to such a question involving
deliberately obfuscated code *wasn't* to try it out on the nearest
interpreter prompt).

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


Re: Any idea how to do this in Python?

2006-10-17 Thread jmdeschamps

Lad wrote:
 Dennis,
 Thank you for your reply
 You say:
 Pretend you are the computer/application/etc.  How would YOU
  perform such a ranking?
 That is what I do not know , how to perform such ranking.
 Do you have any idea?

 Regards,
 Lad.
take a piece of paper to *play* the use-case you wrote about.

Do things one step at a time, and figure what is needed,

Example:
1- a user is on a web page # ok I need a web page
2- a user sends info to the server # ok the web page needs a input
widget of sorts AND I need a server app
3- analyse (or decide ) what type of info the user may send (selected
choices, free text, etc)
4- the user must be identified in some way (so to discriminate him from
others), so the also must be that type of input...

etc, etc
At the end you will have a better picture of things required - then you
build them ;-)

Jean-Marc

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


Re: Any idea how to do this in Python?

2006-10-17 Thread Theerasak Photha
On 17 Oct 2006 02:56:45 -0700, Lad [EMAIL PROTECTED] wrote:

 Dennis,
 Thank you for your reply
 You say:
 Pretend you are the computer/application/etc.  How would YOU
  perform such a ranking?
 That is what I do not know , how to perform such ranking.
 Do you have any idea?

The details are very sketchy, but if it's just one item in particular
that's being favored, you could just have something like 'Google
sponsored ads', where there's a small box with links to everything
related to Siemens Mobile at the top.

(keke, he said 'Siemens', lol)

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


Re: Cannot import a module from a variable

2006-10-17 Thread Fredrik Lundh
Tim Williams wrote:

 eval( 'reload(%s)' % modname)

reload takes a module object, not a module name.  since you need to have the
object, you might as well pass it to the reload() function.

/F 



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


Re: Output from subprocess.Popen()

2006-10-17 Thread Clodoaldo Pinto Neto
Fredrik Lundh wrote:
 Clodoaldo Pinto Neto wrote:

  But I still don't understand what is happening. The manual says that
  when shell=True the executable argument specifies which shell to use:

 no, it says that when shell=True, it runs the command through the
 default shell.  that is, it hands it over to the shell for execution,
 pretty much as if you'd typed it in yourself.

If shell=True, the executable argument specifies which shell to use.

Taken from 6.8.1 v2.4:

The executable argument specifies the program to execute. It is very
seldom needed: Usually, the program to execute is defined by the args
argument. If shell=True, the executable argument specifies which shell
to use. On Unix, the default shell is /bin/sh. On Windows, the default
shell is specified by the COMSPEC environment variable.

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


Re: Cannot import a module from a variable

2006-10-17 Thread Duncan Booth
Tim Williams [EMAIL PROTECTED] wrote:

 The import statement expects a name (a symbol), not a string.

 
 eval( 'import %s' % modname)
 
 and
 
 eval( 'reload(%s)' % modname)
 
 Usual warnings about eval apply,  but in this case it is usable.

Did you actually try your suggestion before posting?

 modname = 'os'
 eval( 'import %s' % modname)

Traceback (most recent call last):
  File pyshell#4, line 1, in module
eval( 'import %s' % modname)
  File string, line 1
import os
 ^
SyntaxError: invalid syntax
 

Also, it is pretty pointless to import the module and not know which 
arbitrary variable name it will have created. It is much simpler just to 
use the __import__ builtin:

 module = __import__(modname)
 module
module 'os' from 'C:\Python25\lib\os.pyc'

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


Re: A friendlier, sugarier lambda -- a proposal for Ruby-like blocks in python

2006-10-17 Thread Paul Boddie
Theerasak Photha skrev:
 On 14 Oct 2006 09:25:00 -0700, Paul Boddie [EMAIL PROTECTED] wrote:

  Unlike Java, Python's first class functions and
  methods are already highly useful for callback-based systems

 Curious: how well does the use of returning inner functions work as a
 strategy for providing effectively 'anonymous' callbacks? e.g.

 def outer(x):
   def inner(y):
 ...
   return inner

Well enough, I'd imagine. There may be people who resent having to use
a statement to create a block of code, especially one which defines a
local name (the horror!), but as the lambda replacement discussions
showed, a sub-statement code block doesn't necessarily have an
acceptable formulation in non-Lisp-like languages. Or, at least, people
struggled to find such a formulation in Python which didn't severely
affect readability, and there are people who regard even
uncontroversial but related things as list comprehensions as being much
less readable than most other constructs in the language.

Paul

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


We're recruiting Python programmers

2006-10-17 Thread Dale Strickland-Clark
I'll keep this brief. Please see the web site for details

Thanks.
-- 
Dale Strickland-Clark
We are recruiting Python programmers. Please see the web site.
Riverhall Systems www.riverhall.co.uk

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


Re: Alphabetical sorts

2006-10-17 Thread Neil Cerutti
On 2006-10-17, Ron Adam [EMAIL PROTECTED] wrote:
 Neil Cerutti wrote:
 On 2006-10-16, Ron Adam [EMAIL PROTECTED] wrote:
 I have several applications where I want to sort lists in
 alphabetical order. Most examples of sorting usually sort on
 the ord() order of the character set as an approximation.
 But that is not always what you want.
 
 Check out strxfrm in the locale module.

 It looks to me this would be a good candidate for a
 configurable class. Something preferably in the string module
 where it could be found easier.

 Is there anyway to change the behavior of strxfrm or strcoll?
 For example have caps before lowercase, instead of after?

You can probably get away with writing a strxfrm function that
spits out numbers that fit your definition of sorting.

-- 
Neil Cerutti
Whenever I see a homeless guy, I always run back and give him
money, because I think: Oh my God, what if that was Jesus?
--Pamela Anderson
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: What's up with the starship?

2006-10-17 Thread A.M. Kuchling
On Mon, 16 Oct 2006 14:50:03 -0500, 
[EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 suggests that it was sufficiently obscure that either a) nobody who knew
 about it found a way to take advantage of it, or b) it was only recently

It might well be difficult to exploit to run arbitrary code because
your exploit code needs to have no unprintable bytes in it; repr()
turns unprintable characters into \xNN, after all, and isn't doing a
straightforward string copy.  (But hackers can be very clever...)

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


Re: Alphabetical sorts

2006-10-17 Thread Jorgen Grahn
On Mon, 16 Oct 2006 22:22:47 -0500, Ron Adam [EMAIL PROTECTED] wrote:
...
 I see this is actually a very complex subject.
...
 It looks to me this would be a good candidate for a configurable class. 
 Something preferably in the string module where it could be found easier.

/And/ choosing a locale shouldn't mean changing a process-global state.
Sometimes you want to perform something locale-depending in locale A,
followed by doing it in locale B. Switching locales today takes time and has
the same problems as global variables (unless there is another interface I
am not aware of).

But I suspect that is already a well-known problem.

/Jorgen

-- 
  // Jorgen Grahn grahn@Ph'nglui mglw'nafh Cthulhu
\X/ snipabacken.dyndns.org  R'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Newbie: datetime conversion question

2006-10-17 Thread kevin evans
Hi,
I'm trying to convert some code from Ruby to Python, specifically..

timestamp = %08x % Time.now.to_i

Make a hex version of the current timestamp. Any ideas how best to do
this in python gratefully received..

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


Re: Newbie: datetime conversion question

2006-10-17 Thread Fredrik Lundh
kevin evans wrote:

 I'm trying to convert some code from Ruby to Python, specifically..

 timestamp = %08x % Time.now.to_i

 Make a hex version of the current timestamp. Any ideas how best to do
 this in python gratefully received..

that's perfectly valid Python code, provided Time is an object that has a now
property which in turn has a to_i property.

but assuming that you don't have such an object, you can do something like:

timestamp = %02x % time.time()

/F 



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


Re: Newbie: datetime conversion question

2006-10-17 Thread Carsten Haese
On Tue, 2006-10-17 at 08:43, kevin evans wrote:
 Hi,
 I'm trying to convert some code from Ruby to Python, specifically..
 
 timestamp = %08x % Time.now.to_i
 
 Make a hex version of the current timestamp. Any ideas how best to do
 this in python gratefully received..

import time
timestamp = %08x % int(time.time())

-Carsten


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


Re: Newbie: datetime conversion question

2006-10-17 Thread hg
kevin evans wrote:
 Hi,
 I'm trying to convert some code from Ruby to Python, specifically..
 
 timestamp = %08x % Time.now.to_i
 
 Make a hex version of the current timestamp. Any ideas how best to do
 this in python gratefully received..
 


how about

import time
%08X% (int)(time.mktime(time.localtime()))

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


Re: Newbie: datetime conversion question

2006-10-17 Thread skip

kevin I'm trying to convert some code from Ruby to Python,
kevin specifically..

kevin timestamp = %08x % Time.now.to_i

kevin Make a hex version of the current timestamp. Any ideas how best
kevin to do this in python gratefully received..

Try

import time
timestamp = hex(int(time.time()))

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


Re: Newbie: datetime conversion question

2006-10-17 Thread Carsten Haese
On Tue, 2006-10-17 at 08:49, hg wrote:
 import time
 %08X% (int)(time.mktime(time.localtime()))

Have you not had your coffee yet or are you trying to win an obfuscated
python programming competition? ;)

-Carsten


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


Re: COM Error -- Urgent help

2006-10-17 Thread Neil Hodgson
Teja:

 ie=win32com.client.Dispatch('internetexplorer.application')
 ie.Visible=1
 
 class GenericFunctions:
 def __init__(self):
 print In Constructor of Generic Functions
 def MyNavigate(self,dest):
 ie.Navigate(dest)

You are using an interface created on the main thread here.

...
 d=pythoncom.CoGetInterfaceAndReleaseStream(s,
 pythoncom.IID_IDispatch)
 my_ie=win32com.client.Dispatch(d)
 #d.MyNavigate(dest)
 obj.MyNavigate(dest)  # this is gving an error.

After all the trouble of marshalling the interface into this thread 
you aren't using it. Pass my_ie to MyNavigate. I also had some errors 
before changing from thread to threading.

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


RE: Any idea how to do this in Python?

2006-10-17 Thread Matthew Warren
 On 17 Oct 2006 02:56:45 -0700, Lad [EMAIL PROTECTED] wrote:
 
  Dennis,
  Thank you for your reply
  You say:
  Pretend you are the computer/application/etc.  How would YOU
   perform such a ranking?
  That is what I do not know , how to perform such ranking.
  Do you have any idea?
  
Maybe something like,

As you capture the input from the web form in your python app on the
server, pull out the keywords you are interested in and store those
together with logon/user information in a database.

Alongside that, store the text for all your adverts in a database along
with a list of keywords for each advert.

Then, when it comes to displaying the targeted adverts on a webpage,
grab the user keywords from the database, use them to match against
adverts that have the same keywords stored in the database, then choose
from those adverts and include the output into your webpage.

Something like that should at least ensure the relevant ad's turn up on
the page. As to a more sophisticated 'weighting' scheme, you could start
doing things like associating values with keywords, matching up which
keywords a user has used against the keywords stored against different
ads, sum up the total score for each ad, the ads with the highest scores
based on the user keywords given should be displayed first..

I havent a clue if there are 'official' ways of doing it, but that's the
kind of thing I'd start looking at, anyhoo

Matt.

To the list: apologies for appended text, I  cant get to google groups
to post today :/



This email is confidential and may be privileged. If you are not the intended 
recipient please notify the sender immediately and delete the email from your 
computer. 

You should not copy the email, use it for any purpose or disclose its contents 
to any other person.
Please note that any views or opinions presented in this email may be personal 
to the author and do not necessarily represent the views or opinions of Digica.
It is the responsibility of the recipient to check this email for the presence 
of viruses. Digica accepts no liability for any damage caused by any virus 
transmitted by this email.

UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK
Reception Tel: + 44 (0) 115 977 1177
Support Centre: 0845 607 7070
Fax: + 44 (0) 115 977 7000
http://www.digica.com

SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South 
Africa
Tel: + 27 (0) 21 957 4900
Fax: + 27 (0) 21 948 3135
http://www.digica.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie: datetime conversion question

2006-10-17 Thread hg
Carsten Haese wrote:
 On Tue, 2006-10-17 at 08:49, hg wrote:
 import time
 %08X% (int)(time.mktime(time.localtime()))
 
 Have you not had your coffee yet or are you trying to win an obfuscated
 python programming competition? ;)
 
 -Carsten
 
 
Just one cup

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


Tertiary Operation

2006-10-17 Thread abcd
x = None
result = (x is None and  or str(x))

print result, type(result)

---
OUTPUT
---
None type 'str'


y = 5
result = (y is 5 and it's five or it's not five)

print result

-
OUTPUT
-
it's five

...what's wrong with the first operation I did with x?  I was expecting
result to be an empty string, not the str value of None.

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


Re: COM Error -- Urgent help

2006-10-17 Thread Teja
This is the trae back ,can you help me please.

Traceback (most recent call last):
  File C:\Documents and Settings\dzxbrn\Desktop\Stop Test\13
Oct\MainThread.py, line 13, in threadFunction
obj.MyNavigate(dest)  # this is gving an error.
  File C:\Documents and Settings\dzxbrn\Desktop\Stop Test\13
Oct\GenericFunctions.py, line 9, in MyNavigate
ie.Navigate(dest)
  File C:\Python24\Lib\site-packages\win32com\client\dynamic.py, line
489, in __getattr__
raise AttributeError, %s.%s % (self._username_, attr)
AttributeError: internetexplorer.application.Navigate
None
Fredrik Lundh wrote:
 Teja wrote:

  s=pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch,i­­e)
 
 thread.start_new_thread(self.nav, (s,'www.google.com')
 
  I am getting an attribute error

 the traceback tells you what attribute Python was looking for, and may also 
 provide
 additional clues.  can you post the traceback too?  make sure you include all 
 of it.
 
 /F

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


Re: Book about database application development?

2006-10-17 Thread Kent Johnson
Wolfgang Keller wrote:
 I know about the existence of MVC. But what I'm actually missing is a nice 
 textbook that teaches how to actually implement it (and other design patterns 
 which are useful for database applications) in a real-world application in a 
 way that leads to non-ridiculous behaviour of the resulting application when 
 it gets actually used.

Maybe you would like Martin Fowler's Patterns of Enterprise Application 
Architecture
http://martinfowler.com/books.html#eaa

 Preferrably using a language for the examples that's readable for someone who 
 has learned programming ages ago with Pascal and is now using Python because 
 he _hates_ everything that remotely ressembles to any mutation of 
 C(++/#/Java).

Examples are mostly Java and C#, sorry!

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


pylab package dependencies (was: Plotting histograms)

2006-10-17 Thread Lou Pecora
In article [EMAIL PROTECTED],
 Robert Kern [EMAIL PROTECTED] wrote:

 I presume what you did was something like this:
 
from matplotlib import pylab
[N,x] = hist(eig, 10)
 
 What you actually want is this:
 
from matplotlib import pylab
[N,x] = pylab.hist(eig, 10)
 
 Or, if you're at the interactive prompt (but remember that it is inadvisable 
 to 
 do so in modules):
 
from matplotlib.pylab import *
[N,x] = hist(eig, 10)
 
 You will probably want to review the section of the tutorial on importing 
 modules if you don't understand the differences.


Is pylab part of matplotlib?  I always thought it was the other way 
around. I have a similar view of numpy as part of scipy.  Maybe I'm 
confused on the dependencies.  I find it confusing in the examples 
sometimes when the bigger package is imported (e.g. scipy) and then a 
subpackage is also imported.  Like this:

from scipi import *
from scipi import numpy

I know I've seen stuff like that, but I don't get it.  The dependencies 
are confusing to me.  

I did a search of the tutorial on 'import' but didn't find the answer.

-- Lou Pecora  (my views are my own) REMOVE THIS to email me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tertiary Operation

2006-10-17 Thread Richard Brodie

abcd [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]

x = None
 result = (x is None and  or str(x))

 ...what's wrong with the first operation I did with x?  I was expecting
 result to be an empty string, not the str value of None.

Your evil tertiary hack has failed you because the empty string
counts as false in a boolean context. Please learn to love the
new conditional expression syntax:

http://docs.python.org/whatsnew/pep-308.html 


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


Re: Tertiary Operation

2006-10-17 Thread Tim Chase
 x = None
 result = (x is None and  or str(x))
 
 print result, type(result)
 
 ---
 OUTPUT
 ---
 None type 'str'
 
 
 y = 5
 result = (y is 5 and it's five or it's not five)
 
 print result
 
 -
 OUTPUT
 -
 it's five
 
 ...what's wrong with the first operation I did with x?  I was expecting
 result to be an empty string, not the str value of None.

An empty string evaluates to False, so it then continues to the 
other branch.  Either of the following should suffice:

# return a non-empty string
x is None and None or str(x)

# invert the logic and return
# something in the and portion
x is not None and str(x) or 

There are more baroque ways of writing the terniary operator in 
python (although I understand 2.5 or maybe python 3k should have 
a true way of doing this).  My understanding is that one common 
solution is something like

{True: , False: str(x)}[x is None]

-tkc



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


Re: Tertiary Operation

2006-10-17 Thread Carsten Haese
On Tue, 2006-10-17 at 09:30, abcd wrote:
 x = None
 result = (x is None and  or str(x))
 
 print result, type(result)
 
 ---
 OUTPUT
 ---
 None type 'str'

The condition and result1 or result2 trick only works if result1 is an
expression with a True boolean value. The empty string has a false
boolean value.

You could force result1 to have a true boolean value by sticking it into
a list thusly:

result = (x is None and [] or [str(x)])[0]

But that's ugly. Use Python 2.5 where there is a true conditional
expression or find another way to solve your problem.

-Carsten


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


Re: Max-plus library

2006-10-17 Thread Martin Manns
Sébastien Boisgérault wrote:
 Robert Kern wrote:
 Martin Manns wrote:
 Hello,

 Is there any library that allows employing max-plus dioids in
 python (e.g. based on numpy/scipy)?
 Google says no and I haven't heard of any, so I imagine that there aren't.
 There might be something buried in some of the control theory packages, but 
 as I
 neither know what max-plus dioids are, nor have I any current interest in 
 them,
 I can't give you any better pointers.
 
 See http://cermics.enpc.fr/~cohen-g//SED/index-e.html for a two-page
 introduction to the field and its applications. Definitely worth a look
 IMHO.
 
 The second software you refer to
 (http://www-rocq.inria.fr/MaxplusOrg/soft.html) is a Scilab package but
 essentially made of C and Fortran files. Getting a working binding for
 Python may not be that hard ...
 

Thank you for the fast replies. Since I currently have not the time to
write bindings, I will probably have to stick to the Matlab implementation.

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


Re: Newbie: datetime conversion question

2006-10-17 Thread kevin evans
Great stuff - many thanks


hg wrote:
 Carsten Haese wrote:
  On Tue, 2006-10-17 at 08:49, hg wrote:
  import time
  %08X% (int)(time.mktime(time.localtime()))
 
  Have you not had your coffee yet or are you trying to win an obfuscated
  python programming competition? ;)
  
  -Carsten
  
  
 Just one cup
 
 hg

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


Looking for assignement operator

2006-10-17 Thread Alexander Eisenhuth
Hello,

is there a assignement operator, that i can overwrite?

class MyInt:
def __init__(self, val):
assert(isinstance(val, int))
self._val = val

a = MyInt(10)

# Here i need to overwrite the assignement operator
a = 12


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


How to invoke ipython in Mac OS X?

2006-10-17 Thread Lou Pecora
I installed the SciPy superpackage and have pylab, matplotlib, scipy, 
and numpy apparently running well.  But I want to use matplotlib/pylab 
interactively.  The instructions suggest doing this in IPython.  But 
using ipython on the command line gives me an error.  The system doesn't 
know the command.  Apparently there is no ipython executable in one of 
the bin directories.  I thought the superpackage would add that 
automatically, but I guess not.  

Can anyone tell me how to get ipython running on my MacOSX 10.4 system?

Thanks for any help.

(Yes, I asked on the SciPy email list, but never got an answer.)

-- Lou Pecora  (my views are my own) REMOVE THIS to email me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tertiary Operation

2006-10-17 Thread abcd
Carsten Haese wrote:
 Use Python 2.5 where there is a true conditional
 expression or find another way to solve your problem.

python 2.5 once we upgrade (hopefully soon), anyways...an earlier post
suggested the inverse...

x = None
result = (x is not None and str(x) or )

which works just fine.

thanks.

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


Re: Looking for assignement operator

2006-10-17 Thread Simon Brunning
On 10/17/06, Alexander Eisenhuth [EMAIL PROTECTED] wrote:
 Hello,

 is there a assignement operator, that i can overwrite?

Soirry, no, assignment is a statement, not an operator, and can't be overridden.

-- 
Cheers,
Simon B
[EMAIL PROTECTED]
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tertiary Operation

2006-10-17 Thread Fredrik Lundh
Tim Chase wrote:

 {True: , False: str(x)}[x is None]

first the localtime/mktime roundtrip with a simulated cast, and now this?  in 
less
than one hour?  solar flares?

/F 



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


Re: Looking for assignement operator

2006-10-17 Thread Fredrik Lundh
Alexander Eisenhuth wrote:

 is there a assignement operator, that i can overwrite?

no.

/F 



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


Re: Problem creating animated gif

2006-10-17 Thread Fredrik Lundh
abcd [EMAIL PROTECTED] wrote:

 Any ideas?  Basically I want to make an animated GIF out of a bunch of
 images taken using the ImageGrab module.

the screen is an RGB device, but the gifmaker wants palette images (mode P).
to fix this, insert

im = im.convert(P)

after the grab (or before the call to makedelta).

/F 



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


Problem creating animated gif

2006-10-17 Thread abcd
I am using gifmaker.py from PIL v1.1.5 on python 2.4.1.

CODE

import ImageGrab, gifmaker

seq = []

while keepOnGoing:
im = ImageGrab.grab()
seq.append(im)

fp = open(out.gif, wb)
gifmaker.makedelta(fp, seq)
fp.close()

---

however I am getting this error:

Exception in thread Thread-3:
Traceback (most recent call last):
  File c:\Python24\lib\threading.py, line 442, in __bootstrap
self.run()
  File c:\foo.py, line 10, in run
gifmaker.makedelta(fp, seq)
  File c:\gifmaker.py, line 79, in makedelta
for s in getheader(im) + getdata(im):
  File c:\Python24\Lib\site-packages\PIL\GifImagePlugin.py, line 383,
in getdata
ImageFile._save(im, fp, [(gif, (0,0)+im.size, 0,
RAWMODE[im.mode])])
KeyError: 'RGB'


Any ideas?  Basically I want to make an animated GIF out of a bunch of
images taken using the ImageGrab module.

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


Return returns nothing in recursive function

2006-10-17 Thread Matthew Warren
Hallo people,

I have the following code that implements a simple recursive tree like
structure.

The trouble is with the GetTreeBranch function, the print statement
prints a valid value but the return immediatley afterward doesn't return
anything.

Can anyone help me with why?


Thanks,

Matt.

Code and output follow;

'''
dirtree

A simple implementation of a filesystem-like tree
datastructure.
'''

def MakeNewTree(rootname='root'):
'''MakeNewTree

Creates an empty tree with a 'root' node.
If the parameter rootname is not given, it
defaults to 'root'.
'''
return [{rootname:[]}]

def DoThingsToTree(path,value,tree,delete=False):
'''_DoThingsToTree

You should not use this function.
'''
if type(path)==type(''):
path=path.lstrip('/').rstrip('/').split('/')
for item in tree:
if type(item)==type({}) and item.has_key(path[0]):
if len(path)==1:
if not delete:
try:
item[path[0]].append(value)
except KeyError:
item[path[0]]=value
else:
if value is not None:
del(item[path[0]][value])
else:
del(tree[tree.index(item)])
break
else:
_DoThingsToTree(path[1:],value,item[path[0]],delete)

def GetTreeBranch(path,tree):
if type(path)==type(''):
path=path.lstrip('/').rstrip('/').split('/')
for item in tree:
if type(item)==type({}) and item.has_key(path[0]):
if len(path)==1:
print 'returning',tree[tree.index(item)]
return tree[tree.index(item)]
else:
GetTreeBranch(path[1:],item[path[0]])

def AddItemToTree(path,value,tree):
'''AddITemToTree

Add an item onto a 'branch' of the tree.
pathshould be a '/' separated string that
defines a path to the branch required.
value   an object to put onto the branch
treethe tree to operate on.
'''
DoThingsToTree(path,value,tree)

def AddBranchToTree(path,branch,tree):
'''AddBranchToTree

Add a new branch to the tree.
pathshould be a '/' separated string that
defines a path to the branch required.
branch  an object used as the branch identifier
(usually a string)
treethe tree to operate on
'''
DoThingsToTree(path,{branch:[]},tree)

def DelItemFromTree(path,index,tree):
'''DelItemFromTree

Remove an item from the tree.
pathshould be a '/' separated string that
defines a path to the branch required.
index   the numeric index of the item to delete
on the branch to delete. items are indexed
in the order they are added, from 0
'''
DoThingsToTree(path,index,tree,delete=True)


def DelBranchFromTree(path,tree):
'''DelBranchFromTree

Remove a branch and all items and subbranches.
pathshould be a '/' separated string that
defines a path to the branch required.
treeThe tree to delete the branch from.
'''
DoThingsToTree(path,None,tree,delete=True)


OUTPUT;

 from dirtree import *
 MyTree=MakeNewTree('Matt')
 AddBranchToTree('Matt','Good',MyTree)
 AddBranchToTree('Matt','Bad',MyTree)
 AddItemToTree('Matt/Good','Computers',MyTree)
 AddItemToTree('Matt/Bad','Drinking',MyTree)
 a=GetTreeBranch('Matt/Bad',MyTree)
returning {'Bad': ['Drinking']}
 a



This email is confidential and may be privileged. If you are not the intended 
recipient please notify the sender immediately and delete the email from your 
computer. 

You should not copy the email, use it for any purpose or disclose its contents 
to any other person.
Please note that any views or opinions presented in this email may be personal 
to the author and do not necessarily represent the views or opinions of Digica.
It is the responsibility of the recipient to check this email for the presence 
of viruses. Digica accepts no liability for any damage caused by any virus 
transmitted by this email.

UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK
Reception Tel: + 44 (0) 115 977 1177
Support Centre: 0845 607 7070
Fax: + 44 (0) 115 977 7000
http://www.digica.com

SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South 
Africa
Tel: + 27 (0) 21 957 4900
Fax: + 27 (0) 21 948 3135
http://www.digica.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tertiary Operation

2006-10-17 Thread Carsten Haese
On Tue, 2006-10-17 at 09:48, Tim Chase wrote:
 [...]
 Either of the following should suffice:
 
   # return a non-empty string
   x is None and None or str(x)

This one can be optimized to just str(x) since str(None)==None.

[...]
 There are more baroque ways of writing the terniary operator in 
 python (although I understand 2.5 or maybe python 3k should have 
 a true way of doing this).

Python 2.5 does already.

   My understanding is that one common 
 solution is something like
 
   {True: , False: str(x)}[x is None]

As Fredrik pointed out in not so many words, this is not a good
solution. Besides being ugly, the major problem with this solution is
that both branches are evaluated regardless of the outcome of the
condition. This is not good if the expression is unsafe to calculate
under the wrong condition, or if the expressions are expensive to
calculate, or if the expressions have side effects.

The condition and result1 or result2 hack at least prevents the
evaluation of the non-applicable expression due to the short-circuiting
nature of the and and or operators.

-Carsten


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


Re: Tertiary Operation

2006-10-17 Thread Steven D'Aprano
On Tue, 17 Oct 2006 06:30:32 -0700, abcd wrote:

 x = None
 result = (x is None and  or str(x))

Boolean operators and and or stop as soon as a result is known. So:

X and Y evaluates as X if X is false; otherwise it evaluates as Y.
X or Y evaluates as X if X is true; otherwise it evaluates as Y.

(x is None) evaluates as true, so (x is None and ) evaluates as .
() evaluates as false, so ( or str(None)) evaluates as str(None).

The important factor you missed is, I think, that the empty string is
false in a boolean context.

 if '':
... print empty string evaluates as true
... else:
... print empty string evaluates as false
...
empty string evaluates as false


 y = 5
 result = (y is 5 and it's five or it's not five)

(y is 5) evaluates as true, so (y is 5 and it's five) evaluates as it's
five.
it's five evaluates as true, so (it's five or it's not five)
evaluates as it's five.


Your basic logic is okay, but you shouldn't test equality with is.

== tests for equality;
is tests for object identity.

In the case of None, it is a singleton; every reference to None refers to
the same object. But integers like 5 aren't guaranteed to be singletons.
In your case, you were lucky that, by a fluke of implementation, y is 5
was true. But watch:

 1+4 is 5
True
 10001 + 10004 == 10005
True
 10001 + 10004 is 10005
False

Always use == to test for equality, and (is) only to test for actual
object identity (is this object the same as this one, not just two
objects with the same value?).


-- 
Steven.

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


Re: Looking for assignement operator

2006-10-17 Thread Rob Wolfe

Alexander Eisenhuth wrote:
 Hello,

 is there a assignement operator, that i can overwrite?

You can't overwrite assignment operator, but you can
overwrite methods of numeric objects:

http://docs.python.org/ref/numeric-types.html

HTH,
Rob

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


Re: Tertiary Operation

2006-10-17 Thread Roy Smith
In article [EMAIL PROTECTED],
 abcd [EMAIL PROTECTED] wrote:

 Carsten Haese wrote:
  Use Python 2.5 where there is a true conditional
  expression or find another way to solve your problem.
 
 python 2.5 once we upgrade (hopefully soon), anyways...an earlier post
 suggested the inverse...
 
 x = None
 result = (x is not None and str(x) or )
 
 which works just fine.
 
 thanks.

Why not just:

if x is None:
   result = str(x)
else:
   result = 

It's a couple more lines of code, but it's obvious what it means.  I know 
about boolean short-circuit evaluation, and the and/or trick, but I still 
look at

result = (x is not None and str(x) or )

and have to puzzle through exactly what's going on there.  You are going to 
write your code once.  It's going to be read many many times by different 
people.  It's worth a few more keystrokes on your part to save all those 
future maintenance programmers headaches later.

You won't really understand just how important readability is until you're 
maintaining a million lines of old code, most of it written by people who 
are no longer on the project.  I spend a lot of time staring at code 
somebody else wrote and muttering things like, What the  does this 
do?  That's just money down the toilet.

If I have to reach for a reference manual to look up operator binding rules 
to understand a piece of code, that's bad.  If I have to start making notes 
on a piece of scrap paper, Let's see, if x is this, then that's true, so 
blah, blah, that's bad.  If I look at something subtle, don't realize it's 
subtle, and come to an incorrect conclusion about what it does, then base 
some other decisions on that incorrect conclusion, that's really, really 
bad.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for assignement operator

2006-10-17 Thread Laurent Pointal
Alexander Eisenhuth a écrit :
 Hello,
 
 is there a assignement operator, that i can overwrite?

Adding to Simon Brunning reply (assignment is a statement).

 class MyInt:
 def __init__(self, val):
 assert(isinstance(val, int))
 self._val = val
 
 a = MyInt(10)
 
 # Here i need to overwrite the assignement operator
 a = 12

Here you bind the 12 (Python int value) to name 'a', then 'a' has the
int type, not your MyInt (which value has been lost).

You may define a 'set' method, and write:
a = MyInt(10)
a.set(12)

And, if a is a member of another class, you may define an accessor for
that 'a' member in that class, which automatically call your set method
when giving an int value.

b.a = MyInt(10)
b.a = 12--- b.a.set(12)

A+

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


Re: Format a number as currency! I can't find any help on this simple problem.

2006-10-17 Thread jr
Hi, Bernard.
Just tried the first 2 commands on win XP, Python 2.5 under Idle.
An Error is raised: unsupported locale setting (lib/locale.py in
setlocale, line 476).
Actually I get the error also under Python 2.4.3
Any idea what I'm missing?
Thanks in advance.
Jürgen
Bernard wrote:
  import locale
  locale.setlocale(locale.LC_ALL, 'English_United States.1252')
 'English_United States.1252'
  conv = locale.localeconv()
  x = 1234567.8
  locale.format(%d, x, grouping=True)
 '1,234,567'
  locale.format(%s%.*f, (conv['currency_symbol'], 
  conv['int_frac_digits'], x), grouping=True)
 '$1,234,567.80'

 Hi Richards,

 This works for me. I agree it's a bit complicated compared to C# but it
 works. I'd put it in a function if I had to use it.


 Richard Kessler wrote:
  I am relatively new to Python.  Love it, but I find things that I can do
  easily in .NET and cannot find a way to do in Python. I need to format a
  number as currency, for example 12343.56 to $12,343.56.
 
  In C# all I need to do is decimal x = 12343.56 then 
  x.ToString($###,###.00);
 
  I cannot find a way to do this in Python. I must be missing something very
  simple here. I have tried the locale module but it will not put in the 
  commas.
  I hope I do not have to write my own formatting routine...surely one is out
  there and I just can't find it.
 
  Running on XP Pro. Python 2.4.3.
  
  Thanks much in advance,
  
  Richard

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


Re: Looking for assignement operator

2006-10-17 Thread Steven D'Aprano
On Tue, 17 Oct 2006 15:50:47 +0200, Alexander Eisenhuth wrote:

 Hello,
 
 is there a assignement operator, that i can overwrite?

No.

We were just discussing the reasons why Python will not and can not have
an assignment operator just a few days ago. Check the archives for more
details.


 class MyInt:
   def __init__(self, val):
   assert(isinstance(val, int))

isinstance() considered harmful:

http://www.canonical.org/~kragen/isinstance/

   self._val = val

Seems kind of pointless. What does MyInt do that ordinary ints don't?
Apart from slow your program down and require extra programming effort.

 a = MyInt(10)
 
 # Here i need to overwrite the assignement operator a = 12

Can't happen. a is just a name, not an object with methods that can be
called. a can be bound to anything, not just MyInt instances. Objects
like MyInt(10) can have no name, one name or many names:

mylist = [0, MyInt(10), 20, 30]  # MyInt instance has no name
x = MyInt(10)  # MyInt instance has one name
x = y = z = MyInt(10)  # MyInt instance has many names



-- 
Steven.

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


Re: Looking for assignement operator

2006-10-17 Thread Jerry


On Oct 17, 8:50 am, Alexander Eisenhuth [EMAIL PROTECTED]
wrote:
 Hello,

 is there a assignement operator, that i can overwrite?

 class MyInt:
 def __init__(self, val):
 assert(isinstance(val, int))
 self._val = val

 a = MyInt(10)

 # Here i need to overwrite the assignement operator
 a = 12

 Thanks
 Alexander

I believe the property function is what you are looking for.  e.g.

class MyClass:
def __init__(self, val):
self.setval(val)

def getval(self):
return self._val

def setval(self, val):
assert(isinstance(val, int))
self._val = val

_val = property(self.getval, self.setval)

--
Jerry

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


Re: Format a number as currency! I can't find any help on this simple problem.

2006-10-17 Thread Jerry
Replace the conv function call with locale.localeconv.

--
Jerry

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


Re: Looking for assignement operator

2006-10-17 Thread Bruno Desthuilliers
Steven D'Aprano wrote:
 On Tue, 17 Oct 2006 15:50:47 +0200, Alexander Eisenhuth wrote:
 
 Hello,

 is there a assignement operator, that i can overwrite?
 
 No.
 
 We were just discussing the reasons why Python will not and can not have
 an assignment operator just a few days ago. Check the archives for more
 details.
 
 
 class MyInt:
  def __init__(self, val):
  assert(isinstance(val, int))
 
 isinstance() considered harmful:

Trying to convert val to an int would probably be better indeed:

class MyInt(object):
  def __init__(self, val):
self.val = int(val)

My 2 cents
-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


stdout not flushed before os.execvp()

2006-10-17 Thread Thomas Guettler
Hi,

I noticed, that sys.stout does not get flushed before the process is
replaced. The last print statements (before execvp()) disappear.

It only happens, if the output is redirected to a file (if sys.stdout is
not line buffered).

#testexec.py
import os
print Messsage
os.execvp(/bin/true, [/bin/true])


=== python tmp/testexec.py 
Messsage

=== python tmp/testexec.py   out ; cat out


Is this a bug or feature?

My version:
Python 2.4.2 (#1, May  2 2006, 08:28:01) 
GCC 4.1.0 (SUSE Linux)] on linux2


-- 
Thomas Güttler, http://www.thomas-guettler.de/ http://www.tbz-pariv.de/
E-Mail: guettli (*) thomas-guettler + de
Spam Catcher: [EMAIL PROTECTED]

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


Re: How to invoke ipython in Mac OS X?

2006-10-17 Thread Jerry
Did you install it with the --install-scripts command line option?  If
you did, then there will be a ipython script located in the
$INSTALL_SCRIPTS/bin directory.  If you didn't, then I think the
default location is /usr/lib/python or something like that.

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


Re: Problem: Python search path - module order

2006-10-17 Thread Thomas Guettler
aznach wrote:

 Hello!

 I have a shared hosting account at GrokThis.net and have a problem with
 the module order of the Python search path.

 I'd like to use django's svn trunk instead of the
 Django-0.95-py2.4.egg provided in site-packages.

 I use ~/.bash_profile to set:
 
 export PYTHONPATH=$HOME/local/lib/python:$HOME/django_src
 

you can use sys.path.insert(0, ...) in the python code.

-- 
Thomas Güttler, http://www.thomas-guettler.de/ http://www.tbz-pariv.de/
E-Mail: guettli (*) thomas-guettler + de
Spam Catcher: [EMAIL PROTECTED]

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


Re: How to invoke ipython in Mac OS X?

2006-10-17 Thread Diez B. Roggisch
Lou Pecora wrote:

 I installed the SciPy superpackage and have pylab, matplotlib, scipy,
 and numpy apparently running well.  But I want to use matplotlib/pylab
 interactively.  The instructions suggest doing this in IPython.  But
 using ipython on the command line gives me an error.  The system doesn't
 know the command.  Apparently there is no ipython executable in one of
 the bin directories.  I thought the superpackage would add that
 automatically, but I guess not.
 
 Can anyone tell me how to get ipython running on my MacOSX 10.4 system?

This is just a guess - but did you check your

/Library/Frameworks/Python.framework/Versions/Current/bin

(out of my head, but should be precise enough to get you there)

directory for the ipython-binary? Usually, that will be the prefix of
anything compiled/installed to framework-builds. So either you add that to
your path, or create links to e.g. /usr/local/bin



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


Re: Looking for assignement operator

2006-10-17 Thread Bruno Desthuilliers
Jerry wrote:
(snip)
 I believe the property function is what you are looking for. 

It is not.

 e.g.
 
 class MyClass:

Descriptors don't work fine with old-style classes. Should be:

class MyClass(object):

 def __init__(self, val):
 self.setval(val)
 
 def getval(self):
 return self._val
 
 def setval(self, val):
 assert(isinstance(val, int))
 self._val = val
 
 _val = property(self.getval, self.setval)

NameError : self is not defined.
Should be :
_val = property(getval, setval)

but then - since setval() now calls _vals.__set__(), which itself calls
setval(), you have a nice infinite recursion (well, almost infinite -
hopefully, Python takes care of it).

May I kindly suggest that you learn more about properties and test your
code before posting ?-)

Anyway, even with the following correct code, this won't solve the OP's
question:
class MyClass(object):
def __init__(self, val):
self.val = val

def _getval(self):
return self._val

def _setval(self, val):
self._val = int(val)

val = property(_getval, _setval)


m = MyClass(42)
m
= __main__.MyClass object at 0x2ae5eaa00410
m.val
= 42
m = 42
m
= 42
type(m)
= type 'int'


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urllib.urlopen: Errno socket error

2006-10-17 Thread kgrafals
Dennis,

I tried a ProxyHandler with the following code ...

proxy_support = urllib2.ProxyHandler({})
opener = urllib2.build_opener(proxy_support)
urllib2.install_opener(opener)

... but it's giving me the same result.

Then I tried to tunnel using code from ...

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/213238

... but it too gave me an error ...

Traceback (most recent call last):
  File pyshell#7, line 1, in module
tunnel.run(tunnel_this)
  File C:/Python25/My Python/PyTunnel.py, line 124, in run
Threads.append( thread_it(tid=0,proxy=self.get_proxy(),\
  File C:/Python25/My Python/PyTunnel.py, line 81, in get_proxy
proxy.connect((self._phost,self._pport))
  File string, line 1, in connect
gaierror: (11001, 'getaddrinfo failed')

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


Re: Tertiary Operation

2006-10-17 Thread Christophe
abcd a écrit :
 x = None
 result = (x is None and  or str(x))
 
 print result, type(result)
 
 ---
 OUTPUT
 ---
 None type 'str'
 
 
 y = 5
 result = (y is 5 and it's five or it's not five)
 
 print result
 
 -
 OUTPUT
 -
 it's five
 
 ...what's wrong with the first operation I did with x?  I was expecting
 result to be an empty string, not the str value of None.
 

the condition and if_true or if_false is NOT a ternary operator 
but an ugly hack that breaks in some situations. It just happens that 
you stumbled on one of those situations : if_true must never evaluate 
as False. Please, do not use that ugly hack anymore and do a proper if 
block.

Or use Python 2.5 with the official ternary operator ;)

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


Re: Looking for assignement operator

2006-10-17 Thread Alexander Eisenhuth
Wow, thanks a lot for your quick answers.

That assignement is no operator, but a statemant is a pity, but indeed I came 
foward with overwritten methods for numeric types

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


Re: Format a number as currency! I can't find any help on this simple problem.

2006-10-17 Thread Peter Otten
jr wrote:

  import locale
  locale.setlocale(locale.LC_ALL, 'English_United States.1252')
 'English_United States.1252'

 Just tried the first 2 commands on win XP, Python 2.5 under Idle.
 An Error is raised: unsupported locale setting (lib/locale.py in
 setlocale, line 476).
 Actually I get the error also under Python 2.4.3
 Any idea what I'm missing?

Let your machine decide

 locale.setlocale(locale.LC_ALL, )
'de_DE.UTF-8'

or try something less specific:

 locale.setlocale(locale.LC_ALL, en_US)
'en_US'

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


Re: Tertiary Operation

2006-10-17 Thread Bruno Desthuilliers
abcd wrote:
 x = None
 result = (x is None and  or str(x))

You don't need the parenthesis.

 print result, type(result)
 
 ---
 OUTPUT
 ---
 None type 'str'
 
 
 y = 5
 result = (y is 5 and it's five or it's not five)

By all means *don't* use identity tests in such a context. Try with
10 instead of 5:
 x = 10
 x is 10
False


 print result
 
 -
 OUTPUT
 -
 it's five
 
 ...what's wrong with the first operation I did with x?  I was expecting
 result to be an empty string, not the str value of None.

As other already pointed, an empty string (as well as an empty list,
tuple, dict, set IIRC, and zero int or float) evals to False in a
boolean context.

Python 2.5 has a ternary operator. If you need to deal with older Python
versions, another possible 'ternary op hack' is :

x = None
(str(x), )[x is None]
= 
x = 42
(str(x), )[x is None]
= 42

This relies on the fact that False == 0 and True == 1.

NB : if you don't want to eval both terms before (which is how it should
be with a real ternanry operator), you can rewrite it like this:

result = (str, lambda obj:)[x is None)(x)

But this begins to be unreadable enough to be replaced by a good old
if/else...

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to invoke ipython in Mac OS X?

2006-10-17 Thread Lou Pecora
In article [EMAIL PROTECTED],
 Diez B. Roggisch [EMAIL PROTECTED] wrote:

 Lou Pecora wrote:
 
  I installed the SciPy superpackage and have pylab, matplotlib, scipy,
  and numpy apparently running well.  But I want to use matplotlib/pylab
  interactively.  The instructions suggest doing this in IPython.  But
  using ipython on the command line gives me an error.  The system doesn't
  know the command.  Apparently there is no ipython executable in one of
  the bin directories.  I thought the superpackage would add that
  automatically, but I guess not.
  
  Can anyone tell me how to get ipython running on my MacOSX 10.4 system?
 
 This is just a guess - but did you check your
 
 /Library/Frameworks/Python.framework/Versions/Current/bin


Just checked it. Nothing there for IPython.

 directory for the ipython-binary? Usually, that will be the prefix of
 anything compiled/installed to framework-builds. So either you add that to
 your path, or create links to e.g. /usr/local/bin

I'm not quite following this last suggestion.  Can you explain more. 
Sorry.

-- Lou Pecora  (my views are my own) REMOVE THIS to email me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: What's up with the starship?

2006-10-17 Thread rurpy

[EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] wrote:
  [EMAIL PROTECTED] wrote:
 
   I don't think that would help in the case of Pywin32 since the
   Sourceforge dates for build 210 are 9/22.
   I emailed Mark Hammond but have not heard anything back yet.
 
  In the case of pywin32, are you at all sure that you actually
  downloaded anything from starship.python.net?  AFAICT all the files are
  now hosted on sf, and there doesn't seem to be any vaguely new files in
  the backup of /home/www.

 The files I downloaded were from sourceforge.  I don't know if
 starship.python.net hosts the source files or plays any role in
 building the disrtribution package.  It may be that is all done
 elsewhere.  But given starship.python.net's historical association
 with Pywin32, I am not going to just assume that.

In email, Mark Hammond said that that the Pywin32 code is not
hosted at starship.python.net, nor are the distributions built there.
(I assume this does not apply to the very old win32all stuff that
*is* at python.net but I doubt anyone uses those anymore.)

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


Re: Tertiary Operation

2006-10-17 Thread Steven Bethard
abcd wrote:
 x = None
 result = (x is None and  or str(x))
 print result, type(result)
 
 ---
 OUTPUT
 ---
 None type 'str'
 
 
[snip]
 ...what's wrong with the first operation I did with x?

You weren't using Python 2.5:

Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit 
(Intel)] on win32
Type help, copyright, credits or license for more information.
  x = None
  '' if x is None else str(x)
''
 

Time to upgrade. ;-)

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


  1   2   3   >