Re: Box plot in Python

2007-03-15 Thread James Stroud
Sebastian Bassi wrote:
> Hello,
> 
> Is there a graphic package for Python that provides support for box 
> plots? (see
> http://en.wikipedia.org/wiki/Box_plot and
> http://en.wikipedia.org/wiki/Image:R-speed_of_light_boxplot.png for
> information on box plots).
> 
> I have N sets of data, each with X "points".
> Example:
> 
> Set 1:
> Point 1: 0.21
> Point 2: 0.92
> Point 3: 0.18
> Point 4: 0.12
> ... cut 
> Point 203: 0.91
> 
> then:
> 
> Set 2:
> Point 1: 0.11
> Point 2: 0.3
> Point 3: 0.82
> Point 4: 0.11
> ... cut 
> Point 191: 0.09
> 
> 
> 
> I know that R would do it, but I don't know how to use R and would
> like to keep on working in Python.
> 
> Best,
> SB.

Have you considered rpy?

Also, pychart can do anything. You can do a boxplot in pychart if you 
are modestly creative.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Constructor of object

2007-03-15 Thread inline
Thanks. But can I change returned by xml.get_widget() object type from
gtk.Window to HelloWindow?

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


Re: Attribute monitoring in a class

2007-03-15 Thread Bruno Desthuilliers
Gabriel Genellina a écrit :
> En Wed, 14 Mar 2007 10:01:54 -0300, Joel Andres Granados 
> <[EMAIL PROTECTED]> escribió:
> 
>> Bruno Desthuilliers wrote:
>>> Joel Andres Granados a écrit :
> 
 I'm
 working with code that is not of my authorship and there is a class
 attribute that is changes by directly referencing it (object.attr =
 value) instead of using a getter/setter (object.setAttr(Value) )
> 
>>> yes : object.__setattr__(self, name, value)
>> I used this ^^^ one.  Thank for the help.
> 
> The problem with __setattr__ is that it slows down significantly *all* 
> attributes.
> Yours is the typical case when it's good to switch from using simple 
> attributes to using properties. 

If this has to become a feature of the class, yes, indeed. If it's just 
a temporary hack for debugging, the using the __getattr__ hook is 
quicker and less intrusive.

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


Sorry (was Re: Cteni unicode retezcu ze souboru UTF-8 s BOM?)

2007-03-15 Thread Petr Prikryl
Sorry for the mess,

The message should have been sent to the Czech
Python mailing list. My fault.

pepr

"Petr Prikryl" wrote...
> Ahoj všeci,
> Tak nějak prakticky poprvé se dostávám k tomu, 
> jak přečíst unicode řetězce ze souboru, který
> je uložen ve formátu UTF-8 se signaturou
> na začátku (BOM). Nějak se mi nedaří.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dict.items() vs dict.iteritems and similar questions

2007-03-15 Thread Laurent Pointal
Paul Rubin a écrit :
> Laurent Pointal <[EMAIL PROTECTED]> writes:
>> Both work, you may prefer xrange/iteritems for iteration on large
>> collections, you may prefer range/items when processing of the result
>> value explicitly need a list (ex. calculate its length) or when you are
>> going to manipulate the original container in the loop.
> 
> You can use len(d) if d is a dict.

Yes, as long as you have a semantic relation between the original dict
and the extracted keys. But once you have extracted the keys, and pass
them around your functions, if you miss the relationship, you have
either a list container or a generator. Not considering the case where
original dict is modified between keys extraction and keys usage...

But as we dont know more about OP needs...


A+

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


Re: spawn process in a new console window

2007-03-15 Thread Laurent Pointal
[EMAIL PROTECTED] a écrit :
> On Mar 14, 9:56 pm, [EMAIL PROTECTED] wrote:
>> Hello,
>>
>> I have a script that launches a sequence of other programs, some GUI,
>> some console.  I'd like the console programs to launch in their own
>> console window, instead of all of them sharing the script's console.
>> How do I do that?
>>
> 
> Would the subprocess module help here?  It's available in Python 2.4
> onwards.  I think it's supposed to be a one stop shop for all your
> external application launching needs (Python group, please correct me
> if I'm wrong here).
> 
> -Greg
> 

Try to use "start"

>>> import os
>>> os.system("start cmd")

Open a new console with a cmd shell in it.

See start documentation here http://www.ss64.com/nt/start.html
Or typing help start on the command line.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what are Python equivalent to MATLAB persistent or C++ static?

2007-03-15 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, dmitrey wrote:

> Thank you in advance,

For what?  Hint: Don't "hide" the question in the subject line.

I don't know MATLAB's `persistent` but I know that ``static`` in C++ can
be used in different places with different meanings.

It seems you are asking questions how to translate some constructs from
other languages 1:1 into Python.  Without context this may lead you to
programming some other language in Python, resulting in fighting the
language because you don't use "pythonic" idioms to solve your problems.

C++-static function's names on module level should start with an
underscore:

def _i_am_not_meant_to_be_public():
pass

It's a naming convention for things that are considered internal.

C++-static class members are class attributes in Python:

class Spam(object):
i_am_a_class_attribute = 42

def __init__(self):
self.i_am_an_instance_attribute = 'Viking'

And C++static local variables don't exist in Python.  There are ways to
emulate them with mutable default arguments, but that's at least
debatable.  Use a class instead.

Ciao,
Marc 'BlackJack' Rintsch

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


Re: most complete xml package for Python?

2007-03-15 Thread John Machin
On Mar 15, 9:04 am, "metaperl" <[EMAIL PROTECTED]> wrote:
> On Mar 14, 5:34 pm, "John Machin" <[EMAIL PROTECTED]> wrote:
>
> > Given keywords like "Amara" and "Elementtree" and past history, it
> > looked to me like a troll of one kind trying to incite a troll of
> > another kind to pop out from under the bridge and chew on his
> > ankle :-)
>
> Well, I'm not a troll. And I am now even less impressed with
> ElementTree. It does not preserve the document but reforms it in
> certain cases.
>
> 
>
> gets rewritten as
>
> 
>
> which leads to problems when embedding Dojo Rich Text Editors.

As BlackJack has pointed out, that's syntactically equivalent. If that
bothers you, best you don't check out what it does with namespace
prefixes.

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


Re: dict.items() vs dict.iteritems and similar questions

2007-03-15 Thread bearophileHUGS
Laurent Pointal:
> you may prefer range/items when processing of the result
> value explicitly need a list (ex. calculate its length)

Creating a very long list just to know the len of an iterator is
barbaric, so sometimes I use this:

def leniter(iterator):
if hasattr(iterator, "__len__"):
return len(iterator)
nelements = 0
for _ in iterator:
nelements += 1
return nelements

Bye,
bearophile

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


Re: Python books?

2007-03-15 Thread André
On Mar 15, 2:38 am, [EMAIL PROTECTED] (Alex Martelli) wrote:
> BartlebyScrivener <[EMAIL PROTECTED]> wrote:
> > On Mar 14, 3:50 pm, [EMAIL PROTECTED] (Aahz) wrote:
>
> > > Some people prefer shorter books -- Python for Dummies (for new
> > > programmers) and Python in a Nutshell (for experienced programmers) both
> > > try to give a thorough survey of Python while keeping the book easy to
> > > carry.
>
> Not for me to comment about my own books, but I can second your
> recommendation for your "for Dummies" for beginners.

Python in a Nutshell is a favourite of mine; highly recommended.
(However, I do not have the newer version ... yet!)
>
> > And other people like lots of examples and code organized around
> > practical projects a person might like to accomplish using Python. The
> > Python Cookbook 2nd edition is great for this, and Martelli et al are
> > great writers, as well as great programmers.
>
So is the Python Cookbook (i.e. highly recommended).

