Re: Fetching a clean copy of a changing web page

2007-07-16 Thread Diez B. Roggisch
John Nagle schrieb:
I'm reading the PhishTank XML file of active phishing sites,
 at http://data.phishtank.com/data/online-valid/;  This changes
 frequently, and it's big (about 10MB right now) and on a busy server.
 So once in a while I get a bogus copy of the file because the file
 was rewritten while being sent by the server.
 
Any good way to deal with this, short of reading it twice
 and comparing?

Make them fix the obvious bug they have would be the best of course.

Apart from that - the only thing you could try is to apply a SAX parser 
on the input stream immediatly, so that at least if the XML is non-valid 
because of the way they serve it you get to that ASAP. But it will only 
shave off a few moments.

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


Re: Fetching a clean copy of a changing web page

2007-07-16 Thread Miles
On Jul 16, 1:00 am, John Nagle [EMAIL PROTECTED] wrote:
 I'm reading the PhishTank XML file of active phishing sites,
 at http://data.phishtank.com/data/online-valid/;  This changes
 frequently, and it's big (about 10MB right now) and on a busy server.
 So once in a while I get a bogus copy of the file because the file
 was rewritten while being sent by the server.

 Any good way to deal with this, short of reading it twice
 and comparing?

 John Nagle

Sounds like that's the host's problem--they should be using atomic
writes, which is usally done be renaming the new file on top of the
old one.  How bogus are the bad files?  If it's just incomplete,
then since it's XML, it'll be missing the /output and you should
get a parse error if you're using a suitable strict parser.  If it's
mixed old data and new data, but still manages to be well-formed XML,
then yes, you'll probably have to read it twice.

-Miles

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


Re: how to implementation latent semantic indexing in python..

2007-07-16 Thread Paul Rubin
[EMAIL PROTECTED] (Alex Martelli) writes:
 You may get more responses (as in, 0!-) if you give some URL about what
 this algorithm is supposed to do.

http://en.wikipedia.org/wiki/Latent_semantic_analysis

Very cool stuff.
-- 
http://mail.python.org/mailman/listinfo/python-list


embedded python in dll with C

2007-07-16 Thread Mick Duprez
Hi All,
I can't quite get my head around embedding Python in a C app and I
have a few questions if I may, here is the background.
I want to create a dll plugin that has the Python interpreter embedded
in it for use in scripting an established application. So far I have
created the interface dll and py module using swig. So far so good,
now some questions -

1) Would it be best to combine my swig generated .c file into the same
dll as my plugin dll or leave it seperate, in other words should I
just embed the interpreter into the C 'plugin' dll and create the
interface module and dll seperately to import into python scripts?

2) Once I have done this would it be appropriate just to use something
like this in my C code -

PyRun_SimpleString(import my_plugin_script);
PyRun_SimpleString(init_func_from_script());

where 'init_func_from_script' establishes callbacks for C to use from
the script using the new interface module/dll? The C application has
it's own functions for registering callbacks by passing in a list of
the functions, I'm hoping this will work.

I'll give it a go in the mean time, just looking for the right/better
way to do this, thanks.

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


Re: How to determine which method was used in an inheritance heirarchy?

2007-07-16 Thread Michele Simionato
On Jul 16, 7:18 am, Erik Jones [EMAIL PROTECTED] wrote:
 On Jul 15, 2007, at 11:23 PM, Michele Simionato wrote:

  On Jul 16, 5:51 am, Erik Jones [EMAIL PROTECTED] wrote:
  Say you're given a call event frame for a method call.  How can you
  tell if the code being executed came from a super class of the object
  or class the method was called on?

  Erik Jones

  You look if the method was defined in self.__class__.__dict__.

 Michele Simionato

 That doesn't seem to cover calling super class __init__ methods.


I am probably missing something. In the following code the
method check_init checks if the current instance
possess an __init__ or if it just inherits one
from the ancestors. Is this what you want?

class B(object):
def __init__(self):
'something'
def check_init(self):
if '__init__' in self.__class__.__dict__:
print 'possesses __init__'
else:
print 'inherits __init__'

class C(B):
'something else'
def __init__(self):
print 'calling C.__init__'

class D(B):
pass

c = C()
d = D()

c.check_init() #possesses __init__
d.check_init() #inherits __init__

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


Re: determining the source code and module based on the class

2007-07-16 Thread thebjorn
On Jul 16, 6:55 am, alf [EMAIL PROTECTED] wrote:
...
 now I need a piece of code which based on the class name can point to
 the module as well as the line number where the given class is defined.

 Is it doable in Python?

look in the inspect module.

-- bjorn

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


Re: How to determine which method was used in an inheritance heirarchy?

2007-07-16 Thread Erik Jones

On Jul 16, 2007, at 1:31 AM, Erik Jones wrote:

 On Jul 16, 2007, at 12:53 AM, Michele Simionato wrote:

 On Jul 16, 7:18 am, Erik Jones [EMAIL PROTECTED] wrote:
 On Jul 15, 2007, at 11:23 PM, Michele Simionato wrote:

 On Jul 16, 5:51 am, Erik Jones [EMAIL PROTECTED] wrote:
 Say you're given a call event frame for a method call.  How can  
 you
 tell if the code being executed came from a super class of the  
 object
 or class the method was called on?

 Erik Jones

 You look if the method was defined in self.__class__.__dict__.

Michele Simionato

 That doesn't seem to cover calling super class __init__ methods.


 I am probably missing something. In the following code the
 method check_init checks if the current instance
 possess an __init__ or if it just inherits one
 from the ancestors. Is this what you want?

 class B(object):
 def __init__(self):
  'something'
 def check_init(self):
 if '__init__' in self.__class__.__dict__:
 print 'possesses __init__'
 else:
 print 'inherits __init__'

 class C(B):
 'something else'
 def __init__(self):
 print 'calling C.__init__'

 class D(B):
 pass

 c = C()
 d = D()

 c.check_init() #possesses __init__
 d.check_init() #inherits __init__

 Ok, I see how I was pretty vague with my original questions.
 Given the pattern where you need to call a base class's constructor  
 (or, other overriden method of the same name as that being called  
 on the child class object):

 class A(object):
   def __init__(self):
   print self.__class__.__name__

 class B(A):
   def __init__(self):
   A.__init__(self)
   print self.__class__.__name__

 B()

 This will output:

 B
 B

 How can I get

 A
 B

Perhaps an even better example of what I'm trying to do would be in  
order (this is minus any exception handling):

import sys

def mytrace(frame, event, arg):
 if event == 'call':
 func_name = frame.f_code.co_name

 if func_name in frame.f_locals['self'].__class__.__dict__:
 print frame.f_locals['self'].__class__.__name__
 else:
 for base in frame.f_locals['self'].__class__.__bases__:
 if func_name in base.__dict__:
 print base.__name__
 break


class A(object):
 def __init__(self):
 pass

class B(A):
 def __init__(self):
 A.__init__(self)

sys.settrace(mytrace)
B()

This will output:

B
B

whereas I'm shooting for:

B
A



Erik Jones

Software Developer | Emma®
[EMAIL PROTECTED]
800.595.4401 or 615.292.5888
615.292.0777 (fax)

Emma helps organizations everywhere communicate  market in style.
Visit us online at http://www.myemma.com


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


Re: 2**2**2**2**2 wrong? Bug?

2007-07-16 Thread Hendrik van Rooyen
 Wayne Brehaut [EMAIL PROTECTED] wrote:

 On Sun, 15 Jul 2007 17:37:13 -0400, Steve Holden [EMAIL PROTECTED]
 wrote:
 
 Wayne Brehaut wrote:
  On Fri, 13 Jul 2007 14:32:03 -0700, [EMAIL PROTECTED]

8 -

 Also, I tend to follow the general Evolutionarily Stable Strategy
 generally called Retaliator.  In the simple game of Hawk vs. Dove a
 Hawk always attacks and defends to the death, whereas a Dove always
 runs. A mixed strategy would be to sometimes attack-and-defend and
 sometimes run, and a special case is to always run except when you're
 attacked--then defend to the death; i.e., behave like a Dove to a Dove
 and like a Hawk to a Hawk. 
 
 In Game Theory, if not in practice, Retaliator is dominant over both
 pure Hawk and pure Dove, partly because some who present like Hawks
 are actually Bullies--who behave like Hawks until an opponent defends,
 then behave  like Doves.

*grin* - you realise of course, that this stated strategy leaves you wide
open to trolls of the Lets see what we can provoke him into responding
kind - from people whose sense of humour is either subtle, or evil...

- Hendrik

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


Re: Access Object From 2 Applications or Fix Scheduler

2007-07-16 Thread Hendrik van Rooyen
 Robert Rawlins - Think Blue  wrote:


Hello Guys,

I have two applications which I need to get talking and sharing an object, what
’s the best way to do this? Basically my first application parses an XML
document into a bunch of lists and tuples etc, and I need to access the data in
these lists and tuples from my second application. Is this possible? And what’s
the simplest method?

This problem all evolves from a hack/work around I’ve had to place together as
I have been having problems with sched, these two applications used to be a
single one to start with but for some reason when scheduling tasks using the
sched module they wouldn’t ever run when supposed too, so I’d schedule it to
run every 2 minutes and it would run between 3 and 15 minutes :-s so I ripped
it out into its own application and it now runs every 2 minutes exactly.

I either need to fix my sched issues or the memory share, either way I’m quite
happy, just need to get it working smoothly.

Any ideas?


You have already split the thing, so I would:

schedule the XML parser and make it do its stuff.
then pickle the results using cPickle
then from this first thing, either:
write the pickles to temp files and start the second thing
using eg os.system()
or start the second thing and use a named pipe to
pass the pickles over for unpickling and processing,
or use one of the popens,
or have a look at Pyro,
or start the second thing as a thread and use a Queue..

of course this whole scheme will fall apart if the combined
processing takes longer than the scheduling interval.

HTH - Hendrik


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

Re: 2**2**2**2**2 wrong? Bug?

2007-07-16 Thread Tim Roberts
Jim Langston [EMAIL PROTECTED] wrote:

Gah!  Python goes right to left?  Dang, I haven't seen that since APL.

No, *exponentiation* in Python goes right to left, as it does in all the
languages I've used that support an exponentiation operator.
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza  Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to determine which method was used in an inheritance heirarchy?

2007-07-16 Thread Erik Jones
On Jul 16, 2007, at 12:53 AM, Michele Simionato wrote:

 On Jul 16, 7:18 am, Erik Jones [EMAIL PROTECTED] wrote:
 On Jul 15, 2007, at 11:23 PM, Michele Simionato wrote:

 On Jul 16, 5:51 am, Erik Jones [EMAIL PROTECTED] wrote:
 Say you're given a call event frame for a method call.  How can you
 tell if the code being executed came from a super class of the  
 object
 or class the method was called on?

 Erik Jones

 You look if the method was defined in self.__class__.__dict__.

Michele Simionato

 That doesn't seem to cover calling super class __init__ methods.


 I am probably missing something. In the following code the
 method check_init checks if the current instance
 possess an __init__ or if it just inherits one
 from the ancestors. Is this what you want?

 class B(object):
 def __init__(self):
   'something'
 def check_init(self):
 if '__init__' in self.__class__.__dict__:
 print 'possesses __init__'
 else:
 print 'inherits __init__'

 class C(B):
 'something else'
 def __init__(self):
 print 'calling C.__init__'

 class D(B):
 pass

 c = C()
 d = D()

 c.check_init() #possesses __init__
 d.check_init() #inherits __init__

Ok, I see how I was pretty vague with my original questions.   Given  
the pattern where you need to call a base class's constructor (or,  
other overriden method of the same name as that being called on the  
child class object):

class A(object):
def __init__(self):
print self.__class__.__name__

class B(A):
def __init__(self):
A.__init__(self)
print self.__class__.__name__

B()

This will output:

B
B

How can I get

A
B

Erik Jones

Software Developer | Emma®
[EMAIL PROTECTED]
800.595.4401 or 615.292.5888
615.292.0777 (fax)

Emma helps organizations everywhere communicate  market in style.
Visit us online at http://www.myemma.com


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


How to import java class used Jython in Python?

2007-07-16 Thread datulaida ali

Hi all...
How to import Semantic class used Jython in Python?
here my java code..

JAVA CODE

import java.text.BreakIterator ;

class Semantic {

  // native C++ method
  //public native void printMessage( String message );
public native String printMessage( String message );
  // load library JNIPrintMessage into JVM
  static {
 System.loadLibrary( JNIPrintMessage );
  }


 public static void main(String [] args) {

  String l = i go to school;
  pilih_ayat(l);


 }

 public static String pilih_ayat(String n){

   JNIPrintWrapper wrapper = new JNIPrintWrapper();

  String ayat_siap =  wrapper.printMessage(n);
   System.out.println(output  + ayat_siap);
   return n;
   }//end pilih ayat


 public Semantic(){
 System.out.println (Berjaya);
 }
}//end class

JAVA OUTPUT

