Re: Tkinter Radio button on the second window

2008-09-05 Thread Dream
Thank you very much.

Now I use "window2=Toplevel()" to create the second window, and it
works well.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ?

2008-09-05 Thread Terry Reedy



Marco Bizzarri wrote:


I understand that Python is a balance between different forces (like
any software object around the world) and I'm simply asking some
pointers to the discussion leading to this balance.


The original decisions by Guido were nearly 20 years ago and other 
discussions are scattered through the archive of this and the py-dev 
list.  But here is a pointer.  Why go through the trouble of writing 
functions that will set, get, and delete an attribute and the trouble of 
calling those functions when you can use Python's existing syntax to do 
it directly?  More particularly, why would/should Guido force the 
combersome indirection and time-penalty for writing, reading, and 
execution on *every* Python programmer?


Of course, from my viewpoint, and for my usage,languages that do so 
force are obnoxious.


tjr

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


Re: Creating directories

2008-09-05 Thread david wright
--- On Fri, 9/5/08, srinivasan srinivas <[EMAIL PROTECTED]> wrote:

> From: srinivasan srinivas <[EMAIL PROTECTED]>
> Subject: Creating directories
> To: [email protected]
> Date: Friday, September 5, 2008, 1:44 AM
> Can someone tell me is there any module available to create
> directories??
> 
> I tried os, tempfile.
> I was facing some issues with os.mkdir(). The mode setting
> was not proper with this method.
> 
> I created the directory 'stdin' with '0700'
> mode using os.mkdir() method.
> $> ls -alR stdin/
> stdin/:
> total 12
> drwx--S---   2 munisams munisams 4096 Sep  3 02:00 .
> What is that 'S' in the group permission field??
> 

this appears to be working, what where you expecting? 

"An upper case "S" means there is no executable permission, but the set group 
id function is active- that is, a file in this directory will belong to the 
same group id as the directory itself."


If the parent directory has the set group id set, the child will as well.
i.e.
[EMAIL PROTECTED]:~$ cd /tmp/
[EMAIL PROTECTED]:/tmp$ mkdir test
[EMAIL PROTECTED]:/tmp$ ls -ld test
drwxr-xr-x 2 dwright dwright 1024 2008-09-04 05:19 test
[EMAIL PROTECTED]:/tmp$ ls -la test
drws--  2 dwright dwright 1024 2008-09-04 05:19 .
drwxrwxrwt 13 rootroot3072 2008-09-04 05:19 ..
[EMAIL PROTECTED]:/tmp$ chmod 2700 test
[EMAIL PROTECTED]:/tmp$ ls -la test
total 4
drwx--S---  2 dwright dwright 1024 2008-09-04 05:19 .
drwxrwxrwt 13 rootroot3072 2008-09-04 05:19 ..

[EMAIL PROTECTED]:~$ python
Python 2.4.4 
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.mkdir('/tmp/test/TEST', 0700)

[EMAIL PROTECTED]:/tmp$ ls -la test
total 5
drwx--S---  3 dwright dwright 1024 2008-09-04 05:20 .
drwxrwxrwt 13 rootroot3072 2008-09-04 05:19 ..
drwx--S---  2 dwright dwright 1024 2008-09-04 05:20 TEST

[EMAIL PROTECTED]:/tmp$ ls -la test/TEST
total 2
drwx--S--- 2 dwright dwright 1024 2008-09-04 05:20 .
drwx--S--- 3 dwright dwright 1024 2008-09-04 05:20 ..

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


derived classes and __getattr__

2008-09-05 Thread Alexandru Moșoi
i'm facing the following problem:

class Base(object):
  def __getattr__(self, attr): return lambda x: attr + '_' + x

def dec(callable):
  return lambda *args: 'dec_' + callable(*args)

class Derived(Base):
   what_so_ever = dec(Base.what_so_ever) # wrong, base doesn't have
what_so_ever
   mumu = dec(Base.mumu)  # wrong, base
doesn't have mumu

any idea how to do this?
--
http://mail.python.org/mailman/listinfo/python-list


[ANN] final 2008 Python courses, San Francisco

2008-09-05 Thread wesley chun
Need to get up-to-speed with Python as quickly as possible? Come join
me, Wesley Chun, author of Prentice-Hall's bestseller "Core Python
Programming," for another comprehensive intro course plus a 1-day
Internet programming course coming up in November in beautiful
Northern California! I look forward to meeting you!

(Comprehensive) Introduction to Python
Mon-Wed, 2008 Nov 10-12, 9am-5pm

Internet Programming with Python
Sat, 2008 Nov 15, 9am-5pm

courses can be taken separately or combined for a discounted price.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(COMPREHENSIVE) INTRODUCTION TO PYTHON

Although this course may appear to those new to Python, it is also
perfect for those who have tinkered with it and want to "fill in the
gaps" and/or want to get more in-depth formal training.  It combines
the best of both an introduction to the language as well as a "Python
Internals" training course.

We will immerse you in the world of Python in only a few days, showing
you more than just its syntax (which you don't really need a book to
learn, right?). Knowing more about how Python works under the covers,
including the relationship between data objects and memory management,
will make you a much more effective Python programmer coming out of
the gate. 3 hands-on labs each day will help hammer the concepts home.

Come find out why Google, Yahoo!, Disney, ILM/LucasFilm, VMware, NASA,
Ubuntu, YouTube, and Red Hat all use Python. Users supporting or
jumping to Plone, Zope, TurboGears, Pylons, Django, Google App Engine,
Jython, IronPython, and Mailman will also benefit!

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
INTERNET PROGRAMMING WITH PYTHON

This is a one-day course with lecture and lab exposing attendees to
FOUR distinct areas of Internet programming:

* Network Programming using Sockets -- we introduce client/server
architecture and how to program sockets using Python.

* Internet Client Programming -- we learn how to use Python's standard
library to create FTP, NNTP, POP3, and SMTP clients

* Web Programming -- before you jump on all the web framework
bandwagons, it's a good idea to learn basics and the basis of how all
web servers deliver dynamic content back to the client browser to
prepare you better when jumping to a full-stack web framework

* Intro to Django -- a lightweight introduction to the Django web
framework including whipping up a very simple blog application in
20min!

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

WHERE: near the San Francisco Airport (SFO/San Bruno), CA, USA

WEB:   http://cyberwebconsulting.com (click "Python Training")

FLYER: http://starship.python.net/crew/wesc/flyerPP1combo.pdf

LOCALS: easy freeway (101/280/380) with lots of parking plus public
transit (BART and CalTrain) access via the San Bruno stations, easily
accessible from all parts of the Bay Area

VISITORS: free shuttle to/from the airport, free high-speed internet,
free breakfast and regular evening receptions; fully-equipped suites

See website for costs, venue info, and registration.  Discounts are
available for multiple registrations as well as for teachers/students.

Hope to see you there!
-- wesley

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
 http://corepython.com

"Python Web Development with Django", Addison Wesley, (c) 2008
http://withdjango.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
--
http://mail.python.org/mailman/listinfo/python-list


atomic section in code

2008-09-05 Thread Ahmad Humayun
Hi there,

I need to create an atomic section in Python code i.e. there is no
context switch to any other thread during the running of that piece of
code. Would would do the trick?


thanks,

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


Re: max(), sum(), next()

2008-09-05 Thread Manu Hack
On Thu, Sep 4, 2008 at 4:25 PM, castironpi <[EMAIL PROTECTED]> wrote:
> On Sep 4, 2:42 pm, [EMAIL PROTECTED] wrote:
>> David C. Ullrich:
>>
>> > At least in mathematics, the sum of the elements of
>> > the empty set _is_ 0, while the maximum element of the
>> > empty set is undefined.
>>
>> What do you think about my idea of adding that 'default' argument to
>> the max()/min() functions?
>>
>> Bye,
>> bearophile
>
> For max and min, why can't you just add your argument to the set
> itself?
>
> The reason max([]) is undefined is that max( S ) is in S.

It makes sense.

>The reason sum([]) is 0 is that sum( [ x ] ) - x = 0.

It doesn't make sense to me.  What do you set x to?
--
http://mail.python.org/mailman/listinfo/python-list


Re: derived classes and __getattr__

2008-09-05 Thread Peter Otten
Alexandru Moșoi wrote:

> i'm facing the following problem:
> 
> class Base(object):
>   def __getattr__(self, attr): return lambda x: attr + '_' + x
> 
> def dec(callable):
>   return lambda *args: 'dec_' + callable(*args)
> 
> class Derived(Base):
>what_so_ever = dec(Base.what_so_ever) # wrong, base doesn't have
> what_so_ever
>mumu = dec(Base.mumu)  # wrong, base
> doesn't have mumu
> 
> any idea how to do this?

__getattr__() is defined in the class to create instance attributes on the
fly. If you want class attributes you have to put the __getattr__() method
into the class of the class, or "metaclass":

class Base(object):
class __metaclass__(type):
def __getattr__(self, attr):
return lambda self, x: attr + '_' + x

def dec(callable):
return lambda *args: 'dec_' + callable(*args)

class Derived(Base):
   what_so_ever = dec(Base.what_so_ever)

d = Derived()
print d.what_so_ever("42")

I don't see how you can turn this into something useful...

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

Re: derived classes and __getattr__

2008-09-05 Thread Fredrik Lundh

Alexandru Mos,oi wrote:


i'm facing the following problem:

class Base(object):
  def __getattr__(self, attr): return lambda x: attr + '_' + x

def dec(callable):
  return lambda *args: 'dec_' + callable(*args)

class Derived(Base):
   what_so_ever = dec(Base.what_so_ever) # wrong, base doesn't have
what_so_ever
   mumu = dec(Base.mumu)  # wrong, base
doesn't have mumu

any idea how to do this?


ever thought of using Python to write Python programs?



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


Re: atomic section in code

2008-09-05 Thread Fredrik Lundh

Ahmad Humayun wrote:


I need to create an atomic section in Python code i.e. there is no
context switch to any other thread during the running of that piece of
code. Would would do the trick?


use a lock, and make sure that anyone that needs access to the shared 
state you're manipulating in that section uses the same lock.


lock = threading.Lock() # or RLock() etc [1]

with lock:
section

this only works if everyone honors the lock, of course; there's no way 
in Python to lock out non-cooperating external threads.




1) see http://effbot.org/zone/thread-synchronization.htm

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


Re: ctypes error on Windows

2008-09-05 Thread Thomas Heller
Fredrik Lundh schrieb:
> Fredrik Lundh wrote:
> 
>>> I do have the tidy.dll installed (if I didn't, I couldn't even import 
>>> the tidy module).
>> 
>> typing the following into the Python interpreter might give you some 
>> more clues:
>> 
>> >>> import _tidy
>> >>> _tidy.__file__
>> >>> dir(_tidy)
> 
> or not, since ctypes is involved.
> 
> have you checked for multiple copies of tidy.dll?
> 
> if you have MSVC on your machine, try using "dumpbin /exports" on the 
> DLL to check that it really exports the symbols the binding expects.
> 

Or use dependencywalker (google for it).

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


Re: max(), sum(), next()

2008-09-05 Thread Ken Starks

David C. Ullrich wrote:
In article 
<[EMAIL PROTECTED]>,

 Mensanator <[EMAIL PROTECTED]> wrote:


On Sep 3, 2:18 pm, Laszlo Nagy <[EMAIL PROTECTED]> wrote:

[EMAIL PROTECTED] wrote:

Empty Python lists [] don't know the type of the items it will
contain, so this sounds strange:

sum([])

0
Because that [] may be an empty sequence of someobject:

You are right in that sum could be used to sum arbitrary objects.
However, in 99.99% of the cases, you will be summing numerical values.
When adding real numbers, the neutral element is zero. ( X + 0 = X) It
is very logical to return zero for empty sequences.

No it isn't. Nothing is not 0, check with MS-Access, for instance:

Null + 1 returns Null. Any arithmetic expression involving a
Null evaluates to Null. Adding something to an unknown returns
an unknown, as it should.

It is a logical fallacy to equate unknown with 0.


Which has nothing to do with the "right" value for an
empty sum. If they hear about what you said here in
sci.math they're gonna kick you out - what do you
imagine the universally accepted value of \sum_{j=1}^0 
is?




For example, the water table elevation in ft above Mean Sea Level
is WTE = TopOfCasing - DepthToWater.

TopOfCasing is usually known and constant (until resurveyed).
But DepthToWater may or may not exist for a given event (well
may be covered with fire ants, for example).

Now, if you equate Null with 0, then the WTE calculation says
the water table elevation is flush with the top of the well,
falsely implying that the site is underwater.

And, since this particular site is on the Mississippi River,
it sometimes IS underwater, but this is NEVER determined by
water table elevations, which, due to the CORRECT treatment
of Nulls by Access, never returns FALSE calculations.


sum([])

0

is a bug, just as it's a bug in Excel to evaluate blank cells
as 0. It should return None or throw an exception like sum([None,1])
does.


Same way, if we would have a prod() function, it should return one for
empty sequences because X*1 = X. The neutral element for this operation
is one.

Of course this is not good for summing other types of objects. But how
clumsy would it be to use

sum( L +[0] )

or

if L:
value = sum(L)
else:
value = 0

instead of sum(L).

Once again, this is what sum() is used for in most cases, so this
behavior is the "expected" one.

Another argument to convince you: the sum() function in SQL for empty
row sets returns zero in most relational databases.

But of course it could have been implemented in a different way... I
believe that there have been excessive discussions about this decision,
and the current implementation is very good, if not the best.

Best,

Laszlo




I suppose the following is accepted by statisticians. Here,
for reference, here is the what the 'R' statistic package
says on the subject 9if you type 'help(sum)'



Sum of Vector Elements
Description
sum returns the sum of all the values present in its arguments.

Usage
sum(..., na.rm = FALSE)

Arguments
... numeric or complex or logical vectors.
na.rm logical. Should missing values be removed?

Details
This is a generic function: methods can be defined for it directly or 
via the Summary group generic. For this to work properly, the arguments 
... should be unnamed, and dispatch is on the first argument.


If na.rm is FALSE an NA value in any of the arguments will cause a value 
of NA to be returned, otherwise NA values are ignored.


Logical true values are regarded as one, false values as zero. For 
historical reasons, NULL is accepted and treated as if it were integer(0).


Value
The sum. If all of ... are of type integer or logical, then the sum is 
integer, and in that case the result will be NA (with a warning) if 
integer overflow occurs. Otherwise it is a length-one numeric or complex 
vector.

