Re: wxPython problems with Fedora Core 5

2006-06-03 Thread Frank Millman

writeson wrote:
> Hi all,
>
> I'm trying to use wxPython from a fairly new installation of Fedora
> Core 5. I installed wxPython using yum -y install wxPython and that all
> seemed to work fine. However, when I run Python and do this:
>
> import wx
>
> I get this:
>
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "/usr/lib/python2.4/site-packages/wx/__init__.py", line 45, in ?
> from wxPython import wx
>   File "/usr/lib/python2.4/site-packages/wxPython/__init__.py", line
> 20, in ?
> import wxc
> ImportError: /usr/lib/libwx_gtk2-2.4.so.0: undefined symbol:
> pango_x_get_context
>
> Anyone have any ideas what's going on and what I can do to fix this?
>
> Thanks in advance,
> Doug

Here is a link to a message in the wxpython-users mailing list archive,
which apparently gives the solution to your problem.

http://tinyurl.com/gf276

I cannot vouch for it. I installed wxPython on FC5 without any
problems, using the FC4 binary rpm's from wxPython.org.

Hope it works for you.

Frank Millman

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


Re: An oddity in list comparison and element assignment

2006-06-03 Thread anton . vredegoor
Alex Martelli wrote:

> <[EMAIL PROTECTED]> wrote:

>> Can somebody please shut down this bot? I think it's running out of 
> 
> Much as you might love for somebody to "shut me down", that
> (unfortunately, no doubt, from your viewpoint) is quite unlikely to
> happen.  Although "making predictions is always difficult, especially
> about the future", the most likely course of events is that I shall
> continue for a while to survive, probably in tolerable health.

You've got that completely wrong. I was not trying to kill you but I was 
trying to revive you. A process that is not evolving is dead. Stopping 
it frees up valuable resources that enable it to become alive again.

Anton

'being alive is being mutable'
-- 
http://mail.python.org/mailman/listinfo/python-list


Missing unicode data?

2006-06-03 Thread Klaus Alexander Seistrup
Hi group,

I just came across the following exception:

#v+

$ python
Python 2.4.2 (#2, Sep 30 2005, 21:19:01)
[GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import unicodedata
>>> u'\N{LATIN LETTER SMALL CAPITAL BARRED B}'
UnicodeDecodeError: 'unicodeescape' codec can't decode bytes in position 0-38: 
unknown Unicode character name
>>> unicodedata.name(u'\u1d03')
Traceback (most recent call last):
  File "", line 1, in ?
ValueError: no such name
>>> ^D
$ 

#v-

When checking unicodedata.name() against each uchar in the file 
/usr/share/unidata/UnicodeData-4.0.1d1b.txt that came with the 
console-data package on my Ubuntu Linux installation a total of 
1226 unicode characters seems to be missing from the unicodedata 
module (2477 missing characters when checking against the latest 
database from unicode.org¹).  Is this a deliberate omission?

Cheers,
Klaus.

 ¹) http://www.unicode.org/Public/UNIDATA/UnicodeData.txt
-- 
Klaus Alexander Seistrup
SubZeroNet, Copenhagen, Denmark
http://magnetic-ink.dk/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: image lib & Qt4

2006-06-03 Thread Fredrik Lundh
Fredrik Lundh wrote:

>> To get better performance, you should be able to use PIL's tostring() 
>> method together with the QImage(buffer, width, height, depth, 
>> colortable, numColors, bitOrder) form of the QImage constructor.

I've posted a simple ImageQt interface module for PIL and PyQt4 here:

 http://svn.effbot.python-hosting.com/stuff/sandbox/pil/ImageQt.py

this interface handles 1, P, L, and RGB images efficiently.  usage:

 im = Image.open(...) # or some other pil operation

 qim = ImageQt.toimage(im)

 # to access the QImage, use qim.image.  e.g:

 label.setPixmap(QtGui.QPixmap.fromImage(qim.image))

note that the toimage() function returns a wrapper object, not a QImage 
instance.  I didn't find a reliable way to subclass from QImage, nor any 
other way to attach custom attributes to an existing QImage object.  if 
anyone knows how to do that, let me know.



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


Re: import confused by contents of working directory

2006-06-03 Thread greg
Jon wrote:
> It appears that (windows) python searches in the current working
> directory before looking in the local site-packages directory, or that
> '.' comes first in sys.path?

Unless it behaves very differently on Windows from
everything else, this isn't quite true. The current
directory is only put in the path when using the
interpreter interactively. When you do

   python somefile.py

the directory containing somefile.py is put at the
beginning of sys.path, not the current directory.
So you'd still have the same problem even if you
weren't cd'ed to the directory containing the test
program.

The moral is not to put your test program in the
same directory as your package files. (Or if you
must, have it delete sys.path[0] before importing
anything.)

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


Re: Selection in Tkinter Text widget.

2006-06-03 Thread greg
Ant wrote:

> Strange behaviour though (IMHO), that the selection is only shown if
> the widget has focus.

It's only strange if you're used to certain platforms.
This is normal behaviour in the Macintosh world. One
of the original Apple UI Guidelines was that there
should only be one selection visible at a time, so
that it's always clear what you're operating on.

(They seem to be breaking that now in MacOSX, which
I think is a backward step...)

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


Re: New to Python: Do we have the concept of Hash in Python?

2006-06-03 Thread greg
A.M wrote:

> In essence, Ruby language is the best, but Ruby platform is too young for 
> me. I'll give Ruby another two years and come back to it again.
> 
> I found the Python language quite powerful and easy. With mature and strong 
> community support.

Welcome aboard. It'll be interesting to see whether
you *still* want to switch back to Ruby after getting
to know Python for two years!

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


Re: Trying to get FreeImagePy to work.

2006-06-03 Thread Michele Petrazzo
Iain King wrote:
>> I'll try out FIPY's resizing tomorrow too.  OTOH, I have functions
>> to convert between PIL and wxPython, and functions to convert
>> betweem PIL and FIPY, but I don't see a function to convert FIPY to
>> wxPython?
>> 
> 
> Image at:  http://www.snakebomb.com/misc/example.tif
> 
> Iain
> 

Yes it's min-is-white::

michele:~$ tiffinfo example.tif
TIFFReadDirectory: Warning, example.tif: unknown field with tag 37680
(0x9330) encountered.
TIFF Directory at offset 0x1520 (5408)
   Subfile Type: (0 = 0x0)
   Image Width: 1696 Image Length: 1162
   Resolution: 200, 200 pixels/inch
   Bits/Sample: 1
   Compression Scheme: CCITT Group 4
   Photometric Interpretation: min-is-white# <--
   FillOrder: msb-to-lsb
   Samples/Pixel: 1
   Rows/Strip: 1162
   Planar Configuration: single image plane
   ImageDescription: DS
michele:~$

So you *need* to invert it to work correctly with PIL!

P.s. Added the convertToWx function, that return a wx.Image, to the 
Image class.

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


Re: Missing unicode data?

2006-06-03 Thread Fredrik Lundh
Klaus Alexander Seistrup wrote:

> When checking unicodedata.name() against each uchar in the file 
> /usr/share/unidata/UnicodeData-4.0.1d1b.txt that came with the 
> console-data package on my Ubuntu Linux installation a total of 
> 1226 unicode characters seems to be missing from the unicodedata 
> module (2477 missing characters when checking against the latest 
> database from unicode.org¹).  Is this a deliberate omission?

I'm pretty sure unicodename.name() doesn't look in the UnicodeData file 
on your machine, nor in the latest file from unicode.org.  in other 
words, you get whatever version that was used to create the Unicode data 
set in your Python distribution.

this is usually the version that was current when that Python version 
was originally released (i.e. in your case, when 2.4 was released).

iirc, 2.4 uses Unicode 3.2, and 2.5 uses Unicode 4.1.  to update, use 
the tools under Tools/unicode.



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


Re: Making a second window with Tkinter

2006-06-03 Thread Rob Williscroft
greenflame wrote in news:1149305472.893535.67770
@h76g2000cwa.googlegroups.com in comp.lang.python:

> Ok so I played with your script. Here is a script that more closely
> mimics what I would like to do except that the way I make the variable
> deckstr will be different. The only thing I am confused about is that
> it opens the second window in the beginning and when I click on the
> button, it does nothing even after I have closed the other window.
> 
> from Tkinter import *
> from string import join
> 
> root = Tk()
> 
> def showdeck(deck):
>deckwin = Toplevel()
>deckstr = join(deck, "\n")
>Label(deckwin, text=deckstr, justify=LEFT, anchor=W,
> font="Courier").pack(fill=X)
> 
> L = Button(root, text="Show Deck", font="Courier",
> command=showdeck(list('zxcvbnm')))

You made the buttons command option None (which is what 
showdeck() returns), you need to make command a function 
that calls showdeck(list('zxcvbnm')).
 
L = Button(root, text="Show Deck", font="Courier",
command= lambda : showdeck(list('zxcvbnm')))

> L.pack()
> 
> root.mainloop()
> 

lambda's docs online:
http://docs.python.org/ref/lambdas.html

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


can python be a "shell" of c++ program?

2006-06-03 Thread key9
Hi all

I have some data to process, whith complex mechanism,I put these process 
mechanism as plugins.
and design lots of classes to abstract data themselves.

but the question is how to drive them work together.

That cause too much jobs: I should write UI,parser..almost a completed 
system.

The problem is I don't know what these processed data will finally needed to 
display to user.
maybe this , may be that, these can not know on design time.

what I need is on outside of program,
I can use some interface to get these data what I want , or push back data, 
or told program to recalculate it.


can I have a way to drive c++ code use this script-like way ?


thank you very much



 key9








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


Re: logging

2006-06-03 Thread Baurzhan Ismagulov
Hello Vinay,

On Wed, May 31, 2006 at 03:05:13PM -0700, Vinay Sajip wrote:
> > Hmm, log1 decides once whether to print an event, and after that it gets
> > printed in log1 and all its ancestors, regardless of their level? I find
> > this quite counter-intuitive. I'd instead expect that each logger
> > decides whether to print an event according to its own level. Could you
> > give an example why one would want the python behavior?
> 
> Loggers are hierarchical for a reason - not just randomly named
> channels. ...

Thanks for the explanation! Please note that I am not questioning the
usefulness of hierarchical logging -- I think it's a Good Thing. What I
can't understand is the motivation for the single place of decision
whether a message should be printed ("is enabled" in log4j terms) or
not.

Consider the following scenario: root is CRITICAL, l01 is DEBUG, a debug
message is logged on l01. l01 decides that the message should be
printed, and _both_ root and l01 print it. Now, it is good that the
message is propagated to root, but why doesn't root decide for itself
whether to print it or not?

For instance, I log root to syslog and have only critical messages
there. I log l01 to console to debug. I want that my message to l01 is
not printed by root since its level is CRITICAL. This is why I want that
each logger re-evaluates the message level for itself. Could you perhaps
give a useful example why one could want loggers to decide once?


And another thing I couldn't find how to do: I want to have several
debug levels. I can log messages without problems, but numeric values in
the configuration file cause error messages during
logging.config.fileConfig. Can I specify numeric values in the config
file?


With kind regards,
Baurzhan.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Missing unicode data?

2006-06-03 Thread Klaus Alexander Seistrup
Fredrik Lundh skrev:

> I'm pretty sure unicodename.name() doesn't look in the Unicode-
> Data file on your machine, nor in the latest file from unicode.org.

I am pretty sure of that, too.  I was only using those files as a 
reference against the unicode data that comes with my python interpreter.

> in other words, you get whatever version that was used to create 
> the Unicode data set in your Python distribution.

I see.

> iirc, 2.4 uses Unicode 3.2, and 2.5 uses Unicode 4.1.  to update, 
> use the tools under Tools/unicode.

Thanks for the hint.

Mvh, 

-- 
Klaus Alexander Seistrup
SubZeroNet, Copenhagen, Denmark
http://magnetic-ink.dk/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: grouping a flat list of number by range

2006-06-03 Thread joh12005

thanks to all !

my version was far less clever/long thant the one you posted, i'm going
to examine all these with much interest, and learn...

best regards.

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


Re: An oddity in list comparison and element assignment

2006-06-03 Thread michael . f . ellis
Hey Alex, lighten up! Python is a programming language -- not your
family, religion, or civil rights.
Cheers,
Mike

Alex Martelli wrote:
> <[EMAIL PROTECTED]> wrote:
>...
> > (As an aside, may I point out that Python In A Nutshell states on page
> > 46 "The result of S*n or n*S is the concatenation of n copies of S". It
> > might be well to put a warning in a future edition that this is not
> > strictly the case.)
>
> Can you give me an example where, say, for a sequence S,
>
> x = S * 3
>
> is not structurally the same as
>
> x = copy.copy(S) + copy.copy(S) + copy.copy(S)
>
> ...?  That is, where the "* 3" on a sequence is NOT the concatenation of
> three copies (ordinary copies, of course!) of that sequence?  I don't
> think you can... and I can't repeatedly explain or point to the
> distinction between normal, ordinary, shallow copies on one side, and
> "deep copies" on the other, every single time in which that distinction
> MIGHT be relevant (because some reader might not be aware of it); such
> endless repetition would bloat the Nutshell totally away from its role
> as a CONCISE desktop reference, and seriously hamper its usefulness
> (particularly by DESTROYING any trace of usefulness for anybody who's
> finally *GOT* this crucial bit, but not just in that way).
>
>
> > languages and methodologies.  As I noted in an earlier reply, I don't
> > realistically expect Python to change the behavior of the == operator.
>
> Then you might have avoided trying to convince anybody, or even trying
> to IMPLY, that in an ideal version of Python == *SHOULD* behave your way
> -- Python's semantics *ARE* entirely up for rediscussion at the moment,
> with an eye on the future "Python 3000" release, so this is one of the
> very rare periods of the history of the language where backwards
> incompatibility of a potential change is _NOT_ a blocking point.
>
> By asserting that your version of == would be "more natural", and trying
> to defend that assertion by vague handwaving references to maths and
> "real world", you managed to entirely shift MY mindstate (and possibly
> that of several other discussants) into one of total and absolute
> opposition to the proposal -- having by now spent considerable time and
> energy pondering and debating the issue, I am now entirely convinced
> that a language with such an == operator instead of Python's current one
> would be such a total, unadulterated disaster that I would refuse to use
> that language, no matter what other "good" features it might present to
> me.  I've walked away from great jobs, just because they would have
> required me to use some technology I just could not stand, more than
> once already in my life: and this IS how strongly (and negatively) I
> feel about your claim that, for built-in ==, your semantics would be in
> any way preferable to Python's.
>
> By managing to thus focus my mindset (and make me spend my energy and
> time) in opposition to your claims of "more natural", you have at least
> managed to ensure that I will not now lend any scrap of help or support
> to your debugging needs.  If you were as pragmatic as you claim to be,
> this kind of consideration WOULD have weighed highly in your choices.
>
> I.ie., if you had WANTED to attract any such support and help, a
> completely different attitude than that "most natural" claim would have
> been ENORMOUSLY more productive -- and your continuing attempts to
> debate that issue aren't helping AT ALL either:
>
> > I do think that a problem arose when it was adopted from C and extended
> > to allow comparison of containers.  In C, you can use it to compare
> > integers, floats, and pointers and everyone understands that p==q does
> > not imply *p == *q.
>
> If that is so, then everyone is utterly, totally, entirely, horribly
> *WRONG*, because, in C, p==q ***DOES*** imply *p == *q (whenever p --
> and by consequence q, given equality -- may legitimately be
> dereferenced: p == q == 0 does not imply anything about *p and/or *q,
> which may produce random results, crash the process, or whatever -- of
> course).
>
> You no doubt meant to say something entirely different from what you
> ACTUALLY said, but I respectfully suggest you spare your breath rather
> than keep trying to defend an indefensible position.
>
> I do NOT agree, and I cannot imagine any state of the world that would
> get me to agree, with your claim that "a problem arose" by allowing
> equality comparison of containers in Python (many other languages allow
> such comparisons, BTW; I would consider it a horrible wart if a language
> claiming to be "higher level" did NOT).  That you're "supporting" (HA!)
> your absurd claim with an equally absurd (and obviously, wholly false,
> unfounded, and misplaced) claim about C pointers doesn't "help", of
> course, but even perfectly accurate claims about C (or machine code, or
> Cobol, or RPG...) would be pretty much uninteresting and irrelevant.
>
> > Moreover, compilers issue warnings abou

Re: [ANN] lxml 1.0 released

2006-06-03 Thread Stefan Behnel
Kent Johnson wrote:
> Stefan Behnel wrote:
>> Hallo everyone,
>>
>> I have the honour to announce the availability of lxml 1.0.
>>
>> http://codespeak.net/lxml/
>>
>> It's downloadable from cheeseshop:
>> http://cheeseshop.python.org/pypi/lxml
> 
> Are there any plans to offer a Windows installer?

Already there. :)