output  (S(NLP i) (VP go(PP to(NLP school
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Can a low-level programmer learn OOP?

2007-07-16 Thread Bruno Desthuilliers
Wayne Brehaut a écrit :
 On Sat, 14 Jul 2007 06:01:56 +0200, Bruno Desthuilliers
 [EMAIL PROTECTED] wrote:
 
 Chris Carlen a écrit :
 Hi:

  From what I've read of OOP, I don't get it.  I have also found some 
 articles profoundly critical of OOP.  I tend to relate to these articles.

 
 === 8 ===
 
 Hence, being a hardware designer rather than a computer scientist, I am 
 conditioned to think like a machine.  I think this is the main reason 
 why OOP has always repelled me.
 OTOH, OO is about machines - at least as conceveid by Alan Key, who 
 invented the term and most of the concept. According to him, each object 
 is a (simulation of) a small machine.
 
 Oh you young'uns, not versed in The Ancient Lore, but filled with
 self-serving propaganda from Xerox PARC, Alan Kay, and Smalltalk
 adherents everywhere!

Not feeling concerned.

(snip pro-simula/anti-Xerox propaganda).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-16 Thread Paul Rubin
Diez B. Roggisch [EMAIL PROTECTED] writes:
 For example, SPARK does not support dynamic allocation of memory so
 things such as pointers and heap variables are not supported.

Right, Spark uses a profile intended for embedded systems, so
no unpredictable gc delays etc.

 Which is not to say that trivial code couldn't have errors, and if
 it's extremely cruical code, it's important that it hasn't errors. But
 all I can see is that you can create trustable, simple sub-systems in
 such a language. And by building upon them, you can ensure that at
 least these won't fail.

Yes, that's the usual approach.

 But to stick with the example: if the path-planning of the UAV that
 involves tracking a not before-known number of enemy aircrafts steers
 the UAV into the ground, no proven-not-to-fail radius calculation will
 help you.

Whether the program uses dynamic memory allocation or not, there
either has to be some maximum number of targets that it can be
required to track, or else it's subject to out-of-memory errors.
If a maximum number is specified, then memory requirements can
be computed from that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getting text inside the HTML tag

2007-07-16 Thread Stefan Behnel
Bruno Desthuilliers wrote:
 [EMAIL PROTECTED] a écrit :
 On Jul 14, 12:47 pm, Nikola Skoric [EMAIL PROTECTED] wrote:
 I'm using sgmllib.SGMLParser to parse HTML. I have successfuly parsed
 start
 tags by implementing start_something method. But, now I have to fetch
 the
 string inside the start tag and end tag too. I have been reading through
 SGMLParser documentation, but just can't figure that out... can somebody
 help? :-)

 -- 
 Now the storm has passed over me
 I'm left to drift on a dead calm sea
 And watch her forever through the cracks in the beams
 Nailed across the doorways of the bedrooms of my dreams

 Oi! Try Beautiful Soup instead. That seems to be the defacto HTML
 parser for Python:
 
 Nope. It's the defacto parser for HTML-like tag soup !-)

Very true. As long as you're dealing with something that looks pretty much
like HTML, I actually don't think you can beat lxml.html (and it's still
getting better every day).

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


how good does PyGTK work on windows?

2007-07-16 Thread krishnakant Mane
hello,
I will be writing some code in PyGTK to run on linux.  but I want to
know if there are any installers or distutils available for PyGTK on
windows?
I have heard that installing gimp or even pygtk is next to impossible
and is very tedious if at all one gets success.
can any one share their experiences with installing and running pygtk on windos?
any links for downloading proper packages will be highly appreciated.
regards,
Krishnakant.
-- 
http://mail.python.org/mailman/listinfo/python-list


running a Delphi part from Python ?

2007-07-16 Thread Stef Mientki

I'm starting to get used to wxPython (coming from Delphi),
and it seems it can do almost everything I need.

Now one thing I'm missing is a good RichEditor.
I've a good RichEdit in Delphi ...
... so what are the possibilities to include that in Python ?

The most simple for me to do,
seems to create a DLL, which contains the RichEdit and all it's controls,
as an MDI child window.

So how could I interface to some Delphi-DLL in Python ?
And maybe even more complicated,
is a MDI-child written in a Delphi-DLL,
identical to the wxPython MDI-child
( If I remember well, I read somewhere that MDI is implemented in it's own 
manner,
not equal to the standard Windows MDI interface)

thanks,
Stef Mientki
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to determine which method was used in an inheritance heirarchy?

2007-07-16 Thread Gabriel Genellina
En Mon, 16 Jul 2007 03:56:18 -0300, Erik Jones [EMAIL PROTECTED] escribió:

 Perhaps an even better example of what I'm trying to do would be in
 order (this is minus any exception handling):

 import sys

 def mytrace(frame, event, arg):
  if event == 'call':
  func_name = frame.f_code.co_name

  if func_name in frame.f_locals['self'].__class__.__dict__:
  print frame.f_locals['self'].__class__.__name__
  else:
  for base in frame.f_locals['self'].__class__.__bases__:
  if func_name in base.__dict__:
  print base.__name__
  break


 class A(object):
  def __init__(self):
  pass

 class B(A):
  def __init__(self):
  A.__init__(self)

 sys.settrace(mytrace)
 B()

 This will output:

 B
 B

If you don't mind post-processing the results, you can log the function  
name and source module (from frame.f_code.co_name and co_filename) and  
current line number (frame.f_lineno). Later, obtaining the class name from  
those is a bit tricky (and not even the inspect module does it right), but  
perhaps using the tokenizer module, watching for lines that contain  
class name is enough.

-- 
Gabriel Genellina

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


Re: running a Delphi part from Python ?

2007-07-16 Thread Stef Mientki
Bruno Desthuilliers wrote:
 Stef Mientki a écrit :

 I'm starting to get used to wxPython (coming from Delphi),
 and it seems it can do almost everything I need.

 Now one thing I'm missing is a good RichEditor.
 
 Scintilla is for you, then. IIRC, there's a wxWidget widget embedding 
 it, and quite a few editors using it.
 
AFAIK, Scintilla is a code editor.
What I need looks more like ms-word,
handling lists, tables, images, formulas.

thanks,
Stef Mientki
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can a low-level programmer learn OOP?

2007-07-16 Thread Bruno Desthuilliers
Wayne Brehaut a écrit :
(snip)
  after Bruno made the
 claim: OO is about machines - at least as conceveid by Alan Key, who
 invented the term and most of the concept.

Please reread more carefully the above. I do give credit to Smalltalk's 
author for the *term* OOP, and *most* (not *all*) of the concepts (I 
strongly disagree with your opinion that message-passing is not a core 
concept of OO).

FWIW, I first mentionned Simula too (about the state-machine and 
simulation aspect), then sniped this mention because I thought it was 
getting a bit too much OT - we're not on comp.object here.

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


RE: Access Object From 2 Applications or Fix Scheduler

2007-07-16 Thread Robert Rawlins - Think Blue
Thanks Hendrik  Alex for your suggestions,

I'm glad to see that there are lots of options for me here, and I'll give
them all of a decent exploration to see what my best option is, starting the
second app in a named pipe sounds like a fair solution, but I've not don't
this before, how easy is it to have the second application ready to receive
the new dictionary data?

Just out of interest though I'd still like to know why my first application
schedules didn't work properly, should I be starting them all in their own
thread? Would that work better?

Thanks Guys,

Rob

-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED]
On Behalf Of Hendrik van Rooyen
Sent: 16 July 2007 07:29
To: python-list@python.org
Subject: Re: Access Object From 2 Applications or Fix Scheduler

 Robert Rawlins - Think Blue  wrote:


Hello Guys,

I have two applications which I need to get talking and sharing an 
object, what
s the best way to do this? Basically my first application parses an XML
document into a bunch of lists and tuples etc, and I need to access the data
in these lists and tuples from my second application. Is this possible? And
whats the simplest method?


This problem all evolves from a hack/work around Ive had to place 
together as
I have been having problems with sched, these two applications used to be a
single one to start with but for some reason when scheduling tasks using the
sched module they wouldnt ever run when supposed too, so Id schedule 
it to
run every 2 minutes and it would run between 3 and 15 minutes :-s so I
ripped it out into its own application and it now runs every 2 minutes
exactly.

I either need to fix my sched issues or the memory share, either way 
Im quite
happy, just need to get it working smoothly.

Any ideas?


You have already split the thing, so I would:

schedule the XML parser and make it do its stuff.
then pickle the results using cPickle
then from this first thing, either:
write the pickles to temp files and start the second thing using eg
os.system() or start the second thing and use a named pipe to pass the
pickles over for unpickling and processing, or use one of the popens, or
have a look at Pyro, or start the second thing as a thread and use a Queue..

of course this whole scheme will fall apart if the combined processing takes
longer than the scheduling interval.

HTH - Hendrik



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


Re: Fetching a clean copy of a changing web page

2007-07-16 Thread Stefan Behnel
Diez B. Roggisch wrote:
 John Nagle wrote:
I'm reading the PhishTank XML file of active phishing sites,
 at http://data.phishtank.com/data/online-valid/;  This changes
 frequently, and it's big (about 10MB right now) and on a busy server.
 So once in a while I get a bogus copy of the file because the file
 was rewritten while being sent by the server.

Any good way to deal with this, short of reading it twice
 and comparing?
 
 Apart from that - the only thing you could try is to apply a SAX parser
 on the input stream immediatly, so that at least if the XML is non-valid
 because of the way they serve it you get to that ASAP.

Sure, if you want to use lxml.etree, you can pass the URL right into
etree.parse() and it will throw an exception if parsing from the URL fails to
yield a well-formed document.

http://codespeak.net/lxml/
http://codespeak.net/lxml/dev/parsing.html

BTW, parsing and serialising it back to a string is most likely dominated by
the time it takes to transfer the document over the network, so it will not be
much slower than reading it using urlopen() and the like.

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


Re: Fetching a clean copy of a changing web page

2007-07-16 Thread Amit Khemka
On 7/16/07, John Nagle [EMAIL PROTECTED] wrote:
 I'm reading the PhishTank XML file of active phishing sites,
 at http://data.phishtank.com/data/online-valid/;  This changes
 frequently, and it's big (about 10MB right now) and on a busy server.
 So once in a while I get a bogus copy of the file because the file
 was rewritten while being sent by the server.

 Any good way to deal with this, short of reading it twice
 and comparing?

If you have:
1. Ball park estimate of the size of XML
2. Some footers or last tags in the XML

May be you can use the above to check the xml and catch the bogus ones !

cheers,

-- 

Amit Khemka
website: www.onyomo.com
wap-site: www.owap.in
Home Page: www.cse.iitd.ernet.in/~csd00377

Endless the world's turn, endless the sun's Spinning, Endless the quest;
I turn again, back to my own beginning, And here, find rest.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getting text inside the HTML tag

2007-07-16 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
 On Jul 14, 12:47 pm, Nikola Skoric [EMAIL PROTECTED] wrote:
 I'm using sgmllib.SGMLParser to parse HTML. I have successfuly parsed start
 tags by implementing start_something method. But, now I have to fetch the
 string inside the start tag and end tag too. I have been reading through
 SGMLParser documentation, but just can't figure that out... can somebody
 help? :-)

 --
 Now the storm has passed over me
 I'm left to drift on a dead calm sea
 And watch her forever through the cracks in the beams
 Nailed across the doorways of the bedrooms of my dreams
 
 Oi! Try Beautiful Soup instead. That seems to be the defacto HTML
 parser for Python:

Nope. It's the defacto parser for HTML-like tag soup !-)

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


Re: Trying to choose between python and java

2007-07-16 Thread Bruno Desthuilliers
Anthony Irwin a écrit :
 Hi All,
 
(snip)
 Also does anyone else have any useful comments about python vs java 
 without starting a flame war.

I guess I'd better not answer, then !-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PIL cutting off letters

2007-07-16 Thread nosp
test
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Access Object From 2 Applications or Fix Scheduler

2007-07-16 Thread Robert Rawlins - Think Blue
Also Hendrik,

I should probably mention that the second application is a constant running
application, it's nothing something that can just be 'started' by the first
one, its running non-stop and just needs data passed into it regularly when
the first application finds it.

Application 1   Application 2
Work with dict
Work with dict
Work with dict
Work with dict
New XML Found, Parse Into Dict --  Work with new dict
Work with new dict
Work with new dict
Work with new dict

You see how that works? Application 1 has a function that runs every minute
and _may_ find a new xml file, if it does then I need it to parse that file
into a list of dictionary and then pass that into application 2, which then
starts using it :-)

Now we may be able to avoid this if there is some type of file watcher
function available in python, my second application could then just watch
the XML file and as soon as a new one is available parse it itself. Is that
something you've heard of?

Thanks,

Rob


-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED]
On Behalf Of Hendrik van Rooyen
Sent: 16 July 2007 07:29
To: python-list@python.org
Subject: Re: Access Object From 2 Applications or Fix Scheduler

 Robert Rawlins - Think Blue  wrote:


Hello Guys,

I have two applications which I need to get talking and sharing an 
object, what
s the best way to do this? Basically my first application parses an XML
document into a bunch of lists and tuples etc, and I need to access the data
in these lists and tuples from my second application. Is this possible? And
whats the simplest method?


This problem all evolves from a hack/work around Ive had to place 
together as
I have been having problems with sched, these two applications used to be a
single one to start with but for some reason when scheduling tasks using the
sched module they wouldnt ever run when supposed too, so Id schedule 
it to
run every 2 minutes and it would run between 3 and 15 minutes :-s so I
ripped it out into its own application and it now runs every 2 minutes
exactly.

I either need to fix my sched issues or the memory share, either way 
Im quite
happy, just need to get it working smoothly.

Any ideas?


You have already split the thing, so I would:

schedule the XML parser and make it do its stuff.
then pickle the results using cPickle
then from this first thing, either:
write the pickles to temp files and start the second thing using eg
os.system() or start the second thing and use a named pipe to pass the
pickles over for unpickling and processing, or use one of the popens, or
have a look at Pyro, or start the second thing as a thread and use a Queue..

of course this whole scheme will fall apart if the combined processing takes
longer than the scheduling interval.

HTH - Hendrik



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


Re: running a Delphi part from Python ?

2007-07-16 Thread tool69
Stef Mientki a écrit :

 AFAIK, Scintilla is a code editor.
 What I need looks more like ms-word,
 handling lists, tables, images, formulas.
 
 thanks,
 Stef Mientki


So you'll need the RichTextCtrl

http://www.wxpython.org/docs/api/wx.richtext.RichTextCtrl-class.html

See a sample in the demo under Recent Additions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how good does PyGTK work on windows?

2007-07-16 Thread Jarek Zgoda
krishnakant Mane napisał(a):

 I will be writing some code in PyGTK to run on linux.  but I want to
 know if there are any installers or distutils available for PyGTK on
 windows?
 I have heard that installing gimp or even pygtk is next to impossible
 and is very tedious if at all one gets success.
 can any one share their experiences with installing and running pygtk on
 windos?
 any links for downloading proper packages will be highly appreciated.

There's no problem with installing PyGTK on Windows. While it doesn't
look as pretty as on Linux and some people mention newer versions (2.8
and on) performing bit unstable, I did not realize any instabilities.
Just use package from gladewin32 project, there are separate downloads
with development tools and without. Then just install pycairo, pygobject
and pygtk packages from PyGTK project.

-- 
Jarek Zgoda
Skype: jzgoda | GTalk: [EMAIL PROTECTED] | voice: +48228430101

We read Knuth so you don't have to. (Tim Peters)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Access Object From 2 Applications or Fix Scheduler