> If you like _substantial_ examples, rather than the simple/short ones
> typically used in manageable-sized books, Hetland's "Practical Python"
> was also a great buy (I believe it's now been replaced by "Beginning
> Python" by the same author, but unfortunately I haven't seen that one).

I have both; Beginning Python (From Novice to Professional) is a
huge improvement over Practical Python and is my number
one recommendation for a book to read from cover to cover.
(For absolute beginners, there is a book by Dawson
which might be better).  However, Beginning Python covers Python 2.5
which
doesn'te quite fit the requirement of the original poster.
Nonetheless,
on the grand scheme of things, there are so few differences between
2.5
and 2.5 that it should not matter.

I haven't look at Python for Dummies so I can't comment and compare
with other books.

André
>
> In general I dislike books that try to teach a language (or other
> technology) via "substantial examples", because the issues with the
> examples may obscure those with the language or technology; e.g.,
> Stroustrup tries that route in "The C++ Programming Language", as Lutz
> does in "Programming Python", and to my taste the results are inferior.
>
> However, at least in "Practical Python" (can't speak for "Beginning
> Python"), Hetland managed to pull it off -- perhaps by placing the
> substantial programs he develops as successive examples in a clever
> sequence, so that at each step he's not dealing with many diverse new
> issues but just manageably few of them.
>
> Alex


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


Re: most complete xml package for Python?

2007-03-15 Thread Paul Boddie
On 14 Mar, 17:45, Steve Holden <[EMAIL PROTECTED]> wrote:
>
> Although the phrase "without even checking them all out" hardly lends
> credence to the OP's assertion of Amara's superiority, and does tend to
> support a hypothesis involving some ulterior motive (or would if less
> ingenuously done).

It's an opinion being expressed, qualified with evidence to show that
it's weakly substantiated. Hardly a reason to "call FUD" or to suspect
an astroturfing campaign - FUD being one of the most readily used
terms (and consequently one of the most overused or inappropriately
used terms) when people disagree in the technology domain, anyway.

If the inquirer has it wrong, a gentle process of education is
necessary, although it should be noted that the process does involve
listening to their account of what they are trying to achieve rather
than telling them that they are stupid for using a particular tool or
other.

Paul

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


Computer Job Vacancy

2007-03-15 Thread sumberbisnis
Computer Job Vacancy
http://www.jobbankdata.com/job-computer.htm

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


Re: print and softspace in python

2007-03-15 Thread Bruno Desthuilliers
Phoe6 a écrit :
> print and softspace in python
> In python, whenever you use >>>print statement

Drop the '>>>' part. It's just the default Python shell prompt.

> it will append a
> newline by default. If you don't want newline to be appended, you got
> use a comma at the end (>>>print 10,)
> When, you have a list of characters and want them to be printed
> together a string using a for loop,

Why would one use a for loop to do so ? This is inefficient (even in C - 
it's mostly a system limitation). If you have a list of characters 
(actually, a list of one-character strings - there's no 'char' type in 
Python) and want to print it as a string, then first turn that list into 
a string, then print it:

 >>> list1=['a','b','c']
 >>> print "".join(list1)

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


Re: Returning other instance from __init__

2007-03-15 Thread Paul Boddie
On 15 Mar, 06:21, [EMAIL PROTECTED] (Alex Martelli) wrote:
> Paulo da Silva <[EMAIL PROTECTED]> wrote:
> >
> > I would like to implement something like this:
> >
> > class C1:
> >   def __init__(self,xxx):
> >   if ... :
> >   self.foo = foo
> >   self.bar = bar
> >   else:
> >   self=C1.load(xxx)
> >
> >   def load(xxx):
> >   ...
> >   return instance_of_C1
> >   load=staticmethod(load)
> >
> > This does not seem correct. How can I do it?
>
> Use __new__ for such purposes, not __init__.  (You need to make C1
> newstyle, e.g. inherit from object, to make special method __new__
> work).

Call me a traditionalist, but why wouldn't a factory function be good
enough?

def C1(xxx):
if ...:
return the_real_C1()
else:
return load(xxx)

def load(xxx):
...
return instance_of_C1

Or perhaps seeing more special methods and decorators just puts me in
a grumpy mood. ;-) For me, the power of Python is derived from being
able to do things like making callables "constructors" whilst
providing some illusion that C1 (in this case) is a class.

Paul

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


Re: Circular Class Logic

2007-03-15 Thread half . italian
> Remove the line above
> and add this below:
> def initFoo():
>   import baz
>   Foo.baz = baz.Baz()
> initFoo()

I got it to work, but I had to add a check to see if the class
variable had been set..

def initBaz():
  import Baz
  Foo.baz = Baz.Baz()

class Foo:
  baz = None
  def __init__(self):
if Foo.baz == None:
  Foo.baz = True
  initBaz()

What exactly is being accomplished by having the init function outside
of the class?  If there is no check, wouldn't it just execute every
time an object is instantiated anyway?

> Instead of initFoo, you could use a custom metaclass. Or a class decorator (if
> and when they become available...)

I haven't tried either of those yet.  The names scare me. :)  Sounds
like this might be a good time to explore them.

> The code above is an effective way of doing what you want. But I'd think about
> the actual need of doing such things - are you sure it's a good design?
>

I thought it was a good design, but now I'm not so sure.  I'm
untrained, so often I dont know the right way to do things.  As I
build this into the libraries, I'll keep an eye on how the code is
developing and go from there.Thanks for the help!

~Sean

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


Re: dict.items() vs dict.iteritems and similar questions

2007-03-15 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> Laurent Pointal:
>> you may prefer range/items when processing of the result
>> value explicitly need a list (ex. calculate its length)
> 
> Creating a very long list just to know the len of an iterator is
> barbaric, so sometimes I use this:
> 
> def leniter(iterator):
> if hasattr(iterator, "__len__"):
> return len(iterator)
> nelements = 0
> for _ in iterator:
> nelements += 1
> return nelements
> 
Of course this is a little like the Heisenberg uncertainty principle if 
the iterator has no __len__ attribute - once you know how long it is you 
no longer have access to the elements. Or did I miss something?

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note:  http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007

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


cx_Oracle and unicode data

2007-03-15 Thread looping
Hi,

I need to get data from an Oracle DB that contains unicode data
(chinese text).
But the chinese data that I receive is wrong (only ¿).
After a look at the Oracle documentation I've found an environment
variable called NLS_LANG that you could set to define what charset the
DB client use and it work fine.

But it's not what I call a 'clean' solution and I suppose that it must
exist another way to force the client DB to use UTF8, or another
solution to get my data.
Could someone help me ?
Thanks.

Example:

# -*- coding: latin1 -*-
import os
import cx_Oracle

os.environ["NLS_LANG"] = ".UTF8"

con = cx_Oracle.connect("demo/[EMAIL PROTECTED]")
cur = con.cursor()
cur.execute("select DESCRIPTION from DEC_DESCRIPTION where
DEC_DESCRIPTION_ID = 1792528")
val1 = cur.fetchone()[6]
val2 = cur.fetchone()[6]
print con.encoding, con.nencoding, con.maxBytesPerCharacter
cur.close()
print val1.decode(con.encoding)
print val2.decode(con.encoding)

del os.environ["NLS_LANG"]


>>>
UTF-8 UTF-8 3
珀マザーボードのテスト作業 颇マザーボードのテスト作業マザーボードのテスト作業,

without NLS_LANG setting I get:
>>>
WINDOWS-1252 WINDOWS-1252 1
¿ ¿,
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Tools for GUI/graphics

2007-03-15 Thread [EMAIL PROTECTED]
You should take a look at matplotlib (http://
matplotlib.sourceforge.net/). It's possible to integrate the graphic
display into a python application, as well as writing files and
display them in a browser.

Bernhard

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


Re: spawn process in a new console window

2007-03-15 Thread eglaser


Greg,

Thanks for the tip.  I will check out subprocess.

Eli

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


Re: spawn process in a new console window

2007-03-15 Thread eglaser
On Mar 15, 5:12 am, Laurent Pointal <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] a écrit :
>
>
>
> > On Mar 14, 9:56 pm, [EMAIL PROTECTED] wrote:
> >> Hello,
>
> >> I have a script that launches a sequence of other programs, some GUI,
> >> some console.  I'd like the console programs to launch in their own
> >> console window, instead of all of them sharing the script's console.
> >> How do I do that?
>
> > Would the subprocess module help here?  It's available in Python 2.4
> > onwards.  I think it's supposed to be a one stop shop for all your
> > external application launching needs (Python group, please correct me
> > if I'm wrong here).
>
> > -Greg
>
> Try to use "start"
>
> >>> import os
> >>> os.system("start cmd")
>
> Open a new console with a cmd shell in it.
>
> See start documentation herehttp://www.ss64.com/nt/start.html
> Or typing help start on the command line.


It looks like 'start' might be exactly what I need.  Thanks.

Eli

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


Re: cx_Oracle and unicode data

2007-03-15 Thread GHUM
loo ping,

> But it's not what I call a 'clean' solution and I suppose that it must
> exist another way to force the client DB to use UTF8, or another
> solution to get my data.

I share your feeling. I asked a similiar question ~1 year ago; and:
your solution is the only one.

The oracle-libs get their encoding from the environment. I also
learned that it often is helpfull to first set the environment and
THEN import cx_Oracle (which loads the oci.dll)

> import os
> os.environ["NLS_LANG"] = ".UTF8"
> import cx_Oracle
>

> cur.execute("select DESCRIPTION from DEC_DESCRIPTION where
> DEC_DESCRIPTION_ID = 1792528")

Additionally: UTF8 has different numbers of bytes per character. Your
select will only succeed for the time that DESCRIPTION encoded in UTF8
is shorter or equal to length(DESCRIPTION)

I got into the habbit to cast those fields to
NVARCHAR2(as big as I think it may get)

Harald

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


Re: Circular Class Logic

2007-03-15 Thread Paul McGuire
On Mar 15, 7:01 am, [EMAIL PROTECTED] wrote:
> > Remove the line above
> > and add this below:
> > def initFoo():
> >   import baz
> >   Foo.baz = baz.Baz()
> > initFoo()
>
> I got it to work, but I had to add a check to see if the class
> variable had been set..
>
> def initBaz():
>   import Baz
>   Foo.baz = Baz.Baz()
>
> class Foo:
>   baz = None
>   def __init__(self):
> if Foo.baz == None:
>   Foo.baz = True
>   initBaz()
>
> What exactly is being accomplished by having the init function outside
> of the class?  If there is no check, wouldn't it just execute every
> time an object is instantiated anyway?
>
> > Instead of initFoo, you could use a custom metaclass. Or a class decorator 
> > (if
> > and when they become available...)
>
> I haven't tried either of those yet.  The names scare me. :)  Sounds
> like this might be a good time to explore them.
>
> > The code above is an effective way of doing what you want. But I'd think 
> > about
> > the actual need of doing such things - are you sure it's a good design?
>
> I thought it was a good design, but now I'm not so sure.  I'm
> untrained, so often I dont know the right way to do things.  As I
> build this into the libraries, I'll keep an eye on how the code is
> developing and go from there.Thanks for the help!
>
> ~Sean

Just initialize Folder at module level - see below.
-- Paul

class Folder(object):
def __init__(self,path):
self.path = path
pass

def __repr__(self):
return self.__class__.__name__+"("+self.path+")"

class Disk(Folder):
def __init__(self,driveLetter):
super(Disk,self).__init__(driveLetter+":/")

# hokey function to test if a drive letter points to a drive, I'm
# sure there's a better way
import os,string
def isDisk(d):
try:
os.stat(d + ":/")
return True
except:
return False

# instead of calling some initFolder() method, just include this
statement
# at module level in the module that declares both classes
Folder.allDisks = map(Disk,[d for d in string.uppercase if isDisk(d)])

# now can reference allDisks through Folder instances
f = Folder("C:/temp")
print f.allDisks


prints:
[Disk(C:/), Disk(D:/), Disk(E:/)]


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


Re: dict.items() vs dict.iteritems and similar questions

2007-03-15 Thread Bruno Desthuilliers
Steve Holden a écrit :
> [EMAIL PROTECTED] wrote:
>> Laurent Pointal:
>>> you may prefer range/items when processing of the result
>>> value explicitly need a list (ex. calculate its length)
>>
>> Creating a very long list just to know the len of an iterator is
>> barbaric, so sometimes I use this:
>>
>> def leniter(iterator):
>> if hasattr(iterator, "__len__"):
>> return len(iterator)
>> nelements = 0
>> for _ in iterator:
>> nelements += 1
>> return nelements
>>
> Of course this is a little like the Heisenberg uncertainty principle if 
> the iterator has no __len__ attribute - once you know how long it is you 
> no longer have access to the elements. Or did I miss something?

yes, that's one of the side effects. Another interesting case:

import itertools
it = itertools.cycle(range(10))
print "it has %d elements" % leniter(it)


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


Re: dict.items() vs dict.iteritems and similar questions

2007-03-15 Thread bearophileHUGS
Steve Holden:
> once you know how long it is you
> no longer have access to the elements. Or did I miss something?

Now and then I need to know how many elements there are, and not what
they are, so in those situations storing them isn't necessary.

Bye,
bearophile

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


Re: looking for a simple crypto library

2007-03-15 Thread hg
P?nar Yanarda? wrote:

>  Hi all,
> 
> I'm looking for a crypto library which can simply:
> 
> - extracts a public key from a (X.509) certificate,
> 
> - supports public-key algorithms.
> 
> Any suggestions?
> 
> With love,
> --
> P?nar "PINguAR" Yanarda?
> http://pinguar.org
pyopenssl ?

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


Re: ANN: ActivePython 2.5.0.0 is now available

2007-03-15 Thread dan . shechter
On Mar 13, 9:56 pm, Trent Mick <[EMAIL PROTECTED]> wrote:
> I'm happy to announce that ActivePython 2.5.0.0 is now available for download
> from:
>  http://www.activestate.com/products/activepython/
>
> This is the first release of ActivePython for Python version 2.5. Apologies
> for the long delay between core Python 2.5 and this release. The good news is
> that part of the reason for this delay was to finally get approval to include
> crypto in ActivePython, hence:
>
> Changes in this release include:
> - Full OpenSSL support (finally!)
> - Update to Python 2.5 (duh)
> - [Mac OS X] Universal build (finally!)
> - [Windows] Update to PyWin32 build 210
> - All the new standard extensions: SQLite,ctypes, ElementTree
> - [Linux] Rationalized the build names.
> - [Mac OS X] A sane uninstall script
>
> See the release notes for full 
> details:http://aspn.activestate.com/ASPN/docs/ActivePython/2.5/relnotes.html
>
> What is ActivePython?
> -
>
> ActivePython is ActiveState's binary distribution of Python. Builds for
> Windows, Mac OS X, Linux, HP-UX and AIX are made freely available.
>
> ActivePython includes the Python core and the many core extensions: zlib and
> bzip2 for data compression, the Berkeley DB (bsddb) and SQLite (sqlite3)
> database libraries, the Tix GUI widgets for Tkinter, ElementTree for XML
> processing,ctypes(on supported platforms) for low-level library access, and
> others. The Windows distribution ships with PyWin32 -- a suite of Windows
> tools developed by Mark Hammond, including bindings to the Win32 API and
> Windows COM. See this page for full 
> details:http://aspn.activestate.com/ASPN/docs/ActivePython/2.5/whatsincluded
>
> As well, ActivePython ships with a wealth of documentation for both new and
> experienced Python programmers. In addition to the core Python docs,
> ActivePython includes the "What's New in Python" series, "Dive into Python",
> the Python FAQs & HOWTOs, and the Python Enhancement Proposals (PEPs).
>
> An online version of the docs can be found here:
>  http://aspn.activestate.com/ASPN/docs/ActivePython/2.5/welcome.html
>
> We would welcome any and all feedback to:
>  [EMAIL PROTECTED]
>
> Please file bugs against ActivePython at:
>  http://bugs.activestate.com/query.cgi?set_product=ActivePython
>
> On what platforms does ActivePython run?
> 
>
> ActivePython includes installers for the following platforms:
>
> - AIX/PowerPC
> - HP-UX/PA-RISC
> - Linux/x86
> - Linux/x86_64: "x86_64" is also known as "AMD64"
> - Solaris/SPARC
> - Solaris/x86
> - Mac OS X
> - Windows/x64: "x64" is also known as "AMD64"
> - Windows/x86
>
> Extra Bits
> --
>
> ActivePython releases also include the following:
>
> - ActivePython25.chm: An MS compiled help collection of the full
>ActivePython documentation set. Linux users of applications such as
>xCHM might find this useful. This package is installed by default on
>Windows.
>
> Extra bits are available from:
>  http://downloads.activestate.com/ActivePython/etc/
>
> Thanks, and enjoy!
>
> Trent, Python Tech Lead
>
> --
> Trent Mick
> trentm at activestate.com

is ctypes supported on ActivePython for Windows x64?

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


Re: Box plot in Python

2007-03-15 Thread Rob Clewley
Matplotlib supports boxplots in a very straightforward fashion and is
reasonably documented (just google it!) I actually just submitted a
patch for extra boxplot features in matplotlib, which you can find on
the sourceforge patch tracker.
-Rob
-- 
http://mail.python.org/mailman/listinfo/python-list


wxTextCtrl - copy and paste 65, 000 characters of text into it only seems to hold 30, 003

2007-03-15 Thread abcd
I have a wxTextCtrl:

wx.TextCtrl(self.myPanel, -1, "", style=wx.TE_MULTILINE)

I take a set of text (65,000 characters), and paste it into the text
control.  all looks well.  Then when I click a button I print out the
entered text and the length of that text.  Here is what I am seeing...

1. Paste in text (65,000 characters)
2. Click button
3. Output on screen shows that the message length (i.e. len(msg)) is
30003  (strange since it should be 65000)
4. Select all text in the text control and hit delete.  The text
control should now be empty.
5. Paste in text (65,000 characters)
6. Click Button
7. Output on screen shows that the message length (i.e. len(msg)) is
65000 (as expected).

Any idea why the first time it gives me 30003, but on subsequent
attempts I get 65000?

Thanks

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


Re: Returning other instance from __init__

2007-03-15 Thread Alex Martelli
Paul Boddie <[EMAIL PROTECTED]> wrote:
   ...
> > > class C1:
> > >   def __init__(self,xxx):
   ...
> > Use __new__ for such purposes, not __init__.  (You need to make C1
> > newstyle, e.g. inherit from object, to make special method __new__
> > work).
> 
> Call me a traditionalist, but why wouldn't a factory function be good
> enough?

That depends on whether you need name C1 to refer to a class, or not.

If you want name C1 to be usable outside this module as a class (to
subclass it, use with isinstance or issubclass, be available to an IDE's
classbrowser or other means of introspection including pydoc, etc), then
making name C1 refer to a function instead would not work.

> Or perhaps seeing more special methods and decorators just puts me in
> a grumpy mood. ;-) For me, the power of Python is derived from being
> able to do things like making callables "constructors" whilst
> providing some illusion that C1 (in this case) is a class.

For me, OTOH, it's not just smoke and mirrors (or as you say
"illusion"), there's also plenty of real power, and __new__ is part of
that.  (Decorators however are just handy syntax -- they let you avoid
repeating one name three times, and avoiding repetition is a good thing,
but their real power is essentially that of higher-order-functions that
could of course be used with other syntax if need be).


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


Re: Returning other instance from __init__

2007-03-15 Thread Paulo da Silva
Alex Martelli escreveu:
> Paulo da Silva <[EMAIL PROTECTED]> wrote:
...

> 
> E.g.:
> 
> class C1(object):
> def __new__(cls, xxx):
> if xxx: return type.__new__(cls, xxx)
> else: return C1.load(xxx)
> @staticmethod
>  def load(xxx): return ...whatever...
>  def __init__(self, xxx):
>  if hasattr(self, 'foo'): return
>  self.foo = 'foo'
>  self.bar = 'bar'
> 


Just for a better understanding ...
Can I do this?

class C1(object):
def __new__(cls, xxx):
if xxx:
cls.foo='foo'
cls.bar='bar'
return type.__new__(cls, xxx)
else:
return C1.load(xxx)
@staticmethod
def load(xxx): return ...whatever...
# OMMIT THE __init__
# or
def __init__(self, xxx):
pass
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dict.items() vs dict.iteritems and similar questions

2007-03-15 Thread Alex Martelli
Steve Holden <[EMAIL PROTECTED]> wrote:

> [EMAIL PROTECTED] wrote:
> > Laurent Pointal:
> >> you may prefer range/items when processing of the result
> >> value explicitly need a list (ex. calculate its length)
> > 
> > Creating a very long list just to know the len of an iterator is
> > barbaric, so sometimes I use this:
> > 
> > def leniter(iterator):
> > if hasattr(iterator, "__len__"):
> > return len(iterator)
> > nelements = 0
> > for _ in iterator:
> > nelements += 1
> > return nelements
> > 
> Of course this is a little like the Heisenberg uncertainty principle if
> the iterator has no __len__ attribute - once you know how long it is you
> no longer have access to the elements. Or did I miss something?

Right.  However, "return sum(1 for _ in iterator)" may be a handier way
to express the same desctructive semantics as the last 4 lines here.


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


Multiline code - trailing slash usage

2007-03-15 Thread abcd
When do I need to use a trailing slash to separate code over multiple
lines.

For example:

x = "hello world, this is my multiline " + \
 "string"

x = {'name' : \
  'bob'}

Do I need to use the "\" in the above examples?  When do i need to use
it?

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


Re: Returning other instance from __init__

2007-03-15 Thread Paul Boddie
On 15 Mar, 15:50, [EMAIL PROTECTED] (Alex Martelli) wrote:
> Paul Boddie <[EMAIL PROTECTED]> wrote:
> > Call me a traditionalist, but why wouldn't a factory function be good
> > enough?
>
> That depends on whether you need name C1 to refer to a class, or not.

Right.

> If you want name C1 to be usable outside this module as a class (to
> subclass it, use with isinstance or issubclass, be available to an IDE's
> classbrowser or other means of introspection including pydoc, etc), then
> making name C1 refer to a function instead would not work.

True. I can easily buy the argument about wanting to subclass C1,
although you'd always have the real class available somewhere as well.
For things like IDEs, class browsers and so on, I think more work
needs to be done to make these things more "aware" - it sounds like
they expect a more rigid language (like Java), but I do have some
awareness of why it's tempting to let them operate on their current
level of introspection.

> > Or perhaps seeing more special methods and decorators just puts me in
> > a grumpy mood. ;-) For me, the power of Python is derived from being
> > able to do things like making callables "constructors" whilst
> > providing some illusion that C1 (in this case) is a class.
>
> For me, OTOH, it's not just smoke and mirrors (or as you say
> "illusion"), there's also plenty of real power, and __new__ is part of
> that.