It just takes a minute longer sometimes, but Windows users are not forgotten.

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


Re: image lib & Qt4

2006-06-03 Thread K.S.Sreeram
Fredrik Lundh wrote:
> Fredrik Lundh wrote:
> 
> I've posted a simple ImageQt interface module for PIL and PyQt4 here:
> 
>  http://svn.effbot.python-hosting.com/stuff/sandbox/pil/ImageQt.py
> 

I'm getting an 'unknown raw mode' error on ImageQt.py:59:
  data = im.tostring( "raw", "BGRX" )

Does this only work with PIL 1.1.6 snapshots? I currently have PIL 1.1.5.

Regards
Sreeram



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Initializing an attribute that needs the object

2006-06-03 Thread David Pratt
Hi John. Thank you for the tips and the link. This is helpful. Many thanks.

Regards
David


> A new-style class is one which inherits ultimately from the type that is 
> called "object".
> 
> class NewStyleClass(object):
>  pass
> 
> class OldStyleClass():
>  pass
> 
> Docs are a bit u ...
> See this: http://www.python.org/doc/newstyle/
> 
> HTH,
> John
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


[ANN] pkipplib v0.04 is out

2006-06-03 Thread Jerome Alet
Hi there,

I'm pleased to announce pkipplib v0.04

This GPLed Python library allows you to create, manage or parse IPP
(Internet Printing Protocol) requests.

In addition, it exposes a CUPS() class which allows one to interact with a
CUPS print server (or an IPP printer).

Written in pure Python, there's no need to link with the CUPS' libraries,
and it doesn't even require any CUPS related software to work.

The mid to long term goal is to support all of the CUPS' IPP API.

Summary of changes :

  - Support for HTTP Basic authentication when connecting to a CUPS
  server was added.

  - General reliability was improved.

To learn more about it, see examples of use, or download it :

http://www.pykota.com/software/pkipplib/

Thank you for reading.

Jerome Alet

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


Re: image lib & Qt4

2006-06-03 Thread Fredrik Lundh
K.S.Sreeram wrote:

> I'm getting an 'unknown raw mode' error on ImageQt.py:59:
>   data = im.tostring( "raw", "BGRX" )
> 
> Does this only work with PIL 1.1.6 snapshots? I currently have
 > PIL 1.1.5.

it was developed on Python 2.4.3 and PIL 1.1.5, so it should work.  and 
BGRX support has been in there for ages (at least since 1.1.1).

what happens if you do:

$ python
 >>> import Image
 >>> im = Image.new("RGB", (100, 100))
 >>> print len(im.tostring("raw", "BGRX"))
4



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


Re: Initializing an attribute that needs the object

2006-06-03 Thread Bruno Desthuilliers
David Pratt a écrit :

David, please, don't top-post (fixed)

> 
> Bruno Desthuilliers wrote:
> 
(snip)
>>
>> Hint : Python classes are objects too.
>>
>>
>> class Factory(object):
>>def __init__(self, handler_class):
>>  self.handler = handler_class(self)
>>
>> class SomeHandler(object):
>>def __init__(self, factory):
>>  self.factory = factory
>>
>> f = Factory(SomeHandler)

> Hi Bruno. This is certainly what I was missing. Thank you. I am afraid I 
> am behind the times with use of object. Will I only use object when I am 
> not subclassing? 

If you subclass from a new-style class (almost all classes in the 
standard lib are...), you don't need to anything more.Else, yes, inherit 
from 'object', or set 'type' as the metaclass. Both classes defined 
below are 'new-style' classes:

class Parrot:
   __metaclass__ = type

class CheeseChop(object):
   pass


And now:

class DeadParrot(Parrot):
   pass

is a new-style class too.


 > Where will I find a document that provides info on the
 > use of object in new style classes?

In the Fine Manual(tm), of course. Googling python.org for "type 
unification" or "new-style" should give relevant answers.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: image lib & Qt4

2006-06-03 Thread K.S.Sreeram
My bad.
I was hacking the code trying to support RGBA mode images, and
inadvertently i tried im.tostring("raw","BGRX") on the RGBA mode image.

So BGRX does indeed work for RGB mode images.

While trying to support RGBA mode images, i realized that a BGRA raw
mode is needed for working with QImage. It doesn't seem to be supported
by PIL. Any workarounds?

Regards
Sreeram

Fredrik Lundh wrote:
> $ python
>  >>> import Image
>  >>> im = Image.new("RGB", (100, 100))
>  >>> print len(im.tostring("raw", "BGRX"))
> 4



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: after del list , when I use it again, prompt 'not defined'.how could i delete its element,but not itself?

2006-06-03 Thread Bruno Desthuilliers
Piet van Oostrum a écrit :
>>SuperHik <[EMAIL PROTECTED]> (S) escribió:
> 
> 
>>S> [EMAIL PROTECTED] wrote:
>>
python wrote:

>after del list , when I use it again, prompt 'not defined'.how could i
>delete its element,but not itself?

This is a way:

>>>a = range(10)
>>>del a[:]
>>
>>S> or simply
>>S> a = []
>>
>>>a