2007-07-16 Thread Gabriel Genellina
En Mon, 16 Jul 2007 06:04:07 -0300, Robert Rawlins - Think Blue  
[EMAIL PROTECTED] escribió:

 Now we may be able to avoid this if there is some type of file watcher
 function available in python, my second application could then just watch
 the XML file and as soon as a new one is available parse it itself. Is  
 that
 something you've heard of?

See this (the first solution works on any platform; others are Windows  
specific)
http://tgolden.sc.sabren.com/python/win32_how_do_i/watch_directory_for_changes.html
or try Google with those keywords.

-- 
Gabriel Genellina

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


intact

2007-07-16 Thread Kishore kumar Manikonda


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

Re: running a Delphi part from Python ?

2007-07-16 Thread Stef Mientki
tool69 wrote:
 Stef Mientki a écrit :
 
 AFAIK, Scintilla is a code editor.
 What I need looks more like ms-word,
 handling lists, tables, images, formulas.

 thanks,
 Stef Mientki
 
 
 So you'll need the RichTextCtrl
 
 http://www.wxpython.org/docs/api/wx.richtext.RichTextCtrl-class.html
 
 See a sample in the demo under Recent Additions.

Well it's better,
- it has lists
- it has images, but no image editing,
It doesn't have
- drag  drop
- tables,
- formula editing,
- screen capture,
- links
- embedded code
- CSS
- 
so unfortunately it's not yet sufficient :-(

thanks,
Stef Mientki
-- 
http://mail.python.org/mailman/listinfo/python-list


Compiling python2.5 on IBM AIX

2007-07-16 Thread bravo . loic
hi,

I'm trying to make a local install of python 2.5 on AIX and I'm
getting some trouble with _curses.

Here is how I tried to compile it :


export BASE=/usr/local/python251

cd Python.2.5.1
./configure --prefix=${BASE}/\
LDFLAGS=-L\${BASE}/lib/\
PPFLAGS=-I\${BASE}/include/\

make
make test
make altinstall

and the compilation stop with the following pb :

ld: 0711-317 ERROR: Undefined symbol: _unctrl
ld: 0711-317 ERROR: Undefined symbol: .__fixsfsi
ld: 0711-317 ERROR: Undefined symbol: .setsyx
ld: 0711-317 ERROR: Undefined symbol: ._setqiflush
ld: 0711-317 ERROR: Undefined symbol: .initscr32
ld: 0711-317 ERROR: Undefined symbol: wacs_map
ld: 0711-317 ERROR: Undefined symbol: ._getsyx
ld: 0711-317 ERROR: Undefined symbol: .getattrs
ld: 0711-317 ERROR: Undefined symbol: .w32attrset
ld: 0711-317 ERROR: Undefined symbol: .w32insch
ld: 0711-317 ERROR: Undefined symbol: .p32echochar
ld: 0711-317 ERROR: Undefined symbol: .w32echochar
ld: 0711-317 ERROR: Undefined symbol: .box32
ld: 0711-317 ERROR: Undefined symbol: .w32addch
ld: 0711-317 ERROR: Undefined symbol: .w32attroff
ld: 0711-317 ERROR: Undefined symbol: .w32attron
ld: 0711-345 Use the -bloadmap or -bnoquiet option to obtain more
information.
*** WARNING: renaming _curses since importing it failed: No such
file or directory
error: No such file or directory
make: 1254-004 The error code from the last command is 1.


Stop.

I've compiled ncurses-5.6 in ${BASE}/lib but this haven't solved the
pb.

Any clue ?

Best regards

--

BL

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


Python-URL! - weekly Python news and links (Jul 16)

2007-07-16 Thread Gabriel Genellina
QOTW:  That's a property of open source projects. Features nobody really
needs are not implemented. - Gregor Horvath
http://groups.google.com/group/comp.lang.python/msg/1fcefd79c7aa4832

I'm working in a Java shop, with eclipse - one of the most intimate
IDE-lanaguage-relationships imaginable.  I get all the auto-completion,
refactoring and whatnot-suppopport.

And I'd swap it for python + emacs every minute. Diez B. Roggisch


How to properly add dynamic methods to classes and instances:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/cc04b8e480d4be62/

Enumerating efficiently the power set of a given set
is not as easy as first thought:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/d9211cd6c65e1d3a/

A classic question revisited twice: Does Python pass parameters
by reference or by value?, and a clear explanation by Ben Finney:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/45732106f147ac07/

http://groups.google.com/group/comp.lang.python/browse_thread/thread/56e7d62bf66a435c/

Still looking for a way to cleanly reraise an exception after
modifying its message?  Proves to be a hard task, this thread
started a couple weeks ago:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/ae351de24f72a834/

A subtle problem with disappearing processes when using os.wait
and subprocess.Popen simultaneously:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/d8a302bdbfdbf5ef/

For someone coming from electronics and close to the hardware, it's
hard to grasp some OOP concepts - but why should one care? (Plus some
anecdotes from some '60s newbies...)

http://groups.google.com/group/comp.lang.python/browse_thread/thread/916e1f2cfe390bbd/

Bools, their misbehavior as ints, and what will happen in Python 3000:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/e0e07894a2aa42cb/


Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

The Python Papers aims to publish the efforts of Python enthusiats.
http://pythonpapers.org/

Readers have recommended the Planet sites:
http://planetpython.org
http://planet.python.org

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

http://groups.google.com/groups?oi=djqas_ugroup=comp.lang.python.announce

Python411 indexes podcasts ... to help people learn Python ...
Updates appear more-than-weekly:
http://www.awaretek.com/python/index.html

Steve Bethard continues the marvelous tradition early borne by
Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim
Lesher of intelligently summarizing action on the python-dev mailing
list once every other week.
http://www.python.org/dev/summary/

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

Python Success Stories--from air-traffic control to on-line
match-making--can inspire you or decision-makers to whom you're
subject with a vision of what the language makes practical.
http://www.pythonology.com/success

The Python Software Foundation (PSF) has replaced the Python
Consortium as an independent nexus of activity.  It has official
responsibility for Python's development and maintenance.
http://www.python.org/psf/
Among the ways you can support PSF is with a donation.
http://www.python.org/psf/donate.html

Kurt B. Kaiser publishes a weekly report on faults and patches.
http://www.google.com/groups?as_usubject=weekly%20python%20patch

Although unmaintained since 2002, the Cetus collection of Python
hyperlinks retains a few gems.
http://www.cetus-links.org/oo_python.html

Python FAQTS

Re: questions about functions inside a function

2007-07-16 Thread Duncan Booth
[EMAIL PROTECTED] [EMAIL PROTECTED] wrote:

 What I want is, the value of i should be bounded to the anonymous
 function. And the output should like this:
 
 for f in a:
  print f()
 0
 1
 4
 9
 
 How to achieve this?

Use default arguments when defining your function: default arguments are 
evaluated when the function is defined, bound arguments get the current 
value of the variable at the point when it is referenced during the call.

Also, since you give your function a name anyway ('b') you might as well 
use a named function as being clearer than using lambda:

 a = []
 for i in range(4):
def b(i=i):
return i**2
a.append(b)


 for f in a:
f()


0
1
4
9
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: running a Delphi part from Python ?

2007-07-16 Thread Bruno Desthuilliers
Stef Mientki a écrit :
 
 I'm starting to get used to wxPython (coming from Delphi),
 and it seems it can do almost everything I need.
 
 Now one thing I'm missing is a good RichEditor.

Scintilla is for you, then. IIRC, there's a wxWidget widget embedding 
it, and quite a few editors using it.

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


Implementaion of random.shuffle

2007-07-16 Thread shabda raaj

I was going through the docs for
module-randomhttp://docs.python.org/lib/module-random.html
And I came through this,
 *shuffle*( x[, random])
Shuffle the sequence x in place. The optional argument random is a
0-argument function returning a random float in [0.0, 1.0); by default, this
is the function random().

Note that for even rather small len(x), the total number of permutations of
x is larger than the period of most random number generators; this implies
that most permutations of a long sequence can never be generated.
Why would we need to generate the total number of permutations for the list
while trying to shuffle it? Should not we just use a knuth
shufflehttp://en.wikipedia.org/wiki/Knuth_shuffle#Shuffling_algorithmswhich
does not require us to generate the total number of permutations. As
long as len(x) is smaller than period of random number generator, a
permutation can be generated.

A quick first draft of implemetation  might be,

import random

def shuffle(list_):
   for i in range(len(list_)):
   j = random.randint(i, len(list_)-1)
   list_[i], list_[j] = list_[j], list_[i]
if __name__ == '__main__':
 a = range(100)
 shuffle(a)
 print a

This is my first post to the list, I am not sure if this is the correct
place to ask these questions. Please advise if this is not the correct
place.

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

Re: questions about functions inside a function

2007-07-16 Thread Wildemar Wildenburger
[EMAIL PROTECTED] wrote:
 I want to create a list of function.

 Here is my code:
 In [9]: a = []

 In [10]: for i in range(4):
 : b = lambda : i**2
 : a.append(b)
 :
 :

 In [11]: for f in a:
 : f()
 :
 :
 9
 9
 9
 9

 What I want is, the value of i should be bounded to the anonymous function. 
 And the output should like this:

 for f in a:
  print f()
 0
 1
 4
 9

 How to achieve this?

 Thanks a lot!

   
I fail to see the point, sorry. Why would you want that? If you simply 
want a list of values you do:

 a = [i**2 for i in range(4)]

Can you elaborarate on what it is you really want.

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


Re: questions about functions inside a function

2007-07-16 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
 I want to create a list of function.
 
 Here is my code:
 In [9]: a = []
 
 In [10]: for i in range(4):
: b = lambda : i**2
: a.append(b)
:
:
 
 In [11]: for f in a:
: f()
:
:
 9
 9
 9
 9
 
 What I want is, the value of i should be bounded to the anonymous 
 function. And the output should like this:
 
 for f in a:
 print f()
 0
 1
 4
 9
 
 How to achieve this?
 
  a = [lambda i=i:i**2 for i in range(4)]
  for f in a:
... print f()
...
0
1
4
9
 

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

Re: questions about functions inside a function

2007-07-16 Thread Wildemar Wildenburger
Wildemar Wildenburger wrote:
 for f in a:
  print f()
 0
 1
 4
 9

 How to achieve this?

 Thanks a lot!

   
 
 I fail to see the point, sorry. Why would you want that? If you simply 
 want a list of values you do:

   
 a = [i**2 for i in range(4)]
 

 Can you elaborarate on what it is you really want.

 /W
   

Sorry, I'm an idiot. Nevermind. :-/

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


BeautifulSoup prettify help

2007-07-16 Thread news.sf.sbcglobal.net
Hi,

Is there a way to make the prettify() use 4 spaces instead of 1 for each 
level of indentation? Or maybe make it use tabs instead?

TIA,
TEd 


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


Re: Dynamic method

2007-07-16 Thread Lawrence Oluyede
Bruno Desthuilliers [EMAIL PROTECTED]
wrote:
  I agree that in general the solution explained by Alex and you is better.
 
 They are not better - they are correct.

Another way is to use the 'types' module:

In [1]: class T(object):
   ...: pass
   ...: 

In [2]: t = T()

In [3]: import types

In [5]: types.MethodType?
Type:   type
Base Class: type 'type'
String Form:type 'instancemethod'
Namespace:  Interactive
Docstring:
instancemethod(function, instance, class)

Create an instance method object.


In [10]: m = types.MethodType(lambda self: 3, t, T)

In [11]: t.m = m

In [12]: t.m()
Out[12]: 3


-- 
Lawrence, oluyede.org - neropercaso.it
It is difficult to get a man to understand 
something when his salary depends on not
understanding it - Upton Sinclair
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implementaion of random.shuffle

2007-07-16 Thread Steve Holden
shabda raaj wrote:
 I was going through the docs for module-random 
 http://docs.python.org/lib/module-random.html  And I came through this,
  
 * shuffle*(   x[, random])
 
 
 Shuffle the sequence x in place. The optional argument random is a
 0-argument function returning a random float in [0.0, 1.0); by
 default, this is the function random().
 
 Note that for even rather small |len(x)|, the total number of
 permutations of x is larger than the period of most random number
 generators; this implies that most permutations of a long sequence
 can never be generated.
 
 Why would we need to generate the total number of permutations for the 
 list while trying to shuffle it? Should not we just use a knuth shuffle 
 http://en.wikipedia.org/wiki/Knuth_shuffle#Shuffling_algorithms which 
 does not require us to generate the total number of permutations. As 
 long as len(x) is smaller than period of random number generator, a 
 permutation can be generated.
 
 A quick first draft of implemetation  might be,
 
 import random
 
 def shuffle(list_):
 for i in range(len(list_)):
 j = random.randint(i, len(list_)-1)
 list_[i], list_[j] = list_[j], list_[i]
 if __name__ == '__main__':
   a = range(100)
   shuffle(a)
   print a
 
 This is my first post to the list, I am not sure if this is the correct 
 place to ask these questions. Please advise if this is not the correct 
 place.
 
This is an excellent place to post the question. If it were to turn out 
that your concerns were genuine that you might end up posting a patch to 
the issue tracker and possibly then involving the developers. Until your 
suspicions are confirmed, however, let the developers get on with 
development.

You, like all (or most) Python users, have the source of the standard 
library at your disposal. Had you looked at .../Lib/random.py you would 
have found that the implementation of shuffle() reads as follows:

 def shuffle(self, x, random=None, int=int):
 x, random=random.random - shuffle list x in place; return None.

 Optional arg random is a 0-argument function returning a random
 float in [0.0, 1.0); by default, the standard random.random.
 

 if random is None:
 random = self.random
 for i in reversed(xrange(1, len(x))):
 # pick an element in x[:i+1] with which to exchange x[i]
 j = int(random() * (i+1))
 x[i], x[j] = x[j], x[i]

So it would appear that the developers chose the Knuth algorithm (with a 
slight variation) for *their* implementation. Now you have to ask 
yourself whether your surmise is genuinely correct (in which case the 
documentation may contain a bug) or whether the documentation is indeed 
correct and you are in error.

Note that there is no intent to generate all permutations of the list 
and then choose one (that would indeed be a sub-optimal solution). The 
documentation is only talking about whether the algorithm can in theory 
produce all possible permutations of all possible input lists. It's 
possible that the comment in the documentation is left over from an 
earlier version. What do you think?

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: Accessing Python variables in an extension module

2007-07-16 Thread MD
Hi Alex,
   Thanks for your reply. It was exactly what I was looking for. Two
additional questions
1) Is there anyway to find out which modules a variable belongs to
when I have only its name (and its not qualified with the complete
name like module.varname)
2) Is there anyway to find the type of the object in C using something
like a switch statement? I was looking for something like this
   switch type(object) {
  STRING: This is a string object;
  break;
  INTEGER: This is an integer object;
  break;
  BOOLEAN: This is a boolean object;
  .
  .
  }