NB: the sum of an empty set is zero, by definition.

References
Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S 
Language. Wadsworth & Brooks/Cole.

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


Re: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ?

2008-09-05 Thread Marco Bizzarri
On Thu, Sep 4, 2008 at 7:15 PM, Timothy Grant <[EMAIL PROTECTED]> wrote:
>
> I think the most obvious solution to the problem is effective unit
> tests. If you type "a.y =1" and have a test that asserts a.x == 1 then
> you would quite quickly discover that you made a typo.
>
>
> --
> Stand Fast,
> tjg. [Timothy Grant]
>

Right; that is one of the things I try to do to avoid this sort of problems.

-- 
Marco Bizzarri
http://notenotturne.blogspot.com/
http://iliveinpisa.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: configure kdevelop for python

2008-09-05 Thread Kushal Das
On Sunday 31 August 2008 01:59:11 pm Sindhu wrote:
> am a newbie to python language and kdevelop, so i would like to know
> how to configure kdevelop for python programming? complete with a
> debugger?
Read here http://www.kde.in/index.php/Getting_started_with_KDevelop

Kushal
-- 
Fedora Ambassador, India
http://kushaldas.in
http://dgplug.org (Linux User Group of Durgapur)

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


Re: derived classes and __getattr__

2008-09-05 Thread Alexandru Mosoi
On Sep 5, 11:47 am, Peter Otten <[EMAIL PROTECTED]> wrote:
> Alexandru Moșoi wrote:
> > i'm facing the following problem:
>
> > class Base(object):
> >   def __getattr__(self, attr): return lambda x: attr + '_' + x
>
> > def dec(callable):
> >   return lambda *args: 'dec_' + callable(*args)
>
> > class Derived(Base):
> >    what_so_ever = dec(Base.what_so_ever) # wrong, base doesn't have
> > what_so_ever
> >    mumu = dec(Base.mumu)                          # wrong, base
> > doesn't have mumu
>
> > any idea how to do this?
>
> __getattr__() is defined in the class to create instance attributes on the
> fly. If you want class attributes you have to put the __getattr__() method
> into the class of the class, or "metaclass":
>
> class Base(object):
>     class __metaclass__(type):
>         def __getattr__(self, attr):
>             return lambda self, x: attr + '_' + x
>
> def dec(callable):
>     return lambda *args: 'dec_' + callable(*args)
>
> class Derived(Base):
>    what_so_ever = dec(Base.what_so_ever)
>
> d = Derived()
> print d.what_so_ever("42")
>
> I don't see how you can turn this into something useful...
>
> Peter

10x. it works. however I have another small problem. now,
d.third('blah') doesn't work because instance d doesn't have 'third'
attribute. I was expecting derived class to inherit the metaclass as
well, but it didn't.
--
http://mail.python.org/mailman/listinfo/python-list

Re: "Full" element tag listing possible with Elementtree?

2008-09-05 Thread Stefan Behnel
[EMAIL PROTECTED] wrote:
> I have the unenviable task of turning about 20K strangely formatted
> XML documents from different sources into something resembling a
> clean, standard, uniform format.  I like Elementtree and have been
> using it to step through the documents to get a feel for their
> structure.  .getiterator() gives me a depth-first traversal that
> eliminates the hierarchy of the elements.  What I'd like is to be able
> to traverse elements while keeping track of ancestors, and print out
> the full structure of all of an ancestor's nodes as I arrive at each
> node.

Try lxml.etree. It's an extended re-implementation of ElementTree based on
libxml2. Amongst tons of other features, it provides its Elements with a
getparent() method and allows you to iterate over their ancestors (and other
XPath axes), or to iterate over a parsed document in an iterparse-like fashion
(called iterwalk).

http://codespeak.net/lxml/

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


Re: derived classes and __getattr__

2008-09-05 Thread Peter Otten
Alexandru  Mosoi wrote:

> On Sep 5, 11:47 am, Peter Otten <[EMAIL PROTECTED]> wrote:
>> Alexandru Moșoi wrote:
>> > i'm facing the following problem:
>>
>> > class Base(object):
>> > def __getattr__(self, attr): return lambda x: attr + '_' + x
>>
>> > def dec(callable):
>> > return lambda *args: 'dec_' + callable(*args)
>>
>> > class Derived(Base):
>> > what_so_ever = dec(Base.what_so_ever) # wrong, base doesn't have
>> > what_so_ever
>> > mumu = dec(Base.mumu)                          # wrong, base
>> > doesn't have mumu
>>
>> > any idea how to do this?
>>
>> __getattr__() is defined in the class to create instance attributes on
>> the fly. If you want class attributes you have to put the __getattr__()
>> method into the class of the class, or "metaclass":
>>
>> class Base(object):
>> class __metaclass__(type):
>> def __getattr__(self, attr):
>> return lambda self, x: attr + '_' + x
>>
>> def dec(callable):
>> return lambda *args: 'dec_' + callable(*args)
>>
>> class Derived(Base):
>> what_so_ever = dec(Base.what_so_ever)
>>
>> d = Derived()
>> print d.what_so_ever("42")
>>
>> I don't see how you can turn this into something useful...
>>
>> Peter
> 
> 10x. it works. however I have another small problem. now,
> d.third('blah') doesn't work because instance d doesn't have 'third'
> attribute. I was expecting derived class to inherit the metaclass as
> well, but it didn't.

That has nothing to do with inheritance:

>>> type(Derived)


If Python doesn't find an attribute in the instance it looks it up in the
class but not in the metaclass:

>>> Base.third
 at 0x2b5f8028aa28>
>>> Base().third
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'Base' object has no attribute 'third'

I think you should go back to the drawing board now and look for a simpler
approach to solve your actual problem...

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

Re: derived classes and __getattr__

2008-09-05 Thread Michele Simionato
On Sep 5, 11:46 am, Alexandru  Mosoi <[EMAIL PROTECTED]> wrote:
> I have another small problem. now,
> d.third('blah') doesn't work because instance d doesn't have 'third'
> attribute. I was expecting derived class to inherit the metaclass as
> well, but it didn't.

Yep, it is explained here: 
https://www.ibm.com/developerworks/linux/library/l-pymeta2/
It would help if you told us the real problem you are trying to solve.
--
http://mail.python.org/mailman/listinfo/python-list


Re: atomic section in code

2008-09-05 Thread Ahmad Humayun
On Sep 5, 1:59 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> Ahmad Humayun wrote:
> > I need to create an atomic section in Python code i.e. there is no
> > context switch to any other thread during the running of that piece of
> > code. Would would do the trick?
>
> use a lock, and make sure that anyone that needs access to the shared
> state you're manipulating in that section uses the same lock.
>
>      lock = threading.Lock() # or RLock() etc [1]
>
>      with lock:
>          section
>
> this only works if everyone honors the lock, of course; there's no way
> in Python to lock out non-cooperating external threads.
>
> 
>
> 1) seehttp://effbot.org/zone/thread-synchronization.htm

Thats true, but this will ensure mutual exclusion; not atomicity

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


newbie question: how to run a python file if it is in a package

2008-09-05 Thread neoedmund
for example:

X.py is in aaa.bbb and it has a line like "import aaa.bbb.Y"
how can I run X.py avoiding it saying such like "ImportError: No
module named aaa.bbb"?

Is all runnable script must be in the default package?

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


Re: atomic section in code

2008-09-05 Thread Diez B. Roggisch

Ahmad Humayun schrieb:

On Sep 5, 1:59 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:

Ahmad Humayun wrote:

I need to create an atomic section in Python code i.e. there is no
context switch to any other thread during the running of that piece of
code. Would would do the trick?

use a lock, and make sure that anyone that needs access to the shared
state you're manipulating in that section uses the same lock.

 lock = threading.Lock() # or RLock() etc [1]

 with lock:
 section

this only works if everyone honors the lock, of course; there's no way
in Python to lock out non-cooperating external threads.



1) seehttp://effbot.org/zone/thread-synchronization.htm


Thats true, but this will ensure mutual exclusion; not atomicity


AFAIC that kind of mutual exclusion is what atomicity is about. What 
else do you expect to happen?


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


Re: newbie question: how to run a python file if it is in a package

2008-09-05 Thread Diez B. Roggisch

neoedmund schrieb:

for example:

X.py is in aaa.bbb and it has a line like "import aaa.bbb.Y"
how can I run X.py avoiding it saying such like "ImportError: No
module named aaa.bbb"?

Is all runnable script must be in the default package?


There is no such thing as a "default package"

All imports are resolved over the "sys.path" list of directories (or eggs).

There are various ways to modify this:


 - by hand. If you know X.py lives below aaa/bbb, you can get it's
   __file__-attribute, and walk the way down two levels. Then add the
   resulting path to sys.path. All this has to be done before any
   import of aaa.bbb occurs.

 - modify the environment variable PYTHONPATH to contain the root of
   aaa.bbb before starting the script.

 - write a custom .pth-file and place it into your pythno installation.
   The pth-file will contain the above mentioned root path.

 - use setuptools to create script entry-points, and install your whole
   application either fully, or as so-called egg-link. Possibly inside
   a virtualenv. This would be my personally preferred method.

 - simply copy your wohe aaa.bbb-stuff into site-packages. Make sure you
   do that whenever you change something in your code.


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


Re: Case-insensitive string compare?

2008-09-05 Thread Maric Michaud
Le Friday 05 September 2008 08:30:44 Fredrik Lundh, vous avez écrit :
> Maric Michaud wrote:
>  > You''ll often see for loops written like this :
> >
> > for i in (e for e in iterable if predicate(e)) :
> > ...
>
> luckily, I don't.  most people, when faced with that problem, writes it
> in the obvious way:
>
> for i in iterable:
> if predicate(i):
> ...

So do I, most often, but this construct is common, I think because it makes 
clear what the for loop is iterating over, also it comes naturally once used 
to the more elaborated 

for i in (expr(e) for e in iterable if predicate(e)) :

This one is truly a gain for readability IMO, compared to :

 for i in iterable:
 i = expr(i)
 if predicate(i):

In the latter, the reader need more effort to figure out what finally "i" is 
in the loop.

>
> to avoid an extra iterator and save typing.
>

and at the cost of an extra indentation level.

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



-- 
_

Maric Michaud

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


Re: atomic section in code

2008-09-05 Thread Michele Simionato
On Sep 5, 10:59 am, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
>
> 1) seehttp://effbot.org/zone/thread-synchronization.htm

The page you link here is WAYS better than the standard documentation
of the threading module.
Generally speaking, the effbot zone contains a lot of improvements
over the standard docs
which are lacking in various areas.
I have always wondered why they are kept separated. Wouldn't be nice
to have the standard
docs integrated with the effbot docs? Are there plans in this sense
and if not, why not?

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


Re: Python and Cyrillic characters in regular expression

2008-09-05 Thread phasma
string = u"Привет"
(u'\u041f\u0440\u0438\u0432\u0435\u0442',)

string = u"Hi.Привет"
(u'Hi',)

On Sep 4, 9:53 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> phasma wrote:
> > Hi, I'm trying extract all alphabetic characters from string.
>
> > reg = re.compile('(?u)([\w\s]+)', re.UNICODE)
> > buf = re.match(string)
>
> > But it's doesn't work. If string starts from Cyrillic character, all
> > works fine. But if string starts from Latin character, match returns
> > only Latin characters.
>
> can you provide a few sample strings that show this behaviour?
>
> 

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

Re: Case-insensitive string compare?

2008-09-05 Thread Maric Michaud
Le Friday 05 September 2008 08:24:29 Fredrik Lundh, vous avez écrit :
> Maric Michaud wrote:
> > "premature optimization is the root of all evil"
>
> So is use by that statement by people who don't have the slightest idea
> about what it actually means.
>
> The full version is
>
> "We should forget about small efficiencies, say about 97% of the time:
> premature optimization is the root of all evil."
>
> Note the use of "small efficiencies".  That is, in Python, things like
> local binding, inlining, slots, lazy generation of short sequences, etc.
>   That is, things that takes time to write and reduces maintainability.
>
> It's not about having an excuse for writing crappy code with large
> inefficienies.
>
> And it's definitely not about programmers intentionally picking a dumb
> solution so they can optimize it later.
>

Yes, I'm aware of that, thanks, but Chris Rebert was proposing to alter the 
data structure in order to achieve this simple comparison, I don't think it 
fails into your concern.

>  > If the OP's proposal seems already messy, how about ths one :
>  > if lib.lower() not in ( e[0] for e in stage_map.items() ) :
>  > ...
>

Sorry, should be read :

if lib.lower() not in ( e[0] for e in stage_map.values() ) :

and it was the expression for comparison Chris's solution lead to, not a 
proposal.

> Given that your solution is just a remarkably inefficient way to write
> "lib.lower() not in stage_map", and thus doesn't solve the OP:s problem,
> I suspect you're taking the "evil" part of Hoare's dictum a few bits too
> literally.
>

I suspect you are coming to conclusions a bit quickly, without taking the pain 
of understanding the whole discussion.

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



-- 
_

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


Re: path slashes cleaning

2008-09-05 Thread Michael Wronna

Am 04.09.2008, 15:27 Uhr, schrieb Mike Driscoll <[EMAIL PROTECTED]>:


On Sep 4, 8:25 am, "Mathieu Prevot" <[EMAIL PROTECTED]> wrote:

Hi,

for scripts that take arguments, I would like to remove the trailing
slash if it's present.

Is there something else than:

a='/usr/local/lib/'
if a[-1] == '/':
  a = list(a)
  a.pop()
  ''.join(a)

Thanks,
Mathieu


How about this:

if a[-1] == '/':
a = a[:-1]

Mike


Hi, how about
a.rstrip('/')
? Michael
--
http://mail.python.org/mailman/listinfo/python-list

Re: max(), sum(), next()

2008-09-05 Thread Ken Starks

David C. Ullrich wrote:



I don't see why you feel the two should act the same.
At least in mathematics, the sum of the elements of
the empty set _is_ 0, while the maximum element of the
empty set is undefined. 


And both for good reason:

(i) If A and B are disjoint sets we certainly want to
have sum(A union B) = sum(A) + sum(B). This requires
sum(empty set) = 0.

(ii) If A is a subset of B then we should have
max(A) <= max(B). This requires that max(empty set)
be something that's smaller than everything else.
So we give up on that.


Do we give up? Really ?

From wikipedia: http://en.wikipedia.org/wiki/Empty_set
(Uses wikipedia's LaTeX notation -- I hope those interested
are OK with that )