[]
> 
> 
> Then you *have* deleted the list

Not necessarily:

 >>> a = range(10)
 >>> b = a
 >>> id(a)
1078034316
 >>> id(b)
1078034316
 >>> a is b
True
 >>> a = []
 >>> b
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 >>> id(a)
1078043724
 >>> id(b)
1078034316
 >>>

What as been deleted is the association ('binding') between the name 'a' 
and the list object at 1078034316. This object won't be suppressed until 
there are no more names bound to it.

> and created a new one, which is different
> from keeping the list and deleting the elements:

indeed !-)

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


Re: image lib & Qt4

2006-06-03 Thread Fredrik Lundh
K.S.Sreeram wrote:

> I was hacking the code trying to support RGBA mode images, and
> inadvertently i tried im.tostring("raw","BGRX") on the RGBA mode image.
> 
> So BGRX does indeed work for RGB mode images.
> 
> While trying to support RGBA mode images, i realized that a BGRA raw
> mode is needed for working with QImage. It doesn't seem to be supported
> by PIL. Any workarounds?

sure!  here's a patch:

Index: ImageQt.py
===
--- ImageQt.py  (revision 342)
+++ ImageQt.py  (working copy)
@@ -58,6 +61,14 @@
  elif im.mode == "RGB":
  data = im.tostring("raw", "BGRX")
  format = QImage.Format_RGB32
+elif im.mode == "RGBA":
+try:
+data = im.tostring("raw", "BGRA")
+except SystemError:
+# workaround for earlier versions
+r, g, b, a = im.split()
+im = Image.merge("RGBA", (b, g, r, a))
+format = QImage.Format_ARGB32
  else:
  raise ValueError("unsupported image mode %r" % im.mode)



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


carshing the interpreter in two lines

2006-06-03 Thread gangesmaster
the following (random) code crashes my interpreter
(python 2.4.3/winxp):

from types import CodeType as code
exec code(0, 5, 8, 0, "hello moshe", (), (), (), "", "", 0, "")

i would expect the interpreter to do some verifying, at least for
sanity (valid opcodes, correct stack size, etc.) before executing
artbitrary code... after all, it was the BDFL who said """I'm not
saying it's uncrashable. I'm saying that if you crash it, it's a
bug unless proven harebrained."""


-tomer

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


Re: image lib & Qt4

2006-06-03 Thread K.S.Sreeram
thanks!
so does that mean the BGRA raw mode is supported in PIL 1.1.6?

Regards
Sreeram

Fredrik Lundh wrote:
> K.S.Sreeram wrote:
> 
>> I was hacking the code trying to support RGBA mode images, and
>> inadvertently i tried im.tostring("raw","BGRX") on the RGBA mode image.
>>
>> So BGRX does indeed work for RGB mode images.
>>
>> While trying to support RGBA mode images, i realized that a BGRA raw
>> mode is needed for working with QImage. It doesn't seem to be supported
>> by PIL. Any workarounds?
> 
> sure!  here's a patch:
> 
> Index: ImageQt.py
> ===
> --- ImageQt.py  (revision 342)
> +++ ImageQt.py  (working copy)
> @@ -58,6 +61,14 @@
>   elif im.mode == "RGB":
>   data = im.tostring("raw", "BGRX")
>   format = QImage.Format_RGB32
> +elif im.mode == "RGBA":
> +try:
> +data = im.tostring("raw", "BGRA")
> +except SystemError:
> +# workaround for earlier versions
> +r, g, b, a = im.split()
> +im = Image.merge("RGBA", (b, g, r, a))
> +format = QImage.Format_ARGB32
>   else:
>   raise ValueError("unsupported image mode %r" % im.mode)
> 
> 
> 




signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Leo 4.4.1 beta 1 released

2006-06-03 Thread Edward K. Ream
Leo 4.4.1 beta 1 is now available at:
http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106

Leo is a text editor, data organizer, project manager and much more. See:
http://webpages.charter.net/edreamleo/intro.html

The highlights of Leo 4.4.1:

- A new colorizer plugin controlled by jEdit language description files.
  At present this plugin only reliably colors @language python code.
- Multiple editors in Leo's body pane.
- Search commands now support regex replace patterns: \1, \2, etc.
- Support for external debuggers: see 
http://webpages.charter.net/edreamleo/debuggers.html
- The scripting plugin now creates a Debug Script button.
- Several new commands including run-unit-test, python-help and 
toggle-invisibles.
- The help-for-command commands now contains information for almost all 
commands.
- A new shortcut_button plugin.

Links:
--
Leo:  http://webpages.charter.net/edreamleo/front.html
Home: http://sourceforge.net/projects/leo/
Download: http://sourceforge.net/project/showfiles.php?group_id=3458
CVS:  http://leo.tigris.org/source/browse/leo/
Quotes:   http://webpages.charter.net/edreamleo/testimonials.html


Edward K. Ream   email:  [EMAIL PROTECTED]
Leo: http://webpages.charter.net/edreamleo/front.html



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


Re: integer to binary...

2006-06-03 Thread Grant Edwards
On 2006-06-02, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote:
> Grant Edwards a écrit :
>> On 2006-06-01, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>> 
>> 
>>>does anyone know a module or something to convert numbers like integer
>>>to binary format ?
>> 
>> 
>> They _are_ in binary format.
>
> Not really.

Yes, really.  Otherwise the bitwise boolean operations you
demonstrated wouldn't work as shown.

 (7).__class__
>
 dir((7))
> ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__',
> '__delattr__', '__div__', '__divmod__', '__doc__', '__float__',
> '__floordiv__', '__getattribute__', '__getnewargs__', '__hash__',
> '__hex__', '__init__', '__int__', '__invert__', '__long__',
> '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__',
> '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__',
> '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__',
> '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__',
> '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__',
> '__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__']


The fact that they impliment the xor operator is pretty much
proof that integers are stored in binary format -- xor is only
defined for binary numbers.

-- 
Grant Edwards   grante Yow!  ... Blame it on the
  at   BOSSA NOVA!!!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: integer to binary...

2006-06-03 Thread Tim Chase
> The fact that they impliment the xor operator is pretty much
> proof that integers are stored in binary format -- xor is only
> defined for binary numbers.

Um...let's not use bad logic/proofs for evidencing this...

 >>> hasattr(set(), "__xor__")
True

:)

-tkc



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


Re: can python be a "shell" of c++ program?

2006-06-03 Thread James
Yes you can, although it might be a fair bit of work depending on the
complexity of your codebase. Basically you would need to write Python
extensions to expose your C++ classes as Python modules, using SWIG or
the Python extension code in the Boost C++ libraries. You'd then embed
an interpreter in your program which would allow you to use Python
code within it - either from a script or individual commands.

It's a fairly common use of Python :)

James

On 03/06/06, key9 <[EMAIL PROTECTED]> wrote:
> Hi all
>
> I have some data to process, whith complex mechanism,I put these process
> mechanism as plugins.
> and design lots of classes to abstract data themselves.
>
> but the question is how to drive them work together.
>
> That cause too much jobs: I should write UI,parser..almost a completed
> system.
>
> The problem is I don't know what these processed data will finally needed to
> display to user.
> maybe this , may be that, these can not know on design time.
>
> what I need is on outside of program,
> I can use some interface to get these data what I want , or push back data,
> or told program to recalculate it.
>
>
> can I have a way to drive c++ code use this script-like way ?
>
>
> thank you very much
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do you practice Python?

2006-06-03 Thread James
Thirded here. Perhaps better for me is that although I program
client-side Java for my job, as much of the backend as possible I code
in Python, which makes it easier to do a lot of data processing stuff
much simpler than Java would. And it's let me use and understand all
of the new features of the language... last time I did it for a job
was in the days of Python 1.5.2.

Being non-critical utilities on the backend means whenever new
features are introduced I can upgrade my code to take advantage of
them without worrying about things going wrong as well ;)

James

On 02/06/06, Jarek Zgoda <[EMAIL PROTECTED]> wrote:
> I second that. I moved from Python to J2EE in my job, but I didn't stop
> writing Python code for my spare-time projects. Now, when tight schedule
> made my project's manager to shift paradigm from buzz to productivity, I
> am happy I can write programs in Python again. On AS/400, but still
> better than Java... :D
>
> --
> Jarek Zgoda
> http://jpa.berlios.de/
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: carshing the interpreter in two lines

2006-06-03 Thread sam
tomer:

It is my opinion that you would loose performance if the Python
interpreter had the additional task of verifying byte code. It might be
more appropriate to have a preprocessor that did the verifying as it
compiled the byte code.

Sam Schulenburg

gangesmaster wrote:
> the following (random) code crashes my interpreter
> (python 2.4.3/winxp):
>
> from types import CodeType as code
> exec code(0, 5, 8, 0, "hello moshe", (), (), (), "", "", 0, "")
>
> i would expect the interpreter to do some verifying, at least for
> sanity (valid opcodes, correct stack size, etc.) before executing
> artbitrary code... after all, it was the BDFL who said """I'm not
> saying it's uncrashable. I'm saying that if you crash it, it's a
> bug unless proven harebrained."""
> 
> 
> -tomer

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


Re: How do you practice Python?

2006-06-03 Thread James
Any code which requires serious algorithmic work I write and test in
Python before converting into Java - it's so much easier to use
Python's datatypes and interpreter to get things right before having
to deal with Java's clunky class libraries.

James

On 02/06/06, Norbert Kaufmann <[EMAIL PROTECTED]> wrote:
> Convince your project manager to develop prototypes. No one in your
> company is better and faster in prototyping than the Python expert Ray.
>
> HTH
>
> Norbert
-- 
http://mail.python.org/mailman/listinfo/python-list


ANN: PQRC - Python Quick Reference Card - v 0.55

2006-06-03 Thread Laurent Pointal
[for those who dont read clp.announce]

The Python Quick Reference Card (PQRC) aims to provide a printable quick
reference documentation for the Python language and some of its main
standard libraries (currently for Python 2.4).

PQRC tries to group informations about same/similar subject to avoid
searching in multiple places.

It is published under a Creative Common [by nc sa] license.

It is still a work in progress, but currently usable, you can get it at:

http://www.limsi.fr/Individu/pointal/python/pqrc/


And I'll maintain a fixed URL at

http://laurent.pointal.org/python/pqrc/


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


elementtree and inclusion of special characters

2006-06-03 Thread André
I'm using elementtree to process some html files, by building a tree,
manipulating it, and writing it back.  One problem I encounter is that
elementtree converts some symbols in an unwanted way.  For example, the
symbol ">" is converted to ">".  This is fine in html code, but not
if the page includes some script like the example below


function init() {
var a = 1;
if (a > 0)
   {
   alert("Spam alert");
   }
}


The resulting code, with "a > 0" is not understood by the browser...

Any suggestions as to how I can circumvent this problem in an easy way?

André

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


Re: image lib & Qt4

2006-06-03 Thread Fredrik Lundh
K.S.Sreeram wrote:

> so does that mean the BGRA raw mode is supported in PIL 1.1.6?