I don't want to run all the C Py***_Check functions on the object.
Something like the switch statement above will lead to nice and clean
code.
Thanks again for your reply.

Regards,
-Manas

On Jul 15, 11:02 pm, [EMAIL PROTECTED] (Alex Martelli) wrote:
 MD [EMAIL PROTECTED] wrote:
  Hi,

 I would like to access variables defined in my Python program in
  a C module extension for Python. Is this possible? I looked at the
  Python C API reference but didn't find anything there that could help
  me.

 If they're global variables of a certain module XYZ, your C code may
 import XZY (or look it up in the C API equivalent of the sys.modules
 dict) and get those variables as attributes of object XYZ.  Is that what
 you mean by ``variables defined in your Python program''...?

 Alex


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


Re: questions about functions inside a function

2007-07-16 Thread [EMAIL PROTECTED]
Hi,
Duncan Booth wrote:
 [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:

 What I want is, the value of i should be bounded to the anonymous
 function. And the output should like this:

 for f in a:
  print f()
 0
 1
 4
 9

 How to achieve this?

 Use default arguments when defining your function: default arguments are
 evaluated when the function is defined, bound arguments get the current
 value of the variable at the point when it is referenced during the call.

 Also, since you give your function a name anyway ('b') you might as well
 use a named function as being clearer than using lambda:

 a = []
 for i in range(4):
   def b(i=i):
   return i**2
   a.append(b)

   
 for f in a:
   f()

   
 0
 1
 4
 9

Thanks for some quick replies.

I'm trying to minimize a function f(X) (X = [x1, x2, ..., xn]) using
scipy.optimize.fmin_cobyla.  The parameter of the function is a list of
N variables. fmin_cobyla also accept a 'cons' parameter as constraint
function, which is a list of functions.

In order to make sure all variables be larger than 0, I tried to created
constraint function like this:

cons = []
for i in range(N):
c = lambda x: x[i] - 1e-10
cons.append(c)

But when functions in cons are evaluated, the value in all functions are
all the same(N-1, which is the last value of i in the loop).

What I want is, when functions in cons be evaluated, every function
refers to a different variable in X.

Regards

Xiao Jianfeng

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


Trouble with email package

2007-07-16 Thread Torsten Bronger
Hallöchen!

I thought that with the following code snippet, I could generate a
MIME email stub:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from email.MIMEText import MIMEText
from email.Generator import Generator
import sys

message = MIMEText(uHallöchen!, _charset=utf-8)
Generator(sys.stdout).flatten(message)

However, MIMEText doesn't see that uHallöchen! is a unicode and
encodes it accoring to _charset.  Additionally, it is encoded as
base64 (why?).  But okay, I added some lines to work around it:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from email.MIMEText import MIMEText
from email.Generator import Generator
from email.Charset import Charset
import sys

charset = Charset(utf-8)
charset.body_encoding = None
message = MIMEText(uHallöchen!.encode(utf-8), _charset=utf-8)
message.set_charset(charset)
Generator(sys.stdout).flatten(message)

However, the result of this is

Content-Type: text/plain; charset=utf-8
MIME-Version: 1.0
Content-Transfer-Encoding: base64

Hallöchen!

The Content-Transfer-Encoding is wrong.  Okay (well, not okay but)
then I added message[Content-Transfer-Encoding] = 8bit to my
code and got

Content-Type: text/plain; charset=utf-8
MIME-Version: 1.0
Content-Transfer-Encoding: base64
Content-Transfer-Encoding: 8bit

Hallöchen!

I mean, I can work around anything, but is the email package just
rather buggy or do I something completely misguided here?  Thanks
for any hints!

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
  Jabber ID: [EMAIL PROTECTED]
  (See http://ime.webhop.org for ICQ, MSN, etc.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Tkinter Primer/Tutorial?

2007-07-16 Thread W. Watson
Thanks for the tips to the posters above. Wow, the Grayson book is $98 on 
Amazon. I think I'll see if I can get a library loan!

Midway on the NMT page, they fleetingly mention Lutz, but give no reference 
on it. From Amazon:

Learning Python, Second Edition [ILLUSTRATED] (Paperback)
by Mark Lutz (Author), David Ascher (Author)


BartlebyScrivener wrote:
 On Jul 15, 9:46 am, W. Watson [EMAIL PROTECTED] wrote:
 Is there a primer out there on these two items? I have the Python tutorial,
 but would like either a Tkinter tutorial/primer to supplement it, or a
 primer/tutorial that addresses both.
 
 http://www.freenetpages.co.uk/hp/alan.gauld/tutgui.htm
 
 rd
 

-- 
  Wayne Watson (Nevada City, CA)

Web Page: speckledwithStars.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Embedding/Extending Python in/with C++: non-static members?

2007-07-16 Thread dmoore
Hi Folks:

I have a question about the use of static members in Python/C
extensions. Take the simple example from the Extending and Embedding
the Python Interpreter docs:

A simple module method:

static PyObject *
spam_system(PyObject *self, PyObject *args)
{
 ...
}

listed in a method table:

static PyMethodDef SpamMethods[] = {
...
{system,  spam_system, METH_VARARGS,
 Execute a shell command.},
...
{NULL, NULL, 0, NULL}/* Sentinel */
};

that is registered with:

PyMODINIT_FUNC
initspam(void)
{
(void) Py_InitModule(spam, SpamMethods);
}

I have an application that embed multiple interpreters. I want to be
able to register methods for each interpreter that access C++ state
data relevant to that particular interpreter. In other words I want to
be able to register non-static class members in a class like the
following:

class PythonSpamModuleInstance
{
PythonSpamModuleInstance()
{
SpamMethods[0]={system,  spam_system, METH_VARARGS,Execute
a shell command.};
SpamMethods[1]={NULL, NULL, 0, NULL};
PyObject *spammodule=Py_InitModule(spam, SpamMethods); //
Needs an INCREF call?
}
~PythonSpamModuleInstance()
{
PyObject_Del(spam, SpamMethods);
}
PyObject *spam_system(PyObject *self, PyObject *args)
{
 // accesses non-static data in this class
}
PyMethodDef SpamMethods[2];
PyObject *spammodule;
// Other data specific to this instance of the module
};

The idea is that each time my app launches an embedded Interpreter it
will create an accompanying instance of PythonSpamModuleInstance that
allows the Interpreter to call the registered non-static C++ member
function spam_system. Calls to that member function will also affect
state information.

So the questions: will this work? In particular, will the use of non-
static member functions cause problems? Is there a better way of
creating extension modules for multiple embedded interpreters? If I am
forced to use static methods, how do i figure out which interpreter is
calling them?

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


Re: Accessing Python variables in an extension module

2007-07-16 Thread Diez B. Roggisch
MD wrote:

 Hi Alex,
Thanks for your reply. It was exactly what I was looking for. Two
 additional questions
 1) Is there anyway to find out which modules a variable belongs to
 when I have only its name (and its not qualified with the complete
 name like module.varname)

No.

 2) Is there anyway to find the type of the object in C using something
 like a switch statement? I was looking for something like this
switch type(object) {
   STRING: This is a string object;
   break;
   INTEGER: This is an integer object;
   break;
   BOOLEAN: This is a boolean object;
   .
   .
   }
 I don't want to run all the C Py***_Check functions on the object.
 Something like the switch statement above will lead to nice and clean
 code.

In python, 

obj.__class__.__name__

should work. I don't know what to write in C to accomplish that, but it
can't be too hard. Factor it away in a function.

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


Re: Trouble with email package

2007-07-16 Thread Torsten Bronger
Hallöchen!

Ingrid Bronger writes:

 [...]

 The Content-Transfer-Encoding is wrong.  Okay (well, not okay but)
 then I added message[Content-Transfer-Encoding] = 8bit to my
 code and got

 Content-Type: text/plain; charset=utf-8
 MIME-Version: 1.0
 Content-Transfer-Encoding: base64
 Content-Transfer-Encoding: 8bit

 Hallöchen!