Mathematics

[edit] Extended real numbers

Since the empty set has no members, when it is considered as a subset of 
any ordered set, then any member of that set will be an upper bound and 
lower bound for the empty set. For example, when considered as a subset 
of the real numbers, with its usual ordering, represented by the real 
number line, every real number is both an upper and lower bound for the 
empty set.[3] When considered as a subset of the extended reals formed 
by adding two "numbers" or "points" to the real numbers, namely negative 
infinity, denoted -\infty\!\,, which is defined to be less than every 
other extended real number, and positive infinity, denoted +\infty\!\,, 
which is defined to be greater than every other extended real number, then:


\sup\varnothing=\min(\{-\infty, +\infty \} \cup \mathbb{R})=-\infty,

and

\inf\varnothing=\max(\{-\infty, +\infty \} \cup \mathbb{R})=+\infty.

That is, the least upper bound (sup or supremum) of the empty set is 
negative infinity, while the greatest lower bound (inf or infimum) is 
positive infinity. By analogy with the above, in the domain of the 
extended reals, negative infinity is the identity element for the 
maximum and supremum operators, while positive infinity is the identity 
element for minimum and infimum.

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


Re: newbie question: how to run a python file if it is in a package

2008-09-05 Thread neoedmund
On Sep 5, 8:12 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> neoedmund schrieb:
>
> > for example:
>
> > X.py is in aaa.bbb and it has a line like "import aaa.bbb.Y"
> > how can I run X.py avoiding it saying such like "ImportError: No
> > module named aaa.bbb"?
>
> > Is all runnable script must be in the default package?
>
> There is no such thing as a "default package"
>
> All imports are resolved over the "sys.path" list of directories (or eggs).
>
> There are various ways to modify this:
>
>   - by hand. If you know X.py lives below aaa/bbb, you can get it's
>     __file__-attribute, and walk the way down two levels. Then add the
>     resulting path to sys.path. All this has to be done before any
>     import of aaa.bbb occurs.
>
>   - modify the environment variable PYTHONPATH to contain the root of
>     aaa.bbb before starting the script.
>
>   - write a custom .pth-file and place it into your pythno installation.
>     The pth-file will contain the above mentioned root path.
>
>   - use setuptools to create script entry-points, and install your whole
>     application either fully, or as so-called egg-link. Possibly inside
>     a virtualenv. This would be my personally preferred method.
>
>   - simply copy your wohe aaa.bbb-stuff into site-packages. Make sure you
>     do that whenever you change something in your code.
>
> Diez

thanks Diez, i think your answer is almost perfect.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Case-insensitive string compare?

2008-09-05 Thread J. Clifford Dyer
On Thu, 2008-09-04 at 18:48 -0500, Robert Dailey wrote:
> Thanks everyone for your help. I'm not opposed to using [key.lower()
> for key in stage_map] at all, I was just curious to see if there were
> any cleaner alternatives. It looks like that is what I'll be using.
> I'm not familiar with how python works internally, but coming from C++
> it seems like "remaking" the map would be slow. However, speed is not
> my main concern in my particular situation, I'm just curious to learn
> more about python.

You should be opposed to that particular solution.  You have just taken
a dictionary lookup (very fast) and turned it into a list traversal
(slow).  Even if speed isn't your main concern, this is an unnecessary
de-optimization.  You are deliberately slowing down your program to
avoid a slightly more verbose lookup later.  Your data structure might
as well be a list of tuples to begin with, to avoid creating a new list.
You have effectively made your keys useless as keys.  

If your lookups need to be case insensitive, make the key lower case,
and store the cased version in the value, whether as a tuple or a dict
(depending on whether you want named access).

d = {
   'foo': {'key': 'Foo', 'value': 'val1'}
   'spam': {'key': 'sPAm', 'value': 'val2'}
}

search = 'FOO'.lower()
if search in d:
result = d[search]
key = result['key']
value = result['value']

The only reason I wouldn't use this solution is if you expect to have
keys that will be identical when made lowercase, but if you're doing
case-insensitive lookup, you obviously don't expect this to be an issue.

Cheers,
Cliff


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


Re: derived classes and __getattr__

2008-09-05 Thread Alexandru Mosoi
On Sep 5, 1:13 pm, Peter Otten <[EMAIL PROTECTED]> wrote:
> Alexandru  Mosoi wrote:
> > On Sep 5, 11:47 am, Peter Otten <[EMAIL PROTECTED]> wrote:
> >> Alexandru Moșoi wrote:
> >> > i'm facing the following problem:
>
> >> > class Base(object):
> >> > def __getattr__(self, attr): return lambda x: attr + '_' + x
>
> >> > def dec(callable):
> >> > return lambda *args: 'dec_' + callable(*args)
>
> >> > class Derived(Base):
> >> > what_so_ever = dec(Base.what_so_ever) # wrong, base doesn't have
> >> > what_so_ever
> >> > mumu = dec(Base.mumu)                          # wrong, base
> >> > doesn't have mumu
>
> >> > any idea how to do this?
>
> >> __getattr__() is defined in the class to create instance attributes on
> >> the fly. If you want class attributes you have to put the __getattr__()
> >> method into the class of the class, or "metaclass":
>
> >> class Base(object):
> >> class __metaclass__(type):
> >> def __getattr__(self, attr):
> >> return lambda self, x: attr + '_' + x
>
> >> def dec(callable):
> >> return lambda *args: 'dec_' + callable(*args)
>
> >> class Derived(Base):
> >> what_so_ever = dec(Base.what_so_ever)
>
> >> d = Derived()
> >> print d.what_so_ever("42")
>
> >> I don't see how you can turn this into something useful...
>
> >> Peter
>
> > 10x. it works. however I have another small problem. now,
> > d.third('blah') doesn't work because instance d doesn't have 'third'
> > attribute. I was expecting derived class to inherit the metaclass as
> > well, but it didn't.
>
> That has nothing to do with inheritance:
>
> >>> type(Derived)
>
> 
>
> If Python doesn't find an attribute in the instance it looks it up in the
> class but not in the metaclass:
>
> >>> Base.third
>
>  at 0x2b5f8028aa28 Base().third
>
> Traceback (most recent call last):
>   File "", line 1, in 
> AttributeError: 'Base' object has no attribute 'third'
>
> I think you should go back to the drawing board now and look for a simpler
> approach to solve your actual problem...
>
> Peter


i somehow fixed the problem using:

  def __getattr__(self, attr):
return
functools.partial(Base.__metaclass__.__getattr__(self.__class__,
attr), self)

however this looks ugly enough to look for another solution. i still
have one more question: why do I have to bind self? (without which
functions fail expecting an instance)
--
http://mail.python.org/mailman/listinfo/python-list

Regarding subprocess module

2008-09-05 Thread tarun
Hello all,

I wrote the following code:

import subprocess,time
cmdExe = "C:\\WINDOWS\\system32\\cmd.exe"
myProcess = subprocess.Popen(cmdExe,stdin=subprocess.PIPE)
time.sleep(2)
myProcess.stdin.write('cd Desktop\r\n')

I copied the above lines of code to a file and tried executing the python
file from dos box (command prompt) on windows
I want subprocess.Popen to open a new dos box. But it works in the same
window. What should I do to open the subprocess in new window?

Thanks & Regards.
Tarun
--
http://mail.python.org/mailman/listinfo/python-list

Core dumped while interacting with OpenOffice.org via pyuno

2008-09-05 Thread Marco Bizzarri
Hi all.

I'm experiencing a core dump while working in the following environment

- debain etch
- python2.3
- openoffice.org 2.4
- Zope 2.8.8

I was able to get a core dump, and the backtrace shows the following:

Core was generated by `python2.3 tests/testActs.py'.
Program terminated with signal 11, Segmentation fault.
#0  0xb6b5219c in ?? () from /usr/lib/openoffice/program/libuno_cppu.so.3
(gdb) bt
#0  0xb6b5219c in ?? () from /usr/lib/openoffice/program/libuno_cppu.so.3
#1  0xb6b547d3 in ?? () from /usr/lib/openoffice/program/libuno_cppu.so.3
#2  0xb6b531d2 in ?? () from /usr/lib/openoffice/program/libuno_cppu.so.3
#3  0xb6b53748 in uno_threadpool_enter () from
/usr/lib/openoffice/program/libuno_cppu.so.3
#4  0xb5c80c8c in ?? () from /usr/lib/openoffice/program/liburp_uno.so
#5  0xb5c7d1e8 in ?? () from /usr/lib/openoffice/program/liburp_uno.so
#6  0xb5c8710e in ?? () from /usr/lib/openoffice/program/liburp_uno.so
#7  0xb5c8727c in ?? () from /usr/lib/openoffice/program/liburp_uno.so
#8  0xb5c76a62 in ?? () from /usr/lib/openoffice/program/liburp_uno.so
#9  0xb68c76c7 in ?? () from /usr/lib/openoffice/program/libuno_sal.so.3
#10 0x08797840 in ?? ()
#11 0x0989b6e0 in ?? ()
#12 0x in ?? ()

Now, I can understand that the information I provided are not enough
to give me suggestions on solving this issue; so, I'm asking
suggesions on investigating the issue, namely:

- should I ask here or is it better if I ask on a openoffice forum?
- should I use a debug-enabled python in order to have more meaningful
backtraces?
- is there something else I should do in order to have more clues
("Read The Fine Manual (tm)" is an acceptable answer)

Regards
Marco

-- 
Marco Bizzarri
http://notenotturne.blogspot.com/
http://iliveinpisa.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


[ANN] PyDM 1.1

2008-09-05 Thread Mohamed Yousef
PyDM 1.1 is released and now available from

http://sourceforge.net/projects/pycdm/


PyDM is a Multi-Threaded Download Manager in Python , this is the second release

Features :-

1) Http handling at socket level no external http libs
2) Two interfaces with core , one in Qt and the other is Console
3) Download Pausing (Qt Interface)
4) Download Resume (Qt Interface)
5) Saving Downloaded Files in a list (Powered by SQLite)
6) Configuration file (PyDM.ini) for number of threads,Temp Directory
and download directory
7) Displaying Rate/Status/Url/Filename for each downloaded file

Regards ,
Mohamed Yousef
--
http://mail.python.org/mailman/listinfo/python-list


Re: derived classes and __getattr__

2008-09-05 Thread Bruno Desthuilliers

Alexandru Mosoi a écrit :
(snip)

i somehow fixed the problem using:

  def __getattr__(self, attr):
return
functools.partial(Base.__metaclass__.__getattr__(self.__class__,
attr), self)

however this looks ugly enough to look for another solution. i still
have one more question: why do I have to bind self? (without which
functions fail expecting an instance)


Because the partial type doesn't implement the descriptor protocol 
(which is implemented by function type to return a method).

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

int((9.2-9.0)*10) is 1, int((9.21-9.0)*10) is 2, why?

2008-09-05 Thread bcm
Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit
(Intel)] on win32
The following line of code describes an  funny question:
>>> int((9.2-9.0)*10)
1
>>> int((9.21-9.0)*10)
2
>>> int((9.1-9.0)*10)
0
>>> int((9.11-9.0)*10)
1
>>> int((8.2-8.0)*10)
1
>>> int((8.23-8.0)*10)
2

why? anybody can explain it?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Curious: 2134 2004-10-06 08:55:20Z fredrik

2008-09-05 Thread Akathorn Greyhat
2008/9/5 Gabriel Genellina <[EMAIL PROTECTED]>
>
>
> I'd say the import mechanism got confused about the actual source of the
> error. Probably it happened on line 3 in *another* module, but the traceback
> got messed. Perhaps "core" is a package and contains "import data" at line
> 3?
>
> The $Id: stuff comes from some version control system -probably svn- and
> identifies the file version.
>
> --
> Gabriel Genellina
>
> --
> http://mail.python.org/mailman/listinfo/python-list



Interesting... =P

You are right, the package "core" contains "import data", but that module
doesn't exist, so it raises this strange error

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

‘A Byte of Python’ updated for Python 3.0

2008-09-05 Thread Kushal Das
Hi all,
Swaroop just released the latest version of his book "A Byte of
Python", the new version is for Python 3.0.
Read the post at http://www.swaroopch.com/blog/book-updated-for-python-3000/

The book can be found at http://www.swaroopch.com/notes/Python

Kushal

-- 
http://fedoraproject.org
http://kushaldas.in
http://badvista.org
http://noooxml.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: int((9.2-9.0)*10) is 1, int((9.21-9.0)*10) is 2, why?

2008-09-05 Thread John Machin
On Sep 5, 11:12 pm, bcm <[EMAIL PROTECTED]> wrote:
> Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit
> (Intel)] on win32
> The following line of code describes an  funny question:>>> int((9.2-9.0)*10)
> 1
> >>> int((9.21-9.0)*10)
> 2
> >>> int((9.1-9.0)*10)
> 0
> >>> int((9.11-9.0)*10)
> 1
> >>> int((8.2-8.0)*10)
> 1
> >>> int((8.23-8.0)*10)
>
> 2
>
> why? anybody can explain it?


Try looking one step at a time:
>>> 9.2
9.1993

That wasn't hard, was it? Do you need any further explanation? If so,
look here:
http://docs.python.org/tut/node16.html


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


cx_oracle and commands

2008-09-05 Thread gaius hammond
Hi all,


I am having a very strange problem with cx_Oracle, has anyone seen this kind of 
behavior before:



ActivePython 2.5.2.2 (ActiveState Software Inc.) based on
Python 2.5.2 (r252:60911, Mar 27 2008, 18:53:24) [C] on sunos5
Type "help", "copyright", "credits" or "license" for more information.
>>> from commands import getstatusoutput
>>> (status, output) = getstatusoutput('ls')
>>> status
0
>>> from cx_Oracle import connect, SYSDBA
>>> db = connect(mode=SYSDBA)
>>> (status, output) = getstatusoutput('ls')
Traceback (most recent call last):
  File "", line 1, in 
  File "/opt/ASpy25/lib/python2.5/commands.py", line 55, in getstatusoutput
sts = pipe.close()
IOError: [Errno 10] No child processes



Basically, once I have made a connection to Oracle I can no longer use 
getstatusoutput(). This is a real problem as
I need to get a list of things to work on from Oracle then spawn commands to 
process them...


Thanks,


G





-- 
[EMAIL PROTECTED]
http://www.gaius.org.uk/

"First things first, but not necessarily in that order" -- The 
Doctor, "Doctor Who" 





-
Visit Pipex Business: The homepage for UK Small Businesses

Go to http://www.pipex.co.uk/business-services

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


Re: int((9.2-9.0)*10) is 1, int((9.21-9.0)*10) is 2, why?

2008-09-05 Thread bcm
On Sep 5, 9:29 pm, John Machin <[EMAIL PROTECTED]> wrote:
> On Sep 5, 11:12 pm, bcm <[EMAIL PROTECTED]> wrote:
>
>
>
> > Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit
> > (Intel)] on win32
> > The following line of code describes an  funny question:>>> 
> > int((9.2-9.0)*10)
> > 1
> > >>> int((9.21-9.0)*10)
> > 2
> > >>> int((9.1-9.0)*10)
> > 0
> > >>> int((9.11-9.0)*10)
> > 1
> > >>> int((8.2-8.0)*10)
> > 1
> > >>> int((8.23-8.0)*10)
>
> > 2
>
> > why? anybody can explain it?
>
> Try looking one step at a time:>>> 9.2
>
> 9.1993
>
> That wasn't hard, was it? Do you need any further explanation? If so,
> look here:http://docs.python.org/tut/node16.html

thanks a lot, i am really really stupid ~*v*~
--
http://mail.python.org/mailman/listinfo/python-list


Spring Python 0.6.0 has been released

2008-09-05 Thread Goldfish
Spring Python 0.6.0, the python offshoot of the Spring framework and
Spring Security, has been released (http://
springpython.webfactional.com).

See 
http://sourceforge.net/project/showfiles.php?group_id=184275&package_id=214366&release_id=624328
for more details. BTW, if you click on the release notes link, there
is a report
pulled from JIRA (our new bug tracking software) showing the issues.
For more details,
you have to create an account at jira.springframework.org, and then
surf to Spring
Python. There, you can see it all nicely bundled at
http://jira.springframework.org/secure/IssueNavigator.jspa?reset=true&pid=10270&fixfor=11085.

Spring Python is moving forward in tremendous ways! Working with the
build team
in England, we have gotten things integrated with a continuous
integration server.
See http://build.springframework.org/browse/EXT, and then surf into
the Spring Python
parts to see our results. This is great! Just check out
http://build.springframework.org/browse/EXT-PYQUICK-19
for archived sample of the success of this project. If you look
closely, you may
notice that MySQL and PostGreSQL test cases have been commented out.
That is because
we don't have support for those RDBMS's on CI at this point in time.
Don't
be alarmed. I have run tests with and without thos test suites, and
the difference
in code coverage is 85% vs. 83%. Hopefully, in the future, we can get
an integration
environment that includes those tests as well.

This project focuses on quality. That is why I started this project
using TDD practices
and intend to proceed in this fashion. By integrating with CI, we now
have true
visibility into this. Another goal is to get code coverage metrics
captured. Tools
have been updated and show a measurement of 83% at this point in time.
I don't
know the industry average, but I'm willing to bet it is way below
that. I am
personally test infected, and I want to see the number higher.

The next immediate thing is to update Spring Python to support
CherryPy 3.1. We
are way behind and need to catch up. I have been working with Sylvain,
author of
"CherryPy Essentials: Rapid Python Web Application Development", and
we
are close to getting PetClinic and all the supporting components of
Spring Python
working. This is exciting because integrating with 3rd party web
frameworks opens
doors for Spring Python.

Have any ideas of where you think Spring Python can go? Send me a
message here,
or start a new topic on our forum at 
http://forum.springframework.org/forumdisplay.php?f=45.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Core dumped while interacting with OpenOffice.org via pyuno

2008-09-05 Thread Maric Michaud
Le Friday 05 September 2008 15:04:22 Marco Bizzarri, vous avez écrit :
> Hi all.
>
> I'm experiencing a core dump while working in the following environment
>
> - debain etch
> - python2.3
> - openoffice.org 2.4
> - Zope 2.8.8
>
> I was able to get a core dump, and the backtrace shows the following:
>
> Core was generated by `python2.3 tests/testActs.py'.
> Program terminated with signal 11, Segmentation fault.
> #0  0xb6b5219c in ?? () from /usr/lib/openoffice/program/libuno_cppu.so.3
... lot of backtrace ...
> #9  0xb68c76c7 in ?? () from /usr/lib/openoffice/program/libuno_sal.so.3
> #10 0x08797840 in ?? ()
> #11 0x0989b6e0 in ?? ()
> #12 0x in ?? ()
>
> Now, I can understand that the information I provided are not enough
> to give me suggestions on solving this issue; so, I'm asking
> suggesions on investigating the issue, namely:
>
> - should I ask here or is it better if I ask on a openoffice forum?