possibly; I haven't checked.  it does mean that some future version will 
most likely support it, at least.



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


Re: integer to binary...

2006-06-03 Thread Grant Edwards
On 2006-06-03, Tim Chase <[EMAIL PROTECTED]> wrote:
>> The fact that they impliment the xor operator is pretty much
>> proof that integers are stored in binary format -- xor is only
>> defined for binary numbers.
>
> Um...let's not use bad logic/proofs for evidencing this...
>
> >>> hasattr(set(), "__xor__")
> True

Sets aren't numbers.  Perhaps I should have phrased it better:
xor is only defined for numbers if they are represented in
binary.  If numbers were represented in something other than
binary, then an xor operation on those numbers wouldn't make
sense.

-- 
Grant Edwards   grante Yow!  .. I want to perform
  at   cranial activities with
   visi.comTuesday Weld!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: elementtree and inclusion of special characters

2006-06-03 Thread Fredrik Lundh
André wrote:

> I'm using elementtree to process some html files, by building a tree,
> manipulating it, and writing it back.  One problem I encounter is that
> elementtree converts some symbols in an unwanted way.  For example, the
> symbol ">" is converted to ">".  This is fine in html code, but not
> if the page includes some script like the example below
> 
> 
> function init() {
> var a = 1;
> if (a > 0)
>{
>alert("Spam alert");
>}
> }
> 
> 
> The resulting code, with "a > 0" is not understood by the browser...

ET is an XML library, and an XHTML-aware browser has no problems dealing 
with that, but I assume you might want to support tag soup parsers like 
IE6 as well ;-)

to write true HTML 4.0, you need a HTML serializer.  there's a good one 
in Kid (though I don't know how hard it would be to use that one with a 
preexisting tree, rather than a Kid "event stream").

another alternative is the HTMLTree class in Ian Bicking's commentary
application:

http://svn.pythonpaste.org/Paste/apps/Commentary/trunk/commentary/dumbpath.py

(you may have to tweak that module somewhat to be able to use it without 
elementtidy).



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


__builtins__.loglog - logging more pythonic, decent & scalable ? - Re: "No handlers could be found for logger xxx"

2006-06-03 Thread robert
As more and more python packages are starting to use the bloomy 
(Java-ish) 'logging' module in a mood of responsibility and as I am not 
overly happy with the current "thickener" style of usage, I want to put 
this comment and a alternative most simple default framework for 
discussion.
Maybe there are more Python users which like to see that imported 
(managed) logging issue more down-to-earth and flexible ? ...

Vinay Sajip wrote:
 > robert wrote:
 >
 >>some packages like paramiko use the logging. I get this messages:
 >>"No handlers could be found for logger xxx" on stderr
 >>
 >>Why is un-initialized logging allowed to chatter at all?
 >
 > You could invoke logging.basicConfig with a level of CRITICAL. This
 > will generally filter out logging messages.

Meanwhile i looked on logging and its doc:

The doc of for example basicConfig (promising to be quite simple/silent):

"basicConfig( )

Does basic configuration for the logging system by creating a 
StreamHandler with a default Formatter and adding it to the root logger. 
The functions debug(), info(), warning(), error() and critical() will 
call basicConfig() automatically if no handlers are defined for the root 
logger. "

=> So far I don't get any idea what will happen after doing this. What 
is a StreamHandler? a "default Formatter"? CRITICAL? what is this 
default magic behavior? even if silent behavior is installed log(), 
debug() consume still a lot of execution time => I have to read the 
logging code anyway => for my needs i rendered dead the Logger() in 
app-init / dead the line in logging which chatters within my standard 
set of Python patches.

I looked around a little more and think, that logging it is really a 
_FRAMEWORK_ - non-pythonic . a declarative monster.

Meaning: too big the interface and too big its basic footprint. without 
a decent scaling. too loud. it takes lots of time until one understands 
the basics. even the simplest setup example has not less than 8 lines - 
strange "filehandlers" and "formatters" are going on - and it is a 
framework which does a lot of obscure things, its class collection reads 
more like an magic application only understandable by its immediate 
programmers - rather than a stdlib part.
Its almost a Java-ish ego class bunch.

Some wide spread packages like paramiko use it already - inside stdlib 
only cookielib so far. Yet, just for providing the option they are 
costly pre-importing almost the whole framework functionality (in 
memory, frozen apps etc.) and have considerable costs during execution 
(regarding my step-in debugging sessions: seems to do very very late 
dispatching).
Python is still not an OS on its own but a programming language/library 
which should fit into OS'es.
( though they meanwhile put the CJK codecs etc. into the python core !? 
:-) )

Yes, one could use such functionality - but one does only in rarest cases.
I did and do logging a lot, but always had quite simple paths. I'd 
usually still not go though that framework in almost all cases, because 
it would require many hours until I really know whats going magically in 
all kinds of cases.

99% of my app logging needs were and are fulfilled by a simple direct 
module function as simple as:

def doLog(text,level,**kwattrs):
 #  in case write to file or whatever ...

and so I simply know really what will happen. Collecting all logs is 
also so easy with Python, that it could be _enabled_ by a much much 
simpler and pythonic one-function-framework: a empty log-hook function 
in the python __builtins__:

=

def loglog(text, channel='default', level=0, **kwattrs):
 pass

=

yet there could go any complex hierarchical channel names through that 
like channel="mypackage.mymodule.subtheme" or even multi-hierarchical 
channel classes/objects similar to exception-class-catching in addition 
to string-catching. Example:

=
class MyLogChannelAA(MyLogChannelA, MyLogAspectXY)

loglog(text, MyLogChannelAA, __debug__,  lcls=locals() )
=

If that simple would be the recommended standard logging interface in 
Python, I think, really a significant fraction of Python programmers 
would first understand and than use ( call and consume ) it - and 
(decent) modules would not blow up the machine unconditionally just for 
a mere specialized option.

For massive usage apps could shortcut THEMSELVES with bloomy names and 
level-constants like logdebug() logerror() 
(Recommendations at best - no more framework.)

Still this would be flexible enough and a super-hierarchical obscure 
logger and handler collection as exposed by "logging" or any other 
alternative could still be hooked in, while no module which does logging 
has to PRE-IMPORT SUCH A FAT SPECIAL LOGGING FRAMEWORK.

 > Un-initialized logging chatters because 

restarting multiple instances of apache - newbie Q

2006-06-03 Thread [EMAIL PROTECTED]
hi all,

i am new to python programming, so thanks for your patience in advance.

I have a small script that I am working on that i want to restart
multiple instances of apaches on our developers servers. We have about
25 developers each with their own apache.


import sys, os

try:
   file = open("users.dat", "r")
except IOError, message:
   print >> sys.stderr, "File could not be opened:", message
   sys.exit( 1 )

fdata = file.xreadlines()

for data in fdata:
   fields = data.split("_")
#   print "USER: " + fields[0] + " ADDRESS: " + fields[1].strip("\n")
print '/etc/init.d/httpd_' + fields[0] + ' restart



each users apache is named 'httpd_{user}'

I am not sure how to do this cleanly other than in a shell script.

I want to restart the apache and wait until complete to restart the
next users apache.

Any advice is appreciated .. 

again, thanks for your time.
-mike

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


Re: carshing the interpreter in two lines

2006-06-03 Thread Alex Martelli
sam <[EMAIL PROTECTED]> wrote:

> tomer:
> 
> It is my opinion that you would loose performance if the Python
> interpreter had the additional task of verifying byte code. It might be
> more appropriate to have a preprocessor that did the verifying as it
> compiled the byte code.

But in this case, there is no "compiled" -- just the code type's
constructor:

> > from types import CodeType as code
> > exec code(0, 5, 8, 0, "hello moshe", (), (), (), "", "", 0, "")

Yes, code() itself could do some sanity checking.  But so could 'exec'
-- it's never a particularly fast operation anyway... and most
definitely NOT on the critical path of normal operations.   I'd rather
have "defense in depth", in this case.


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


Python + WinCE + serial port

2006-06-03 Thread pcm
Hi,

Has anyone ever worked on a Python-WinCE-based program that involved serial
port management ?

Regards,

Philippe

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


Re: carshing the interpreter in two lines

2006-06-03 Thread Mel Wilson
sam wrote:
> tomer:
> 
> It is my opinion that you would loose performance if the Python
> interpreter had the additional task of verifying byte code. It might be
> more appropriate to have a preprocessor that did the verifying as it
> compiled the byte code.

Possibly.  A good book on the topic is Douglas Hofstadter's 
_Goedel, Escher, Bach: an Eternal Golden Braid_.

Particularly starting from the chapter "Contracrostipunctus".

 Cheers,Mel.



> Sam Schulenburg
> 
> gangesmaster wrote:
>> the following (random) code crashes my interpreter
>> (python 2.4.3/winxp):
>>
>> from types import CodeType as code
>> exec code(0, 5, 8, 0, "hello moshe", (), (), (), "", "", 0, "")
>>
>> i would expect the interpreter to do some verifying, at least for
>> sanity (valid opcodes, correct stack size, etc.) before executing
>> artbitrary code... after all, it was the BDFL who said """I'm not
>> saying it's uncrashable. I'm saying that if you crash it, it's a
>> bug unless proven harebrained."""
>>
>>
>> -tomer
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python + WinCE + serial port

2006-06-03 Thread Fuzzyman

pcm wrote:
> Hi,
>
> Has anyone ever worked on a Python-WinCE-based program that involved serial
> port management ?
>