I found the cause of this part of my trouble.

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
  Jabber ID: [EMAIL PROTECTED]
  (See http://ime.webhop.org for ICQ, MSN, etc.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: questions about functions inside a function

2007-07-16 Thread Duncan Booth
[EMAIL PROTECTED] [EMAIL PROTECTED] wrote:

 In order to make sure all variables be larger than 0, I tried to created
 constraint function like this:
 
 cons = []
 for i in range(N):
  c = lambda x: x[i] - 1e-10
  cons.append(c)
 
 But when functions in cons are evaluated, the value in all functions are
 all the same(N-1, which is the last value of i in the loop).
 
 What I want is, when functions in cons be evaluated, every function
 refers to a different variable in X.

So pass i in as a default value:

for i in range(N):
   def c(x, i=i):
   return x[i] - 1e-10
   cons.append(c)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: questions about functions inside a function

2007-07-16 Thread [EMAIL PROTECTED]
On Jul 16, 4:49 am, [EMAIL PROTECTED] [EMAIL PROTECTED]
wrote:

(snipped)


 What I want is, the value of i should be bounded to the anonymous function.
 And the output should like this:

 for f in a:
  print f()
 0
 1
 4
 9

 How to achieve this?

 Thanks a lot!



The functools module, in Python 2.5 allows:

 import functools
 square = lambda i: i ** 2
 anon = [functools.partial(square, i) for i in range(4)]
 for f in anon:
... print f()
...

--
Hope this helps,
Steven

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


Re: running a Delphi part from Python ?

2007-07-16 Thread Chris Mellon
On 7/16/07, Stef Mientki [EMAIL PROTECTED] wrote:
 tool69 wrote:
  Stef Mientki a écrit :
 
  AFAIK, Scintilla is a code editor.
  What I need looks more like ms-word,
  handling lists, tables, images, formulas.
 
  thanks,
  Stef Mientki
 
 
  So you'll need the RichTextCtrl
 
  http://www.wxpython.org/docs/api/wx.richtext.RichTextCtrl-class.html
 
  See a sample in the demo under Recent Additions.

 Well it's better,
 - it has lists
 - it has images, but no image editing,
 It doesn't have
 - drag  drop
 - tables,
 - formula editing,
 - screen capture,
 - links
 - embedded code
 - CSS
 - 
 so unfortunately it's not yet sufficient :-(


This goes far beyond the requirement for a rich text editor. You're
now talking about rich object integration, which is about 80% of a
full featured word processor. You won't find a cross platform
implementation that's suitable for use as a component in anything.

Delphi components are tightly tied to the Delphi runtime environment
and its' gui abstractions, so embedding it as is is will be a massive
hack (and require extensive C code) if its even possible.

However, any company who writes such a full featured control is likely
to package it as an ActiveX control so they can get the sales from the
VB guys, and you can embed ActiveX control in wxPython applications
(Windows only, of course).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic method

2007-07-16 Thread Bruno Desthuilliers
Lawrence Oluyede a écrit :
 Bruno Desthuilliers [EMAIL PROTECTED]
 wrote:
 I agree that in general the solution explained by Alex and you is better.
 They are not better - they are correct.
 
 Another way is to use the 'types' module:

True - and that's somewhat cleaner since it doesn't expose the internals 
of the descriptor protocol. OTHO, it can lead to strange results with 
callables not implementing the descriptor protocol:

class MyCallable(object):
   def __init__(self, name):
 self.name = name
   def __call__(self):
 print self.name

fun = MyCallable('gizmo')

class Foo(object):
   pass

f = Foo()
f.fun = types.MethodType(fun, f, Foo)
f.fun()

=
Traceback (most recent call last):
   File stdin, line 1, in module
   File /tmp/python-17437zds.py, line 16, in module
 f.fun()
TypeError: __call__() takes exactly 1 argument (2 given)

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


Private functions and inheritance

2007-07-16 Thread Maciej Bliziński
Hello,

I've come across something that I don't quite understand about
Python's inheritance. Consider the following code snippet:

class A(object):
def call_bar(self): return self.bar()
def call___bar(self): return self.__bar()
def __bar(self): return A::__bar()
def bar(self): return A::bar()

class B(A):
def __bar(self): return B::__bar()
def bar(self): return B::bar()

b = B()
print calling B::call_bar():, b.call_bar()
print calling B::call___bar():, b.call___bar()

The result is:

calling B::call_bar(): B::bar()
calling B::call___bar(): A::__bar()

In the latter case, it calls the base class' implementation. It
probably goes along with Python's spec, but I found it surprising. I
don't want to expose the __bar() function outside, but on the other
hand i want to defer its implementation to a subclass. It seems like I
need to make it public, doesn't it?

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


Re: Implementaion of random.shuffle

2007-07-16 Thread shabda raaj
On Jul 16, 5:53 pm, Steve Holden [EMAIL PROTECTED] wrote:
 shabda raaj wrote:
  I was going through the docs for module-random
  http://docs.python.org/lib/module-random.html  And I came through this,

  * shuffle*(x[, random])

  Shuffle the sequence x in place. The optional argument random is a
  0-argument function returning a random float in [0.0, 1.0); by
  default, this is the function random().

  Note that for even rather small |len(x)|, the total number of
  permutations of x is larger than the period of most random number
  generators; this implies that most permutations of a long sequence
  can never be generated.

  Why would we need to generate the total number of permutations for the
  list while trying to shuffle it? Should not we just use a knuth shuffle
  http://en.wikipedia.org/wiki/Knuth_shuffle#Shuffling_algorithms which
  does not require us to generate the total number of permutations. As
  long as len(x) is smaller than period of random number generator, a
  permutation can be generated.

  A quick first draft of implemetation  might be,

  import random

  def shuffle(list_):
  for i in range(len(list_)):
  j = random.randint(i, len(list_)-1)
  list_[i], list_[j] = list_[j], list_[i]
  if __name__ == '__main__':
a = range(100)
shuffle(a)
print a

  This is my first post to the list, I am not sure if this is the correct
  place to ask these questions. Please advise if this is not the correct
  place.

 This is an excellent place to post the question. If it were to turn out
 that your concerns were genuine that you might end up posting a patch to
 the issue tracker and possibly then involving the developers. Until your
 suspicions are confirmed, however, let the developers get on with
 development.

 You, like all (or most) Python users, have the source of the standard
 library at your disposal. Had you looked at .../Lib/random.py you would
 have found that the implementation of shuffle() reads as follows:

  def shuffle(self, x, random=None, int=int):
  x, random=random.random - shuffle list x in place; return None.

  Optional arg random is a 0-argument function returning a random
  float in [0.0, 1.0); by default, the standard random.random.
  

  if random is None:
  random = self.random
  for i in reversed(xrange(1, len(x))):
  # pick an element in x[:i+1] with which to exchange x[i]
  j = int(random() * (i+1))
  x[i], x[j] = x[j], x[i]

 So it would appear that the developers chose the Knuth algorithm (with a
 slight variation) for *their* implementation. Now you have to ask
 yourself whether your surmise is genuinely correct (in which case the
 documentation may contain a bug) or whether the documentation is indeed
 correct and you are in error.

 Note that there is no intent to generate all permutations of the list
 and then choose one (that would indeed be a sub-optimal solution). The
 documentation is only talking about whether the algorithm can in theory
 produce all possible permutations of all possible input lists. It's
 possible that the comment in the documentation is left over from an
 earlier version. What do you think?

 regards
   Steve
 --
 Steve Holden+1 571 484 6266   +1 800 494 3119
 Holden Web LLC/Ltd  http://www.holdenweb.com
 Skype: holdenweb  http://del.icio.us/steve.holden
 --- Asciimercial --
 Get on the web: Blog, lens and tag the Internet
 Many services currently offer free registration
 --- Thank You for Reading -

Oh, I wasn't aware that I could see the source of all python modules.
I guess, then the implementation is correct(its just the knuth
shuffle,
moving downward), its just the doc which is in error.
Might be we should log a doc bug for this?

--Shabda


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


win32com ppt saveas, not allowing spaces?

2007-07-16 Thread Lance Hoffmeyer
Hey all,

As always, thanks in advance!


I am trying to save a ppt presentation but am having problems regarding spaces 
and am wondering
if I am doing something wrong or whether this is a bug?  Also, is there a way 
around this other
than not using spaces in paths or filenames?  I can create filesnames without 
spaces but don't have
much control over paths.

Lance


WB.SaveAs(C:/temp/00_FINAL. + time.strftime(%Y.%m.%d.(%I.%M.%S%p), 
time.localtime())  +  .ppt)

saves the file C:\temp\00_FINAL.2007.07.16.(09.43.50AM).ppt


but

WB.SaveAs(C:/tmp dir/00_FINAL. + time.strftime(%Y.%m.%d.(%I.%M.%S%p), 
time.localtime())  +  .ppt)

gives the error:

Traceback (most recent call last):
  File C:\temp\ppt.py, line 412, in ?
WB.SaveAs(C:/tmp dir/00_FINAL. + time.strftime(%Y.%m.%d.(%I.%M.%S%p), 
time.localtime())  +  .ppt)
  File C:\Program 
Files\Python\lib\site-packages\win32com\gen_py\91493440-5A91-11CF-8700-00AA0060263Bx0x2x8.py,
 line 6827, in SaveAs
return self._oleobj_.InvokeTypes(2036, LCID, 1, (24, 0), ((8, 1), (3, 49), 
(3, 49)),FileName, FileFormat, EmbedTrueTypeFonts)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft 
Office PowerPoint 2003', 'Presentation.SaveAs : The path or file name for 
C://tmp%20dir/00_FINAL.2007.07.16.(09.44.01AM).ppt is invalid. Please check 
that the path and file
name are correct.', '', 0, -2147467259), None)

Tool completed with exit code 1

Also,

WB.SaveAs(C:/temp/00 FINAL. + time.strftime(%Y.%m.%d.(%I.%M.%S%p), 
time.localtime())  +  .ppt)

yields:

C:/temp/00%20FINAL.2007.07.16.(09.45.35AM).ppt



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


Re: How to determine which method was used in an inheritance heirarchy?

2007-07-16 Thread Erik Jones
On Jul 16, 2007, at 3:37 AM, Gabriel Genellina wrote:

 En Mon, 16 Jul 2007 03:56:18 -0300, Erik Jones [EMAIL PROTECTED]  
 escribió:

 Perhaps an even better example of what I'm trying to do would be in
 order (this is minus any exception handling):

 import sys

 def mytrace(frame, event, arg):
  if event == 'call':
  func_name = frame.f_code.co_name

  if func_name in frame.f_locals['self'].__class__.__dict__:
  print frame.f_locals['self'].__class__.__name__
  else:
  for base in frame.f_locals['self'].__class__.__bases__:
  if func_name in base.__dict__:
  print base.__name__
  break


 class A(object):
  def __init__(self):
  pass

 class B(A):
  def __init__(self):
  A.__init__(self)

 sys.settrace(mytrace)
 B()

 This will output:

 B
 B

 If you don't mind post-processing the results, you can log the  
 function
 name and source module (from frame.f_code.co_name and co_filename) and
 current line number (frame.f_lineno). Later, obtaining the class  
 name from
 those is a bit tricky (and not even the inspect module does it  
 right), but
 perhaps using the tokenizer module, watching for lines that contain
 class name is enough.


I was afraid of that.  I used pretty much that tokenizer trick for a  
unit test generator I wrote in php a while back and felt like that  
was pretty clunky then.

Erik Jones

Software Developer | Emma®
[EMAIL PROTECTED]
800.595.4401 or 615.292.5888
615.292.0777 (fax)

Emma helps organizations everywhere communicate  market in style.
Visit us online at http://www.myemma.com


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


Re: Accessing Python variables in an extension module

2007-07-16 Thread Alex Martelli
MD [EMAIL PROTECTED] wrote:

 Hi Alex,
Thanks for your reply. It was exactly what I was looking for. Two
 additional questions
 1) Is there anyway to find out which modules a variable belongs to
 when I have only its name (and its not qualified with the complete
 name like module.varname)

Loop through all modules in sys.modules and you will find a set (which
may be empty) of modules which happen to have that name as an attribute.
It's a very peculiar thing to do (not clear what you expect to do based
on that information) but not difficult.

 2) Is there anyway to find the type of the object in C using something
 like a switch statement? I was looking for something like this
switch type(object) {
   STRING: This is a string object;
   break;
   INTEGER: This is an integer object;
   break;
   BOOLEAN: This is a boolean object;
   .
   .
   }
 I don't want to run all the C Py***_Check functions on the object.
 Something like the switch statement above will lead to nice and clean
 code.

Each Python object, in C, carries a pointer to its type object.  Of
course there are unbounded numbers of types, but at least you can get
such information as the type's name and the module if any in which it
may have been defined, essentially like you'd do with type(somobj) if
you were working directly in Python.


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


Re: Private functions and inheritance

2007-07-16 Thread Bjoern Schliessmann
Maciej Blizi?ski wrote:

 calling B::call_bar(): B::bar()
 calling B::call___bar(): A::__bar()

(BTW, there is no :: operator in Python. It should be, e. g., 
B.bar().)

 In the latter case, it calls the base class' implementation. It
 probably goes along with Python's spec, but I found it surprising.

__-prepended names are dynamically mangled to include the class
name. Hence, B.__bar doesn't overwrite A.__bar in B.

 I don't want to expose the __bar() function outside,

In principle, you do. Always. Public or Private is just convention
in Python. Even __-prepended names can be accessed from outside.

Couldn't find it in the docs though. Quite inconcise.

Regards,


Björn

-- 
BOFH excuse #120:

we just switched to FDDI.

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


Re: Private functions and inheritance

2007-07-16 Thread Diez B. Roggisch
Maciej Bliziński wrote:

 Hello,
 
 I've come across something that I don't quite understand about
 Python's inheritance. Consider the following code snippet:
 
 class A(object):
 def call_bar(self): return self.bar()
 def call___bar(self): return self.__bar()
 def __bar(self): return A::__bar()
 def bar(self): return A::bar()
 
 class B(A):
 def __bar(self): return B::__bar()
 def bar(self): return B::bar()
 
 b = B()
 print calling B::call_bar():, b.call_bar()
 print calling B::call___bar():, b.call___bar()
 
 The result is:
 
 calling B::call_bar(): B::bar()
 calling B::call___bar(): A::__bar()
 
 In the latter case, it calls the base class' implementation. It
 probably goes along with Python's spec, but I found it surprising. I
 don't want to expose the __bar() function outside, but on the other
 hand i want to defer its implementation to a subclass. It seems like I
 need to make it public, doesn't it?

Yep. Just use a single underscore, and that's it. The reason why this
doesn't work as expected is that the name-mangling introduced by the
leading double underscores is purely a lexical scope based mechanism.

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

how to read python-doc in ubuntu?

2007-07-16 Thread ZelluX
Hi all,
I'm a new comer to Python.
I've installed python-doc module, but just don't know how to open it.
Could you help me?

Many thanks ^_^
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: running a Delphi part from Python ?

2007-07-16 Thread markacy
On 16 Lip, 11:33, Stef Mientki [EMAIL PROTECTED]
wrote:
 tool69 wrote:
  Stef Mientki a écrit :

  AFAIK, Scintilla is a code editor.
  What I need looks more like ms-word,
  handling lists, tables, images, formulas.

  thanks,
  Stef Mientki

  So you'll need the RichTextCtrl

 http://www.wxpython.org/docs/api/wx.richtext.RichTextCtrl-class.html

  See a sample in the demo under Recent Additions.

 Well it's better,
 - it has lists
 - it has images, but no image editing,
 It doesn't have
 - drag  drop
 - tables,
 - formula editing,
 - screen capture,
 - links
 - embedded code
 - CSS
 - 
 so unfortunately it's not yet sufficient :-(

 thanks,
 Stef Mientki

Of course You can always write one, that's succicient for Your needs,
and make it available under GPL. ;-)

Cheers,

Marek

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

Re: questions about functions inside a function

2007-07-16 Thread [EMAIL PROTECTED]
Duncan Booth wrote:
 [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 
 In order to make sure all variables be larger than 0, I tried to created
 constraint function like this:

 cons = []
 for i in range(N):
  c = lambda x: x[i] - 1e-10
  cons.append(c)

 But when functions in cons are evaluated, the value in all functions are
 all the same(N-1, which is the last value of i in the loop).

 What I want is, when functions in cons be evaluated, every function
 refers to a different variable in X.
 
 So pass i in as a default value:
 
 for i in range(N):
def c(x, i=i):
return x[i] - 1e-10
cons.append(c)

Thanks all of you have read or replied.

Both Duncan's and Steven's solution work well. Thanks!

I love python, not only because of the language itself, and also the so kind 
community!


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


Re: Implementaion of random.shuffle

2007-07-16 Thread Hrvoje Niksic
Steve Holden [EMAIL PROTECTED] writes:

 So it would appear that the developers chose the Knuth algorithm
 (with a slight variation) for *their* implementation. Now you have
 to ask yourself whether your surmise is genuinely correct (in which
 case the documentation may contain a bug) or whether the
 documentation is indeed correct and you are in error.

That is a good question.  The random module uses the Mersenne twister,
which has a repetition period of 2**19937.  The number of n-sized
permutations of a list with n elements is n!, while each shuffle
requires n calls to the PRNG.  This means that to be able to generate
all permutations, the PRNG must have a period of at least n! * n.  In
the case of MT, it means that, regarding the period, you are safe for
lists with around 2079 elements.  shuffle's documentation may have
been written before the random module was converted to use the MT.

2**19937 being a really huge number, it's impossible to exhaust the
Mersenne twister by running it in sequence.  However, there is also
the question of the spread of the first shuffle.  Ideally we'd want
any shuffle, including the first one, to be able to produce any of the
n! permutations.  To achieve that, the initial state of the PRNG must
be able to support at least n! different outcomes, which means that
the PRNG must be seeded by at least log2(n!) bits of randomness from
an outside source.  For reference, Linux's /dev/random stops blocking
when 64 bits of randomness are available from the entropy pool, which
means that, in the worst case, shuffling more than 20 elements cannot
represent all permutations in the first shuffle!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: questions about functions inside a function

2007-07-16 Thread Jeremy Sanders
[EMAIL PROTECTED] wrote:

 What I want is, the value of i should be bounded to the anonymous
 function. And the output should like this:
...
 How to achieve this?

This doesn't answer your question (others have), but another (perhaps
clearer) way to do such things is something like

class MyFunc(object):
  A function object.
  def __init__(self, val):
 self.val = val

  def __call__(self):
 Return value squared
 return self.val**2

a = []
for i in range(4):
  a.append(MyFunc(i))

for f in a:
  f()


Jeremy

-- 
Jeremy Sanders
http://www.jeremysanders.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


questions about functions inside a function

2007-07-16 Thread [EMAIL PROTECTED]
I want to create a list of function.

Here is my code:
In [9]: a = []

In [10]: for i in range(4):
: b = lambda : i**2
: a.append(b)
:
:

In [11]: for f in a:
: f()
:
:
9
9
9
9

What I want is, the value of i should be bounded to the anonymous function. 
And the output should like this:

for f in a:
 print f()
0
1
4
9

How to achieve this?

Thanks a lot!


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


Re: how to read python-doc in ubuntu?

2007-07-16 Thread Diez B. Roggisch
ZelluX wrote:

 Hi all,
 I'm a new comer to Python.
 I've installed python-doc module, but just don't know how to open it.
 Could you help me?
 
 Many thanks ^_^

dpkg -L package-name 

will list the contents of the package at question.

Doc packages usually reside under

/usr/shar/doc/package-name

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


Re: Implementaion of random.shuffle