Oh, I like the illusion! The illusion is what makes Python so
powerful, after all.

Paul

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


Pickle Problem

2007-03-15 Thread tonyr1988
I'm a complete python n00b writing my first program (or attempting to,
anyway). I'm trying to make the transition from Java, so if you could
help me, it would be greatly appreciated. Here's the code I'm stuck on
(It's very basic):

class DemoClass:
def __init__(self):
self.title = ["Hello", "Goodbye"]

def WriteToFile(self, path = "test.txt"):
fw = file(path, "w")
pickle.dump(self.title, fw)
fw.close()

if __name__=='__main__':
x = DemoClass
x.WriteToFile

It doesn't do any file I/O at all (that I see). I hope my syntax is
alright. If I just call WriteToFile, shouldn't it perform with the
default path? It gives me no errors and pretends to execute just fine.

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


Re: Multiline code - trailing slash usage

2007-03-15 Thread Steve Holden
abcd wrote:
> When do I need to use a trailing slash to separate code over multiple
> lines.
> 
> For example:
> 
> x = "hello world, this is my multiline " + \
>  "string"
> 
> x = {'name' : \
>   'bob'}
> 
> Do I need to use the "\" in the above examples?  When do i need to use
> it?
> 
It's only needed if the end of the line could also be the end of the 
statement. So if there's an unclosed parenthesis, bracket or brace you 
can move to the next line without using a continuation backslash.

So it's needed in the first example, but not in the second.

Note also, by the way, that the Python interpreter will concatenate two 
adjacent string literals, so you could also have written

x = "hello world, this is my multiline " \
  "string"

and this would have saved you a run-time string concatenation :)

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note:  http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007

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


Re: Multiline code - trailing slash usage

2007-03-15 Thread Larry Bates
abcd wrote:
> When do I need to use a trailing slash to separate code over multiple
> lines.
> 
> For example:
> 
> x = "hello world, this is my multiline " + \
>  "string"
> 
> x = {'name' : \
>   'bob'}
> 
> Do I need to use the "\" in the above examples?  When do i need to use
> it?
> 
You need to use it when your are not inside some context that makes it
clear to Python that there's more to the line:

You don't need it here because python knows you are inside a list (same is
true for tuple).

a=[1,
   2,
   3
  ]

Same for a dictionary:

a={'a1': 1,
   'a2': 2,
   'a3': 3
  }

Also when you are inside call list of a function

a=foo(a,"this is a very long string",
  arg3, arg4,
  kwarg1='one', kwarg2='two')

Python knows you aren't done because you haven't provided the closing
parenthesis.

I do this in list comprehensions also:

n=[(variable1, variable2) for variable1, variable2 in something
   if variable1.startswith('z')]

You do need it in your first example, but not in your second.

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


Re: Multiline code - trailing slash usage

2007-03-15 Thread Steven Bethard
abcd wrote:
> When do I need to use a trailing slash to separate code over multiple
> lines.
> 
> For example:
> 
> x = "hello world, this is my multiline " + \
>  "string"

Yes.

> 
> x = {'name' : \
>   'bob'}

No.

You don't need trailing slashes whenever there's a pair of {}, [] or () 
wrapping things.

I never use trailing slashes -- I just wrap the expression in parentheses.

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


Re: Pickle Problem

2007-03-15 Thread Mike Kent
On Mar 15, 11:13 am, "tonyr1988" <[EMAIL PROTECTED]> wrote:

> if __name__=='__main__':
> x = DemoClass
> x.WriteToFile
>

You meant to create a DemoClass instance object, but instead, you
obtained a reference to the class object.  You want 'x = DemoClass()'
instead.
You meant to call the WriteToFile method, but instead, you obtained a
reference to the method object.  You want 'x.WriteToFile()' instead.

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


Re: Pickle Problem

2007-03-15 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, tonyr1988
wrote:

> if __name__=='__main__':
>   x = DemoClass
>   x.WriteToFile

In Python classes, functions and methods are first class objects.  You
bind the `DemoClass` class object to the name `x`, you are *not* creating
an instance of `DemoClass`.

Then you access the attribute `WriteToFile` of the `DemoClass` class
object.  But you don't do anything with it.

In [39]: class DemoClass(object): pass
   :

In [40]: x = DemoClass

In [41]: x
Out[41]: 

In [42]: y = DemoClass()

In [43]: y
Out[43]: <__main__.DemoClass object at 0xb5a3fd4c>

In [44]: x()
Out[44]: <__main__.DemoClass object at 0xb5a3fc2c>

You have to call the class object and the method to see any effects.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Multiline code - trailing slash usage

2007-03-15 Thread Bruno Desthuilliers
abcd a écrit :
> When do I need to use a trailing slash to separate code over multiple
> lines.
> 
> For example:
> 
> x = "hello world, this is my multiline " + \
>  "string"

Here you don't need the +

> x = {'name' : \
>   'bob'}

And here you don't need the antislash

> Do I need to use the "\" in the above examples?  When do i need to use
> it?
> 

IIRC, lists, tuples and dicts litterals, function args, list comps and 
generator expressions can span multiple lines. In any other case, you 
need the antislash. But you'd better check in the FineManual...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pickle Problem