Because of the size of the runtime and the fragility of the GUI
toolkits, there has been little serious development with PythonCE.
(Little not none - and it's great to have Python available.)

There is no built in support for the serial port in PythonCE (AFAIK).
Your best bet is using ctypes (for which a PythonCE port has been done)
and the microsoft API.

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

> Regards,
> 
> Philippe

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


Pyrex list/array

2006-06-03 Thread Jim Lewis
I'm trying to move a function into pyrex for speed. The python side
needs to pass a list to the pyrex function. Do I need to convert to
array or something so pyrex can generate tight code? I'm not clear how
to do this.

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


Re: grouping a flat list of number by range

2006-06-03 Thread Gerard Flanagan
[EMAIL PROTECTED] wrote:
> hello,
>
> i'm looking for a way to have a list of number grouped by consecutive
> interval, after a search, for example :
>
> [3, 6, 7, 8, 12, 13, 15]
>
> =>
>
> [[3, 4], [6,9], [12, 14], [15, 16]]
>
> (6, not following 3, so 3 => [3:4] ; 7, 8 following 6 so 6, 7, 8 =>
> [6:9], and so on)


Just another 'itertools.groupby' variation.  It considers the whole
range of numbers spanned by the dataset - eg. in your example,
range(3,17) - so possibly not very efficient if the range is large and
the data sparse within the range.

def get_intervals(data):
  intervals = [ [], [] ]
  for k,g in groupby(range(data[0],data[-1]+2), lambda x:x in data):
intervals[k].append( list(g)[0] )  #k is 0 or 1
  return zip(intervals[1],intervals[0])

a = [3, 6, 7, 8, 12, 13, 15]

assert get_intervals(a) == [(3,4),(6, 9),(12,14),(15,16)]   


Gerard

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


wxpython wxgrid question

2006-06-03 Thread rbann11
Hi,

  I am looking for example code that consists of just a frame and a
grid(10x2).  The grid must fill the its parent even if the frame is
resized.

  Thanks in advance,

Roger

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


Re: carshing the interpreter in two lines

2006-06-03 Thread sam
Mel:
Wow that book brings back memories. I scanned my copy to review the
subject covered, and came to the conclusion that mind reading
algorithms are the answer.

Sam Schulenburg

Mel Wilson wrote:
> sam wrote:
> > tomer:
> >
> > It is my opinion that you would loose performance if the Python
> > interpreter had the additional task of verifying byte code. It might be
> > more appropriate to have a preprocessor that did the verifying as it
> > compiled the byte code.
>
> Possibly.  A good book on the topic is Douglas Hofstadter's
> _Goedel, Escher, Bach: an Eternal Golden Braid_.
>
> Particularly starting from the chapter "Contracrostipunctus".
>
>  Cheers,Mel.
>
>
>
> > Sam Schulenburg
> >
> > gangesmaster wrote:
> >> the following (random) code crashes my interpreter
> >> (python 2.4.3/winxp):
> >>
> >> from types import CodeType as code
> >> exec code(0, 5, 8, 0, "hello moshe", (), (), (), "", "", 0, "")
> >>
> >> i would expect the interpreter to do some verifying, at least for
> >> sanity (valid opcodes, correct stack size, etc.) before executing
> >> artbitrary code... after all, it was the BDFL who said """I'm not
> >> saying it's uncrashable. I'm saying that if you crash it, it's a
> >> bug unless proven harebrained."""
> >>
> >>
> >> -tomer
> >

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


Re: how to erase a variable

2006-06-03 Thread greenflame
Ok thanks all!

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


Re: Making a second window with Tkinter

2006-06-03 Thread greenflame
What you said about why my code is wrong is still a bit fuzzy but it
worked!

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


Python less error-prone than Java

2006-06-03 Thread Christoph Zwerschke
You will often hear that for reasons of fault minimization, you should 
use a programming language with strict typing:
http://turing.une.edu.au/~comp284/Lectures/Lecture_18/lecture/node1.html

I just came across a funny example in which the opposite is the case.

The following is a binary search algorithm in Java. It searches a value 
in an ordered array a of ints:

public static int binarySearch(int[] a, int key) {
 int low = 0;
 int high = a.length - 1;
 while (low <= high) {
 int mid = (low + high) / 2;
 int midVal = a[mid];
 if (midVal < key)
 low = mid + 1;
 else if (midVal > key)
 high = mid - 1;
 else
 return mid; // key found
 }
 return -(low + 1);  // key not found.
}

Now the same thing, directly converted to Python:

def binarySearch(a, key):
 low = 0
 high = len(a) - 1
 while low <= high:
 mid = (low + high) / 2
 midVal = a[mid]
 if midVal < key:
 low = mid + 1
 elif midVal > key:
 high = mid - 1;
 else:
 return mid # key found
 return -(low + 1) # key not found.

What's better about the Python version? First, it will operate on *any* 
sorted array, no matter which type the values have.

But second, there is a hidden error in the Java version that the Python 
version does not have.

See the following web page if you dont find it ;-)
http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html

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


Re: wxpython wxgrid question

2006-06-03 Thread Jim Segrave
In article <[EMAIL PROTECTED]>,
 <[EMAIL PROTECTED]> wrote:
>Hi,
>
>  I am looking for example code that consists of just a frame and a
>grid(10x2).  The grid must fill the its parent even if the frame is
>resized.

This simple program makes a two element window, the lower half of
which is a gridded set of labels which resize with the window. The
important part is the columnconfigure() and rowconfigure() method
calls on the container widget for the grid.
See 
http://infohost.nmt.edu/tcc/help/pubs/tkinter/grid-config.html>
http://infohost.nmt.edu/tcc/help/pubs/tkinter/grid-config.html

#!/usr/local/bin/python

from Tkinter import *

root = Tk()
# create a frame (unused, but shared with gridded frame)
f = Frame(height = 100)
f.pack(expand = YES, fill = BOTH)

# create a frame for a gridded display
gf = Frame()
gf.pack(expand = YES, fill = BOTH)

# create a 3 x 4 array of labels, each with a different background
# Make each row and column have equal weights, so they'll
# grow and shrink together
for row in range(3):
gf.rowconfigure(row, weight = 1)
for col in range(4):
gf.columnconfigure(col, weight = 1)
Label(gf, text = "Row: %d\nCol: %d" % (row, col),
  bg = "#%02x%02x%02x" % ((row * 4 + col) * 16,
  (row * 4 + col) * 16,
  (row * 4 + col) * 16),
  fg = "#ff"
  ).grid(row = row, column = col, sticky = NSEW)



root.mainloop()





-- 
Jim Segrave   ([EMAIL PROTECTED])

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


Python & ncurses

2006-06-03 Thread cga2000
Can anyone recommend a nice sample application that demonstrates the
capabilities of python+ncurses and a clean/elegant UI?

Thanks,

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


Re: grouping a flat list of number by range

2006-06-03 Thread Steven Bethard
Gerard Flanagan wrote:
> [EMAIL PROTECTED] wrote:
>> hello,
>>
>> i'm looking for a way to have a list of number grouped by consecutive
>> interval, after a search, for example :
>>
>> [3, 6, 7, 8, 12, 13, 15]
>>
>> =>
>>
>> [[3, 4], [6,9], [12, 14], [15, 16]]
>>
>> (6, not following 3, so 3 => [3:4] ; 7, 8 following 6 so 6, 7, 8 =>
>> [6:9], and so on)
> 
> Just another 'itertools.groupby' variation.  It considers the whole
> range of numbers spanned by the dataset - eg. in your example,
> range(3,17) - so possibly not very efficient if the range is large and
> the data sparse within the range.
> 
> def get_intervals(data):
>   intervals = [ [], [] ]
>   for k,g in groupby(range(data[0],data[-1]+2), lambda x:x in data):
> intervals[k].append( list(g)[0] )  #k is 0 or 1
>   return zip(intervals[1],intervals[0])

If you're gonna go this route, you should definitely use a set to check 
containment; ``x in data`` is going to be costly for long lists. 
Defining your key something like the following would be better::

 data_set = set(data)
 def key(x):
 return x in data_set

STeVe

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


Re: Using print instead of file.write(str)

2006-06-03 Thread Tim Roberts
Bruno Desthuilliers <[EMAIL PROTECTED]> wrote:

>Sion Arrowsmith a écrit :
>> A.M <[EMAIL PROTECTED]> wrote:
>> 
>>>I found print much more flexible that write method.
>> 
>> "more flexible"? More convenient, yes. More powerful, maybe. But I
>> don't see more flexible. Everything print can to stdout.write() can
>> do. The reverse isn't true. eg (this appears to be a FAQ on this
>> group, although I can't find it in the FAQ):
>> 
>> for x in range(10):
>> sys.stdout.write(str(x))
>> 
>> to print:
>> 
>> 0123456789
>
>The reverse isn't true ???
>
>   print "".join(str(x) for x in range(10))

What he meant it that it is impossible to produce "0123456789" using 10
separate print statements, while it IS possible with 10 separate writes.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wxpython wxgrid question

2006-06-03 Thread Tim Roberts
[EMAIL PROTECTED] wrote:
>
>  I am looking for example code that consists of just a frame and a
>grid(10x2).  The grid must fill the its parent even if the frame is
>resized.

Have you gone through the wxPython demo application?  It contains examples
of every standard control and almost every behavior you might want.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


So what would Python be?

2006-06-03 Thread Lawrence D'Oliveiro


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


Re: An oddity in list comparison and element assignment

2006-06-03 Thread Terry Reedy

"Alex Martelli" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Terry Reedy <[EMAIL PROTECTED]> wrote:
>
>> <[EMAIL PROTECTED]> wrote in message
>> news:[EMAIL PROTECTED]
>> > (As an aside, may I point out that Python In A Nutshell states on page
>> > 46 "The result of S*n or n*S is the concatenation of n copies of S".

Alex, in responding to this sentence lifted out of context by Michael, I am 
responding more to him and his claim of 'not strictly the case' than to 
you.  What I wrote is also more a draft of a paragraph for a book of mine 
(of no competition to yours) than a suggestion for a future edition of your 
book.

>> It would be more exact to say that S*n is [] extended with S  n times,

A**b is often explained as 'A multiplied by itself b times' or some such. 
It is more exact to say it is '1 multiplied by A b times'

>> which makes it clear that 0*S == S*0 == []

which makes it clear that A**0, including 0**0, is 1.

>> and which avoids the apparently misleading word 'copy'.

Given the number of people, including Michael, who have posted puzzlement 
based on their confusion as to what does and does not get copied, I don't 
think it unfair to call 'copy' 'apparently misleading.  My intention in 
this phrase is to suggest that one who misunderstands 'copy' in this 
context will be mislead while one who understands just what is copied and 
what is not copied will not.

The point of my code snippet was to explain/illustrate what is copied. 
While it will (obviously) only executive as Python code for lists, I 
believe the algorithm is generic if the initial assignment and list.extend 
method are suitably interpreted.

Of course, I presume that in the CPython code, the actual initialization is 
more like (length one blank value)  * (n*len(S)) followed by n slice 
assignments, but the Python code for this would still be list specific and 
would also be more complex, without much aiding comprehension of the 
result.

Strings are a somewhat special case since the characters in the string are 
not wrapped as Python objects unless and until extracted from the string. 
So one cannot as easily talk about the object(s) contained in the sequence.

> Considering that the very next (and final) sentence in that same
> paragraph is "If n is zero or less than zero, the result is an empty
> sequence of the same type as S", I don't think there's anything
> misleading in the quoted sentence.

In its original context, with respect to that issue, no.  But as I said, I 
was responding to Michael's removed-from-context quotation and his claim 
about the need for a warning.  I wonder if you read down to the end, where 
I asked him whether I had missed anything he might find fault with, before 
you responded.

>  Moreover, since the paragraph is about sequences, not just lists,

This *thread* is about repetition of lists, and in particular, a list of 
one (or more) lists, and the consequences of the mutability of the inner 
lists, and that is the context in which I wrote.

> it *WOULD* be horribly wrong to use the phrasing you suggest:

In a generic context, [] would obviously have to be replaced by 'null 
sequence of the type of S', which in many cases is type(S)().  And 'extend' 
would have to be interpreted generically, as something the interpreter 
would do behind the scenes in type(S). __new__, although as I said before, 
I don't think that is exactly what it does do.

>"bah!"*3 is NOT a list,

Duh.,

> it's EXACTLY the
> concatenation of three copies of that string -- no more, no less.

Depends what one means by 'copy'.  See below for your alternate wording.

>> Or one could say that the result *is the same as* (not *is*) the
>
> I find this distinction, in this context, to be empty padding, with zero
> added value on ANY plane -- including the plane of "pedantry";-).