2007-07-16 Thread Steve Holden
Hrvoje Niksic wrote:
 Steve Holden [EMAIL PROTECTED] writes:
 
 So it would appear that the developers chose the Knuth algorithm
 (with a slight variation) for *their* implementation. Now you have
 to ask yourself whether your surmise is genuinely correct (in which
 case the documentation may contain a bug) or whether the
 documentation is indeed correct and you are in error.
 
 That is a good question.  The random module uses the Mersenne twister,
 which has a repetition period of 2**19937.  The number of n-sized
 permutations of a list with n elements is n!, while each shuffle
 requires n calls to the PRNG.  This means that to be able to generate
 all permutations, the PRNG must have a period of at least n! * n.  In
 the case of MT, it means that, regarding the period, you are safe for
 lists with around 2079 elements.  shuffle's documentation may have
 been written before the random module was converted to use the MT.
 
 2**19937 being a really huge number, it's impossible to exhaust the
 Mersenne twister by running it in sequence.  However, there is also
 the question of the spread of the first shuffle.  Ideally we'd want
 any shuffle, including the first one, to be able to produce any of the
 n! permutations.  To achieve that, the initial state of the PRNG must
 be able to support at least n! different outcomes, which means that
 the PRNG must be seeded by at least log2(n!) bits of randomness from
 an outside source.  For reference, Linux's /dev/random stops blocking
 when 64 bits of randomness are available from the entropy pool, which
 means that, in the worst case, shuffling more than 20 elements cannot
 represent all permutations in the first shuffle!

Thanks for this thoughtful analysis. I believe we can therefore leave 
the documentation (which almost certainly *was* written before the 
adoption of MT) alone for now.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: Private functions and inheritance

2007-07-16 Thread Neil Cerutti
On 2007-07-16, Maciej Blizi?ski [EMAIL PROTECTED] wrote:
 Hello,

 I've come across something that I don't quite understand about
 Python's inheritance. Consider the following code snippet:

 class A(object):
 def call_bar(self): return self.bar()
 def call___bar(self): return self.__bar()
 def __bar(self): return A::__bar()
 def bar(self): return A::bar()

 class B(A):
 def __bar(self): return B::__bar()
 def bar(self): return B::bar()

 b = B()
 print calling B::call_bar():, b.call_bar()
 print calling B::call___bar():, b.call___bar()

 The result is:

 calling B::call_bar(): B::bar()
 calling B::call___bar(): A::__bar()

the __* naming convention for class private attributes is
intended to help ensure that attribute names of derived classes
cannot conflict with private attribute names in any base classes.
I.e., you should not use that naming convention when you *intend*
to override it in a derived class. If you do use the __* naming
convention, use it only for attributes that should not be
overrided or accessed by derived classes.

the weasel words from the documentation (which I put in quotes)
are there because the feature doesn't work (in all cases).

-- 
Neil Cerutti
The doctors X-rayed my head and found nothing. --Dizzy Dean
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can a low-level programmer learn OOP?

2007-07-16 Thread [EMAIL PROTECTED]
You are lucky.Our project is a cross-platform cluster computer
managment system
this system can run on both windows and Linux
http://pluster.gf.cs.hit.edu.cn/
I tell you how we solve this problems

 1.  How to most easily learn to write simple PC GUI programs that will
 send data to remote embedded devices via serial comms, and perhaps
 incorporate some basic (x,y) type graphics display and manipulation
 (simple drawing program).  Data may result from user GUI input, or from
 parsing a text config file.  Solution need not be efficient in machine
 resource utilization.  Emphasis is on quickness with which programmer
 can learn and implement solution.

We use tk for GUI and we have a interpreter reads VB form file .frm
in and
display it with tk.You just need to draw forms in VB and save it in
frm formate
load it in your python file
LoadForm(aa.frm)
after that you can use button,menu and so on in python

We use XMLRPC to conmunicate with remote node.XMLRPC is very cool for
you can
invoke a function in remote side in the same way you invoke a local
method.
for example
we have an remote object foo
foo.bar() #invoke bar() in remote side
but XMLRPC is work on network.I'm not sure it can work in serial
 2.  Must be cross-platform: Linux + Windows.  This factor can have a big
 impact on whether it is necessary to learn a new language, or stick with
 C.  If my platform was only Linux I could just learn GTK and be done
 with it.  I wouldn't be here in that case.

and most important is XMLRPC is cross-platform.you can use a linux for
server and windows for client


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


Re: How to determine which method was used in an inheritance heirarchy?

2007-07-16 Thread Chris Mellon
On 7/16/07, Erik Jones [EMAIL PROTECTED] wrote:
 On Jul 16, 2007, at 3:37 AM, Gabriel Genellina wrote:

  En Mon, 16 Jul 2007 03:56:18 -0300, Erik Jones [EMAIL PROTECTED]
  escribió:
 
  Perhaps an even better example of what I'm trying to do would be in
  order (this is minus any exception handling):
 
  import sys
 
  def mytrace(frame, event, arg):
   if event == 'call':
   func_name = frame.f_code.co_name
 
   if func_name in frame.f_locals['self'].__class__.__dict__:
   print frame.f_locals['self'].__class__.__name__
   else:
   for base in frame.f_locals['self'].__class__.__bases__:
   if func_name in base.__dict__:
   print base.__name__
   break
 
 
  class A(object):
   def __init__(self):
   pass
 
  class B(A):
   def __init__(self):
   A.__init__(self)
 
  sys.settrace(mytrace)
  B()
 
  This will output:
 
  B
  B
 
  If you don't mind post-processing the results, you can log the
  function
  name and source module (from frame.f_code.co_name and co_filename) and
  current line number (frame.f_lineno). Later, obtaining the class
  name from
  those is a bit tricky (and not even the inspect module does it
  right), but
  perhaps using the tokenizer module, watching for lines that contain
  class name is enough.


 I was afraid of that.  I used pretty much that tokenizer trick for a
 unit test generator I wrote in php a while back and felt like that
 was pretty clunky then.



Hacky, but maybe this will work:

import sys
import inspect

def mytrace(frame, event, arg):
if event == 'call':
func_name = frame.f_code.co_name
klassOb = frame.f_locals['self'].__class__
for klass in inspect.getmro(klassOb):
cf = klass.__dict__.get(func_name)
if hasattr(cf, func_code) and cf.func_code == frame.f_code:
print klass.__name__


class A(object):
def __init__(self):
pass

class B(A):
def __init__(self):
A.__init__(self)

sys.settrace(mytrace)
B()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Compiling python2.5 on IBM AIX

2007-07-16 Thread Gerard Flanagan
On Jul 16, 12:29 pm, [EMAIL PROTECTED] wrote:
 hi,

 I'm trying to make a local install of python 2.5 on AIX and I'm
 getting some trouble with _curses.

 Here is how I tried to compile it :

 export BASE=/usr/local/python251

 cd Python.2.5.1
 ./configure --prefix=${BASE}/\
 LDFLAGS=-L\${BASE}/lib/\
 PPFLAGS=-I\${BASE}/include/\

 make
 make test
 make altinstall


I haven't compiled it myself, but I'm told that the installation I
work with was compiled with:

export PATH=$PATH:/usr/vacpp/bin:/usr/vacpp/lib
./configure --with-gcc=xlc_r -q64 --with-cxx=xlC_r -q64 --disable-
ipv6 AR=ar -X64
make
make install

if that helps.

Gerard


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


Re: how to read python-doc in ubuntu?

2007-07-16 Thread ZelluX
Got it. Thanks ;-)

Diez B. Roggisch wrote:
 ZelluX wrote:
 
 Hi all,
 I'm a new comer to Python.
 I've installed python-doc module, but just don't know how to open it.
 Could you help me?

 Many thanks ^_^
 
 dpkg -L package-name 
 
 will list the contents of the package at question.
 
 Doc packages usually reside under
 
 /usr/shar/doc/package-name
 
 diez
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Compiling python2.5 on IBM AIX

2007-07-16 Thread Gerard Flanagan
On Jul 16, 12:29 pm, [EMAIL PROTECTED] wrote:
 hi,

 I'm trying to make a local install of python 2.5 on AIX and I'm
 getting some trouble with _curses.

 Here is how I tried to compile it :

 export BASE=/usr/local/python251

 cd Python.2.5.1
 ./configure --prefix=${BASE}/\
 LDFLAGS=-L\${BASE}/lib/\
 PPFLAGS=-I\${BASE}/include/\

 make
 make test
 make altinstall


I haven't compiled it myself, but I'm told that the installation I
work with was compiled with:

export PATH=$PATH:/usr/vacpp/bin:/usr/vacpp/lib
./configure --with-gcc=xlc_r -q64 --with-cxx=xlC_r -q64 --disable-
ipv6 AR=ar -X64
make
make install

if that helps.

Gerard



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


Re: How to determine which method was used in an inheritance heirarchy?

2007-07-16 Thread Erik Jones
On Jul 16, 2007, at 10:35 AM, Chris Mellon wrote:

 On 7/16/07, Erik Jones [EMAIL PROTECTED] wrote:
 On Jul 16, 2007, at 3:37 AM, Gabriel Genellina wrote:

 En Mon, 16 Jul 2007 03:56:18 -0300, Erik Jones [EMAIL PROTECTED]
 escribió:

 Perhaps an even better example of what I'm trying to do would be in
 order (this is minus any exception handling):

 import sys

 def mytrace(frame, event, arg):
  if event == 'call':
  func_name = frame.f_code.co_name

  if func_name in frame.f_locals['self'].__class__.__dict__:
  print frame.f_locals['self'].__class__.__name__
  else:
  for base in frame.f_locals 
 ['self'].__class__.__bases__:
  if func_name in base.__dict__:
  print base.__name__
  break


 class A(object):
  def __init__(self):
  pass

 class B(A):
  def __init__(self):
  A.__init__(self)

 sys.settrace(mytrace)
 B()

 This will output:

 B
 B

 If you don't mind post-processing the results, you can log the
 function
 name and source module (from frame.f_code.co_name and  
 co_filename) and
 current line number (frame.f_lineno). Later, obtaining the class
 name from
 those is a bit tricky (and not even the inspect module does it
 right), but
 perhaps using the tokenizer module, watching for lines that contain
 class name is enough.


 I was afraid of that.  I used pretty much that tokenizer trick for a
 unit test generator I wrote in php a while back and felt like that
 was pretty clunky then.



 Hacky, but maybe this will work:

 import sys
 import inspect

 def mytrace(frame, event, arg):
 if event == 'call':
 func_name = frame.f_code.co_name
 klassOb = frame.f_locals['self'].__class__
 for klass in inspect.getmro(klassOb):
 cf = klass.__dict__.get(func_name)
 if hasattr(cf, func_code) and cf.func_code ==  
 frame.f_code:
 print klass.__name__


 class A(object):
 def __init__(self):
 pass

 class B(A):
 def __init__(self):
 A.__init__(self)

 sys.settrace(mytrace)
 B()

Chris, that is absolutely perfect.  Also, I don't think there is such  
a thing as profiling code that isn't hacky ;)

Erik Jones

Software Developer | Emma®
[EMAIL PROTECTED]
800.595.4401 or 615.292.5888
615.292.0777 (fax)

Emma helps organizations everywhere communicate  market in style.
Visit us online at http://www.myemma.com


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


Re: Re-raising exceptions with modified message

2007-07-16 Thread fumanchu
On Jul 15, 2:55 am, Christoph Zwerschke [EMAIL PROTECTED] wrote:
 Here is a simple solution, but it depends
 on the existence of the args attribute that
 will eventually be deprecated according
 to the docs

If you don't mind using .args, then the solution is usually as simple
as:


try:
Thing.do(arg1, arg2)
except Exception, e:
e.args += (Thing.state, arg1, arg2)
raise


No over-engineering needed. ;)


Robert Brewer
System Architect
Amor Ministries
[EMAIL PROTECTED]

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


Re: Fetching a clean copy of a changing web page

2007-07-16 Thread John Nagle
Miles wrote:
 On Jul 16, 1:00 am, John Nagle [EMAIL PROTECTED] wrote:
 
I'm reading the PhishTank XML file of active phishing sites,
at http://data.phishtank.com/data/online-valid/;  This changes
frequently, and it's big (about 10MB right now) and on a busy server.
So once in a while I get a bogus copy of the file because the file
was rewritten while being sent by the server.

Any good way to deal with this, short of reading it twice
and comparing?

John Nagle
 
 
 Sounds like that's the host's problem--they should be using atomic
 writes, which is usally done be renaming the new file on top of the
 old one.  How bogus are the bad files?  If it's just incomplete,
 then since it's XML, it'll be missing the /output and you should
 get a parse error if you're using a suitable strict parser.  If it's
 mixed old data and new data, but still manages to be well-formed XML,
 then yes, you'll probably have to read it twice.
 
 -Miles

  Yes, they're updating it non-atomically.

  I'm now reading it twice and comparing, which works.
Actually, it's read up to 5 times, until the same contents
appear twice in a row.  Two tries usually work, but if the
server is updating, it may require more.

  Ugly, and doubles the load on the server, but necessary to
get a consistent copy of the data.

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


Re: Re-raising exceptions with modified message

2007-07-16 Thread Gabriel Genellina
En Mon, 16 Jul 2007 13:50:50 -0300, fumanchu [EMAIL PROTECTED] escribió:

 On Jul 15, 2:55 am, Christoph Zwerschke [EMAIL PROTECTED] wrote:
 Here is a simple solution, but it depends
 on the existence of the args attribute that
 will eventually be deprecated according
 to the docs

 If you don't mind using .args, then the solution is usually as simple
 as:


 try:
 Thing.do(arg1, arg2)
 except Exception, e:
 e.args += (Thing.state, arg1, arg2)
 raise


 No over-engineering needed. ;)

If you read enough of this long thread, you'll see that the original  
requirement was to enhance the *message* displayed by a normal traceback -  
the OP has no control over the callers, but wants to add useful  
information to any exception.
Your code does not qualify:

py try:
...   open(a file that does not exist)
... except Exception,e:
...   e.args += (Sorry,)
...   raise
...
Traceback (most recent call last):
   File stdin, line 2, in module
IOError: [Errno 2] No such file or directory: 'a file that does not exist'
py try:
...   x = uá.encode(ascii)
... except Exception,e:
...   e.args += (Sorry,)
...   raise
...
Traceback (most recent call last):
   File stdin, line 2, in module
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in  
position 0:
ordinal not in range(128)

-- 
Gabriel Genellina

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


Re: Pass by reference or by value?

2007-07-16 Thread John DeRosa
On 15 Jul 2007 16:07:43 -0700, [EMAIL PROTECTED] (Aahz) wrote:

[posted and e-mailed]

[top-posting because I want to make only a one-line response]

Please stick this on a web-page somewhere -- it makes an excellent
counterpoint to