2007-03-15 Thread Larry Bates
tonyr1988 wrote:
> I'm a complete python n00b writing my first program (or attempting to,
> anyway). I'm trying to make the transition from Java, so if you could
> help me, it would be greatly appreciated. Here's the code I'm stuck on
> (It's very basic):
> 
> class DemoClass:
>   def __init__(self):
>   self.title = ["Hello", "Goodbye"]
> 
>   def WriteToFile(self, path = "test.txt"):
>   fw = file(path, "w")
>   pickle.dump(self.title, fw)
>   fw.close()
> 
> if __name__=='__main__':
>   x = DemoClass
>   x.WriteToFile
> 
> It doesn't do any file I/O at all (that I see). I hope my syntax is
> alright. If I just call WriteToFile, shouldn't it perform with the
> default path? It gives me no errors and pretends to execute just fine.
> 
Just a couple of "issues" that can be fixed as follows:

import pickle

class DemoClass:
def __init__(self):
self.title = ["Hello", "Goodbye"]

def WriteToFile(self, path):
fw = file(path, "w")
pickle.dump(self.title, fw)
fw.close()

if __name__=='__main__':
path='\\test.txt'
x = DemoClass()
x.WriteToFile(path)

Notes:

1) You have to call (follow by parenthesis) DemoClass() to get an instance.
   What you got was a pointer (x) to the DemoClass not an instance of
   DemoClass.

2) Same for WriteToFile()

3) Probably best to move the path to main and always pass it into
   WriteToFile.

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


Re: Pickle Problem

2007-03-15 Thread Jerry Hill
On 15 Mar 2007 08:13:53 -0700, tonyr1988 <[EMAIL PROTECTED]> wrote:
> if __name__=='__main__':
> x = DemoClass
> x.WriteToFile

Here, you're binding the Class DemoClass to the name x.  What you
probably meant to do is create a new instance of DemoClass, and bind
that to name x, like this:

if __name__=='__main__':
 x = DemoClass()
 x.WriteToFile

When I make that change, your code appears to work fine.

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


Re: Multiline code - trailing slash usage

2007-03-15 Thread Christoph Haas
On Thursday 15 March 2007 15:57, abcd wrote:
> When do I need to use a trailing slash to separate code over multiple
> lines.
>
> For example:
>
> x = "hello world, this is my multiline " + \
>  "string"

Needed. Although you can omit the "+".

> x = {'name' : \
>   'bob'}

Not needed because you are inside the curly brackets {} and it's clear 
where the statement ends.

> Do I need to use the "\" in the above examples?  When do i need to use
> it?

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


Re: Pickle Problem

2007-03-15 Thread Gary Herron
tonyr1988 wrote:
> I'm a complete python n00b writing my first program (or attempting to,
> anyway). I'm trying to make the transition from Java, so if you could
> help me, it would be greatly appreciated. Here's the code I'm stuck on
> (It's very basic):
>
> class DemoClass:
>   def __init__(self):
>   self.title = ["Hello", "Goodbye"]
>
>   def WriteToFile(self, path = "test.txt"):
>   fw = file(path, "w")
>   pickle.dump(self.title, fw)
>   fw.close()
>
> if __name__=='__main__':
>   x = DemoClass
>   x.WriteToFile
>
> It doesn't do any file I/O at all (that I see). I hope my syntax is
> alright. If I just call WriteToFile, shouldn't it perform with the
> default path? It gives me no errors and pretends to execute just fine.
>   
Several people have pointed out the problem, but when you get that 
fixed, I see another bit of trouble.   The pickle format is a binary 
format (be default), but you don't open the file in binary mode.   On 
Unix the distinction is (wisely) irrelevant, but on Windows you should 
open the file with a mode of "wb" not just "w".

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


Re: Multiline code - trailing slash usage

2007-03-15 Thread Duncan Booth
Steve Holden <[EMAIL PROTECTED]> wrote:

> x = "hello world, this is my multiline " \
>   "string"
> 
> and this would have saved you a run-time string concatenation :)

or use parentheses for an alternative which doesn't need the backslash:

x = ("hello world, this is my multiline " 
  "string")


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


Re: Pickle Problem

2007-03-15 Thread Sönmez Kartal
Hi,

You should write your last two lines as ...

x = DemoClass()
x.WriteToFile()

Don't miss paranthesis again... :)

Maybe there are still some mistakes too. Does dump method writes list's 
elements?

Sönmez