Perhaps you should tone down the overwrought emotionalism and take a look 
in a mirror.  In *your* response to Michael you made the *same* 
distinction:

>> Can you give me an example where, say, for a sequence S,
>> x = S * 3
>> is not structurally the same as
>> x = copy.copy(S) + copy.copy(S) + copy.copy(S)

I agree that adding 'structurally' makes the 'padding' even better.

>> concatenation of n *shallow* copies of S.  'Shallow' means that each 
>> copy

> I do not think it would be good to introduce the concept of "shallow" at
> a point in the text which is talking about ALL sequences -- including
> ones, such as strings, for which it just does not apply.

Again, I was not suggesting that you do so.  Adding 'shallow' was 
intentially pedantic for Michael's 'benefit'.  To be clear, I was *NOT* 
supporting his warning suggestion.

> But, thanks for the suggestions, anyway!

We both have the goal of expaining Python better so beginners hit fewer 
bumps on the road.

Terry Jan Reedy



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


Re: numpy bug

2006-06-03 Thread David Isaac
"Boris Borcic" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> after a while trying to find the legal manner to file numpy bug reports,
> since it's a simple one, I thought maybe a first step is to describe the
bug
> here. Then maybe someone will direct me to the right channel.
>
> So, numpy appears not to correctly compute bitwise_and.reduce and
> bitwise_or.reduce : instead of reducing over the complete axis, these
methods
> only take the extremities into account. Illustration :
>
>  >>> from numpy import *
>  >>> bitwise_or.reduce(array([8,256,32,8]))
> 8
>  >>> import numpy
>  >>> numpy.__version__
> '0.9.8'
>  >>>
>
> Platform : Win XP SP2, Python 2.4.2


Most bug reports start on the numpy list,
I believe.  (See above.)

Cheers,
Alan Isaac


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


Re: Python less error-prone than Java

2006-06-03 Thread Simon Percivall
Actually, you're wrong on all levels.

First: It's perfectly simple in Java to create a binary sort that sorts
all arrays that contain objects; so wrong there.

Secondly: The bug has nothing to do with static typing (I'm guessing
that's what you meant. Both Python and Java are strongly typed). The
problem is that ints are bounded in Java. They could easily have been
ints and then automatically coerced to (equivalent to) longs when they
got bigger; that they aren't is more a design fault than anything to do
with static typing. The equivalent in Python would have been if an
overflow exception was raised when the int got too big. It might have
been that way, typing or no typing.

Christoph Zwerschke wrote:
> You will often hear that for reasons of fault minimization, you should
> use a programming language with strict typing:
> http://turing.une.edu.au/~comp284/Lectures/Lecture_18/lecture/node1.html
>
> I just came across a funny example in which the opposite is the case.
>
> The following is a binary search algorithm in Java. It searches a value
> in an ordered array a of ints:
>
> public static int binarySearch(int[] a, int key) {
>  int low = 0;
>  int high = a.length - 1;
>  while (low <= high) {
>  int mid = (low + high) / 2;
>  int midVal = a[mid];
>  if (midVal < key)
>  low = mid + 1;
>  else if (midVal > key)
>  high = mid - 1;
>  else
>  return mid; // key found
>  }
>  return -(low + 1);  // key not found.
> }
>
> Now the same thing, directly converted to Python:
>
> def binarySearch(a, key):
>  low = 0
>  high = len(a) - 1
>  while low <= high:
>  mid = (low + high) / 2
>  midVal = a[mid]
>  if midVal < key:
>  low = mid + 1
>  elif midVal > key:
>  high = mid - 1;
>  else:
>  return mid # key found
>  return -(low + 1) # key not found.
>
> What's better about the Python version? First, it will operate on *any*
> sorted array, no matter which type the values have.
>
> But second, there is a hidden error in the Java version that the Python
> version does not have.
>
> See the following web page if you dont find it ;-)
> http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html
> 
> -- Christoph

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


Re: An oddity in list comparison and element assignment

2006-06-03 Thread Alex Martelli
Terry Reedy <[EMAIL PROTECTED]> wrote:

> > it's EXACTLY the
> > concatenation of three copies of that string -- no more, no less.
> 
> Depends what one means by 'copy'.  See below for your alternate wording.

Please give me a reasonable definition of the unadorned word "copy"
which would make this statement false.  (And, just to forestall one
possible attempt: no, I cannot agree that a ``deepcopy'' is a reasonable
definition of the _unadorned_ word "copy").


> >> Or one could say that the result *is the same as* (not *is*) the
> >
> > I find this distinction, in this context, to be empty padding, with zero
> > added value on ANY plane -- including the plane of "pedantry";-).
> 
> Perhaps you should tone down the overwrought emotionalism and take a look
> in a mirror.  In *your* response to Michael you made the *same* 
> distinction:

I did not *DRAW* any distinction (as you did with your parenthetical
note "(not *is*)", emphasis and all) -- rather, I used one of many
reasonably interchangeable ways to word a concept.  ((In the Nutshell, I
always deliberately try to pick the shortest and most concise way; in my
more spontaneous writing, I strongly tend to wilder exhuberance).

So, having deeply delved into the mirror, I still fail to find any
validity in your criticism: the phrases "S*n is the same as the
concatenation of" and "S*n the concatenation of", taken as definitions
of what S*n means, are such that your emphatic distinction has no added
value whatsoever -- I stand by this assertion and fail to see in it any
emotionalism, overwrought or otherwise.  Care to _defend_ your
criticism, with some _objective_ explanation of why that parenthetical
was warranted (particularly the emphasis within it)?  Or would you
rather continue the personal attacks against me and the unproven
accusations of "overwrought emotionalism" in particular?


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


Re: Using print instead of file.write(str)

2006-06-03 Thread Alex Martelli
Tim Roberts <[EMAIL PROTECTED]> wrote:

> Bruno Desthuilliers <[EMAIL PROTECTED]> wrote:
> 
> >Sion Arrowsmith a écrit :
> >> A.M <[EMAIL PROTECTED]> wrote:
> >> 
> >>>I found print much more flexible that write method.
> >> 
> >> "more flexible"? More convenient, yes. More powerful, maybe. But I
> >> don't see more flexible. Everything print can to stdout.write() can
> >> do. The reverse isn't true. eg (this appears to be a FAQ on this
> >> group, although I can't find it in the FAQ):
> >> 
> >> for x in range(10):
> >> sys.stdout.write(str(x))
> >> 
> >> to print:
> >> 
> >> 0123456789
> >
> >The reverse isn't true ???
> >
> >   print "".join(str(x) for x in range(10))
> 
> What he meant it that it is impossible to produce "0123456789" using 10
> separate print statements, while it IS possible with 10 separate writes.

it's not quite impossible, just cumbersome:

>>> for x in range(10):
...   print x,
...   sys.stdout.softspace=0
... 
0123456789>>> 

Yes, you do need the softspace assignments -- but then, in the write
version you need the explicit str calls, so it's not as if in either
case you're using "just" the print or write-call.

The differences in terms of convenience are surely there (in different
circumstances they will favor one or the other of the two approaches),
but I don't see such differences in either flexibility or power (if one
ignores the issue of convenience, the same tasks can be performed with
either approach).


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


FreeImagePy and PIL

2006-06-03 Thread David Isaac
I am just starting to think about image processing.
What are the overlaps and differences in intended
functionality between FreeImagePy and PIL?

Thanks,
Alan Isaac


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


Re: Python less error-prone than Java

2006-06-03 Thread Alex Martelli
Simon Percivall <[EMAIL PROTECTED]> wrote:
   ...
> with static typing. The equivalent in Python would have been if an
> overflow exception was raised when the int got too big. It might have
> been that way, typing or no typing.

Indeed, it _used_ to be that way --
 STILL says...:

exception OverflowError

Raised when the result of an arithmetic operation is too large to be
represented. This cannot occur for long integers (which would rather
raise MemoryError than give up). Because of the lack of standardization
of floating point exception handling in C, most floating point
operations also aren't checked. For plain integers, all operations that
can overflow are checked except left shift, where typical applications
prefer to drop bits than raise an exception.


Actually, the docs are obsolete on this point, and an int becomes a long
when that's necessary:

>>> sys.maxint+1
2147483648L

but, this operation _would_ have raised OverflowError in old-enough
versions of Python (not sure exactly when the switch happened...).


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


Re: Python less error-prone than Java

2006-06-03 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Christoph Zwerschke  <[EMAIL PROTECTED]> wrote:
>You will often hear that for reasons of fault minimization, you should 
>use a programming language with strict typing:
>http://turing.une.edu.au/~comp284/Lectures/Lecture_18/lecture/node1.html
>
>I just came across a funny example in which the opposite is the case.
.
.
.
>What's better about the Python version? First, it will operate on *any* 
>sorted array, no matter which type the values have.
>
>But second, there is a hidden error in the Java version that the Python 
>version does not have.
>
>See the following web page if you dont find it ;-)
>http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html
.
.
.
This is all worth saying, that is, I agree with the conclusions.

The premises are arguable, though.  For me, this example illustrates
the difficulty faced by people who hear, "strict typing", and think
of Java.

At another level, Python's superiority here is epiphenomenal.  Python
probably has a better model for arithmetic than Java, but BDFL knows
that Python is not without its own flaws, particulary in arithmetic.  

So, here's my summary:  Python's a nice language--a very nice one.
It's safer to use than Java in many ways.  Python's typing is 
STRICTER than Java's, but it's also dynamic, so people get to argue
for decades about which is a better model.  Anyone who thinks typing
is a first-order determinant of code quality is making a big mistake
though, anyway.
-- 
http://mail.python.org/mailman/listinfo/python-list


reordering elements of a list

2006-06-03 Thread greenflame
I am trying to reorder elements of a list and I am stuck as to what
might be the best way to approach this. I have a (main) list of
elements and another (ordering) list (which is may shorter,  but not
longer than the main list) which contains the order in which I want the
elements of the main list but only as far along as the length of the
ordering list. This may be confusing so I will try to give an example.

Suppose the main list is: mainlist = list('qwertyuiop')

Suppose the ordering list is: orderinglist = [3, 4, 2, 1]

Then I am looking for a function that will take mainlist and
orderinglist as arguments and return the following list:

['e', 'r', 'w', 'q', 't', 'y', 'u', 'i', 'o', 'p']

Also by the way the main list is always going to be a list of strings
and the ordering list will be a list of numbers. Also the largest
number in orderinglist will always be equal to the length of
orderinglist. I hope this makes any sense. Thanks for your help.

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


Re: reordering elements of a list