http://starship.python.net/crew/mwh/hacks/objectthink.html
http://effbot.org/zone/python-objects.htm

Eh... That's more than one line. :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can a low-level programmer learn OOP?

2007-07-16 Thread Wayne Brehaut
On Mon, 16 Jul 2007 10:10:05 +0200, Bruno Desthuilliers
[EMAIL PROTECTED] wrote:

Wayne Brehaut a écrit :
(snip)
  after Bruno made the
 claim: OO is about machines - at least as conceveid by Alan Key, who
 invented the term and most of the concept.

Please reread more carefully the above. I do give credit to Smalltalk's 
author for the *term* OOP, and *most* (not *all*) of the concepts (I 
strongly disagree with your opinion that message-passing is not a core 
concept of OO).

One problem is that it's often not clear what lists of properties are
his definition of OOP vs. what are the intended properties of
Smalltalk--his intended impelmentation of OOP. Many of the lists begin
with the basic requirements that everything is an object and
objects communicate by message passing, but the most common
generally agreed upon definition abstracts just four requirements
from these (changing)  lists--attempting to  separate implementation
details from what is essential to the underlying framework. As I note
below, these were:

1.  modularity (class-based? object-based?)
2.  inheritance (sub-classing)
3.  encapsulation (information hiding)
4.  polymorphism ((sub-) class-specific response to a message, or
processing of a method)

Other details in Kay's lists are considered  implementation details,
and important advances or alternatives to pevious methods, but not
required for a language to _be_ OO. It is reputed, though, that in
2003 Kay said
(http://c2.com/cgi/wiki?AlanKaysDefinitionOfObjectOriented)  OOP to
me means only messaging, local retention and protection and hiding of
state-process, and extreme LateBinding of all things.

So I understand your accepting one of Kay's lists as being a
definition of OOP instead of just a description of Smalltalk, or of
accepting this fairly recent definition as being the true one (as
opposed to the previous lists of usually 6 properties). It's hard to
hit a moving target!

FWIW, I first mentionned Simula too (about the state-machine and 
simulation aspect), then sniped this mention because I thought it was 
getting a bit too much OT - we're not on comp.object here.

Understood--sort of--but there is sufficient accurate information
about Simula available on the web now that it's no longer necessary to
use quotes from Kay about OOP and Smalltalk just  because they're more
accessible, as used to be the case. What would be so OT about
referring to Simulain one sentence instead of or in addition to
Smalltalk?

But I digress--my only real objection to your post was your opinion
and claim that Kay invented the term and most of the concept: I've
never seen anyone claim that anyone else invented the term, but for
the claim that he invented most of the concept we need only refer to
Nygaard's claim in How Object-Oriented Programming Started at
http://heim.ifi.uio.no/~kristen/FORSKNINGSDOK_MAPPE/F_OO_start.html
that Simula 67 introduced most of the key concepts of object-oriented
programming: both objects and classes, subclasses (usually referred to
as inheritance) and virtual procedures, combined with safe referencing
and mechanisms for bringing into a program collections of program
structures described under a common class heading (prefixed blocks).

Combine this with the fact--as stated above by Bonnie MacBird (Alan
Kay's significant other)--that Alan Kay has always publicly credited
Simula as the direct inspiration for Smalltalk, and... this
implication of taking credit for the first OOP language is not true,
it is a credit assigned to him by others, and one which he usually
rights when confronted with it. If he acknowledges this perhaps
others should too?

As has been noted before, it's often the fact that a cause becomes a
religion: true believers tend to take it over from the originator, and
this religiosity tends to blind them from the facts. Opinions and
rumours become facts, stories are invented, definitions are changed or
twisted, and another religion is born! Even those who don't belong to
the religion cpme to believe the oft-repreated stories, and then help
spread and perpetuate them. (Continuing in my original humorous vein I
was tempted to use terms like religious zealots, false gospel,
propaganda,  etc., but thought better of it in case I was again
misunderstood.)

Again, I disagree only with this one claim. You make significant
contributions to the group and to ellucidating Python and OOP to the
great unwashed: in contrast, all I've done so far is complain about
those who don't accept the correct (i.e., my) definition or use of
terms.

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


Best method for inter process communications

2007-07-16 Thread JamesHoward
I am looking for a way of performing inter process communication over
XML between a python program and something else creating XML data.

What is the best way of performing this communication?  I could bind a
socket to localhost and perform the data transfer that way, but that
seems inefficient due to the addition of TCP/IP or UDP/IP overhead.
Is there a way to stream data via a custom datastream (I.E. not STDIO,
STDERR, etc)?

Thanks in advance,
Jim Howard

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


Re: Technology solutions for Ruby?

2007-07-16 Thread vasudevram

[ Though the OP posted his message to comp.lang.ruby, I'm cross-
posting it to comp.lang.python, since he mentions Python as a possible
alternative he's looking at, and also because I've recommended Python
for his stated needs. Also, interested to see what other Pythonistas
have to say in response to my reply.
 - Vasudev]

 On Jul 16, 2007, at 2:21 AM, Michael Reiland wrote:

 At the heart of the issue is the fact that I refuse to use Java for this
project, I prefer not to use .Net because of the portability issues,
and
I'd like to get away from C++ for obvious reasons.

 To me this means Ruby, Python, or, as mentioned above, Perl.  If anyone
can tell me of a way to meet the above requirements in either Python
or
Perl, I'm all ears (I just prefer Ruby).

Yes, I think it would be really great for the Ruby community and for
the growth of the language if wxRuby was more mature as a GUI toolkit.
(Not knocking the wxRuby developers at all, its great that they've
even done what they have - I know that creating other language (like
Ruby) bindings to a C++ lib is a non-trivial task).

My suggestion: Python + wxPython + Python DBI + (Py2Exe + InnoSetup)
*might* meet all your needs. (As with any decision about what software
technologies to use, you'll have to evaluate the suggested options to
see if they fit your needs.)

Note: I've used and like both Ruby and Python (saying this after using
many, though not all, language features and libraries of both
languages), and am not trying to discourage you from using Ruby for
your needs; its just that, based on your needs as described, it looks
to me as if Python meets them better than Ruby at present:

 1. GUI - Native Look and Feel.  According to wxRuby the bindings aren't
mature enough for production use.  Does anyone have any experience
with
this and/or can you offer alternatives that provide a native look and
feel (I

I don't know enough about wxRuby to comment.

wxPython has this (Native Look and Feel), I think (used it some, a
while ago), not 100% sure, you can check on the site  - http:/
www.wxpython.org
 - to make sure. The site does say that it is cross-platform:

wxPython is a cross-platform toolkit. This means that the same
program will run on multiple platforms without modification. Currently
supported platforms are 32-bit Microsoft Windows, most Unix or unix-
like systems, and Macintosh OS X.


but that doesn't necessarily mean that it will have native look and
feel on all supported platforms. (The two are not the same thing.)
That's why you will need to check.

wxPython pros: Its fairly easy to learn, at least for simple GUI apps
(e.g. a few widgets / controls and a file dialog or two). I was able
to build these simple ones - see the code, article and screenshots
available here (or from links from here):

http://www.packtpub.com/article/Using_xtopdf

- in quite a short time, starting from zero knowledge of wxPython (I
did know some Python from before), just by looking at the sample apps,
and some reading of the docs.

See the quotes about wxPython: http://www.wxpython.org/quotes.php

2. Databases - contemplating using ActiveRecord, but I would like to use
ODBC to support multiple types of DB's in a uniform way (if you know
of
alternatives to ODBC or ActiveRecord, please let me know).

I think, but again, not sure, that Python DBI + appropriate database
drivers, may meet this need. Basically Python DBI is similar to ODBC
(roughly), and to Perl DBI + DBD, as I understand. There's also ODBC
support in the Win32 extensions package for Python - IIRC, Google for
'win32all' to get it. Its also available as a link from the Python for
Win32 MSI installer on python.org.
I've used Python ODBC some, it works and is easy to use.
See this for a simple example:

http://jugad.livejournal.com/2006/07/07/

(See the second post at that page, titled Publishing ODBC database
content as PDF
. The code shown in the post is not indented as per proper the Python
syntax (LiveJournal messed up the indentation), sorry about that, but
its trivial to correct if you know Python indenting rules). Also read
the Python ODBC docs and examples, of course.

3. Binary - Are there any utilities for compiling Ruby into a binary
executable?  The issue is twofold, speed, and not handing the
customer
the source :)

For Python, there is py2exe (for Windows only). I used py2exe recently
and it works well enough for the simple cases that I tried. (I tried
building EXEs for a simple Python hello-world program, and for a
simple wxPython GUI app based on my xtopdf toolkit. Both worked ok.)
For cross-platform (Windows and Linux, IIRC), there is PyInstaller
(Google for it), haven't tried it out yet, just downloaded it
recently.

I don't think you'll gain much speed by this compiling step, though
(over and above what Python gives you itself, when it compiles
your .py files to .pyc files). The purpose of py2exe is more to hide
the source code than to speed it up, as I understand (could be wrong).

Note: 

Discover instance variables

2007-07-16 Thread JonathanB
Ok, I know there has to be a way to do this, but my google-fu fails me
(once more). I have a class with instance variables (or should they be
called attributes, I'm newish to programming and get really confused
with OO sometimes), like the one in this example:

class Foo():
self.a = bar
self.z = test
self.var = 2

foo = Foo()

I want to print a list of the variables (strings, integers, etc) in
Foo, without knowing their names. So that the user who needs to change
a peice of information can view the variable list, enter the name of
the variable they need to change and then make the change. This is
what I'd like a sample run to look like:

Attributes for foo:
a = bar
z = test
var = 2

Change: a
New value: foobar
Change made!

I can handle the formatting and changing the variable itself, no
problem, but how do I get a list of all the variables in a class
instance? I almost put a list in there called vars and appended all
the variables to it so I could iterate the list, but this sounds like
something useful enough that someone has come up with a better way to
do it than that. It almost looks like self.__dir__() is what I want,
but that returns methods as well, correct? I only want variables, but
I can't think of how to do a list comprehension that would remove the
methods.

JonathanB

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


Re: Can a low-level programmer learn OOP?

2007-07-16 Thread Wayne Brehaut
On Mon, 16 Jul 2007 09:55:35 +0200, Bruno Desthuilliers
[EMAIL PROTECTED] wrote:

Wayne Brehaut a écrit :
 On Sat, 14 Jul 2007 06:01:56 +0200, Bruno Desthuilliers
 [EMAIL PROTECTED] wrote:
 
 Chris Carlen a écrit :
 Hi:

  From what I've read of OOP, I don't get it.  I have also found some 
 articles profoundly critical of OOP.  I tend to relate to these articles.

 
 === 8 ===
 
 Hence, being a hardware designer rather than a computer scientist, I am 
 conditioned to think like a machine.  I think this is the main reason 
 why OOP has always repelled me.
 OTOH, OO is about machines - at least as conceveid by Alan Key, who 
 invented the term and most of the concept. According to him, each object 
 is a (simulation of) a small machine.
 
 Oh you young'uns, not versed in The Ancient Lore, but filled with
 self-serving propaganda from Xerox PARC, Alan Kay, and Smalltalk
 adherents everywhere!

Not feeling concerned.

(snip pro-simula/anti-Xerox propaganda).

Or, more accurately, pro:

1. Nygaard  Dahl as the inventors of most of the concept of OOP
2. Simula as the first OOP
3. Kay as the originator of the term OOP
4. Kay, Xerox PARC, and Smalltalk as making significant useful
advances in implementation of OOP and popularizing it 

and anti:

1. attributing credit for any accomplishment to someone who doesn't
himself claim it and even denies it

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


Re: Pass by reference or by value?

2007-07-16 Thread Beliavsky
On Jul 13, 11:58 pm, sturlamolden [EMAIL PROTECTED] wrote:

snip

 In Fortran you can only pass references.

 integer(4) :: a
 a = 1
 call bar(a)

 subroutine bar(a)
 integer(4) :: a
 a = 0 ! side-effect
 end subroutine

 That means, when a variable is used to call a function, the function
 receives a pointer to the actual argument, not a local copy. That is
 very different from C's copy-passing behaviour.

In Fortran, if a procedure argument is modified within the procedure,
that change is propagated to the value of the argument in the caller.
The standard does NOT mandate how this is accomplished, and one could
in theory write a compiler that makes a local copy of all procedure
arguments, as long as the variables passed as arguments were updated
in the caller. Early implementations of Fortran 90 often made copies
of array arguments, hurting performance. Current compilers do this
less often.

It is common to pass constants and expressions to Fortran procedures,
which does not fit the pass-by-reference paradigm.

Fortran 2003 has the VALUE attribute to give the C pass-by-value
behavior when desired.

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


The ** operator ambiguous?

2007-07-16 Thread Robert Dailey
I noticed that the ** operator is used as the power operator, however
I've seen it used when passing variables into a function. For example,
I was researching a way to combine dictionaries. I found that if you
do this:

a = {t1:a, t2:b}
b = {t3:c}
dict( a, **b )


This combines the two dictionaries. However, I have no idea what the
** operator is here. I know that when you specify ** as a parameter in
a function definition, it represents a dictionary of parameters passed
in. However, in this example it is NOT being used in a function
definition. It is being used when passing variables into a function.
Can someone explain what this means? I looked in the documentation but
I couldn't find anything.

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


Re: The ** operator ambiguous?

2007-07-16 Thread Diez B. Roggisch
Robert Dailey schrieb:
 I noticed that the ** operator is used as the power operator, however
 I've seen it used when passing variables into a function. For example,
 I was researching a way to combine dictionaries. I found that if you
 do this:
 
 a = {t1:a, t2:b}
 b = {t3:c}
 dict( a, **b )
 
 
 This combines the two dictionaries. However, I have no idea what the
 ** operator is here. I know that when you specify ** as a parameter in
 a function definition, it represents a dictionary of parameters passed
 in. However, in this example it is NOT being used in a function
 definition. It is being used when passing variables into a function.
 Can someone explain what this means? I looked in the documentation but
 I couldn't find anything.

It's the opposite to the function definition **-operator:

def foo(a=0, b=1):
 print a,b


foo(**{a:100, b:200})

- 100 200

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


shutil.copyfile problem for GIS data

2007-07-16 Thread Ahmed, Shakir

Need help to copy a personal geodatabase from one location to another:


Trying to copy a personal geodatabase from one location to another
location where all the users are retrieving data from the second
location:

1.  I can copy over the updated personal geodatabase to the working
location and overwrite it, though the file is opened by ArcGIS  users
(Local Installation of Arc GIS  on the users computers).


2.  But problem is that  I can't copy over if the same updated
personal geodatabase to the working location,  if users uses that same
geodatabase through CITRIX - ArcGIS ( user does not have  permission to
edit the data)

3.  the python script which I am using as follows:

import shutil
import os

src = c:\mydata\test\mygeo.mdb
dst = v:\updated\data\mygeo.mdb

shutil.copyfile(src,dst)

I highly appreciate if any one of you can help me and give me a
direction that I can solve this problem.

Thanks in advance.

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


Re: 2**2**2**2**2 wrong? Bug?

2007-07-16 Thread Wayne Brehaut
On Mon, 16 Jul 2007 08:51:31 +0200, Hendrik van Rooyen
[EMAIL PROTECTED] wrote:

 Wayne Brehaut [EMAIL PROTECTED] wrote:

 On Sun, 15 Jul 2007 17:37:13 -0400, Steve Holden [EMAIL PROTECTED]
 wrote:
 
 Wayne Brehaut wrote:
  On Fri, 13 Jul 2007 14:32:03 -0700, [EMAIL PROTECTED]

8 -

 Also, I tend to follow the general Evolutionarily Stable Strategy
 generally called Retaliator.  In the simple game of Hawk vs. Dove a
 Hawk always attacks and defends to the death, whereas a Dove always
 runs. A mixed strategy would be to sometimes attack-and-defend and
 sometimes run, and a special case is to always run except when you're
 attacked--then defend to the death; i.e., behave like a Dove to a Dove
 and like a Hawk to a Hawk. 
 
 In Game Theory, if not in practice, Retaliator is dominant over both
 pure Hawk and pure Dove, partly because some who present like Hawks
 are actually Bullies--who behave like Hawks until an opponent defends,
 then behave  like Doves.

*grin* - you realise of course, that this stated strategy leaves you wide
open to trolls of the Lets see what we can provoke him into responding
kind - from people whose sense of humour is either subtle, or evil...

- Hendrik

Subtle is good  and generally easy enough to spot (Never kid a
kidder!).  As for evil, no problem--I'm also a bit of an Equivocator
(perhaps even  Prevaricator), and probably won't bother to respond to
anyone who seems to be a waste of time or is beyond redemption.

I seldom use a kill filter though since I'm too curious about what
they're going to say next, but can just read and suffer silently when
I choose to!

And thanks for the sage advice!

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


Re: Pass by reference or by value?

2007-07-16 Thread Steve Holden
Beliavsky wrote:
 On Jul 13, 11:58 pm, sturlamolden [EMAIL PROTECTED] wrote:
 
 snip
 
 In Fortran you can only pass references.

 integer(4) :: a
 a = 1
 call bar(a)

 subroutine bar(a)
 integer(4) :: a
 a = 0 ! side-effect
 end subroutine

 That means, when a variable is used to call a function, the function
 receives a pointer to the actual argument, not a local copy. That is
 very different from C's copy-passing behaviour.
 
 In Fortran, if a procedure argument is modified within the procedure,
 that change is propagated to the value of the argument in the caller.
 The standard does NOT mandate how this is accomplished, and one could
 in theory write a compiler that makes a local copy of all procedure
 arguments, as long as the variables passed as arguments were updated
 in the caller. Early implementations of Fortran 90 often made copies
 of array arguments, hurting performance. Current compilers do this
 less often.
 
 It is common to pass constants and expressions to Fortran procedures,
 which does not fit the pass-by-reference paradigm.
 
You can pass a reference to a constant just as easily as you can pass a 
reference to a variable. The only think you have to ensure is that when 
you pass a reference to a constant something stops the procedure from 
changing it.

Some early Fortran compilers omitted this small but important detail, 
leading to programs with incomprehensible semantics, as the values of 
numeric literals could no longer be relied upon.

 Fortran 2003 has the VALUE attribute to give the C pass-by-value
 behavior when desired.
 
regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: Python and Tkinter Primer/Tutorial?

2007-07-16 Thread James Stroud
W. Watson wrote:
 Thanks for the tips to the posters above. Wow, the Grayson book is $98 
 on Amazon. I think I'll see if I can get a library loan!

Its an ebook for $25.00: http://www.manning.com/grayson/

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best method for inter process communications

2007-07-16 Thread marduk
On Mon, 2007-07-16 at 17:22 +, JamesHoward wrote:
 I am looking for a way of performing inter process communication over
 XML between a python program and something else creating XML data.
 
 What is the best way of performing this communication?  I could bind a
 socket to localhost and perform the data transfer that way, but that
 seems inefficient due to the addition of TCP/IP or UDP/IP overhead.
 Is there a way to stream data via a custom datastream (I.E. not STDIO,
 STDERR, etc)?

In *nix, you could also use a named pipe for cheap RPC (os.mkfifo()).

-a

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


Re: Best method for inter process communications

2007-07-16 Thread Steve Holden
JamesHoward wrote:
 I am looking for a way of performing inter process communication over
 XML between a python program and something else creating XML data.
 
 What is the best way of performing this communication?  I could bind a
 socket to localhost and perform the data transfer that way, but that
 seems inefficient due to the addition of TCP/IP or UDP/IP overhead.
 Is there a way to stream data via a custom datastream (I.E. not STDIO,
 STDERR, etc)?
 
Nothing that portable across different platforms, I suspect.

However I see no reason why you can't use pipelines in Unix (in other 
words what's wrong with using stdin/stdout?), and Windows offers 
something called a named pipe. You could even use shared memory if you 
wanted.

Given the radically inefficient representations that XML typically 
requires, however, I think that worrying about localhost socket overhead 
is unnecessary: if your application was *that* critical you wouldn't be 
using XML in the first place.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: The ** operator ambiguous?

2007-07-16 Thread Duncan Booth
Robert Dailey [EMAIL PROTECTED] wrote:

 However, I have no idea what the
 ** operator is here. I know that when you specify ** as a parameter in
 a function definition, it represents a dictionary of parameters passed
 in. However, in this example it is NOT being used in a function
 definition. It is being used when passing variables into a function.
 Can someone explain what this means? I looked in the documentation but
 I couldn't find anything.
 

It is in the documentation. Look in the reference manual section 5.3.4 
Calls (http://docs.python.org/ref/calls.html):

 If the syntax *expression appears in the function call, expression
 must evaluate to a sequence. Elements from this sequence are treated
 as if they were additional positional arguments; if there are
 postional arguments x1,...,xN , and expression evaluates to a
 sequence y1,...,yM, this is equivalent to a call with M+N positional
 arguments x1,...,xN,y1,...,yM. 
 
 A consequence of this is that although the *expression syntax
 appears after any keyword arguments, it is processed before the
 keyword arguments (and the **expression argument, if any - see
 below). So: 
 
 def f(a, b):
 ...  print a, b
 ...
 f(b=1, *(2,))
 2 1
 f(a=1, *(2,))
 Traceback (most recent call last):
   File stdin, line 1, in ?
 TypeError: f() got multiple values for keyword argument 'a'
 f(1, *(2,))
 1 2
 
 It is unusual for both keyword arguments and the *expression syntax
 to be used in the same call, so in practice this confusion does not
 arise. 
 
 If the syntax **expression appears in the function call,
 expression must evaluate to a (subclass of) dictionary, the contents
 of which are treated as additional keyword arguments. In the case of a
 keyword appearing in both expression and as an explicit keyword
 argument, a TypeError exception is raised. 

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


Re: Best method for inter process communications

2007-07-16 Thread Grant Edwards
On 2007-07-16, JamesHoward [EMAIL PROTECTED] wrote:

 I am looking for a way of performing inter process communication over
 XML between a python program and something else creating XML data.

 What is the best way of performing this communication?  I could bind a
 socket to localhost and perform the data transfer that way, but that
 seems inefficient due to the addition of TCP/IP or UDP/IP overhead.
 Is there a way to stream data via a custom datastream (I.E. not STDIO,
 STDERR, etc)?

You could use a named pipe or a Unix domain socket.  The nice
thing about an IP socket is that you get network transparancy:
the two programs can be moved to two different machines.

-- 
Grant Edwards   grante Yow! It's the RINSE CYCLE!!
  at   They've ALL IGNORED the
   visi.comRINSE CYCLE!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Discover instance variables

2007-07-16 Thread Bjoern Schliessmann
JonathanB wrote:
 Ok, I know there has to be a way to do this, but my google-fu
 fails me (once more). I have a class with instance variables (or
 should they be called attributes, I'm newish to programming and
 get really confused with OO sometimes),

To complete confusion, those terms vary with languages :)

 like the one in this example:
 
 class Foo():
 self.a = bar
 self.z = test
 self.var = 2

This will not work. Please use working code for examples.

 I can handle the formatting and changing the variable itself, no
 problem, but how do I get a list of all the variables in a class
 instance? I almost put a list in there called vars and appended
 all the variables to it so I could iterate the list, but this
 sounds like something useful enough that someone has come up with
 a better way to do it than that. 

I'd use exactly this, since there may be attributes you don't want
to be changed from outside (perhaps __class__).

 It almost looks like self.__dir__() is what I want, but that
 returns methods as well, correct? I only want variables, but I
 can't think of how to do a list comprehension that would remove
 the methods. 

That's quite a problem with your concept. There are no variables and
methods. There are only attributes. Attributes may be objects. Some
objects may be callable (like function objects).

If you know exactly what you want to be accessible like this, you
could filter __dir__() output with name/callable/isinstance tests.

Regards,


Björn


-- 
BOFH excuse #320:

You've been infected by the Telescoping Hubble virus.

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


Re: Discover instance variables

2007-07-16 Thread Gabriel Genellina
En Mon, 16 Jul 2007 14:25:48 -0300, JonathanB [EMAIL PROTECTED]  
escribió:

 Ok, I know there has to be a way to do this, but my google-fu fails me
 (once more). I have a class with instance variables (or should they be
 called attributes, I'm newish to programming and get really confused
 with OO sometimes), like the one in this example:

 class Foo():
 self.a = bar
 self.z = test
 self.var = 2

 foo = Foo()

 I want to print a list of the variables (strings, integers, etc) in
 Foo, without knowing their names. So that the user who needs to change
 a peice of information can view the variable list, enter the name of
 the variable they need to change and then make the change. This is

You should define more precisely *which* attributes do you actually want  
in the list, but I think this may serve as a starting point:

py def get_attributes(obj):
...   return [attr for attr in dir(obj) if not attr.startswith('_') and
... type(getattr(obj,attr)) in (
...   int,str,unicode,float,dict,list,tuple)]
...
py f=open(c:\\test.py)
py get_attributes(f)
['mode', 'name', 'softspace']

The list keeps only the types explicitely enumerated. Other types are  
excluded, as well as names starting with _. Another criterion would be  
`not attr.startswith('_') and not callable(getattr(obj,attr))`

-- 
Gabriel Genellina

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


Re: The ** operator ambiguous?

2007-07-16 Thread Gabriel Genellina
En Mon, 16 Jul 2007 14:40:14 -0300, Robert Dailey [EMAIL PROTECTED]  
escribió:

 I noticed that the ** operator is used as the power operator, however
 I've seen it used when passing variables into a function. For example,
 I was researching a way to combine dictionaries. I found that if you
 do this:

 a = {t1:a, t2:b}
 b = {t3:c}
 dict( a, **b )


 This combines the two dictionaries. However, I have no idea what the
 ** operator is here. I know that when you specify ** as a parameter in
 a function definition, it represents a dictionary of parameters passed
 in. However, in this example it is NOT being used in a function
 definition. It is being used when passing variables into a function.
 Can someone explain what this means? I looked in the documentation but
 I couldn't find anything.

See this section in the tutorial  
http://docs.python.org/tut/node6.html#SECTION00670.
If you want the dirty details: http://docs.python.org/ref/calls.html

-- 
Gabriel Genellina

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


Re: Discover instance variables

2007-07-16 Thread Steve Holden
JonathanB wrote:
 Ok, I know there has to be a way to do this, but my google-fu fails me
 (once more). I have a class with instance variables (or should they be
 called attributes, I'm newish to programming and get really confused
 with OO sometimes), like the one in this example:
 
Instance variable are indeed attributes, but you are doing fine with the 
language so don't worry about it.

 class Foo():
 self.a = bar
 self.z = test
 self.var = 2
 
That's unlikely to work, though: the code is in the context of the 
class, not one of its methods, so unless you happen to be declaring a 
class inside another class's method it's unlikely that there's going to 
be a self around when those three lines execute.

What you probably want is something like what follows (I am running it 
interactively so I know I am telling the truth: it keeps me honest :-). 
You should get used to using the interpreter to check your hypotheses - 
it would have told you you were making a mistake above as soon as you 
tried to create a Foo.

  class Foo:
... a = bar
... z = test
... var = 2
...

You can check that Foo (the class) has these attributes:

  Foo.a
'bar'

 foo = Foo()
 
Now foo is an instance of the Foo class. Class attributes can also be 
accessed through instances:

  foo = Foo()
  foo.var
2
 

Binding an instance attribute, however, doesn't change the class, so you 
can use class attributes as a kind of default for instance.

  foo.a = foo
  foo.a
'foo'
  Foo.a
'bar'
 

 I want to print a list of the variables (strings, integers, etc) in
 Foo, without knowing their names. So that the user who needs to change
 a peice of information can view the variable list, enter the name of
 the variable they need to change and then make the change. This is
 what I'd like a sample run to look like:
 
 Attributes for foo:
 a = bar
 z = test
 var = 2
 
 Change: a
 New value: foobar
 Change made!
 
 I can handle the formatting and changing the variable itself, no
 problem, but how do I get a list of all the variables in a class
 instance? I almost put a list in there called vars and appended all
 the variables to it so I could iterate the list, but this sounds like
 something useful enough that someone has come up with a better way to
 do it than that. It almost looks like self.__dir__() is what I want,
 but that returns methods as well, correct? I only want variables, but
 I can't think of how to do a list comprehension that would remove the
 methods.
 
[name for name in dir(x) if not callable(name) and not 
name.startswith(__)]

might come close - I presume you don't want __doc__  and the like.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


  1   2   3   >