tonyr1988 wrote:
> I'm a complete python n00b writing my first program (or attempting to,
> anyway). I'm trying to make the transition from Java, so if you could
> help me, it would be greatly appreciated. Here's the code I'm stuck on
> (It's very basic):
> 
> class DemoClass:
>   def __init__(self):
>   self.title = ["Hello", "Goodbye"]
> 
>   def WriteToFile(self, path = "test.txt"):
>   fw = file(path, "w")
>   pickle.dump(self.title, fw)
>   fw.close()
> 
> if __name__=='__main__':
>   x = DemoClass
>   x.WriteToFile
> 
> It doesn't do any file I/O at all (that I see). I hope my syntax is
> alright. If I just call WriteToFile, shouldn't it perform with the
> default path? It gives me no errors and pretends to execute just fine.
> 

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

Re: dict.items() vs dict.iteritems and similar questions

2007-03-15 Thread Duncan Booth
[EMAIL PROTECTED] (Alex Martelli) wrote:

>> Of course this is a little like the Heisenberg uncertainty principle if
>> the iterator has no __len__ attribute - once you know how long it is you
>> no longer have access to the elements. Or did I miss something?
> 
> Right.  However, "return sum(1 for _ in iterator)" may be a handier way
> to express the same desctructive semantics as the last 4 lines here.

I think I'd prefer the barbaric:

   return len(list(iterator))

since at least it is guaranteed to terminate.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: looking for a simple crypto library

2007-03-15 Thread Paul Rubin
"PÑnar Yanarda¿" <[EMAIL PROTECTED]> writes:
> I'm looking for a crypto library which can simply:
> 
> - extracts a public key from a (X.509) certificate,
> 
> - supports public-key algorithms.

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


Re: Multiline code - trailing slash usage

2007-03-15 Thread Ben Finney
"abcd" <[EMAIL PROTECTED]> writes:

> When do I need to use a trailing slash to separate code over multiple
> lines.
>
> For example:
>
> x = "hello world, this is my multiline " + \
>  "string"

You can either do that, or you can use parentheses:

x = ( "foo" +
  "bar" )

Note that you can make this read better *and* be faster, because
Python's parser will concatenate adjacent string values into a single
string value before compilation:

x = ( "foo"
  "bar" )

Both these result in x being bound to the string value "foobar". The
second example doesn't even involve a concatenation operation at
run-time.

> x = {'name' : \
>   'bob'}

Python allows parentheses '()', brackets '[]' and braces '{}' to
enclose multi-line statements.

x = { 'name':
  "bob" }

> Do I need to use the "\" in the above examples?  When do i need to
> use it?

I almost never use it to extend a statement; only sometimes within a
triple-quoted string. Parentheses can be used just about anywhere you
might otherwise need backslash-escaped line breaks.

-- 
 \"My, your, his, hers, ours, theirs, its. |
  `\  I'm, you're, he's, she's, we're, they're, it's." |
_o__)  -- Anonymous, alt.sysadmin.recovery |
Ben Finney

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


Re: ANN: ActivePython 2.5.0.0 is now available

2007-03-15 Thread Trent Mick
[EMAIL PROTECTED] wrote:
> 
> is ctypes supported on ActivePython for Windows x64?
> 

No.
http://aspn.activestate.com/ASPN/docs/ActivePython/2.5/whatsincluded.html

My understanding (from http://www.python.org/sf/1545507) is that ctypes isn't 
yet ported to Windows/AMD64.  That may have changed though.

Trent

-- 
Trent Mick
trentm at activestate.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what are Python equivalent to MATLAB persistent or C++ static?

2007-03-15 Thread [EMAIL PROTECTED]
Marc 'BlackJack' Rintsch wrote:
> In <[EMAIL PROTECTED]>, dmitrey wrote:
>
> > Thank you in advance,
>
> For what?  Hint: Don't "hide" the question in the subject line.
>
> I don't know MATLAB's `persistent` but I know that ``static`` in C++ can
> be used in different places with different meanings.
>
> It seems you are asking questions how to translate some constructs from
> other languages 1:1 into Python.  Without context this may lead you to
> programming some other language in Python, resulting in fighting the
> language because you don't use "pythonic" idioms to solve your problems.
>
> C++-static function's names on module level should start with an
> underscore:
>
> def _i_am_not_meant_to_be_public():
> pass
>
> It's a naming convention for things that are considered internal.
>
> C++-static class members are class attributes in Python:
>
> class Spam(object):
> i_am_a_class_attribute = 42
>
> def __init__(self):
> self.i_am_an_instance_attribute = 'Viking'
>
> And C++static local variables don't exist in Python.  There are ways to
> emulate them with mutable default arguments, but that's at least
> debatable.  Use a class instead.

If you must, function attributes emulate static:
def  myfunc():
   myfunc.foo += 1
return myfunc.foo
myfunc.foo=0 #initialize the value near the function definition

>>> print  myfunc()
1
>>> print  myfunc()
2
etc

But it's usually a bad idea to use this.  function attributes are
better reserved for information about the function itself (similar to
docstrings).

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


Re: Passing a FILE* from Python into a MinGW/SWIG module

2007-03-15 Thread Ross Ridge
John Pye <[EMAIL PROTECTED]> wrote:
>Is there an official workaround for this? Presumably I need to
>implement a mingw-compatible version of all the 'file' class in
>Python, eg

I'm not familiar with SWIG, but why not pass Python's own file class?
Method calls on Python's file class will be dispatched to C code in
the Python interpreter and so will use the C runtime that Python was
linked with.

Ross Ridge

-- 
 l/  //   Ross Ridge -- The Great HTMU
[oo][oo]  [EMAIL PROTECTED]
-()-/()/  http://www.csclub.uwaterloo.ca/~rridge/ 
 db  //   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pickle Problem

2007-03-15 Thread tonyr1988
On Mar 15, 10:38 am, Gary Herron <[EMAIL PROTECTED]> wrote:
> tonyr1988 wrote:
> > I'm a complete python n00b writing my first program (or attempting to,
> > anyway). I'm trying to make the transition from Java, so if you could
> > help me, it would be greatly appreciated. Here's the code I'm stuck on
> > (It's very basic):
>
> > class DemoClass:
> >def __init__(self):
> >self.title = ["Hello", "Goodbye"]
>
> >def WriteToFile(self, path = "test.txt"):
> >fw = file(path, "w")
> >pickle.dump(self.title, fw)
> >fw.close()
>
> > if __name__=='__main__':
> >x = DemoClass
> >x.WriteToFile
>
> > It doesn't do any file I/O at all (that I see). I hope my syntax is
> > alright. If I just call WriteToFile, shouldn't it perform with the
> > default path? It gives me no errors and pretends to execute just fine.
>
> Several people have pointed out the problem, but when you get that
> fixed, I see another bit of trouble.   The pickle format is a binary
> format (be default), but you don't open the file in binary mode.   On
> Unix the distinction is (wisely) irrelevant, but on Windows you should
> open the file with a mode of "wb" not just "w".

Thanks guys for all the help. Sure enough, it was the parenthesis.
Most of my problems seem to be from under-simplifying (using
semicolons, brackets, etc) or, rarely, over-simplifying (forgetting
parenthesis). The biggest thing that was messing me up was the
mandatory "self" input. For some reason I was thinking that, if I had
parenthesis, I would have to define it. Fixing that works perfectly.

Also, about the binary format for opening files. The program that I'm
working on now is completely Linux-based - it's impossible for it to
work on any other OS. Should I still open with "wb" or not? Either
way, thanks for that tip!

One more (completely irrelevant) question. I don't quite understand
the double-underscore functions / methods / etc, such as __name__,
__main__, __init__. Is there a reason for the double-underscore? Does
it make anything special?

Again, thanks for the help...I'm probably going to ask a lot more of
it before too long. :)

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


Re: Passing a FILE* from Python into a MinGW/SWIG module

2007-03-15 Thread Tommy Nordgren

On 14 mar 2007, at 11.57, John Pye wrote:

> Hi all
>
> I understand that I can't hope to pass a FILE* from the Windows
> version of Python into a SWIG module that I've built using MinGW  
> gcc/g+
> +, because apparently the FILE* structure are different and
> incompatible.
>
> Is there an official workaround for this? Presumably I need to
> implement a mingw-compatible version of all the 'file' class in
> Python, eg
>
> import mingw
> import myswigmodule
>
> F1 = mingw.file("newfile.txt","rw")
> F1.write("somestuff")
> F1.seek(0)
> F2 = mingw.tmpfile()
> myswigmodule.dosomething(F1,F2)
> F2.seek(0)
> print F2.read()
>
> Has anyone done this? Is there a better way that doesn't require users
> of my module to adapt? Do I have to use the dreaded MSVS to compile my
> SWIG module?
>
> Cheers
> JP
Can you get the file descriptor from the FILE *, and use that?

-
This sig is dedicated to the advancement of Nuclear Power
Tommy Nordgren
[EMAIL PROTECTED]



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


Re: dict.items() vs dict.iteritems and similar questions

2007-03-15 Thread skip

Duncan> I think I'd prefer the barbaric:

Duncan>return len(list(iterator))

Duncan> since at least it is guaranteed to terminate.

Are you sure?  There's no guarantee that an iterator will terminate:

len(list(itertools.cycle(range(10

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


Using wildcards with Popen in the Subprocess module

2007-03-15 Thread William Hudspeth
Hello, 

I am needing to pass an argument to the Popen function of the Subprocess
module that includes a wildcard in the filename. It seems that Popen is
not able to expand wildcards, and treats a filename that includes a
wildcard as a literal.

EX.

var1="/path_to_files/filnames*.doc"
result=Popen(["command",var1]).wait()

Can anyone tell me how I can work around this problem?


Thanks, Bill

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


Re: looking for a simple crypto library

2007-03-15 Thread hg
Paul Rubin wrote:

> tlslite

cool !

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


Re: most complete xml package for Python?

2007-03-15 Thread Diez B. Roggisch
metaperl schrieb:
> On Mar 14, 5:34 pm, "John Machin" <[EMAIL PROTECTED]> wrote:
> 
> 
>> Given keywords like "Amara" and "Elementtree" and past history, it
>> looked to me like a troll of one kind trying to incite a troll of
>> another kind to pop out from under the bridge and chew on his
>> ankle :-)
> 
> Well, I'm not a troll. And I am now even less impressed with
> ElementTree. It does not preserve the document but reforms it in
> certain cases.
> 
> 
> 
> gets rewritten as
> 
> 
> 
> which leads to problems when embedding Dojo Rich Text Editors.

Beside the fact that this is a problem of browsers (which won't help you 
much, as you have to deal with this somehow, blaming browsers alone 
isn't solving problems I'm just too aware of), I wonder: which XML 
framework _does_ preserve such tags?

I can't imagine a way of doing so as a DOM node is a DOM node. I could 
only create a custom renderer for HTML to circumvene that specific 
pitfall - but then, you could also create a post-rendering filter 
regex-based that expands the script-tags

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


Re: logging and wx.Timer

2007-03-15 Thread hg
hg wrote:

> Jordan wrote:
> 
>> On Mar 14, 1:52 am, hg <[EMAIL PROTECTED]> wrote:
>>> Hi,
>>>
>>> I read that logging was thread safe ... but can I use it under a GUI
>>> timer ?
>>>
>>> Thanks,
>>>
>>> hg
>> 
>> That was barely enough information to be worthy of a reply.  Need more
>> than that.  What do you mean under a gui timer? What gui? What type of
>> usage? More info = more (and better) help.  Cheers.
>> 
>> JT
> 
> Twas in the title: wx.timer
> 
> REgards,
> 
> hg


FYI, the answer from the wxPython NG is yes ... it should work fine

hg

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


Re: dict.items() vs dict.iteritems and similar questions

2007-03-15 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, skip wrote:

> Are you sure?  There's no guarantee that an iterator will terminate:
> 
> len(list(itertools.cycle(range(10

You have infinite memory?  ;-)

Ciao,
Marc 'BlackJack' Rintsch

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


Re: ANN: ActivePython 2.5.0.0 is now available

2007-03-15 Thread Thomas Heller
Trent Mick schrieb:
> [EMAIL PROTECTED] wrote:
>> 
>> is ctypes supported on ActivePython for Windows x64?
>> 
> 
> No.
> http://aspn.activestate.com/ASPN/docs/ActivePython/2.5/whatsincluded.html
> 
> My understanding (from http://www.python.org/sf/1545507) is that ctypes isn't 
> yet ported to Windows/AMD64.  That may have changed though.
> 
> Trent
> 

I have a patch for ctypes for Windows x64.  It cannot be integrated in the
Python SVN repository in the Python 2.5 branch because of the feature freeze,
so Python 2.6 would be the earliest.

I intend to release a separate Win x64 ctypes version soon (my plan is to
release this when Python 2.5.1 will be released, but this is totally
arbitrary); I still have to run more tests with it.

Thomas

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


Re: Box plot in Python

2007-03-15 Thread Sebastian Bassi
On 3/15/07, Rob Clewley <[EMAIL PROTECTED]> wrote:
> Matplotlib supports boxplots in a very straightforward fashion and is
> reasonably documented (just google it!) I actually just submitted a
> patch for extra boxplot features in matplotlib, which you can find on
> the sourceforge patch tracker.

OK, I will try it.
Thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


Tkinter menu toplevel or frame

2007-03-15 Thread Gigs_
what is the best way to write tkinter menus? As toplevels or as frame 
with Menubutton?

im doing like this
class MyWidget(Frame):
 def __init__(self, master=None):""" should this master be 
parent? Because my first tought was that this is toplevel master than i 
found that its not"""
 Frame.__init__(self, master)# and this too than
 self.config(width=200, height=200)
 self.pack(fill=BOTH, expand=YES)
 self.makeMenuBar()

 def makeMenuBar(self):
 self.menubar = Menu(self.master)
 self.master.config(menu=self.menubar)
 pulldown = Menu(self.menubar, tearoff=0)
 pulldown.add_command(label='New', command=self.new)
 pulldown.add_command(label='Open', command=self.onOpen)
 pulldown.add_command(label='Save', command=self.save)
 pulldown.add_command(label='Save As', command=self.saveas)
 pulldown.add_separator()
 pulldown.add_command(label='Exit', command=self.onExit)
 self.menubar.add_cascade(label='File', underline=0, menu=pulldown)


Please tell me is here anything that I should change.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dict.items() vs dict.iteritems and similar questions

2007-03-15 Thread bearophileHUGS
Alex Martelli:

> Right.  However, "return sum(1 for _ in iterator)" may be a handier way
> to express the same desctructive semantics as the last 4 lines here.

With the speed tests I have done my version did come out as the faster
one.

Bye,
bearophile

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


right-format of integer output as text

2007-03-15 Thread dmitrey
hi all,
I need printing the following:

 1
 2
 3
...
 9
   10
...
   99
 100
...
  999
1000
1001
...
how can I implement this one in the simpliest way?
Thank you in advance,
D.

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


right-format of integer output as text

2007-03-15 Thread dmitrey
hi all,
I need printing the following:

 1
 2
 3
...
 9
   10
...
   99
 100
...
  999
1000
1001
...
how can I implement this one in the simpliest way?
Thank you in advance,
D.

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


Re: right-format of integer output as text

2007-03-15 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, dmitrey wrote:

> how can I implement this one in the simpliest way?
> Thank you in advance,

In [45]: '%10d' % 1
Out[45]: ' 1'

In [46]: '%10d' % 42
Out[46]: '42'

In [47]: '%10d' % 1
Out[47]: ' 1'

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: right-format of integer output as text

2007-03-15 Thread dmitrey
There are some errors occured in displaing previous message, I meant
all right borders are the same, + some number of spaces before integer
numbers, according to the number of digits
D.

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


Re: Circular Class Logic

2007-03-15 Thread half . italian
> Just initialize Folder at module level - see below.
> -- Paul
>
> class Disk(Folder):
> def __init__(self,driveLetter):
> super(Disk,self).__init__(driveLetter+":/")

What is going on there?  Is it just explicitly calling the super's
init function?  How is that really different from this:

class Disk(Folder):
  def __init__(self,driveLetter):
Folder.Folder.__init__(self.path) # ???  Being that Folder is the
superclass?

I'd like to be able to use the shared Disk objects in any class that
is a subclass of Data.  Will the above method still make the Disk
objects available in File.py?  Also, what if the classes are in
different modules.

I'll try to experiment with it this afternoon.  I'm using more
information than just the drive letter.  What if the user wants to
find out the unc path to the share given the drive letter, or copy a
file to the local disk that is not a system disk that has the most
available space on it, or wants to mount or unmount a network drive.

pause...

I'm trying to justify why the Folders/Files really need the drive info
beyond just the paths and I'm having a hard time.  I even just tried
to give an example of how it would be used, and couldn't.  It seems to
make sense on a gut level, but maybe it's just as usefull on it's
own.  There's definitely justification for having Disks be a subclass
of Folder, but not necessarily for there to be an instance of it
available within the classes.  All that kind of work will be external
to the class.

I think I'll backtrace and keep it separate.  Thanks for letting me
think it through.

~Sean

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


Re: right-format of integer output as text

2007-03-15 Thread dmitrey
Thank you Marc, it is exactly the same I asked for.
D.

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


os.path.isfile with *.tar.gz

2007-03-15 Thread Boudreau, Emile
Hello All,
I'm new to Python and it looks like people that post here do get
a good answer back so I figured I'd try my luck.

I'm trying to check a directory to see if there is a file that has the
name "startOfString" + some version number + "inst.tar.gz"
(component-8.3.16-inst.tar.gz) The version number will change quite
frequently so I just want to check if there is a file with that format
name.

I have tried variations of: os.path.isfile( os.path.join("C:\\temp\\",
"rqp-win32-app", "*.tar.gz"))
but nothing seem to work. Does anyone have suggestions on how I could
get this to work?

Thanks in advance for the help,
Emile
 
 This message may contain privileged and/or confidential information.  If 
you have received this e-mail in error or are not the intended recipient, you 
may not use, copy, disseminate or distribute it; do not open any attachments, 
delete it immediately from your system and notify the sender promptly by e-mail 
that you have done so.  Thank you.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Circular Class Logic

2007-03-15 Thread Paul McGuire
On Mar 15, 1:55 pm, [EMAIL PROTECTED] wrote:
> > class Disk(Folder):
> > def __init__(self,driveLetter):
> > super(Disk,self).__init__(driveLetter+":/")
>
> What is going on there?  Is it just explicitly calling the super's
> init function?

What is going on is that Disk is being initialized with a single
character, such as 'D', and then calling the superclass with 'D:/',
the root folder on D.  You're the one who said that Disk was a
subclass of Folder (sorry, you called it "Data"), so I tried to come
up with an example in which this made some kind of sense.

> How is that really different from this:
>
> class Disk(Folder):
>   def __init__(self,driveLetter):
> Folder.Folder.__init__(self.path) # ???  Being that Folder is the
> superclass?
>
Where did self.path come from?  Even though Folder is the superclass,
self.path doesn't exist until the Folder.__init__ method gets called.
This ain't C++ you know.  And as I said above, we are taking a single
character drive letter, and calling the superclass init with the root
directory of that drive, so these are .

> I'd like to be able to use the shared Disk objects in any class that
> is a subclass of Data.  Will the above method still make the Disk
> objects available in File.py?  Also, what if the classes are in
> different modules.
>
> I'll try to experiment with it this afternoon.  I'm using more
> information than just the drive letter.  What if the user wants to
> find out the unc path to the share given the drive letter, or copy a
> file to the local disk that is not a system disk that has the most
> available space on it, or wants to mount or unmount a network drive.
>
Knock yourself out.  I just hacked together these Folder/Disk classes
by way of a half-baked-but-working example.  My point is that to
initialize a class level variable on class Foo, all that is needed is
to assign it in the defining module, that is:

class Foo:
   pass

Foo.fooClassVar = "a class level variable"

Now any Foo or sub-Foo can access fooClassVar.  The type of
fooClassVar can be anything you want, whether it is a Foo, subclass of
Foo or whatever, as long as it has been defined by the time you assign
fooClassVar.

-- Paul

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


Re: Using wildcards with Popen in the Subprocess module

2007-03-15 Thread kyosohma
On Mar 15, 2:04 pm, William Hudspeth <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I am needing to pass an argument to the Popen function of the Subprocess
> module that includes a wildcard in the filename. It seems that Popen is
> not able to expand wildcards, and treats a filename that includes a
> wildcard as a literal.
>
> EX.
>
> var1="/path_to_files/filnames*.doc"
> result=Popen(["command",var1]).wait()
>
> Can anyone tell me how I can work around this problem?
>
> Thanks, Bill

What are you doing, exactly? IF you are just passing in a random
filename, you could do something like this:

var1 = "/path_to_files_/%s" % (filename)

where filename is another variable.

You might also look into using os.system which allows just about any
command line options to be used.

Hope this helps.

Mike

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


Re: Using wildcards with Popen in the Subprocess module

2007-03-15 Thread Fabio FZero
You could use glob and expand the resulting list to astring manually,
but you have to make sure the command accepts the "command file1 file2
file3..." format.

FZero

On Mar 15, 4:04 pm, William Hudspeth <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I am needing to pass an argument to the Popen function of the Subprocess
> module that includes a wildcard in the filename. It seems that Popen is
> not able to expand wildcards, and treats a filename that includes a
> wildcard as a literal.
>
> EX.
>
> var1="/path_to_files/filnames*.doc"
> result=Popen(["command",var1]).wait()
>
> Can anyone tell me how I can work around this problem?
>
> Thanks, Bill


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


problem with str()

2007-03-15 Thread 7stud
I can't get the str() method to work in the following code(the last
line produces an error):


class test:
"""class test"""
def __init__(self):
"""I am init func!"""
self.num = 10
self.num2 = 20
def someFunc(self):
"""I am someFunc in test!"""
print "hello"


obj = test()
obj.someFunc()
names = dir(obj)
print names

methodList = [str for str in names if callable(getattr(obj, str))]
print methodList

x = getattr(obj, methodList[0]).__doc__
print x
print type(x)
print str(getattr(obj, methodList[0]).__doc__)
===

Here is the output:

$ python test1.py
hello
['__doc__', '__init__', '__module__', 'num', 'num2', 'someFunc']
['__init__', 'someFunc']
I am init func!

Traceback (most recent call last):
  File "test1.py", line 23, in ?
print str(getattr(obj, methodList[0]).__doc__)
TypeError: 'str' object is not callable

This is part of some code in Diving Into Python,Chapter 4.  In case a
function doesn't have a __doc__ string, and therefore __doc__ returns
None, the code needs to convert each __doc__ to a string so that the
result is guaranteed to be a string.

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


Re: os.path.isfile with *.tar.gz

2007-03-15 Thread Steve Holden
Boudreau, Emile wrote:
> Hello All,
> I'm new to Python and it looks like people that post here do get 
> a good answer back so I figured I'd try my luck.
> 
> I'm trying to check a directory to see if there is a file that has the 
> name "startOfString" + some version number + "inst.tar.gz" 
> (component-8.3.16-inst.tar.gz) The version number will change quite 
> frequently so I just want to check if there is a file with that format name.
> 
> I have tried variations of: os.path.isfile( os.path.join("C:\\temp\\", 
> "rqp-win32-app", "*.tar.gz"))
> but nothing seem to work. Does anyone have suggestions on how I could 
> get this to work?
> 
> Thanks in advance for the help,
> Emile
> 
>  
>  This message may contain privileged and/or confidential 
> information.  If you have received this e-mail in error or are not the 
> intended recipient, you may not use, copy, disseminate or distribute it; 
> do not open any attachments, delete it immediately from your system and 
> notify the sender promptly by e-mail that you have done so.  Thank you.
> 
Take a look at the glob module documentation. Glob.glob will almost 
certainly do what you want, as it's specifically written to match 
wildcard filenames.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note:  http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007

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


Re: os.path.isfile with *.tar.gz

2007-03-15 Thread Tim Golden
Boudreau, Emile wrote:
> Hello All,
> I'm new to Python and it looks like people that post here do get 
> a good answer back so I figured I'd try my luck.
> 
> I'm trying to check a directory to see if there is a file that has the 
> name "startOfString" + some version number + "inst.tar.gz" 
> (component-8.3.16-inst.tar.gz) The version number will change quite 
> frequently so I just want to check if there is a file with that format name.
> 
> I have tried variations of: os.path.isfile( os.path.join("C:\\temp\\", 
> "rqp-win32-app", "*.tar.gz"))
> but nothing seem to work. Does anyone have suggestions on how I could 
> get this to work?

Well os.path.isfile checks for the existence of one specific
file. Since there isn't a file called c:\temp\rqp-win32-app\*.tar.gz
it will return False. Take a look at the glob module. This will
return a list of files matching a pattern in the way you're
suggesting. Since a non-empty list is True, and an empty one
False in Python, something like the following code might
work: (untested)


import glob

if glob.glob (r"c:\temp\rqp-win32-app\*.tar.gz"):
   print "At least one file matched"
else:
   print "No files matched"



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


New Chess Module

2007-03-15 Thread shatranjchess
I'm releasing a new python chess module called shatranj.
You can get it from www.employees.org/~stannous/shatranj
until I move the project to sourceforge or some other place.

It's a text based (bitboard) chess engine that implements
an alphabeta search with iterative deepening.
It also has a small opening book and stores most of
its information in dictionaries (hash tables).  So for
a python module, it should be fast.

It currently has a very simple evaluation
function so don't expect strong play.  My goal was to
implement a complete program using 64 bit numbers
(bitboards) as the main data structures...sacrificing
speed for code clarity.  I'm hoping that non-programmers
interested in AI or advanced chess players will be able
to pick it up and add some intelligence to it.  Being
written in Python, it's not blazingly fast...but Kasparov
doesn't even look at 2k nodes per second, does he? ;-)

Some things I could use some help with: interface for
xboard and winboard not to mention a better
evaluation function.

(comments and suggestions are welcome...
please email shatranjchess at gmail dot com)

Here's a small interactive session of how it works:

--
>>> from shatranj import *
...reading startup data
...total time to read data 0.0774528980255
...found opening book shatranj-book.bin with 37848 positions
>>> position = Position("r1bqk2r/1ppp/2n5/5N2/2B1n3/8/PPP1QPPP/R1B1K2R")
>>> all_pieces = position.piece_bb["b_occupied"] | 
>>> position.piece_bb["w_occupied"]
>>> other_pieces = position.piece_bb["b_occupied"]
>>> from_square = c4
>>> wtm = 1
>>> mask = position.pinned(from_square,wtm)
>>> ne_pieces = diag_mask_ne[from_square] & all_pieces
>>> nw_pieces = diag_mask_nw[from_square] & all_pieces
>>> moves = ((diag_attacks_ne[from_square][ne_pieces] & other_pieces) | \
...  (diag_attacks_ne[from_square][ne_pieces] & ~all_pieces)
| \
...  (diag_attacks_nw[from_square][nw_pieces] & other_pieces)
| \
...  (diag_attacks_nw[from_square][nw_pieces] & ~all_pieces))
& mask
>>>
>>> moves
1275777090846720L
>>>
>>> tobase(moves,2)
'100100011010101'
>>> display(moves)

+---+---+---+---+---+---+---+---+
  8 |   | . |   | . |   | . |   | . |
+---+---+---+---+---+---+---+---+
  7 | . |   | . |   | . | 1 | . |   |
+---+---+---+---+---+---+---+---+
  6 | 1 | . |   | . | 1 | . |   | . |
+---+---+---+---+---+---+---+---+
  5 | . | 1 | . | 1 | . |   | . |   |
+---+---+---+---+---+---+---+---+
  4 |   | . |   | . |   | . |   | . |
+---+---+---+---+---+---+---+---+
  3 | . | 1 | . | 1 | . |   | . |   |
+---+---+---+---+---+---+---+---+
  2 |   | . |   | . |   | . |   | . |
+---+---+---+---+---+---+---+---+
  1 | . |   | . |   | . |   | . |   |
+---+---+---+---+---+---+---+---+
  a   b   c   d   e   f   g   h

>>> move_list = position.generate_moves(wtm)
>>> moves,san_moves = position.get_move_list(move_list)
>>> san_moves.values()
['Rg1', 'O-O', 'f3', 'a3', 'Rb1', 'f4', 'Ba6', 'Qe3', 'Bh6', 'Bd3',
 'Qg4', 'Ng3', 'Ne7', 'Be6', 'Nxg7', 'Qxe4', 'Ne3', 'b4', 'b3', 'Be3',
'Bg5', 'g3', 'Kf1', 'Rf1', 'Nh6', 'a4', 'Nh4', 'Qh5', 'Kd1', 'h4',
'h3',
'c3', 'Bxf7', 'Nd6', 'Bb5', 'Nd4', 'Qf3', 'g4', 'Qf1', 'Bb3', 'Qd1',
'Qd3', 'Qd2', 'Bd5', 'Bd2', 'Bf4']
>>>
>>> # now play a game!
>>> play()
Shatranj version 1.0
 g: switch sides m: show legal moves
 n: new game l: list game record
 d: display boardb: show book moves
sd: change search depth (2-16) default=5
 q: quit

Shatranj: d

+---+---+---+---+---+---+---+---+
  8 | r | n | b | q | k | b | n | r |
+---+---+---+---+---+---+---+---+
  7 | p | p | p | p | p | p | p | p |
+---+---+---+---+---+---+---+---+
  6 |   | . |   | . |   | . |   | . |
+---+---+---+---+---+---+---+---+
  5 | . |   | . |   | . |   | . |   |
+---+---+---+---+---+---+---+---+
  4 |   | . |   | . |   | . |   | . |
+---+---+---+---+---+---+---+---+
  3 | . |   | . |   | . |   | . |   |
+---+---+---+---+---+---+---+---+
  2 | P | P | P | P | P | P | P | P |
+---+---+---+---+---+---+---+---+
  1 | R | N | B | Q | K | B | N | R |
+---+---+---+---+---+---+---+---+
  a   b   c   d   e   f   g   h



Shatranj:
---

Enjoy,
Sam

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


[email protected]

2007-03-15 Thread [EMAIL PROTECTED]
On Jan 29, 7:12 pm, "Pappy" <[EMAIL PROTECTED]> wrote:
> SHORT VERSION:PythonFile B changes sys.stdout to a file so all 'prints' are 
> written
> to the file.  Pythonfile A launchespythonfile B with os.popen("./B
> 2>&^1 >dev/null &").  PythonB's output disappears into never-never
> land.
>
> LONG VERSION:
> I am working on a site that can kick off large-scale simulations.  It
> will write the output to an html file and a link will be emailed to
> the user.  Also, the site will continue to display "Loading..." if the
> user wants to stick around.
>
> The simulation is legacy, and it basically writes its output to stdout
> (via simple print statements).  In order to avoid changing all these
> prints, I simply change sys.stdout before calling the output
> functions.  That works fine.  The whole thing writes to an html file
> all spiffy-like.
>
> On thecgiend, all I want my (python)cgiscript to do is check for
> form errors, make sure the server isn't crushed, run the simulation
> and redirect to aloadingpage (in detail, I write a constantly
> updating page to the location of the final output file.  When the
> simulation is done, the constantly updating file will be magically
> replaced).  The root problem is that the popen mechanism described
> above is the only way I've found to truly 'Detach' my simulation
> process.  With anything else, Apache (in a *nix environment) sits and
> spins until my simulation is done.  Bah.
>
> Any ideas?
>
> _jason


Did you ever find your answer Mr. _jason?  I'm trying to do the same
thing now but even with the subprocess module the broswer still says
loading until the subprocess is done.

Is there truly NO way to kick of a process and be done with it
forever?

-Greg

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


Re: Importing WMI in a child Thread throws an error

2007-03-15 Thread kyosohma
On Feb 28, 3:08 pm, Tim Golden <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > On Feb 27, 3:32 pm, Tim Golden <[EMAIL PROTECTED]> wrote:
> >> [EMAIL PROTECTED] wrote:
> >>> The problem I have is that since I import WMI, it takes a long time
> >>> and we have users complaining about it. So I stuck the import
> >>> statement into a separate thread and set it to a daemon so it could do
> >>> its thing in the background and the rest of the script would finish
> >>> and exit.
> >> Two things:
>
> >> 1) If you run WMI in a thread, you'll need to call
> >> pythoncom.CoInitialize first:
>
> >> 
> >> import pythoncom
> >> import wmi
>
> >> pythoncom.CoInitialize ()
> >> c = wmi.WMI ()
> >> #
> >> # do things
> >> #
> >> pythoncom.CoUninitialize ()
> >> 
>
> >> 2) If you need a bit of speed running WMI, see the post
> >> I sent a few days ago to someone else:
>
> >>http://mail.python.org/pipermail/python-win32/2007-February/005550.html
>
> >> TJG
>
> > Thanks! This works for my problem. It appears to cut the real time
> > required for my script to run by 30-50%. I tried to figure out how to
> > apply your answer to the other fellow, but I am actually querying WMI
> > for the amount of RAM and the CPU type and I just don't see how to use
> > your example in these cases. I am new to the WMI paradigm.
>
> If you want to post some specific code examples, I'm
> happy to talk you through possible optimisations.
>
> TJG

Sorry I didn't reply right away. Here's the straight WMI code I'm
using:

c = wmi.WMI()
for i in c.Win32_ComputerSystem():
mem = int(i.TotalPhysicalMemory)
compname = i.Name
for i in c.Win32_Processor ():
cputype = i.Name

This code was wrapped in your CoInitialize com objects.

Let me know if you need more code.

Mike

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


Re: Circular Class Logic

2007-03-15 Thread Gabriel Genellina
En Thu, 15 Mar 2007 09:01:07 -0300, <[EMAIL PROTECTED]> escribió:

> I got it to work, but I had to add a check to see if the class
> variable had been set..
>  class Foo:
>   baz = None
>   def __init__(self):
> if Foo.baz == None:
>   Foo.baz = True
>   initBaz()

This is a different approach. You are using instance initialization  
(Foo.__init__) to finish class initialization. Foo.__init__ will be called  
each time you create a Foo instance; that's why you had to check if  
Foo.baz is None.
(BTW, Foo.baz=True is unneeded).
The only problem I can see is that the Foo class is not completely  
initialized until its first instance is created; this may not be a problem  
in your case.

> What exactly is being accomplished by having the init function outside
> of the class?  If there is no check, wouldn't it just execute every
> time an object is instantiated anyway?

What I intended was different:

==
C:\TEMP>type foo.py
class Foo:
 baz = None

 def __init__(self):
 pass

def initFoo():
 import baz
 Foo.baz = baz.Baz()
initFoo()

C:\TEMP>type bar.py
import foo

class Bar(foo.Foo):
 pass

C:\TEMP>type baz.py
import bar

class Baz(bar.Bar):
 pass

C:\TEMP>type test.py
import foo,bar,baz

print foo.Foo.baz
f = foo.Foo()
print f.baz
b = bar.Bar()
print b.baz
print baz.Baz.baz

C:\TEMP>python test.py




==

initFoo is only executed when Foo is imported the first time. Note that  
you can't do that if

> I thought it was a good design, but now I'm not so sure.  I'm
> untrained, so often I dont know the right way to do things.  As I
> build this into the libraries, I'll keep an eye on how the code is
> developing and go from there.Thanks for the help!

Usually Python code is quite concise and straightforward; when I find  
myself writing things too convoluted, I know it's time to  
refactor/redesign. (Anyway some things remain not as simple as I'd like  
:( )
Perhaps you later find the need for a different/better way.

--
Gabriel Genellina

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


Re: merits of Lisp vs Python

2007-03-15 Thread John J. Lee
Jorge Godoy <[EMAIL PROTECTED]> writes:

> [EMAIL PROTECTED] (John J. Lee) writes:
> 
> > John Nagle <[EMAIL PROTECTED]> writes:
> >
> >> John J. Lee wrote:
> >> > "Graham Dumpleton" <[EMAIL PROTECTED]> writes:
> >> >
> >> >>On Mar 11, 12:31 pm, [EMAIL PROTECTED] (John J. Lee) wrote:
> >> 
> >> > Is it possible to ask mod_python to start separate processes to serve
> >> > requests, rather than "separate" interpreters?  We couldn't see a way.
> >> 
> >> That's what CGI does.
> >
> > I meant long running processes, as I hoped was obvious from context...
> 
> Maybe FastCGI should help, then.  It can run "forever" after a request has
> finished so it is suitable for long running processes. 

Yes, we've used FastCGI too.  My question was specifically about
mod_python.


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


Re: Importing WMI in a child Thread throws an error

2007-03-15 Thread Tim Golden
>> If you want to post some specific code examples, I'm
>> happy to talk you through possible optimisations.
>>
>> TJG
> 
> Sorry I didn't reply right away. Here's the straight WMI code I'm
> using:
> 
> c = wmi.WMI()
> for i in c.Win32_ComputerSystem():
> mem = int(i.TotalPhysicalMemory)
> compname = i.Name
> for i in c.Win32_Processor ():
> cputype = i.Name

Well, don't know how much gain you'll get, but yo
could try the following quickies:


import wmi
c = wmi.WMI (find_classes=False)

for i in c.Win32_ComputerSystem (
   ['TotalPhysicalMemory', 'Name']
):
   mem = int (i.TotalPhysicalMemory)
   compnam = i.Name

for i in c.Win32_Processor (['Name']):
   cputype = i.Name



If you were going to repeat these often (say, in
a loop, which doesn't seem likely given you
examples) you might gain a few nanosecs by
pulling the attribute lookup outside the loop:


import wmi
c = wmi.WMI (find_classes=False)

ComputerSystem = c.Win32_ComputerSystem
Processor = c.Win32_Processor

while True:
   for computer_system in ComputerSystem (...): ...
   for processor in Processor (...): ...



But, as everyone else on this list will tell you,
there's no point in optimising unless you know you
need to to, and unless you know where :-) That's
what modules like timeit profiler are for.

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


Re: problem with str()

2007-03-15 Thread Matimus
Don't use built-ins as variable names. Your code will work if you
change this:

> methodList = [str for str in names if callable(getattr(obj, str))]

to this:
> methodList = [s for s in names if callable(getattr(obj, s))]

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


Re: problem with str()

2007-03-15 Thread Larry Bates
7stud wrote:
> I can't get the str() method to work in the following code(the last
> line produces an error):
> 
> 
> class test:
> """class test"""
> def __init__(self):
> """I am init func!"""
> self.num = 10
> self.num2 = 20
> def someFunc(self):
> """I am someFunc in test!"""
> print "hello"
> 
> 
> obj = test()
> obj.someFunc()
> names = dir(obj)
> print names
> 
> methodList = [str for str in names if callable(getattr(obj, str))]
> print methodList
> 
> x = getattr(obj, methodList[0]).__doc__
> print x
> print type(x)
> print str(getattr(obj, methodList[0]).__doc__)
> ===
> 
> Here is the output:
> 
> $ python test1.py
> hello
> ['__doc__', '__init__', '__module__', 'num', 'num2', 'someFunc']
> ['__init__', 'someFunc']
> I am init func!
> 
> Traceback (most recent call last):
>   File "test1.py", line 23, in ?
> print str(getattr(obj, methodList[0]).__doc__)
> TypeError: 'str' object is not callable
> 
> This is part of some code in Diving Into Python,Chapter 4.  In case a
> function doesn't have a __doc__ string, and therefore __doc__ returns
> None, the code needs to convert each __doc__ to a string so that the
> result is guaranteed to be a string.
> 

You masked the built-in str method in your list comprehension.

Try changing to:

methodList = [s for s in names if callable(getattr(obj, str))]

I'll bet it will work then.

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


Re: problem with str()

2007-03-15 Thread kyosohma
On Mar 15, 2:49 pm, "7stud" <[EMAIL PROTECTED]> wrote:
> I can't get the str() method to work in the following code(the last
> line produces an error):
>
> 
> class test:
> """class test"""
> def __init__(self):
> """I am init func!"""
> self.num = 10
> self.num2 = 20
> def someFunc(self):
> """I am someFunc in test!"""
> print "hello"
>
> obj = test()
> obj.someFunc()
> names = dir(obj)
> print names
>
> methodList = [str for str in names if callable(getattr(obj, str))]
> print methodList
>
> x = getattr(obj, methodList[0]).__doc__
> print x
> print type(x)
> print str(getattr(obj, methodList[0]).__doc__)
> ===
>
> Here is the output:
>
> $ python test1.py
> hello
> ['__doc__', '__init__', '__module__', 'num', 'num2', 'someFunc']
> ['__init__', 'someFunc']
> I am init func!
> 
> Traceback (most recent call last):
>   File "test1.py", line 23, in ?
> print str(getattr(obj, methodList[0]).__doc__)
> TypeError: 'str' object is not callable
>
> This is part of some code in Diving Into Python,Chapter 4.  In case a
> function doesn't have a __doc__ string, and therefore __doc__ returns
> None, the code needs to convert each __doc__ to a string so that the
> result is guaranteed to be a string.

Your string comprehension over wrote the str built-in method, turning
it into a variable. If you just type "str" (without the quotes) into
the interpreter, it'll spit out 'someFunc'. Thus, you cannot use str
as the iterator in your code:

methodList = [str for str in names if callable(getattr(obj, str))]

instead, do something like this:

methodList = [i for i in names if callable(getattr(obj, i))]

Have fun!

Mike

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


Re: problem with str()

2007-03-15 Thread Terry Reedy

"7stud" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
|I can't get the str() method to work in the following code(the last
| line produces an error):

If you 'print str' here

| methodList = [str for str in names if callable(getattr(obj, str))]

and again here, you will see the problem; you have reassigned the name 
'str' to something else by using it in the list comp.  Hence the advice to 
never reuse
builtin names unless you mean to lose access to the builtin object.

|print str(getattr(obj, methodList[0]).__doc__)

Here I presume you want the builtin function.  Too bad... ;-)

Terry Jan Reedy



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


Re: New Chess Module

2007-03-15 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> written in Python, it's not blazingly fast...but Kasparov
> doesn't even look at 2k nodes per second, does he? ;-)

Wow, cool.  Out of curiosity how many nodes per second does it look
at?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with str()

2007-03-15 Thread 7stud
Sheesh! You would think that after looking at every inch of the code
for way too many hours, at some point that would have poked me in the
eye.

Thanks all.

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


Re: Tkinter menu toplevel or frame

2007-03-15 Thread Matimus
> Please tell me is here anything that I should change.

The way you have written it, master _must_ be a Toplevel object. So,
maybe parent is the correct name, but it doesn't really matter.

As a side note, there is no reason for this class to inherit Frame.
Aside from packing and sizing the frame, you appear to do nothing else
with it. You could just as easily inherit from object. You should
never make a custom widget that packs itself anyway. A frame object
should act like a frame. What you have made looks more like what I
would call an application class. If you are trying to make a Menu, I
would inherit from that instead.

As an application class (you will still need the new,save... methods
to be defined):

class MyApp(object):
def __init__(self, master=None):
if master:
self.master = master
else:
self.master = Tk()

 frame = Frame(master, width=200, height=200)
 frame.pack(fill=BOTH, expand=YES)

 self.makeMenuBar()

 def makeMenuBar(self):
 self.menubar = Menu(self.master)
 self.master.config(menu=self.menubar)

 pulldown = Menu(self.menubar, tearoff=0)
 pulldown.add_command(label='New', command=self.new)
 pulldown.add_command(label='Open', command=self.onOpen)
 pulldown.add_command(label='Save', command=self.save)
 pulldown.add_command(label='Save As', command=self.saveas)
 pulldown.add_separator()
 pulldown.add_command(label='Exit', command=self.onExit)
 self.menubar.add_cascade(label='File', underline=0,
menu=pulldown)

A menu class (this is untested, but it is close to how I would do it):

class MyMenu(Menu):
def __init__(self, master=None, **kwargs):
Menu.__init__(self, master, **kwargs):
self.master = master

# This is equivalent to self packing, do it outiside of the
widget
# self.master.config(menu=self.menubar)

pulldown = Menu(self, tearoff=0)
pulldown.add_command(label='New', command=self.new)
pulldown.add_command(label='Open', command=self.onOpen)
pulldown.add_command(label='Save', command=self.save)
pulldown.add_command(label='Save As', command=self.saveas)
pulldown.add_separator()
pulldown.add_command(label='Exit', command=self.onExit)
self.add_cascade(label='File', underline=0, menu=pulldown)

You can use this in the application class:

class MyApp(object):
def __init__(self, master=None):
if master:
self.master = master
else:
self.master = Tk()

 self.menubar = MyMenu(self.master)
 self.master.config(menu=self.menubar)

 frame = Frame(master, width=200, height=200)
 frame.pack(fill=BOTH, expand=YES)




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


Re: dict.items() vs dict.iteritems and similar questions

2007-03-15 Thread Duncan Booth
Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:

> In <[EMAIL PROTECTED]>, skip wrote:
> 
>> Are you sure?  There's no guarantee that an iterator will terminate:
>> 
>> len(list(itertools.cycle(range(10
> 
> You have infinite memory?  ;-)

Strangely, Skip's example is exactly the one I tested before posting my 
claim that it would terminate.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New Chess Module

2007-03-15 Thread shatranjchess
On Mar 15, 4:46 pm, Paul Rubin  wrote:
> [EMAIL PROTECTED] writes:
> > written in Python, it's not blazingly fast...but Kasparov
> > doesn't even look at 2k nodes per second, does he? ;-)
>
> Wow, cool.  Out of curiosity how many nodes per second does it look
> at?

depends on your processor speed...on a recent machine (~2.3GHz)
I can get about 2k nps without the psyco boost...but my goal was not
to beat the compiled programs with fast code.  I'd like to develop a
strong program with good evaluation and move ordering.  And perhaps
try search methods other than alphabeta.  Using bitboards should
make the first part easier and using python should help with the
second
part.

--Sam

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


Re: most complete xml package for Python?

2007-03-15 Thread Paul Boddie
Diez B. Roggisch wrote:
> metaperl schrieb:
> >
> > Well, I'm not a troll. And I am now even less impressed with
> > ElementTree. It does not preserve the document but reforms it in
> > certain cases.
> >
> > 
> >
> > gets rewritten as
> >
> > 
> >
> > which leads to problems when embedding Dojo Rich Text Editors.
>
> Beside the fact that this is a problem of browsers (which won't help you
> much, as you have to deal with this somehow, blaming browsers alone
> isn't solving problems I'm just too aware of), I wonder: which XML
> framework _does_ preserve such tags?

I can't remember exactly how I solved this within an XML/XSLT-heavy
Java-based framework, mostly to satisfy Internet Explorer if I
remember correctly, but it does lead to some fairly inelegant hacks.
Something like this might work:



I note that such things are mentioned here (the first search result
for "CDATA" when I tried):

http://www.w3schools.com/xml/xml_cdata.asp

Paul

P.S. I'm off to fix CDATA support in libxml2dom, but I'm sure lxml
supports CDATA. Not sure about Amara, though. ;-)

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


Re: Using wildcards with Popen in the Subprocess module

2007-03-15 Thread William Hudspeth
Hello Mike,

Thanks for responding. I need to pass multiple filenames to an
executable. The filenames are similar to one another, but differ only
slightly, hence the use of the wildcard. The executable works well from
the command line if I pass in a wildcard filename, but Popen can't
expand the wildcard.

>From command line:
% command /path_to_files/filename*.doc

With Popen:
var1="/path_to_files/filnames*.doc"
result=Popen(["command",var1]).wait()

Thanks, I will look into the os.system route.

Bill

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


Python shell on mac os x

2007-03-15 Thread Bert Heymans
Hi!

I'm using iTerm on the mac the keymapping isn't right. On Linux and
Windows it's really nice to be able to hit up to get the previous
command. Does anyone know a way to get the Pyhton shell to work like
on other systems, I always get this when I hit the direction keys:

>>> ^[OA^[OC^[OD

I've been looking for the correct mappings but can't find a proper
reference online nor what the Python shell expects. Any help would be
greatly appreciated! Hints/suggestions on keywords to use in a search
on Google are always welcome :) I don't know where to begin looking
for this kind of information.

kind regards,

- Bert Heymans

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


Re: command line arguments using subprocess

2007-03-15 Thread Gabriel Genellina
En Wed, 14 Mar 2007 16:51:04 -0300, Jim <[EMAIL PROTECTED]> escribió:

> I'm trying to use subprocess to drive a Perl script.  I'm having some
> trouble getting it to spot the command line arguments.  Basically, if
> I call subprocess(args).wait() where args has a second item, I can't
> convince the Perl script to see it.  Below is a pretty small example.
> If someone could get me unstuck, I'd appreciate it.  (Python 2.4.4c1,
> if that helps.)
> args=['/home/ftpmaint/test.pl','a']
> p=subprocess.Popen(args,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,cwd=os.getcwd())

Try with 'perl' explicitely as first argument, or without shell=True; if  
cwd is the current dir, there is no need to include it.

-- 
Gabriel Genellina

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


Re: Python shell on mac os x

2007-03-15 Thread Greg Donald
On 15 Mar 2007 14:56:13 -0700, Bert Heymans <[EMAIL PROTECTED]> wrote:
> >>> ^[OA^[OC^[OD

Is your python built with readline support?

Also, you might check out iPython.


-- 
Greg Donald
http://destiney.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: os.path.isfile with *.tar.gz

2007-03-15 Thread Bruno Desthuilliers
> Boudreau, Emile wrote:
(snip)
>> I have tried variations of: os.path.isfile( os.path.join("C:\\temp\\", 
>> "rqp-win32-app", "*.tar.gz"))

As a side note, the whole point of os.path is to help writing portable 
code. So passing an os.specific path componant is somewhat counter 
productive !-)

(snip answer)

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


lock problem

2007-03-15 Thread Ritesh Raj Sarraf
Hi,

I think there is some lock problem.
Let me show the code first

import os
import sys
import string
import tempfile

import threading
import Queue

from time import sleep

_hostname = None
_username = None
_password = None
_ldapDataFile = None

if _hostname is None or _username is None or _password is None or _ldapDataFile
is None:
sys.stderr.write("Please first set the credentials properly.\n")
sys.exit(1)

_ldapPreCommand = 'ldapsearch -LLL -z 0 "(Sn='
_ldapPostCommand = '*)" -h ' + _hostname + ' -x -D "'  + _username + '" -b
Cn=users,DC=hq,DC=domain,DC=com' + " -w " + _password
NumberOfThreads = 5


#char = 's'
#ldapCommand = _ldapPreCommand + char + _ldapPostCommand
#x = os.system(ldapCommand)
#if x == 1024:
#print "I'm in the exception"
#print x
#sys.exit(1)

ldap_attributes =
['dn:', 'cn:', 'sn:', 'l:', 'st:', 'title:', 'description:', 'postalCode:', 
'telephoneNumber:', 'facsimileTelephoneNumber:',
   'givenName:', 'mail:', 'homePhone:', 'mobile:', 'pager:']

try:
writeFile = open(_ldapDataFile, 'w')
except IOError:
sys.stderr.write("Couldn't open file %s to write.\n" % (writeFile) )
sys.exit(1)

#print "Writing data to %s\n" % (temp_file_name)

def RecordFetcher(char):
(temp_file_fd, temp_file_name) = tempfile.mkstemp()
os.environ['__kabc_ldap'] = temp_file_name
sleep(5) #Let's not thrash the exchange server ;-)
ldapCommand = _ldapPreCommand + char + _ldapPostCommand
if os.system(ldapCommand + "> $__kabc_ldap") != 0:
sys.stderr.write("Couldn't execute the command %s\n" %
(ldapCommand) )
sys.exit(1)
#temp_file_name = "/tmp/tmpnhYrps"
try:
readFile = open(temp_file_name, 'r')
except IOError:
sys.stderr.write("Couldn't open file %s to read.\n" % (readFile) )
sys.exit(1)

for record in readFile.readlines():
if record.startswith(' '): # Remove the junk
pass
record = string.rstrip(record, "\n")
for attrib in ldap_attributes:
if record.startswith(attrib):
try:
FileLock.acquire(True)

if ldap_attributes[0] == attrib: #This attribute is
common/mandatory in all records, so we can rely on it
   writeFile.write("\n")
   
writeFile.write(record)
writeFile.write("\n")

finally:
writeFile.flush()
FileLock.release()
break
readFile.close()
os.remove(temp_file_name)
#writeFile.write("\n")


def run(request, response, func=RecordFetcher):
while 1:
item = request.get()
if item is None:
break
(char, subChar) = item

response.put(func(char+subChar) )

# Start from here
requestQueue = Queue.Queue()
responseQueue = Queue.Queue()

FileLock = threading.Lock()

thread_pool = [
   threading.Thread(
target=run,
args=(requestQueue, responseQueue)
)
   for i in range(NumberOfThreads)
   ]

for t in thread_pool: t.start()

for char in string.lowercase:
# I know this is ugly. Too many cycles
# But ldapsearch or exchange is restricting, the query max result limit is
1000
for subChar in string.lowercase:
requestQueue.put( (char, subChar) )

for t in thread_pool: requestQueue.put(None)

for t in thread_pool: t.join()

writeFile.close()


=

Now as per the above code, "aa" is the first string which will be executed in
Thread-1. In my query to the ldap server, I am getting a record which matches
the "aa" string. I've verified it by putting a breakpoint and checking the
value.

The problem is that when I run the program manually, I don't get the data from
the first thread i.e. of the string "aa".

I'm not sure if there's something wrong in the code mentioned above or is it
really a lock problem.

Can somebody please help about where I'm doing any mistake ?

Thanks,
Ritesh
-- 
Ritesh Raj Sarraf
RESEARCHUT - http://www.researchut.com
"Necessity is the mother of invention."
"Stealing logic from one person is plagiarism, stealing from many is research."
"The great are those who achieve the impossible, the petty are those who
cannot - rrs"

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


Re: what are Python equivalent to MATLAB persistent or C++ static?

2007-03-15 Thread sturlamolden
On Mar 15, 8:09 am, "dmitrey" <[EMAIL PROTECTED]> wrote:
> Thank you in advance,
> Dmitrey

First, "static" can mean at least three different things in C++:

static int myvar1;

void foobar() {
   static int myvar2;
}

class foobar {
   static int myvar3;
}

I assume you are thinking about the second case above - a static
variable inside a function. You can achieve this by binding an
attribute to the function, use a closure, or declare a class
callable.

def foobar1():
   if not 'mystatic' in dir(foobar): foobar.mystatic = 0
   foobar.mystatic += 1
   return foobar.mystatic

def foobar2():
   mystatic = 0
   def closure():
  mystatic += 1
  return mystatic
   return closure

class foobar3:
   mystatic = 0
   def __call__():
  foobar.mystatic += 1
  return foobar.mystatic

Usage:

for i in xrange(0,10): print foobar1()

myclosure = foobar2()
for i in xrange(0,10): print myclosure()

myfoobar3 = foobar3()
for i in xrange(0,10): print myfoobar3()









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


  1   2   >