2006-06-03 Thread Travis E. Oliphant
greenflame wrote:
> I am trying to reorder elements of a list and I am stuck as to what
> might be the best way to approach this. I have a (main) list of
> elements and another (ordering) list (which is may shorter,  but not
> longer than the main list) which contains the order in which I want the
> elements of the main list but only as far along as the length of the
> ordering list. This may be confusing so I will try to give an example.
> 
> Suppose the main list is: mainlist = list('qwertyuiop')
> 
> Suppose the ordering list is: orderinglist = [3, 4, 2, 1]
> 
> Then I am looking for a function that will take mainlist and
> orderinglist as arguments and return the following list:
> 
> ['e', 'r', 'w', 'q', 't', 'y', 'u', 'i', 'o', 'p']
> 
> Also by the way the main list is always going to be a list of strings
> and the ordering list will be a list of numbers. Also the largest
> number in orderinglist will always be equal to the length of
> orderinglist. I hope this makes any sense. Thanks for your help.
> 

NumPy ( http://numeric.scipy.org )  can do this using element-based 
indexing on an array of strings.

Your example:

import numpy
a = numpy.array('qwertyuiop','c')
newlist = a[[2,3,1,0]+range(4,10)].tolist()
print newlist

Returns:

['e', 'r', 'w', 'q', 't', 'y', 'u', 'i', 'o', 'p']


But you can also do it with list comprehension pretty easily, so this is 
probably just a shameless plug for NumPy :-)


-Travis

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


Re: reordering elements of a list

2006-06-03 Thread Roberto Bonvallet
3 Jun 2006 17:46:49 -0700, greenflame <[EMAIL PROTECTED]>:
> Suppose the main list is: mainlist = list('qwertyuiop')
>
> Suppose the ordering list is: orderinglist = [3, 4, 2, 1]
>
> Then I am looking for a function that will take mainlist and
> orderinglist as arguments and return the following list:
>
> ['e', 'r', 'w', 'q', 't', 'y', 'u', 'i', 'o', 'p']

>>> mainlist = list('qwertyuiop')
>>> orderinglist = [3, 4, 2, 1]
>>> [mainlist[i - 1] for i in orderinglist] + mainlist[len(orderinglist):]
['e', 'r', 'w', 'q', 't', 'y', 'u', 'i', 'o', 'p']

Best regards.
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python less error-prone than Java

2006-06-03 Thread Christoph Zwerschke
Simon Percivall wrote:
 > First: It's perfectly simple in Java to create a binary sort that
 > sorts all arrays that contain objects; so wrong there.

My point was that the *same* Java source example, directly converted to 
Python would *automatically* accept all kinds of arrays. No need to make 
any extra efforts. By the way, how would you do it in Java? With 
function overloading? I would not call that perfectly simple.

 > Secondly: The bug has nothing to do with static typing (I'm guessing
 > that's what you meant. Both Python and Java are strongly typed). The
 > problem is that ints are bounded in Java. They could easily have been
 > ints and then automatically coerced to (equivalent to) longs when they
 > got bigger; that they aren't is more a design fault than anything to
 > do with static typing. The equivalent in Python would have been if an
 > overflow exception was raised when the int got too big. It might have
 > been that way, typing or no typing.

Yes, sorry, I meant static typing, not strict typing. But I still do 
think that the bug has to do with static typing. You're right, the 
direct cause is that ints are bounded in Java, and not bounded in 
Python, and that it could well be the other way round. However, doing it 
the other way round would not be so clever and appropriate for the 
respective language due to the difference in static typing.

Java could coerce the result to long, but then it would still crash when 
the result is stored back to the statically typed variable. So that 
would not be very clever.

And Python could produce an overflow error (and did in the past), but 
taking advantage of the possibilities of dynamic typing and 
automatically producing longs is a cleverer solution for Python, and 
that's why it was proposed and accepted in PEP237.

So the difference in static typing is actually the deeper reason why 
ints were made to behave differently in the two languages.

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


Re: Pyrex list/array

2006-06-03 Thread John Machin
On 4/06/2006 4:56 AM, Jim Lewis wrote:
> I'm trying to move a function into pyrex for speed.

You probably didn't expect the Inquisition; nobody does. But here it is, 
nice red uniforms and all:

1. What is your speed requirement and how far short of that are you at 
the moment?
2. Are you sure there is no Python or third-party module that does what 
you want?
3. Is your algorithm the best possible?
4. Is your Python implementation of that algorithm the best possible? 
Have you exposed it to the critical gaze of the speed-freaks in this 
newsgroup?
5. Does your architecture support psyco? If so, have you tried that and 
what were the results?

> The python side
> needs to pass a list to the pyrex function. Do I need to convert to
> array or something so pyrex can generate tight code? I'm not clear how
> to do this.
> 

The question might be better asked on the Pyrex mailing list.

You don't need to convert a list to a C array, and it may not even be 
possible, depending on what type(s) of data you have in the list.

Almost any Python code is also valid Pyrex code. For a start, just 
compile your function with Pyrex and compare the speed. What you do next 
is going to depend very much on what operations you are performing on 
the list and the objects it contains. Watch out for Python built-ins 
like range, xrange, ord, chr, abs, bool, int(a_number), float(a_number), 
divmod, max/min (two_numeric_args). In almost all cases you get cheap 
wins by replacing use of these by simple C-like code -- provided of 
course you are absolutely sure you know what types you are dealing with.

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


Re: Python less error-prone than Java

2006-06-03 Thread Christoph Zwerschke
Cameron Laird wrote:
> So, here's my summary:  Python's a nice language--a very nice one.
> It's safer to use than Java in many ways.  Python's typing is 
> STRICTER than Java's, but it's also dynamic, so people get to argue
> for decades about which is a better model.  Anyone who thinks typing
> is a first-order determinant of code quality is making a big mistake
> though, anyway.

Yes, sorry. It has nothing to do with strict, but with static typing. 
And I should not have chosen such a general subject line (I just meant 
to be funny, but sounded more like a troll). I had just noticed that the 
direct translation of that Java program to Python would not have that 
subtle bug and found that this was worth mentioning.

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


Proposed new PEP: print to expand generators

2006-06-03 Thread James J. Besemer

I would like to champion a proposed enhancement to Python.  I describe the 
basic idea below, in order to gage community interest.  Right now, it's only 
an idea, and I'm sure there's room for improvement.  And of course it's 
possible there's some serious "gotcha" I've overlooked.  Thus I welcome any 
and all comments.

If there's some agreement that this proposal is worth further consideration 
then I'll re-submit a formal document in official PEP format.

Regards

--jb

PEP -- EXTEND PRINT TO EXPAND GENERATORS

NUTSHELL

I propose that we extend the semantics of "print" such that if the object to 
be printed is a generator then print would iterate over the resulting 
sequence of sub-objects and recursively print each of the items in order.

E.g.,

print obj

under the proposal would behave something like

import types

if type( obj ) == types.GeneratorType:
for item in obj:
print item, # recursive call
print   # trailing newline
else:
print obj   # existing  print behavior

I know this isn't precisely how print would work, but I intentionally 
simplified the illustration to emphasize the intended change.  Nevertheless, 
several points above expressly are part of this proposal (subject to 
discussion and possible revision):

Print behavior does not change EXCEPT in the case
that the object being printed is a generator.

Enumerated items are printed with intervening spaces
[alternatively: "" or "\n"].

An enumerated sequence ends with a newline
[alternatively: "" or " "].

Iterators themselves could return iterators as elements, and the proposed 
change to print would recursively serialize any arbitrary "tree" of iterators.

__str__() for complex user-defined objects then could return iterators, and 
arbitrarily complex structures could be printed out without glomming 
everything into a huge string -- only to throw it away in the end.

I expect we likely also would want to modify str() itself to embody this 
serialization behavior.  This additional change would support those cases 
where one actually does want the single large string in the end, say, to 
store into a UI widget.  Still, the string would be constructed once at the 
end, much more efficiently than by building a bunch of smaller, intermediate 
strings.

Then, in an abstract sense, we would not  be changing print at all -- the new 
semantics would be embodied in the change to str().  However, in practice, 
we'd also want to modify print, as an important optimization for a more 
common use case.

The present behavior (displaying, e.g., "") 
would still be available via

print repr( generator )

Note that this behavior presently results from all three of:

print generator
print str( generator )
print repr( generator )

So, this proposal merely ascribes useful new semantics to the first two of 
three redundant language constructs.

MOTIVATION

With increasingly complex objects, the print representation naturally becomes 
more complex.  In particular, when an object consists of a collection of 
sub-objects, it's natural for it's string representation to be defined 
recursively in terms of the sub-components' string representations, with some 
further indication of how they're held together.

This is possible to do with the __str__ overload and the existing print 
semantics.  However, existing semantics require constructing many otherwise 
unnecessary intermediate strings, and, as such, is grossly inefficient. 
Worse, each intermediate string is generally the catenation of several 
previous intermediaries, so the volume of intermediate results steadily 
increases throughout the conversion.  Finally, the cost of string operations 
is proportional to the length of the strings in question, so I expect the 
overall cost increases significantly faster than in direct proportion to the 
size of the output (i.e. it's non-linear).

E.g., instances of the following classes can become arbitrarily expensive to 
print out:

def HtmlTable( object ):
# ...
def __str__( self ):
return ( "\n"
+ "".join([ str( row ) for row in self.head ])
+ "".join([ str( row ) for row in self.rows ])
+ "\n" )

def HtmlRow( object ):
# ...
def __str__( self ):
return ( "\n"
+ "".join([ str( cell ) for cell in self.cells ])
+ "\n" )

def HtmlCell( object ):
# ...
def __str__( self ):
return ( "\n"
+ "".join([ str( datum ) for datum in self.data ])
+ "\n" )

Clearly, printing an arbitrary HtmlTable might require a LOT of unnecessary 
string manipulation.

Using the

Re: Proposed new PEP: print to expand generators

2006-06-03 Thread Terry Reedy

"James J. Besemer" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> I propose that we extend the semantics of "print" such that if the object 
> to
> be printed is a generator then print would iterate over the resulting
> sequence of sub-objects and recursively print each of the items in order.

A generator is an iterator produced by a generator function rather than a 
class.  What treat them differently?

Iterating over an iterator is usually destructive.  So you would be 
printing what it was but no longer is.  This is why iterators are printed 
differently from sequences.

Terry Jan Reedy



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


Re: Proposed new PEP: print to expand generators

2006-06-03 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 "James J. Besemer" <[EMAIL PROTECTED]> wrote:

> I propose that we extend the semantics of "print" such that if the object to 
> be printed is a generator then print would iterate over the resulting 
> sequence of sub-objects and recursively print each of the items in order.

I believe the functionality you desire already exists, or something very 
close to it, in the pprint (pretty printer) module.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reordering elements of a list

2006-06-03 Thread Christoph Zwerschke
greenflame wrote:
> Suppose the main list is: mainlist = list('qwertyuiop')
> Suppose the ordering list is: orderinglist = [3, 4, 2, 1]
> 
> Then I am looking for a function that will take mainlist and
> orderinglist as arguments and return the following list:
> 
> ['e', 'r', 'w', 'q', 't', 'y', 'u', 'i', 'o', 'p']
> 
> Also by the way the main list is always going to be a list of strings
> and the ordering list will be a list of numbers. Also the largest
> number in orderinglist will always be equal to the length of
> orderinglist. I hope this makes any sense. Thanks for your help.

The following will do:

map(lambda c, i: i and mainlist[i-1] or c, mainlist, orderinglist)

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


Re: Proposed new PEP: print to expand generators

2006-06-03 Thread Steven Bethard
James J. Besemer wrote:
> I propose that we extend the semantics of "print" such that if the 
> object to be printed is a generator then print would iterate over the 
> resulting sequence of sub-objects and recursively print each of the 
> items in order.

I don't feel like searching for the specific python-dev threads right 
now, but something like this has been suggested before (I think with a 
"%i" formatting code), and Guido felt strongly that the addition or 
removal of a simple print statement shouldn't change the behavior of the 
surrounding code.

Consider code like::

 items = get_generator_or_None()
 for item in items:
 do_something(item)

Now let's say I insert a debugging line like::

 items = get_generator_or_None()
 print "make sure this isn't None:", items
 for item in items:
 do_something(item)

My debugging line now just broke the rest of my code.  That's not good.


The other reason I don't think this PEP should go forward (at least as 
it is) is that Python 3000 is already going to turn the print statement 
into a function (though the exact details of that function have not been 
hashed out yet).  So adding extra cruft to the print statement is kind 
of wasted effort.

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


Re: Using print instead of file.write(str)

2006-06-03 Thread John Machin
On 3/06/2006 9:47 AM, Bruno Desthuilliers wrote:

> 
> Now, given:
> 
>   bird = "parrot"
>   beautiful = "dead"
> 
> How would you do the following with f.write() ?
> 
>   print "this", bird, "is", beautiful
> 
> (without using string formating, of course...)

Like this:

f.write((' '.join(str(x) for x in ['this', bird, 'is', beautiful]) + '\n'))

... or was that a rhetorical question?

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


Re: Python less error-prone than Java

2006-06-03 Thread Alan Morgan
In article <[EMAIL PROTECTED]>,
Christoph Zwerschke  <[EMAIL PROTECTED]> wrote:
>Simon Percivall wrote:
> > First: It's perfectly simple in Java to create a binary sort that
> > sorts all arrays that contain objects; so wrong there.
>
>My point was that the *same* Java source example, directly converted to 
>Python would *automatically* accept all kinds of arrays.

And the same code converted to SML would automatically work on all
kinds of arrays and SML is statically typed.  It's a language issue,
not a typing issue.

>No need to make any extra efforts.
>By the way, how would you do it in Java? With 
>function overloading? I would not call that perfectly simple.

Since Java doesn't allow function overloading that clearly can't be
the way.  J2SE 5.0 allows generic classes and functions that operate
on generic containers.  There are some gotchas, but it's not drastically
more complex than the original int-only java code.

Alan
-- 
Defendit numerus
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reordering elements of a list

2006-06-03 Thread greenflame
Thank you all for your replies. The only thing is I do not understand
how the code is working. The following are more particular questions.

Travis: Iam sorry, but I do not know what list comprehension is.
Roberto: I do not understand the first half of the last line of your
code. Also thank you for also teaching me to use '+' to append one list
to another. This will be very useful for me.
Christoph: I do not undertand the map method.

Thanks again for all the help. :)

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