Yes.

> - should I use a debug-enabled python in order to have more meaningful
> backtraces?

What you need is more a debug enabled version of pyuno libraries.

> - is there something else I should do in order to have more clues
> ("Read The Fine Manual (tm)" is an acceptable answer)

You can try to find which function call exactly provoke the exception, the 
simplest way is to trace execution flow with some print statments and using 
non forking zope instance (runzope -d if I remember well).




-- 
_

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


Re: cx_oracle and commands

2008-09-05 Thread Edwin . Madari
gaius hammond Wrote:
>Hi all,
>
>
>I am having a very strange problem with cx_Oracle, has anyone 
>seen this kind of behavior before:
>
>
>
>ActivePython 2.5.2.2 (ActiveState Software Inc.) based on
>Python 2.5.2 (r252:60911, Mar 27 2008, 18:53:24) [C] on sunos5
>Type "help", "copyright", "credits" or "license" for more information.
 from commands import getstatusoutput
 (status, output) = getstatusoutput('ls')
 status
>0
 from cx_Oracle import connect, SYSDBA
 db = connect(mode=SYSDBA)
 (status, output) = getstatusoutput('ls')
>Traceback (most recent call last):
>  File "", line 1, in 
>  File "/opt/ASpy25/lib/python2.5/commands.py", line 55, in 
>getstatusoutput
>sts = pipe.close()
>IOError: [Errno 10] No child processes
>
>
>
>Basically, once I have made a connection to Oracle I can no 
>longer use getstatusoutput(). This is a real problem as
>I need to get a list of things to work on from Oracle then 
>spawn commands to process them...
>
>
>Thanks,
>

There is no mode parameter to connect. use try-catch around 
db = connect(mode=SYSDBA) line to see what's going on.
 

Edwin 


The information contained in this message and any attachment may be
proprietary, confidential, and privileged or subject to the work
product doctrine and thus protected from disclosure.  If the reader
of this message is not the intended recipient, or an employee or
agent responsible for delivering this message to the intended
recipient, you are hereby notified that any dissemination,
distribution or copying of this communication is strictly prohibited.
If you have received this communication in error, please notify me
immediately by replying to this message and deleting it and all
copies and backups thereof.  Thank you.


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


Re: Case-insensitive string compare?

2008-09-05 Thread J. Cliff Dyer
Please keep the discussion on-list.

On Fri, 2008-09-05 at 15:36 +0200, Maric Michaud wrote:
> Le Friday 05 September 2008 14:33:22 J. Clifford Dyer, vous avez écrit :
> > On Thu, 2008-09-04 at 18:48 -0500, Robert Dailey wrote:
> > > Thanks everyone for your help. I'm not opposed to using [key.lower()
> > > for key in stage_map] at all, I was just curious to see if there were
> > > any cleaner alternatives. It looks like that is what I'll be using.
> > > I'm not familiar with how python works internally, but coming from C++
> > > it seems like "remaking" the map would be slow. However, speed is not
> > > my main concern in my particular situation, I'm just curious to learn
> > > more about python.
> >
> > You should be opposed to that particular solution.  You have just taken
> > a dictionary lookup (very fast) and turned it into a list traversal
> > (slow).  Even if speed isn't your main concern, this is an unnecessary
> > de-optimization.  You are deliberately slowing down your program to
> > avoid a slightly more verbose lookup later.  Your data structure might
> > as well be a list of tuples to begin with, to avoid creating a new list.
> > You have effectively made your keys useless as keys.
> >
> > If your lookups need to be case insensitive, make the key lower case,
> > and store the cased version in the value, whether as a tuple or a dict
> > (depending on whether you want named access).
> >
> > d = {
> >'foo': {'key': 'Foo', 'value': 'val1'}
> >'spam': {'key': 'sPAm', 'value': 'val2'}
> > }
> >
> > search = 'FOO'.lower()
> > if search in d:
> > result = d[search]
> > key = result['key']
> > value = result['value']
> >
> > The only reason I wouldn't use this solution is if you expect to have
> > keys that will be identical when made lowercase, but if you're doing
> > case-insensitive lookup, you obviously don't expect this to be an issue.
> >
> 
> The OP has already said the keys are case-sensitive, so this is not an 
> option, 
> the only way to do it fast is to index upon insertion all keys in another 
> dict, so you get in final :
> d = { "kEy1" : 1, "Key1" : 2}
> indexes = { "key1" : ["kEy1", "Key1" ] }
> 

That does not get the same behavior as the OP's original solution.  The
OP's solution retrieves the first matching value only.  Mine gets one
arbitrary matching value, determined by the algorithm used for
constructing the search dict (not specified in my solution).  What the
OP actually said was that he can't throw away the case.  You assume that
this means there would be multiple entries distinguished only by case.
That might be true, but given his initial solution, it seemed to me more
likely that he wants to keep the case for display purposes, as in a
dictionary like this:

{
   "Michaud": "Maric",
   "Dyer": "Cliff",
   "D'Amato": "Alphonse",
}

To the OP: If you are looking for multiple matches for a given
case-insensitive key, check out the recent thread on "Python multimap",
for further discussion elaborating on how to map one key to many values
in a dictionary-like object.

At that point, it's probably worth factoring out your solution to a
separate class, so you can work with a clean interface, rather than
repeating the ugly details every time you use it.

Cheers,
Cliff

> > Cheers,
> > Cliff
> >
> >
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> 
> 
> 

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

Re: Case-insensitive string compare?

2008-09-05 Thread Maric Michaud
Le Friday 05 September 2008 14:33:22 J. Clifford Dyer, vous avez écrit :
> On Thu, 2008-09-04 at 18:48 -0500, Robert Dailey wrote:
> > Thanks everyone for your help. I'm not opposed to using [key.lower()
> > for key in stage_map] at all, I was just curious to see if there were
> > any cleaner alternatives. It looks like that is what I'll be using.
> > I'm not familiar with how python works internally, but coming from C++
> > it seems like "remaking" the map would be slow. However, speed is not
> > my main concern in my particular situation, I'm just curious to learn
> > more about python.
>
> You should be opposed to that particular solution.  You have just taken
> a dictionary lookup (very fast) and turned it into a list traversal
> (slow).  Even if speed isn't your main concern, this is an unnecessary
> de-optimization.  You are deliberately slowing down your program to
> avoid a slightly more verbose lookup later.  Your data structure might
> as well be a list of tuples to begin with, to avoid creating a new list.
> You have effectively made your keys useless as keys.
>
> If your lookups need to be case insensitive, make the key lower case,
> and store the cased version in the value, whether as a tuple or a dict
> (depending on whether you want named access).
>
> d = {
>    'foo': {'key': 'Foo', 'value': 'val1'}
>    'spam': {'key': 'sPAm', 'value': 'val2'}
> }
>
> search = 'FOO'.lower()
> if search in d:
>     result = d[search]
>     key = result['key']
>     value = result['value']
>
> The only reason I wouldn't use this solution is if you expect to have
> keys that will be identical when made lowercase, but if you're doing
> case-insensitive lookup, you obviously don't expect this to be an issue.
>

The OP has already said the keys are case-sensitive, so this is not an option, 
the only way to do it fast is to index upon insertion all keys in another 
dict, so you get in final :
d = { "kEy1" : 1, "Key1" : 2}
indexes = { "key1" : ["kEy1", "Key1" ] }

> Cheers,
> Cliff
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list



-- 
_

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


Re: Python and Cyrillic characters in regular expression

2008-09-05 Thread MRAB
On Sep 5, 12:28 pm, phasma <[EMAIL PROTECTED]> wrote:
> string = u"ðÒÉ×ÅÔ"

All the characters are letters.

> (u'\u041f\u0440\u0438\u0432\u0435\u0442',)
>
> string = u"Hi.ðÒÉ×ÅÔ"

The third character isn't a letter and isn't whitespace.

> (u'Hi',)
>

> On Sep 4, 9:53špm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
>
> > phasma wrote:
> > > Hi, I'm trying extract all alphabetic characters from string.
>
> > > reg = re.compile('(?u)([\w\s]+)', re.UNICODE)
> > > buf = re.match(string)
>
> > > But it's doesn't work. If string starts from Cyrillic character, all
> > > works fine. But if string starts from Latin character, match returns
> > > only Latin characters.
>
> > can you provide a few sample strings that show this behaviour?
>
--
http://mail.python.org/mailman/listinfo/python-list


Extract Information from Tables in html

2008-09-05 Thread Jackie Wang
Dear all,

Here is a html code:



 Premier Community Bank of Southwest Florida
 
 Fort Myers, FL



My question is how I can extract the strings and get the results:
Premier Community Bank of Southwest Florida; Fort Myers, FL

Thanks a lot

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


Re: Case-insensitive string compare?

2008-09-05 Thread Maric Michaud
Le Friday 05 September 2008 16:00:39 J. Cliff Dyer, vous avez écrit :
> Please keep the discussion on-list.
>

Sorry for the private email, I sent it again to the list..