Re: reordering elements of a list

2006-06-03 Thread Robert Kern
greenflame wrote:
> Thank you all for your replies. The only thing is I do not understand
> how the code is working. The following are more particular questions.

Actually, these are statements, not questions. But anyways:

> Travis: Iam sorry, but I do not know what list comprehension is.
> Roberto: I do not understand the first half of the last line of your
> code.

That's what a list comprehension is.

> Also thank you for also teaching me to use '+' to append one list
> to another. This will be very useful for me.
> Christoph: I do not undertand the map method.

There is documentation on map() about halfway down this page:

  http://docs.python.org/lib/built-in-funcs.html

Here's a tutorial which you should read:

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

-- 
Robert Kern

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

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


Hostmask matching

2006-06-03 Thread Nexu
I'm trying to write a def to match a string that is an irc hostmask. eg:
[EMAIL PROTECTED]
But using re.search(). I get an error when the string starts with '*'.
What is the best way to solve this?


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


Re: wxpython wxgrid question

2006-06-03 Thread rbann11

Tim Roberts wrote:
> [EMAIL PROTECTED] wrote:
> >
> >  I am looking for example code that consists of just a frame and a
> >grid(10x2).  The grid must fill the its parent even if the frame is
> >resized.
>
> Have you gone through the wxPython demo application?  It contains examples
> of every standard control and almost every behavior you might want.
> --
> - Tim Roberts, [EMAIL PROTECTED]
>   Providenza & Boekelheide, Inc.

Yes, and i have even checked out "wxpython in action".  All of the
examples tend to leave white space on the right of the frame.  I tried
basic a example with sizers and it didnt work.  That why I was
wondering if someone had got it to work.


   Roger

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


Re: Hostmask matching

2006-06-03 Thread John Machin
On 4/06/2006 1:57 PM, Nexu wrote:
> I'm trying to write a def

Perhaps you mean a function?

> to match a string that is an irc hostmask. eg:
> [EMAIL PROTECTED]
> But using re.search().

If you want to find an IRC hostmask in some longer string, yes, use 
re.search(). However if you want to check that a given string could be 
an IRC hostmask, use re.match().

> I get an error when the string starts with '*'.

Do you get an error when the searched string starts with anything else?

> What is the best way to solve this?
> 

A reasonable way would be to ask a question that includes the minimum 
useful information, so that would-be helpers are not forced to guess:

1. your inputs (the re pattern, and the searched string)
2. the expected outcome (match object that spans which part of the 
searched string)
3. the actual outcome (copy/paste of the traceback and error message 
that you got)

Another way might be to Read The Fantastic Manual, in particular the 
section on re syntax, and nut out the answer your self.

In any case, here's my guess as to what's going down:

1. You mean that the pattern starts with '*', not the searched string.
2. The error that you got was something like this:

[snip]
   File "C:\Python24\lib\sre.py", line 180, in compile
 return _compile(pattern, flags)
   File "C:\Python24\lib\sre.py", line 227, in _compile
 raise error, v # invalid expression
sre_constants.error: nothing to repeat

3. You haven't read this part of The Fantastic Manual:

"\"
Either escapes special characters (permitting you to match characters 
like "*", "?", and so forth), or ...

===

As well as TFManual, there's also a HOWTO:
http://www.amk.ca/python/howto/regex/


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


Re: Python less error-prone than Java

2006-06-03 Thread Neil Hodgson
Alan Morgan wrote:

> Since Java doesn't allow function overloading that clearly can't be
> the way.  J2SE 5.0 allows generic classes and functions that operate
> on generic containers.  There are some gotchas, but it's not drastically
> more complex than the original int-only java code.

Doesn't Java restrict generics to only operate on reference types so 
you can't produce a generic binary search that operates on arrays where 
the item type may be int?

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


Re: Python less error-prone than Java

2006-06-03 Thread Alan Morgan
In article <[EMAIL PROTECTED]>,
Neil Hodgson  <[EMAIL PROTECTED]> wrote:
>Alan Morgan wrote:
>
>> Since Java doesn't allow function overloading that clearly can't be
>> the way.  J2SE 5.0 allows generic classes and functions that operate
>> on generic containers.  There are some gotchas, but it's not drastically
>> more complex than the original int-only java code.
>
>Doesn't Java restrict generics to only operate on reference types so 
>you can't produce a generic binary search that operates on arrays where 
>the item type may be int?

Yup, you have to wrap int (and double and float and...).  Blame type
erasure.

Alan
-- 
Defendit numerus
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python less error-prone than Java

2006-06-03 Thread Ilpo Nyyssönen
Christoph Zwerschke <[EMAIL PROTECTED]> writes:

> What's better about the Python version? First, it will operate on
> *any* sorted array, no matter which type the values have.
>
> But second, there is a hidden error in the Java version that the
> Python version does not have.

While I can see your point, I'd say you are totally in the wrong level
here.

With Java generics you can sort a list and still keeping the type of
the contents defined. This is makes the code less error-prone. But why
would you implement binary search as the standard library already has
it for both arrays and lists? This is one big thing that makes code
less error-prone: using existing well made libraries. You can find
binary search from python standard library too (but actually the API
in Java is a bit better, see the return values).

Well, you can say that the binary search is a good example and in real
code you would use the stuff from the libraries. I'd say it is not
good example: How often will you write such algorithms? Very rarely.

Integer overflows generally are not those errors you run into in
programs. The errors happening most often are from my point of view:

1. null pointer errors
2. wrong type (class cast in Java, some weird missing attribute in python)
3. array/list index out of bounds

First and third ones are the same in about every language. The second
one is one where the typing can make a difference. If in the code
level you know the type all the way, there is much less changes of it
being wrong. (The sad thing in the Java generics is that it is a
compile time only thing and that causes some really weird stuff, but
that is too off topic to here.)

In python passing sequences for a function and also from a function is
very easy. You can very easily pass a sequence as argument list. You
can also very easily return a sequence from the function and even
split it to variables directly. This is very powerful tool, but it has
a problem too: How can you change what you return without breaking the
callers? There are many cases where passing an object instead of a
sequence makes the code much easier to develop further.

What's the point? The point is that neither with Java or Python you
want to be doing things in the low level. You really want to be doing
stuff with objects and using existing libraries as much as possible. 
And in that level Java might be less error-prone as it does restrict
the ways you can shoot yourself more.

-- 
Ilpo Nyyssönen # biny # /* :-) */
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Hostmask matching

2006-06-03 Thread Marc Schoechlin
Hi !

Nexu <[EMAIL PROTECTED]> schrieb:
> I'm trying to write a def to match a string that is an irc hostmask. eg:
> [EMAIL PROTECTED]
> But using re.search(). I get an error when the string starts with '*'.
> What is the best way to solve this?

I suppose the problem occurs because you expression is not a valid
regular expression.

A correct regular expression should look like this:
"[EMAIL PROTECTED]"

Best regards

Marc Schoechlin

-- 
I prefer non-proprietary document-exchange.
http://sector7g.wurzel6.de/pdfcreator/
http://www.prooo-box.org/
Contact me via jabber: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Hostmask matching

2006-06-03 Thread Nexu
On Sun, 2006-06-04 at 06:26 +, Marc Schoechlin wrote:
> Hi !
> 
> Nexu <[EMAIL PROTECTED]> schrieb:
> > I'm trying to write a def to match a string that is an irc hostmask. eg:
> > [EMAIL PROTECTED]
> > But using re.search(). I get an error when the string starts with '*'.
> > What is the best way to solve this?
> 
> I suppose the problem occurs because you expression is not a valid
> regular expression.
> 
> A correct regular expression should look like this:
> "[EMAIL PROTECTED]"
Thx for everyones input.

This solved the problem:
host = '[EMAIL PROTECTED]'
mask = '[EMAIL PROTECTED]'
newmask = re.sub('\*', '.*', re.sub('\?', '.', mask))
result in that:
re.search(newmask, host) == True


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