> On Fri, 2008-09-05 at 15:36 +0200, Maric Michaud wrote:
> > Le Friday 05 September 2008 14:33:22 J. Clifford Dyer, vous avez écrit :
> > > On Thu, 2008-09-04 at 18:48 -0500, Robert Dailey wrote:
> > > > Thanks everyone for your help. I'm not opposed to using [key.lower()
> > > > for key in stage_map] at all, I was just curious to see if there were
> > > > any cleaner alternatives. It looks like that is what I'll be using.
> > > > I'm not familiar with how python works internally, but coming from
> > > > C++ it seems like "remaking" the map would be slow. However, speed is
> > > > not my main concern in my particular situation, I'm just curious to
> > > > learn more about python.
> > >
> > > You should be opposed to that particular solution.  You have just taken
> > > a dictionary lookup (very fast) and turned it into a list traversal
> > > (slow).  Even if speed isn't your main concern, this is an unnecessary
> > > de-optimization.  You are deliberately slowing down your program to
> > > avoid a slightly more verbose lookup later.  Your data structure might
> > > as well be a list of tuples to begin with, to avoid creating a new
> > > list. You have effectively made your keys useless as keys.
> > >
> > > If your lookups need to be case insensitive, make the key lower case,
> > > and store the cased version in the value, whether as a tuple or a dict
> > > (depending on whether you want named access).
> > >
> > > d = {
> > >'foo': {'key': 'Foo', 'value': 'val1'}
> > >'spam': {'key': 'sPAm', 'value': 'val2'}
> > > }
> > >
> > > search = 'FOO'.lower()
> > > if search in d:
> > > result = d[search]
> > > key = result['key']
> > > value = result['value']
> > >
> > > The only reason I wouldn't use this solution is if you expect to have
> > > keys that will be identical when made lowercase, but if you're doing
> > > case-insensitive lookup, you obviously don't expect this to be an
> > > issue.
> >
> > The OP has already said the keys are case-sensitive, so this is not an
> > option, the only way to do it fast is to index upon insertion all keys in
> > another dict, so you get in final :
> > d = { "kEy1" : 1, "Key1" : 2}
> > indexes = { "key1" : ["kEy1", "Key1" ] }
>
> That does not get the same behavior as the OP's original solution.  The
> OP's solution retrieves the first matching value only.  Mine gets one
> arbitrary matching value, determined by the algorithm used for
> constructing the search dict (not specified in my solution).

string.lower() in indexes gives the same result, but your right, a set of 
lowered keys could suffice for the exact OP's requirement.

> What the 
> OP actually said was that he can't throw away the case.  You assume that
> this means there would be multiple entries distinguished only by case.
> That might be true, but given his initial solution, it seemed to me more
> likely that he wants to keep the case for display purposes, as in a
> dictionary like this:
>
> {
>"Michaud": "Maric",
>"Dyer": "Cliff",
>"D'Amato": "Alphonse",
> }
>

I didn't want to make gratuitous extrapolations on the OP's data structure, 
but I still think the OP's question was "how to write cleanly a 
case-insensitive comparaison versus all the keys of a dict". Maybe I'm wrong.

--
_

Maric Michaud

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

Re: Extract Information from Tables in html

2008-09-05 Thread Walter Cruz
On Fri, Sep 5, 2008 at 11:29 AM, Jackie Wang <[EMAIL PROTECTED]> wrote:
> Dear all,
>
> Here is a html code:
>
> 
>
> Premier Community Bank of Southwest Florida
> 
> Fort Myers, FL
>
> 
>
> My question is how I can extract the strings and get the results:
> Premier Community Bank of Southwest Florida; Fort Myers, FL

Use BeautifulSoup.

[]'s
- Walter
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python test case management system?

2008-09-05 Thread Mudcat
> What would the behaviour of such a system be? In other words, what is
> a "test case management system" in terms of the things that it does?

The feature set for one tends to vary. In short it's a front end app
which is tied to a db that stores and organizes test cases. The system
will allow you to select and execute test cases based on different
criteria which will then log and store the results. They aren't
extremely complicated however they do need to have a well-built
execution engine that are multi-threaded and can handle several
different things at the same time.
--
http://mail.python.org/mailman/listinfo/python-list


Make Games

2008-09-05 Thread NightZombie
x-no-archive: yes

I want to learn Python so I can make simple games. What are some good
books that'll help me do this?
--
http://mail.python.org/mailman/listinfo/python-list


hashing an array - howto

2008-09-05 Thread Helmut Jarausch

Hi,

I need to hash arrays of integers (from the hash module).

So, I have to derive from array and supply a __hash__ method.
But how to hash an array (of fixed length, say 25)?
What I need is a function which maps a tuple of 25 integers
into 1 integer with good hashing properties.

Does anybody know such a thing?

Many thanks for a hint,

Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany
--
http://mail.python.org/mailman/listinfo/python-list


Re: hashing an array - howto

2008-09-05 Thread Peter Otten
Helmut Jarausch wrote:

> I need to hash arrays of integers (from the hash module).
> 
> So, I have to derive from array and supply a __hash__ method.
> But how to hash an array (of fixed length, say 25)?
> What I need is a function which maps a tuple of 25 integers
> into 1 integer with good hashing properties.
> 
> Does anybody know such a thing?

Have you tried this already?

def __hash__(self):
return hash(self.tostring())

Peter


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


Re: Make Games

2008-09-05 Thread Diez B. Roggisch

NightZombie schrieb:

x-no-archive: yes

I want to learn Python so I can make simple games. What are some good
books that'll help me do this?


Don't know about books, but I don't think it is important that the books 
are about python for game programming - game programming in general will 
help.


On http://pygame.org/ you can see quite a few examples on how to create 
games using pygame, and then there are projects such as pyglet, nodebox 
and of course PyOpenGL itself.


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


Re: Extract Information from Tables in html

2008-09-05 Thread Peter Pearson
On Fri, 5 Sep 2008 11:35:14 -0300, Walter Cruz <[EMAIL PROTECTED]> wrote:
> On Fri, Sep 5, 2008 at 11:29 AM, Jackie Wang <[EMAIL PROTECTED]> wrote:
>> Here is a html code:
>>
>> 
>>
>> Premier Community Bank of Southwest Florida
>> 
>> Fort Myers, FL
>>
>> 
>>
>> My question is how I can extract the strings and get the results:
>> Premier Community Bank of Southwest Florida; Fort Myers, FL
>
> Use BeautifulSoup.

I agree, BeautifulSoup is wonderful.  Here are snippets of
code that I recently used to locate (in each of many HTML
files) the table that contained a particular heading:

  from BeautifulSoup import BeautifulSoup
  import re
  ...
  inlines = ifd.readlines()
  soup = BeautifulSoup( " ".join( inlines ) )
  x = soup.findAll( text = re.compile( "Technical Requirements - General" ) )
  x = x[0].parent
  while x.name != "table":
x = x.parent
  tr_list = x.findAll( "tr", recursive = False )
  print "Table has %d rows." % len( tr_list )


-- 
To email me, substitute nowhere->spamcop, invalid->net.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Can anyone suggest a good crypto package?

2008-09-05 Thread Fett
On Sep 4, 8:04 pm, Paul Rubin  wrote:
> If you just want to authenticate the strings without confidentiality,
> use the built-in HMAC module.  But beware of replay attacks.

I looked into this and it looks like I might be able to get by with
this. I didn't find this function before, I am asking my primary
customer if the signature would be sufficient.

I am having trouble seeing how I would post the encrypted data to a
website and get it back without it changing some. So this option might
work better for me (at least quicker), if he's ok with that option.

By replay attack I assume you mean posting old data with the signature
that is valid for that data? Thanks for the warning, I suppose I could
include a date/timestamp in the data.

Thanks again, this has been very helpful.
--
http://mail.python.org/mailman/listinfo/python-list


Re: PyGUI as a standard GUI API for Python?

2008-09-05 Thread Peter Decker
On Wed, Sep 3, 2008 at 11:57 AM, Diez B. Roggisch <[EMAIL PROTECTED]> wrote:
> Michael Palmer schrieb:
>>
>> As anyone knows, the state of Python GUI programming is a little
>> fractured at this time, with many toolkits, wrappers and meta-wrappers
>> dead and alive, with or without documentation.
>>
>> I've come across two projects that have the appeal of striving for
>> simple, pythonic APIs: PyGUI and wax.  The latter is a wrapper around
>> wxPython. It is  lacking documentation but actually quite usable and
>> concise. The other, PyGUI, has an even nicer API and more docs but has
>> relatively few widgets implemented at this time. It also strives for
>> compatibility with several toolkits (two at this time), which I think
>> is the right idea.
>
> I disagree with that. Meta-wrappers like this will always suffer from
> problems, as they have difficulties providing a consistent api. For example
> wx is said to be very windows-toolkit-centric in it's API. Yes I know that
> it works under Linux with GTK, but it does not come as natural .

With all due respect, it seems like you are not terribly familiar with
wxPython. It uses the native UI toolkit for each platform wherever
possible: Aqua on OS X; MFC on Windows and Gtk on Linux. Applications
tend to look 'natural' on each platform, rather than uniform across
platforms, and I believe that this is what most people prefer.

-- 

# p.d.
--
http://mail.python.org/mailman/listinfo/python-list


Re: max(), sum(), next()

2008-09-05 Thread David C. Ullrich
In article <[EMAIL PROTECTED]>,
 Ken Starks <[EMAIL PROTECTED]> wrote:

> David C. Ullrich wrote:
> 
> > 
> > I don't see why you feel the two should act the same.
> > At least in mathematics, the sum of the elements of
> > the empty set _is_ 0, while the maximum element of the
> > empty set is undefined. 
> > 
> > And both for good reason:
> > 
> > (i) If A and B are disjoint sets we certainly want to
> > have sum(A union B) = sum(A) + sum(B). This requires
> > sum(empty set) = 0.
> > 
> > (ii) If A is a subset of B then we should have
> > max(A) <= max(B). This requires that max(empty set)
> > be something that's smaller than everything else.
> > So we give up on that.
> 
> Do we give up? Really ?

Erm, thanks. I was aware of all that below. If we're
being technical what's below is talking about the sup
and inf, which are not the same as max and min. More
relevant to the present context, I didn't mention what's
below because it doesn't seem likely that saying max([])
= -infinity and min([]) = +infinity is going to make the
OP happy...

>  From wikipedia: http://en.wikipedia.org/wiki/Empty_set
> (Uses wikipedia's LaTeX notation -- I hope those interested
> are OK with that )
> 
> 
> Mathematics
> 
> [edit] Extended real numbers
> 
> Since the empty set has no members, when it is considered as a subset of 
> any ordered set, then any member of that set will be an upper bound and 
> lower bound for the empty set. For example, when considered as a subset 
> of the real numbers, with its usual ordering, represented by the real 
> number line, every real number is both an upper and lower bound for the 
> empty set.[3] When considered as a subset of the extended reals formed 
> by adding two "numbers" or "points" to the real numbers, namely negative 
> infinity, denoted -\infty\!\,, which is defined to be less than every 
> other extended real number, and positive infinity, denoted +\infty\!\,, 
> which is defined to be greater than every other extended real number, then:
> 
>  \sup\varnothing=\min(\{-\infty, +\infty \} \cup \mathbb{R})=-\infty,
> 
> and
> 
>  \inf\varnothing=\max(\{-\infty, +\infty \} \cup \mathbb{R})=+\infty.
> 
> That is, the least upper bound (sup or supremum) of the empty set is 
> negative infinity, while the greatest lower bound (inf or infimum) is 
> positive infinity. By analogy with the above, in the domain of the 
> extended reals, negative infinity is the identity element for the 
> maximum and supremum operators, while positive infinity is the identity 
> element for minimum and infimum.

-- 
David C. Ullrich
--
http://mail.python.org/mailman/listinfo/python-list


Re: hashing an array - howto

2008-09-05 Thread bearophileHUGS
Helmut Jarausch:
> I need to hash arrays of integers (from the hash module).

One of the possible solutions is to hash the equivalent tuple, but it
requires some memory (your sequence must not be tuples already):

assert not isinstance(somelist, tuple)
hash(tuple(somelist))

This is an alternative solution, it doesn't use much memory, but I am
not sure it works correctly:

from operator import xor
hash(reduce(xor, somelist))

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: Core dumped while interacting with OpenOffice.org via pyuno

2008-09-05 Thread Marco Bizzarri
On Fri, Sep 5, 2008 at 3:50 PM, Maric Michaud <[EMAIL PROTECTED]> wrote:
> Le Friday 05 September 2008 15:04:22 Marco Bizzarri, vous avez écrit :
>> Hi all.
>>
>> I'm experiencing a core dump while working in the following environment
>>
>> - debain etch
>> - python2.3
>> - openoffice.org 2.4
>> - Zope 2.8.8
>>
>> I was able to get a core dump, and the backtrace shows the following:
>>
>> Core was generated by `python2.3 tests/testActs.py'.
>> Program terminated with signal 11, Segmentation fault.
>> #0  0xb6b5219c in ?? () from /usr/lib/openoffice/program/libuno_cppu.so.3
> ... lot of backtrace ...
>> #9  0xb68c76c7 in ?? () from /usr/lib/openoffice/program/libuno_sal.so.3
>> #10 0x08797840 in ?? ()
>> #11 0x0989b6e0 in ?? ()
>> #12 0x in ?? ()
>>
>> Now, I can understand that the information I provided are not enough
>> to give me suggestions on solving this issue; so, I'm asking
>> suggesions on investigating the issue, namely:
>>
>> - should I ask here or is it better if I ask on a openoffice forum?
>
> Yes.

Ok

>> - should I use a debug-enabled python in order to have more meaningful
>> backtraces?
>
> What you need is more a debug enabled version of pyuno libraries.

Ok; I will check with the openoffice guys, then.


>> - is there something else I should do in order to have more clues
>> ("Read The Fine Manual (tm)" is an acceptable answer)
>
> You can try to find which function call exactly provoke the exception, the
> simplest way is to trace execution flow with some print statments and using
> non forking zope instance (runzope -d if I remember well).
>

Ok; just for completeness, this is not a running zope application, it
is a ZopeTestCase which is causing me the trouble. And, as usual, it
does not cause it always :-)

Regards
Marco

-- 
Marco Bizzarri
http://notenotturne.blogspot.com/
http://iliveinpisa.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: max(), sum(), next()

2008-09-05 Thread David C. Ullrich
In article 
<[EMAIL PROTECTED]>,
 [EMAIL PROTECTED] wrote:

> David C. Ullrich:
> > At least in mathematics, the sum of the elements of
> > the empty set _is_ 0, while the maximum element of the
> > empty set is undefined.
> 
> What do you think about my idea of adding that 'default' argument to
> the max()/min() functions?

How the Python max and min functions should work has to
do with how people want them to work and how people expect
them to work. I wouldn't know about most people, but I
would have been surprised if min([]) was not an error,
and I would have been disappointed if sum([]) was not 0.

>From a mathematical point of view, not that that's directly
relevant, it doesn't make much sense to me to add that default
argument. The max of a set is supposed to be the largest
element of that set. If the set is empty there's no such
thing.

In Python you'd better make sure that S is nonempty before
asking for max(S). That's not just Python - in math you need
to make certain that S is nonempty and also other conditions
before you're allowed to talk about max(S). That's just the
way it is.

Think about all the previously elected female or black
presidents of the US. Which one was the tallest?

> Bye,
> bearophile

-- 
David C. Ullrich
--
http://mail.python.org/mailman/listinfo/python-list


Re: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ?

2008-09-05 Thread Diez B. Roggisch
Ivan Illarionov schrieb:
> On 4 сент, 21:49, Bruno Desthuilliers
> <[EMAIL PROTECTED]> wrote:
>> Ivan Illarionov a écrit :
>>
>>
>>
>>> On 4 сент, 22:59, Carl Banks <[EMAIL PROTECTED]> wrote:
 You can write code to guard against this if you want:
 class A:
 legal = set(["x"])
 def __setattr__(self,attr,val):
 if attr not in self.legal:
 raise AttributeError("A object has no attribute '%s'" %
 attr)
 self.__dict__[attr] = val
 def __init__(self,x):
 self.y = x
 I suspect most people who go into Python doing something like this
 soon abandon it when they see how rarely it actually catches anything.
>>> '__slots__' is better:
>> For which definition of "better" ? __slots__ are a mean to optimize
>> memory usage, not to restrict dynamism. Being able to dynamically add
>> arbitrary attributes is actually a feature, not a bug, and uselessly
>> restricting users from doing so is not pythonic. IOW : don't do that.
> 
> Carl's example is restricting dynamism in the same way as __slots__.
> I've just suggested a better implementation. It is not me who
> suggested dynamism restriction as a way to guard against errors.

This is not correct. While Carl's Example looks similar, you actually
*can* create new attributes using

obj.__dict__['name'] = value

__slots__ OTOH prevents that because it does create instances *without*
an instance-dict.

This being said, I think we all agree that it's nothing to be desired.


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

Retrieving the name of the class calling an instance method

2008-09-05 Thread mercado mercado
In Python, is it possible for an instance method to know the name of the
class which is calling it? For example, in the sample below, I would like
for the someMethod method to print the name of the class calling it ("bar"
in the first case, "again" in the second).

---
class foo():
def someMethod(self):
print x

class bar():
def __init__(self):
f = foo()
f.someMethod()

class again():
def __init__(self):
f = foo()
f.someMethod()

bar()
again()
---
--
http://mail.python.org/mailman/listinfo/python-list

Re: max(), sum(), next()

2008-09-05 Thread bearophileHUGS
David C. Ullrich:
> I didn't mention what's below because it doesn't seem
> likely that saying max([]) = -infinity and
> min([]) = +infinity is going to make the OP happy...

Well, it sounds cute having Neginfinite and Infinite as built-int
objects that can be compared to any other type and are < of or > of
everything else but themselves. Probably they can be useful as
sentinels, but in Python I nearly never use sentinels anymore, and
they can probably give some other problems...

Bye,
bearophile

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


Re: [MacOS X] plat-mac/errors.rsrc.df.rsrc not installed/created

2008-09-05 Thread Christian Ebert
* Christian Ebert on Thursday, August 28, 2008:
> I am on MacOS 10.4.11, and have a minor recurring problem, when
> using my own Python installation.
> 
> I only stumbled over it when using http operations with the
> Mercurial SCM, and my /tmp/ folder was clobbered with *.rsrc
> temporary files.
> 
> Some references:
> http://www.selenic.com/pipermail/mercurial/2007-October/015039.html
> and, as I forgot about it :( :
> http://www.selenic.com/pipermail/mercurial/2008-August/021072.html
> 
> Apparently for some stuff plat-mac/macresource.py needs to create
> plat-mac/errors.rsrc.df.rsrc. If that fails, at least that is how
> I read macresource.py, it creates them via mkstemp in /tmp/.
> 
> Once I recognize the problem I can work around it by either
> 
> $ sudo mv /tmp/tmp.rsrc 
> /usr/local/lib/python2.5/plat-mac/errors.rsrc.df.rsrc
> 
> or by temporarily "chown myname plat-mac", and, once the file is
> created, "chown root plat-mac" again.
> 
> My 2.5.2 install is under /usr/local, but other Mac users with
> the same setup, do not have the problem.
> 
> I don't need/want the Apple Framework install, and again, others
> do not have the problem with this setup.
> 
> Anyone any ideas?
> 
> The best I could google was
> http://bugs.python.org/issue763708
> but this seems encoding related.

I gather from the overwhelming reaction that I am the only one
experiencing this ;-)

However, if I can provide more info that might be useful, just
tell me.

TIA

c
-- 
  Was heißt hier Dogma, ich bin Underdogma!
[ What the hell do you mean dogma, I am underdogma. ]

_F R E E_  _V I D E O S_  -->>  http://www.blacktrash.org/underdogma/
--
http://mail.python.org/mailman/listinfo/python-list


Re: PyGUI as a standard GUI API for Python?

2008-09-05 Thread Diez B. Roggisch

Peter Decker schrieb:

On Wed, Sep 3, 2008 at 11:57 AM, Diez B. Roggisch <[EMAIL PROTECTED]> wrote:

Michael Palmer schrieb:

As anyone knows, the state of Python GUI programming is a little
fractured at this time, with many toolkits, wrappers and meta-wrappers
dead and alive, with or without documentation.

I've come across two projects that have the appeal of striving for
simple, pythonic APIs: PyGUI and wax.  The latter is a wrapper around
wxPython. It is  lacking documentation but actually quite usable and
concise. The other, PyGUI, has an even nicer API and more docs but has
relatively few widgets implemented at this time. It also strives for
compatibility with several toolkits (two at this time), which I think
is the right idea.

I disagree with that. Meta-wrappers like this will always suffer from
problems, as they have difficulties providing a consistent api. For example
wx is said to be very windows-toolkit-centric in it's API. Yes I know that
it works under Linux with GTK, but it does not come as natural .


With all due respect, it seems like you are not terribly familiar with
wxPython. It uses the native UI toolkit for each platform wherever
possible: Aqua on OS X; MFC on Windows and Gtk on Linux. Applications
tend to look 'natural' on each platform, rather than uniform across
platforms, and I believe that this is what most people prefer.


You got me wrong. I didn't say it doesn't use the native toolkit under 
various OSes, I'm well aware of that it does.


What I *did* say was that wx API is designed primarily with windows' 
toolkit as base, and as a consequence the API tends to be less 
functional for other toolkits, making it harder to work with it. As the 
OP was after a "one API to rule them all" for GUIs, I pointed that out.


See for example this (arguably somewhat dated) post that illustrates my 
point:


http://mail.python.org/pipermail/python-list/2005-March/313354.html

From my personal experience with Qt and Cocoa, I can say that both are 
great, but their full power is unleashed only if used directly - talk 
about Multi-threading in Qt4, or KeyValue-coding in Cocoa. Neither is 
available in wx.


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


Re: hashing an array - howto

2008-09-05 Thread Michael Palmer
On Sep 5, 11:18 am, [EMAIL PROTECTED] wrote:
> Helmut Jarausch:
>
> > I need to hash arrays of integers (from the hash module).
>
> One of the possible solutions is to hash the equivalent tuple, but it
> requires some memory (your sequence must not be tuples already):

why can't it be tuple already? Doesn't matter:

>>> from numpy import arange
>>> a=arange(5)
>>> a
array([0, 1, 2, 3, 4])
>>> hash(a)
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: unhashable type
>>> b=tuple(a)
>>> b
(0, 1, 2, 3, 4)
>>> c=tuple(b)
>>> c
(0, 1, 2, 3, 4)
>>> hash(c)
1286958229

you can discard the tuple, so the memory requirement is transient.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Extract Information from Tables in html

2008-09-05 Thread Stefan Behnel
Hi,

Jackie Wang wrote:
> Here is a html code:
> 
> 
> 
>  Premier Community Bank of Southwest Florida
>  
>  Fort Myers, FL
> 
> 
> 
> My question is how I can extract the strings and get the results:
> Premier Community Bank of Southwest Florida; Fort Myers, FL

Use lxml.html. Something like this should do what you want:

  >>> from lxml import html
  >>> tree = html.parse("http://server.org/thefile.html";)
  >>> all_tds = tree.findall("//td")
  >>> for td in all_tds:
  ... print( td.xpath("normalize-space()") )

Tweak as you see fit, tree iteration is at your service in case you need more.

http://codespeak.net/lxml/

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


Files application architecture

2008-09-05 Thread Benjamin Watine

Hi,

I'm about to develop a small python application and I wonder how to 
organize files in this application.
I'm familar to java, so I'm tempted to use the same convention : 1 file 
per class and 1 folders per package.


I know that packages doesn't exists in python, they are modules instead. 
May I create specific module for each "group of class" ? My application 
follow the MVC paradigm, so basically, I've a package Model, a package 
View, and a package Controller.


So, what are best practices for organizing files and folders in a small 
python project ?
I've found PEP8 (http://www.python.org/dev/peps/pep-0008/) that gives a 
lot of good hints on coding convention, but nothing about files 
organization.


Thanks in advance !

Ben


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


Re: PyGUI as a standard GUI API for Python?

2008-09-05 Thread Todd Whiteman

M.-A. Lemburg wrote:

A long time ago, there was a Python plugin for Netscape
which allowed you to run Python straight in the browser. Perhaps
it's time to revive such an idea... but then you're still missing
out on the GUI part, since you're still stuck with what the
browser has to offer in terms of widget support.



There is still a plugin (extension) for Mozilla based products, that 
enables use of Python in products like Firefox:

http://pyxpcomext.mozdev.org/

Mark Hammond's Python/Mozilla work has enabled products like Komodo, 
Miro (Democracy) and the OLPC project to use Python as a major driver 
for consistent cross-platform GUI applications.


Personally, I believe XULRunner has a lot to offer for Python GUI 
development, I'm currently finishing up some documentation steps to show 
off how to use it specifically for Python (I'll post it to this list 
when it's finished).


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


Re: Retrieving the name of the class calling an instance method

2008-09-05 Thread Maric Michaud
Le Friday 05 September 2008 17:29:39 mercado mercado, vous avez écrit :
> In Python, is it possible for an instance method to know the name of the
> class which is calling it? For example, in the sample below, I would like
> for the someMethod method to print the name of the class calling it ("bar"
> in the first case, "again" in the second).

Note that "self" for somemethod is just a local variable of the calling 
function. You cannot retrieve those local variables without playing with the 
call stack, and this reveal generally a bad design (except for inspection 
purpose).

You have two common solutions here :
- the simplest is to pass the instance of bar or again to the foo constructor 
or as parameter of someMethod, or 
- attach the foo instance to self in both cases and define a proper __get__ 
method in foo, this is far more complex and add magic to the foo class, I 
don't recommand this unless you understand well the descriptor protocol.

>
> ---
> class foo():
> def someMethod(self):
> print x
>
> class bar():
> def __init__(self):
> f = foo()
> f.someMethod()
>
> class again():
> def __init__(self):
> f = foo()
> f.someMethod()
>
> bar()
> again()
> ---



-- 
_

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


Re: Retrieving the name of the class calling an instance method

2008-09-05 Thread Emile van Sebille

mercado mercado wrote:
In Python, is it possible for an instance method to know the name of the 
class which is calling it? 


Well, the class name is in __class__ so changing
  'print x' to
  'print __class__'
will show foo in both cases, which is in fact the name of the class 
which is calling it.


Of course, what you want is the name of the thing chained in front of 
that.  There are and are not ways of getting to that.  Dig into the 
traceback module.


But I'd pass a parameter to foo's __init__ such as foo('bar') and 
foo('again') and it'd always work.


HTH,

Emile


For example, in the sample below, I would 
like for the someMethod method to print the name of the class calling it 
("bar" in the first case, "again" in the second).


---
class foo():
def someMethod(self):
print x
   
class bar():

def __init__(self):
f = foo()
f.someMethod()
   
class again():

def __init__(self):
f = foo()
f.someMethod()

bar()
again()
---




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


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


Re: Files application architecture

2008-09-05 Thread Diez B. Roggisch

Benjamin Watine schrieb:

Hi,

I'm about to develop a small python application and I wonder how to 
organize files in this application.
I'm familar to java, so I'm tempted to use the same convention : 1 file 
per class and 1 folders per package.


I know that packages doesn't exists in python, they are modules instead.


This is wrong. There are packages & modules in python.

http://docs.python.org/tut/node8.html

And please *don't* do put one class per module, as you would do in Java! 
Instead, group related classes into modules, breaking them up into 
several submodules if size or differences in usage suggest so.


May I create specific module for each "group of class" ? My application 
follow the MVC paradigm, so basically, I've a package Model, a package 
View, and a package Controller.


So, what are best practices for organizing files and folders in a small 
python project ?
I've found PEP8 (http://www.python.org/dev/peps/pep-0008/) that gives a 
lot of good hints on coding convention, but nothing about files 
organization.


The MVC pattern is more important in terms of actual classes written, 
not so much regarding their distribution over a set of files. If you 
want, start with one big single module inside a application-naming 
package - or even no package at all. Split up if you need to.


Or just go for

/__init__.py
/model.py
/view.py
/controller.py


if you *must*.

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


Re: hashing an array - howto

2008-09-05 Thread bearophileHUGS
Michael Palmer:
> why can't it be tuple already?

Because if the input list L has tuples and lists, they end having the
same hash value:

>>> L = [[1,2,3], (1,2,3)]
>>> hash(tuple(L[0])), hash(tuple(L[1]))
(-378539185, -378539185)

But it's a not much common situation, and few hash collision pairs
can't damage much, so I agree with you that my assert was useless.
This may solve that problem anyway:

hash(type(L)) ^ hash(tuple(L))

Generally a good hashing functions uses all the input information. If
you use tuple() you ignore part of the input information, that is the
type of L. So xor-ing hash(type(L)) you use that information too.


> you can discard the tuple, so the memory requirement is transient.

Right, but there's lot of GC action, it may slow down the code. So you
can start using hash(tuple(L)), but if later the code performance
comes out bad, you may try a different version that creates less
intermediate garbage.

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: max(), sum(), next()

2008-09-05 Thread castironpi
On Sep 5, 3:28 am, "Manu Hack" <[EMAIL PROTECTED]> wrote:
> On Thu, Sep 4, 2008 at 4:25 PM, castironpi <[EMAIL PROTECTED]> wrote:
> > On Sep 4, 2:42 pm, [EMAIL PROTECTED] wrote:
> >> David C. Ullrich:
>
> >> > At least in mathematics, the sum of the elements of
> >> > the empty set _is_ 0, while the maximum element of the
> >> > empty set is undefined.
>
> >> What do you think about my idea of adding that 'default' argument to
> >> the max()/min() functions?
>
> >> Bye,
> >> bearophile
>
> > For max and min, why can't you just add your argument to the set
> > itself?
>
> > The reason max([]) is undefined is that max( S ) is in S.
>
> It makes sense.
>
> >The reason sum([]) is 0 is that sum( [ x ] ) - x = 0.
>
> It doesn't make sense to me.  What do you set x to?

For all x.
--
http://mail.python.org/mailman/listinfo/python-list


Documentation (was Re: atomic section in code)

2008-09-05 Thread Fredrik Lundh

Michele Simionato wrote:


The page you link here is WAYS better than the standard documentation
of the threading module.
Generally speaking, the effbot zone contains a lot of improvements
over the standard docs which are lacking in various areas.
I have always wondered why they are kept separated. Wouldn't be nice
to have the standard
docs integrated with the effbot docs? Are there plans in this sense
and if not, why not?


There are tons of great supplementary material out there, on blogs, 
personal documentation collections (such as effbot.org), cookbook sites, 
etc.  I don't think all that material absolutely must be posted to 
python.org, but Python users would definitely benefit from improved 
cross-linking.


And this is, of course, something I've lobbied for many times, e.g.

 http://mail.python.org/pipermail/python-list/2005-May/34.html
 http://mail.python.org/pipermail/python-list/2005-December/355625.html
 http://effbot.org/zone/idea-seealso.htm

but I haven't yet figured out how to get something to happen [1].  All 
ideas are welcome.




1) Well, I guess the new Sphinx tool might have gotten some inspiration 
by my work in this domain:


 http://mail.python.org/pipermail/python-dev/2006-January/059978.html

and Andrew Kuchling did some preliminary work for the old Latex work flow:

 http://svn.python.org/view/sandbox/trunk/seealso/

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


Re: atomic section in code

2008-09-05 Thread Fredrik Lundh

Diez B. Roggisch wrote:

AFAIC that kind of mutual exclusion is what atomicity is about. What 
else do you expect to happen?


sounds like he wants/needs non-cooperative, mandatory locking.



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


Re: Case-insensitive string compare?

2008-09-05 Thread Fredrik Lundh

Maric Michaud wrote:

I suspect you are coming to conclusions a bit quickly, without taking the pain 
of understanding the whole discussion.


I'm pretty sure I was the first one to post an answer in this thread, 
and I understand Python design and performance issues very well, thank you.


(but given your talk about "the cost of whitespace" in a response to a 
comment about performance in that other subthread, it's obvious that 
you're just here to provide noise.  plonk plonk.)




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


Re: Python and Cyrillic characters in regular expression

2008-09-05 Thread Fredrik Lundh

phasma wrote:


string = u"Привет"
(u'\u041f\u0440\u0438\u0432\u0435\u0442',)

string = u"Hi.Привет"
(u'Hi',)


the [\w\s] pattern you used matches letters, numbers, underscore, and 
whitespace.  "." doesn't fall into that category, so the "match" method 
stops when it gets to that character.


maybe you could use re.sub or re.findall?

>>> # replace all non-alphanumerics with the empty string
>>> re.sub("(?u)\W+", "", string)
u'Hi\u041f\u0440\u0438\u0432\u0435\u0442'

>>> # find runs of alphanumeric characters
>>> re.findall("(?u)\w+", string)
[u'Hi', u'\u041f\u0440\u0438\u0432\u0435\u0442']
>>> "".join(re.findall("(?u)\w+", string))
u'Hi\u041f\u0440\u0438\u0432\u0435\u0442'

(the "sub" example expects you to specify what characters you want to 
skip, while "findall" expects you to specify what you want to keep.)




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

Re: max(), sum(), next()

2008-09-05 Thread Mensanator
On Sep 5, 1:08 am, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On Thu, 4 Sep 2008 18:09:49 -0700 (PDT), Mensanator <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
>
> > Too bad. I brought this up because I use Python a lot with
> > database work and rarely for proving theorms in ZFC.
>
>         As a by-stander... let the DBMS do its work, don't try to make
> Python do what DBMS SQL does...

Sure, and in most cases I use Visual Basic for Applications
when I need functionality I can't get directly from SQL.

But anybody who's used VBA with Access must know what a PITA
it is. And even when you get it working, you sometimes wish you
hadn't. I have a Mann-Kendall trend analysis that must be done
quarterly on over 150 combinations of well:analyte. It takes
over 6 hours to process this (and I don't know how much is due to
VBA, Access, server, network, etc.). It's something I'd love to
try in Python (if I can find the time to translate it).

But I'm wary of things that Python might do (such as return 0
when summing an empty list) that SQL/VBA does not.


> --
>         Wulfraed        Dennis Lee Bieber               KD6MOG
>         [EMAIL PROTECTED]             [EMAIL PROTECTED]
>                 HTTP://wlfraed.home.netcom.com/
>         (Bestiaria Support Staff:               [EMAIL PROTECTED])
>                 HTTP://www.bestiaria.com/

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


Re: max(), sum(), next()

2008-09-05 Thread Ken Starks

David C. Ullrich wrote:

In article <[EMAIL PROTECTED]>,
 Ken Starks <[EMAIL PROTECTED]> wrote:


David C. Ullrich wrote:


I don't see why you feel the two should act the same.
At least in mathematics, the sum of the elements of
the empty set _is_ 0, while the maximum element of the
empty set is undefined. 


And both for good reason:

(i) If A and B are disjoint sets we certainly want to
have sum(A union B) = sum(A) + sum(B). This requires
sum(empty set) = 0.

(ii) If A is a subset of B then we should have
max(A) <= max(B). This requires that max(empty set)
be something that's smaller than everything else.
So we give up on that.

Do we give up? Really ?


Erm, thanks. I was aware of all that below. If we're
being technical what's below is talking about the sup
and inf, which are not the same as max and min. More
relevant to the present context, I didn't mention what's
below because it doesn't seem likely that saying max([])
= -infinity and min([]) = +infinity is going to make the
OP happy...



Of course you were aware, I have seen enough of your posts
to know that. And I agree that, whatever Wikipedia seems to
imply, max and supremum should be distiguished.

It was your prelude, "At least in mathematics ..." that
made me prick up my ears. So I couldn't resist responding,
without _any_ malice I assure you.

Cheers,
Ken.

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


Re: "Full" element tag listing possible with Elementtree?

2008-09-05 Thread jaime . dyson
On Sep 4, 11:43 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > 
> >    this is node b 
> >    this is node c
> >     
> >      this is node e 
> >   
> >    this is node f 
> > 
>
> > I would want to print the following:
>
> > 
> >  
> >   text: this is node b
> >  
> >   text: this is node c
> >   
> >   
> >text: this is node e
> >  
> >   this is node f
>
> > Is there a simple way to do this?  Any help would be appreciated.
>
> in stock ET, using a parent map is probably the easiest way to do this:
>
>      http://effbot.org/zone/element.htm#accessing-parents
>
> that is, for a given ET structure "tree", you can do
>
> parent_map = dict((c, p) for p in tree.getiterator() for c in p)
>
> def get_parents(elem):
>      parents = []
>      while 1:
>          elem = parent_map.get(elem)
>          if elem is None:
>              break
>          parents.append(elem)
>      return reversed(parents)
>
> for elem in tree.getiterator():
>      print list(get_parents(elem)), elem
>
> 

Fantastic.  Thank you very much, Fredrik!  And thanks for ET!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Make Games

2008-09-05 Thread David

NightZombie wrote:

x-no-archive: yes

I want to learn Python so I can make simple games. What are some good
books that'll help me do this?
--
http://mail.python.org/mailman/listinfo/python-list


  

Good book you can get used;

Python Programming for the Absolute Beginner
http://books.google.com/books?id=DH3TcrHM8s4C



--
Have Fun,
David A.

Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com

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


sqlite3 import performance

2008-09-05 Thread Ben Lee
hi folks --

a quick python and sqlite3 performance question.  i find that
inserting a million rows of in-memory data into an in-memory database
via a single executemany() is about 30% slower than using the sqlite3
CLI and the .import command (reading the same data from a disk file,
even.)  i find this surprising, executemany() i assume is using a
prepared statement and this is exactly what the .import command does
(based on my quick perusal of the source.)

is this discrepancy to be expected?  where is the overhead coming
from?

for full disclosure:  the python code is at the end; run it first to
generate the data file.  to test the CLI, i couldn't find a better way
than to create an init file "sqlcmds" containing

create table test (k int primary key, v int not null);
.import data test

and then run

time sqlite3 -init sqlcmds ':memory:' '.quit'

the python code is

#!/usr/bin/env python

import sqlite3, random, timeit

con = None
def prepare():
global con, cur

con=sqlite3.connect(':memory:')
con.isolation_level="EXCLUSIVE"
cur=con.cursor()

def ins():
global con, data, cur

try:
cur.execute('drop table test')
except:
pass
cur.execute('create table test (key int primary key, val int not
null);')
con.commit()

cur.executemany("INSERT into test (key, val) values (?, 10)",data)
con.commit()

hs = {}

print 'generating data...'
size = 100
data = [[a] for a in random.sample(xrange(1000), size)]
print 'done!'

# save the data for the sqlite3 CLI
f = file('data', 'w')
f.writelines([str(a[0])+"|10\n" for a in data])
f.close()

print 'testing ' + str(size) + ' inserts...'
# test 100K inserts
t = timeit.Timer(stmt='ins()',
 setup="import sqlite3\nfrom __main__ import prepare, ins
\nprepare()")
print t.repeat(3,1)

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


Re: PyGUI as a standard GUI API for Python?

2008-09-05 Thread Peter Decker
On Fri, Sep 5, 2008 at 10:48 AM, Diez B. Roggisch <[EMAIL PROTECTED]> wrote:

> You got me wrong. I didn't say it doesn't use the native toolkit under
> various OSes, I'm well aware of that it does.
>
> What I *did* say was that wx API is designed primarily with windows' toolkit
> as base, and as a consequence the API tends to be less functional for other
> toolkits, making it harder to work with it. As the OP was after a "one API
> to rule them all" for GUIs, I pointed that out.
>
> See for example this (arguably somewhat dated) post that illustrates my
> point:
>
> http://mail.python.org/pipermail/python-list/2005-March/313354.html

OK, that's a little clearer.

That's one of the things that I like about Dabo - it gets rid of the
ugly (IMO) wxPython API and replaces it with a much more consistent
(and, IMO) more Pythonic API. I hated coding in wx, but I love coding
in Dabo.

-- 

# p.d.
--
http://mail.python.org/mailman/listinfo/python-list


Re: xml + mmap cross

2008-09-05 Thread castironpi
On Sep 5, 12:13 am, Stefan Behnel <[EMAIL PROTECTED]> wrote:
> Hi,
>
> this discussion seems pretty much off-topic for a Python list.
>
>
>
> castironpi wrote:
> > In an XML file, entries are stored in serial, sort of like this.
>
> > AAA BBB CCC DDD
>
> > Or more recognizably,
>
> > somethingsomething
>
> > Point is, to change something to something else, you
> > have to recopy everything after that.
>
> > AAA BBB CCC DDD
> > AAA BBBb CCC DDD
>
> > requires 7 writes, 'b CCC DDD', not 1.
>
> > I want to use a simple tree structure to store:
>
> > 0 A-> None, 1
> > 1 B-> None, 2
> > 2 C-> 3, None
> > 3 D-> None, None
>
> > Each node maps to 'Next, Child', or more accurately, 'Next Sibling,
> > First Child'.
>
> Do I understand you right: you want to access serialised XML data

alex23 correctly pointed out last night that XML is always
serialized.  What I mean and possibly what you mean is, a serialized
tree structure.

> as a memory
> mapped file and operate directly on the byte data?

Yes.  Byte data containing both strings, and the structure of the
tree.

> You would still have to
> decode the complete byte sequence to parse it and build your index structure
> in that case.

No, it's saved in an index structure; it's already in one.  To find a/
b/c, read a, read its children to b, read b, read its children to c,
read c.

> How do you plan to store the pointers to a node's next sibling/child? And how
> do you keep them updated over insertions/deletions?

You update them when you insert them.  To add 'c' to a/b, allocate c,
initialize c, read a, read its children to b, read b, read its
children to the end, add c.

When you delete c from a/b/c, however, any references to c that you
have in any programs become invalid.  Don't delete it if you have
them.  The bytes are marked in the file to be no longer in use, which
marking takes up some of the space in the file.

> That, plus the copy
> overhead in a sequential file, will be very costly on each change.

No.  That's the point of a dynamic structure.   are not
stored in memory as 10 consecutive characters.  The file is not
strictly speaking XML.  See below for what they're stored as.

> > You get constant time updates to contents, and log-time searches.
>
> Every XML tree structure gives you log-time searches. But how do you achieve
> constant time updates in a sequential file?

You don't use a sequential file.

> Stefan

I stated earlier that each node would look roughly like:
tag_offset, first_attr, text_offset, tail_offset, first_child,
prev_sibling, next_sibling, parent

Attributes would look like:
key_offset, value_offset, prev_attr, next_attr, node

All these fields are integers that contain an offset into the file.

Simplified:

0 Reserved
1 A.Tag 7 (points to 7 below)
2 A.FirstChild 4 (etc.)
3 A.Contents 0 (None)
4 B.Tag 11
5 B.FirstChild 0
6 B.Contents 15
7 3abc
11 3def
15 5ghijk

This translates to:

ghijk

But isn't stored that way.

The records are all the same size.  The 'Tag' field of a record that
starts at offset J is at offset J.  The 'FirstChild' field of a record
that starts at offset K is at offset K+ 1.

'tag_offset', 'text_offset', 'key_offset', and 'value_offset' contain
offsets of variable-length strings into the file ( 7, 11, 15 ).  The
rest contain offsets of further structures.

There's extra space usage not only in the structure of the tree, but
in the record-keeping of what bytes are available for use, and which
are in use.  You have to grow the file size yourself (like growing an
array) when you need to; the file system won't for you in mmap.  (This
means the alloc-free module I'm looking at will need modifications.)

I'll reemphasize the value of constant-time insertions to a file
though.
--
http://mail.python.org/mailman/listinfo/python-list


Re: pdb bug and questions

2008-09-05 Thread R. Bernstein
castironpi <[EMAIL PROTECTED]> writes:

> On Sep 4, 4:22 pm, Stef Mientki <[EMAIL PROTECTED]> wrote:
>> hello,
>>
>> I'm trying to embed a debugger into an editor.
>> I'm only interested in high level debugging.
>> The first question is what debugger is the best for my purpose ?
>> (pdb, pydb, rpdb2, smart debugger, extended debugger ?
>>
>> Second question, in none of the above debuggers (except rpdb2),
>> I can find a  "break now",
>> so it seems impossible to me to detect unlimited while loops ?
>>
>> For the moment I started with pdb, because most of the debuggers seems
>> to be an extension on pdb.
>> When I launch the debugger ( winXP, Python 2.5) from with my editor
>>   python -u -m pdb  D:\\Data\\test_IDE.py
>> I get this error
>>   IOError: (2, 'No such file or directory', 'D:\\Data\test_IDE.py')
>> NOTICE 1 backslash --^
>>
>> If I launch the debugger with
>>   python -u -m pdb  D:/Data/test_IDE.py
>> It runs fine.
>>
>> This looks like a bug to me.
>> What's the best way to report these kind of bugs ?
>>
>> Although I mostly use os.path.join to be OS independent,
>> these kind of bugs give me the impression,
>> that I can better do the join myself and always use forward slashes.
>> Is this a valid conclusion ?
>>
>> thanks,
>> Stef Mientki
>
> Stef,
>
> I discovered the same problem too with my editor.  I solved it by
> using only the file name, and setting the initial directory on the
> executable.

I don't know if this helps, but in pydb there is an option to set the
initial directory the debugger works in. Inside the debugger there is
the gdb command "cd". 
--
http://mail.python.org/mailman/listinfo/python-list


Determining Processor Vender

2008-09-05 Thread aha
Dose anyone know of a cross-platform method for determining the vendor
of a processor?  Under linux I can check /proc/cpuinfo.  What I'd like
to be able to do is determine if a processor is AMD or Intel, so that
I can use the appropriate numerical libraries for my application.

Regards,

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


Re: Determining Processor Vender

2008-09-05 Thread aha
On Sep 5, 3:00 pm, aha <[EMAIL PROTECTED]> wrote:
> Dose anyone know of a cross-platform method for determining the vendor
> of a processor?  Under linux I can check /proc/cpuinfo.  What I'd like
> to be able to do is determine if a processor is AMD or Intel, so that
> I can use the appropriate numerical libraries for my application.
>
> Regards,
>
> Aquil

Additionally, I've tried the platform module...platform.processor() on
my 64-bit AMD system, under Linux, returns x86_64.  And under windows
retruns an empty string ''
--
http://mail.python.org/mailman/listinfo/python-list


Re: pdb bug and questions

2008-09-05 Thread R. Bernstein
Stef Mientki <[EMAIL PROTECTED]> writes:

> hello,
>
> I'm trying to embed a debugger into an editor.
> I'm only interested in high level debugging.
> The first question is what debugger is the best for my purpose ?
> (pdb, pydb, rpdb2, smart debugger, extended debugger ?
>
> Second question, in none of the above debuggers (except rpdb2),
> I can find a  "break now",
> so it seems impossible to me to detect unlimited while loops ?

I am not sure what you mean by "break now". pdb and pydb allow direct
calls from a program to the debugger via set_trace (which in pydb is
deprecated in favor of I think the more descriptive name: debugger)

But I suspect this is not what you mean to "detect unlimited while
loops"; pydb also has gdb-style signal handling that allows for entry
into the debugger when the debugged python process receives a
particular signal. "info handle" lists all of the interrupts and what
action is to be taken on each. See
http://bashdb.sourceforge.net/pydb/pydb/lib/node38.html

However I believe that signals are only handled by the main thread; so
if that's blocked, the python process won't see the signal.

>
> For the moment I started with pdb, because most of the debuggers seems
> to be an extension on pdb.
> When I launch the debugger ( winXP, Python 2.5) from with my editor
>  python -u -m pdb  D:\\Data\\test_IDE.py
> I get this error
>  IOError: (2, 'No such file or directory', 'D:\\Data\test_IDE.py')
> NOTICE 1 backslash --^
>
> If I launch the debugger with
>  python -u -m pdb  D:/Data/test_IDE.py
> It runs fine.
>
> This looks like a bug to me.
> What's the best way to report these kind of bugs ?

winpdb, pydb and pdb (part of Python) all have Sourceforge projects
which have bug trackers. For pdb, in the past people includng myself,
have reported features, patches and bugs in the Python tracker;
eventually it gets handled. (Eventually in my case means a year or
so.) But if my information is incorrect or out of date, no doubt
someone will correct me.

As mentioned in the last paragraph, pydb also is a Sourceforge project
(part of bashdb) which has a tracker for bug reporting. Using the bug
tracker I think is better than discussing pydb bugs in c.l.p. By
extension, I assume the same is also true for the other debuggers.

Finally, I think rpdb2 is part of the winpdb project on Sourceforge
and again has a bug tracker. My sense is that Nir Aides is very good
about handling bugs reported in winpdb/rpdb.

>
> Although I mostly use os.path.join to be OS independent,
> these kind of bugs give me the impression,
> that I can better do the join myself and always use forward slashes.
> Is this a valid conclusion ?
>
> thanks,
> Stef Mientki
--
http://mail.python.org/mailman/listinfo/python-list


Re: "Full" element tag listing possible with Elementtree?

2008-09-05 Thread Carl Banks
On Sep 5, 2:27 am, [EMAIL PROTECTED] wrote:
> So, for example, if I had a document that looked like this:
>
> 
>this is node b 
>this is node c
> 
>  this is node e 
>   
>this is node f 
> 
>
> I would want to print the following:
>
> 
>  
>   text: this is node b
>  
>   text: this is node c
>   
>   
>text: this is node e
>  
>   this is node f
>
> Is there a simple way to do this?  Any help would be appreciated.
> Thanks..

Fredrik Lundh wrote Element Tree, so he'd know the best solution, but
I'd like to point out that this is also trivially easy with recursion:


def print_nodes(element, ancestors = []):
s = hierarchy = ancestors + ["<" + element.tag + ">"]
if element.text is not None:
s = s + [element.text]
print " ".join(s)
for subelement in element:
print_nodes(subelement,hierarchy)



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


Need formatting suggestion for long strings

2008-09-05 Thread Robert Dailey
Hi,

I find quite often that I'm writing things like this:

raise FatalExcept( "Insufficient number of arguments specified. Exactly {0}
arguments are required. See stage.bat for documentation on accepted
parameters.".format( num_arguments ) )

On my display (Vertical monitor), this exceeds the width of my display, and
to view the entire length of the string I am forced to pan my view left and
right. Is there a special way I can format this string so that it fits
nicely on the screen? Keep in mind that one important factor is that
whitespace is very sensitive, and I do not want line breaks in my script
file to become part of the string itself. I like how C++ handles strings,
like this:

char const* mystring =
"This is a very long string that "
"spans multiple lines and does "
"not include line breaks or tabs "
"from the source file between "
"the strings partitions."


What do you guys prefer? Thanks for reading.
--
http://mail.python.org/mailman/listinfo/python-list

Re: use str as variable name

2008-09-05 Thread Marco Bizzarri
On Thu, Sep 4, 2008 at 10:47 AM, Fredrik Lundh <[EMAIL PROTECTED]> wrote:

>
> (...as Bruno implies, setattr(), len() et al can be and should be viewed as
> generic functions.

Just a question: "generic functions" are not meant in the sense of
"generic functions" of CLOS, am I right?

-- 
Marco Bizzarri
http://notenotturne.blogspot.com/
http://iliveinpisa.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


[PIL] quake like multicoloured text

2008-09-05 Thread Durand
I'm wondering how I could render text with PIL in which different
parts of the text are different characters. This is for a game stats
script where names are written like:
^1Red ^2Green ^3Yellow, etc.
The problem is that I currently use text in the ImageDraw module but
the only way I can think of rendering text is by rendering each bit of
text in a separate colour.

Example:

draw.text((0,0),"Red", fill="red")
draw.text((30,0),"Green", fill="green")
draw.text((60,0),"Yellow", fill="green")

except that I'm not sure how much spacing there is between each
coloured bit of text(30px is assumed in the example)...Would there be
an alternate method of doing this?

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


Re: Need formatting suggestion for long strings

2008-09-05 Thread Jean-Paul Calderone

On Fri, 5 Sep 2008 14:24:16 -0500, Robert Dailey <[EMAIL PROTECTED]> wrote:

Hi,

I find quite often that I'm writing things like this:

raise FatalExcept( "Insufficient number of arguments specified. Exactly {0}
arguments are required. See stage.bat for documentation on accepted
parameters.".format( num_arguments ) )

On my display (Vertical monitor), this exceeds the width of my display, and
to view the entire length of the string I am forced to pan my view left and
right. Is there a special way I can format this string so that it fits
nicely on the screen? Keep in mind that one important factor is that
whitespace is very sensitive, and I do not want line breaks in my script
file to become part of the string itself. I like how C++ handles strings,
like this:

char const* mystring =
   "This is a very long string that "
   "spans multiple lines and does "
   "not include line breaks or tabs "
   "from the source file between "
   "the strings partitions."


What do you guys prefer? Thanks for reading.



mystring = (
   "This is a very long string that "
   "spans multiple lines and does "
   "not include line breaks or tabs "
   "from the source file between "
   "the strings partitions.")

Jean-Paul

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


Re: quake like multicoloured text

2008-09-05 Thread Durand
Oops, I meant, "I'm wondering how I could render text with PIL in
which different
parts of the text are different *colours*."
--
http://mail.python.org/mailman/listinfo/python-list


Re: pdb bug and questions

2008-09-05 Thread Stef Mientki

R. Bernstein wrote:

Stef Mientki <[EMAIL PROTECTED]> writes:

  

hello,

I'm trying to embed a debugger into an editor.
I'm only interested in high level debugging.
The first question is what debugger is the best for my purpose ?
(pdb, pydb, rpdb2, smart debugger, extended debugger ?

Second question, in none of the above debuggers (except rpdb2),
I can find a  "break now",
so it seems impossible to me to detect unlimited while loops ?



I am not sure what you mean by "break now". pdb and pydb allow direct
calls from a program to the debugger via set_trace (which in pydb is
deprecated in favor of I think the more descriptive name: debugger)
  
But I suspect this is not what you mean to "detect unlimited while

loops"; pydb also has gdb-style signal handling that allows for entry
into the debugger when the debugged python process receives a
particular signal. "info handle" lists all of the interrupts and what
action is to be taken on each. See
http://bashdb.sourceforge.net/pydb/pydb/lib/node38.html

However I believe that signals are only handled by the main thread; so
if that's blocked, the python process won't see the signal.
  

Thanks,
Yes, I think the trace option can do the job,
certainly if I display every line.
Didn't know pdb had something like settrace ( the information on pdb is 
very condensed ;-)
  

For the moment I started with pdb, because most of the debuggers seems
to be an extension on pdb.
When I launch the debugger ( winXP, Python 2.5) from with my editor
 python -u -m pdb  D:\\Data\\test_IDE.py
I get this error
 IOError: (2, 'No such file or directory', 'D:\\Data\test_IDE.py')
NOTICE 1 backslash --^

If I launch the debugger with
 python -u -m pdb  D:/Data/test_IDE.py
It runs fine.

This looks like a bug to me.
What's the best way to report these kind of bugs ?



winpdb, pydb and pdb (part of Python) all have Sourceforge projects
which have bug trackers. For pdb, in the past people includng myself,
have reported features, patches and bugs in the Python tracker;
eventually it gets handled. (Eventually in my case means a year or
so.) But if my information is incorrect or out of date, no doubt
someone will correct me.
  

I'll take a look, for the sake of our children ;-)

As mentioned in the last paragraph, pydb also is a Sourceforge project
(part of bashdb) which has a tracker for bug reporting. Using the bug
tracker I think is better than discussing pydb bugs in c.l.p.

c.l.p. ?

 By
extension, I assume the same is also true for the other debuggers.

Finally, I think rpdb2 is part of the winpdb project on Sourceforge
and again has a bug tracker. My sense is that Nir Aides is very good
about handling bugs reported in winpdb/rpdb.
  

Yes I started with rpdb2,
and indeed Nir Aides is very helpfull,
but I think interfaceing rpdb2 is a little too difficult for me,
but I'll certainly add winpdb as the option for external debugging.

For now I think pydb is the choice,
better control and more functions than pdb,
and almost just as easy.

cheers,
Stef
  

Although I mostly use os.path.join to be OS independent,
these kind of bugs give me the impression,
that I can better do the join myself and always use forward slashes.
Is this a valid conclusion ?

thanks,
Stef Mientki


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


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


Re: Need formatting suggestion for long strings

2008-09-05 Thread aha
On Sep 5, 3:29 pm, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
> On Fri, 5 Sep 2008 14:24:16 -0500, Robert Dailey <[EMAIL PROTECTED]> wrote:
> >Hi,
>
> >I find quite often that I'm writing things like this:
>
> >raise FatalExcept( "Insufficient number of arguments specified. Exactly {0}
> >arguments are required. See stage.bat for documentation on accepted
> >parameters.".format( num_arguments ) )
>
> >On my display (Vertical monitor), this exceeds the width of my display, and
> >to view the entire length of the string I am forced to pan my view left and
> >right. Is there a special way I can format this string so that it fits
> >nicely on the screen? Keep in mind that one important factor is that
> >whitespace is very sensitive, and I do not want line breaks in my script
> >file to become part of the string itself. I like how C++ handles strings,
> >like this:
>
> >char const* mystring =
> >    "This is a very long string that "
> >    "spans multiple lines and does "
> >    "not include line breaks or tabs "
> >    "from the source file between "
> >    "the strings partitions."
>
> >What do you guys prefer? Thanks for reading.
>
> mystring = (
>     "This is a very long string that "
>     "spans multiple lines and does "
>     "not include line breaks or tabs "
>     "from the source file between "
>     "the strings partitions.")
>
> Jean-Paul

Can you be more specific?  What is the formatting criteria?  Are you
talking about formatting the string for display or are you talking
about the source?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Need formatting suggestion for long strings

2008-09-05 Thread Robert Dailey
On Fri, Sep 5, 2008 at 2:29 PM, Jean-Paul Calderone <[EMAIL PROTECTED]>wrote:

> mystring = (
>   "This is a very long string that "
>   "spans multiple lines and does "
>   "not include line breaks or tabs "
>   "from the source file between "
>   "the strings partitions.")


At first glance it looks like this is making a tuple. I didn't know this was
legal! But, this is definitely what I was looking for (Assuming it works).

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

  1   2   >