Re: popen and password entry

2006-06-14 Thread Sinan Nalkaya
hi,i have found expect method for this purpose. i`m trying to use pexpect but following code gives me an something strange as a result.# The CODEimport pexpectcmd = '/usr/bin/rsync config [EMAIL PROTECTED]:/tmp/.'
#cmd = 'ssh [EMAIL PROTECTED]'child = pexpect.spawn(cmd)passwd = 'qwe123'try:    i = child.expect(['Password:','Password: ',pexpect.EOF,pexpect.TIMEOUT])    if i == 0:  
child.sendline(passwd)    elif i == 1:    print 1    elif i == 2:    print 2    elif i == 3:    print 3except EOF: print 'EOF'except TIMEOUT: print 'TIMEOUT'print 'finished'
# The resultfinishedException pexpect.ExceptionPexpect:  in > ignored
-- 
http://mail.python.org/mailman/listinfo/python-list

Regular Expression pattern group

2006-06-14 Thread JH
Hi

I am a fussy learner. Could someone explain to me why the following
inconsistency exists between methods? How can it be justified if it is
considered all right?

There are three groups in pattern. However, match object shows 3 groups
in collection, but group has to be indexed from one because the
m.group(0) is the implicit group for whole pattern.

Are these just some things to remember? "Group counting is from one".

>>> p = sre.compile('abc(.(.).)d(ef)')
>>> s
'xxxabc???defxxx'
>>> m = p.search(s)
>>> m.groups()
('???', '?', 'ef')
>>> m.group(0)
'abc???def'
>>> m.group(1)
'???'
>>> m.group(2)
'?'
>>> m.group(3)
'ef'
>>> m.group(4)

Traceback (most recent call last):
  File "", line 1, in -toplevel-
m.group(4)
IndexError: no such group
>>> p.findall(s)
[('???', '?', 'ef')]
>>>

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


Re: nested functions

2006-06-14 Thread Georg Brandl
George Sakkis wrote:
> Ben Finney wrote:
> 
>> "Gregory Petrosyan" <[EMAIL PROTECTED]> writes:
>>
>> > I often make helper functions nested, like this:
>> >
>> > def f():
>> > def helper():
>> > ...
>> > ...
>> >
>> > is it a good practice or not?
>>
>> You have my blessing. Used well, it makes for more readable code.
> 
> I'm not sure it's in general more readable; I typically use nested
> functions for closures only, not helper functions, so I'd read the code
> twice to check if it's a closure and if not why might have been defined
> locally. I prefer to define helpers at the module level, often making
> them 'private' by prepending their name with a single underscore.
> 
>> > What about performance of such constructs?
>>
>> What about it? Set up some examples maningful for your situation, with
>> and without such constructs, and use the profiler to find out.
> 
> It shouldn't come as a surprise if it turns out to be slower, since the
> nested function is redefined every time the outer is called.

That's right. However, if the outer function is only called a few times
and the nested function is called a lot, the locals lookup for the
function name is theoretically faster than the globals lookup. Also,
in methods you can use closures, so you don't have to pass, for example,
self to the inner function.

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


Re: Question about the Exception class

2006-06-14 Thread Georg Brandl
Carl J. Van Arsdall wrote:
> So this is probably a fairly basic question, but help me out because I'm 
> just not lining things up and I'm somewhat new to the world of exception 
> handling.
> 
> What's the benefit to inheriting an exception from and of the available 
> parent exception classes?  Does one subclass have benefits over any 
> other?  Most of what I see involves making a new class and inheriting 
> from Exception so that one can have an exception class with a name of 
> their choosing.  If you didn't care about the name would there be any 
> benefit to making a subclass versus raising StandardError or something 
> else equally vanilla?  Are there any difference to library provided 
> exceptions other than their names?

Creating your own exception hierarchy and using it consistently can help
you debugging when an exception raised by Python itself occurs. Also, you
can customize your own exception objects (such as, add new instance
attributes).

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


Re: Newbie wxpython staticbitmap help please

2006-06-14 Thread jean-michel bain-cornu
janama a écrit :
>   Can somewhone add a wx.Timer example to this to make it check
> if the file exists every minute or so , instead of clicking the button
> to check and update this? Or is there a better way of auto updating my
> little gui apps StaticBitmap if a file exists?
Why won't you write it yourself using the demo ?
It's clear and well documented.
Regards,
jm
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is Expressiveness in a Computer Language

2006-06-14 Thread Raffael Cavallaro
On 2006-06-14 16:36:52 -0400, Pascal Bourguignon <[EMAIL PROTECTED]> said:

> In lisp, all lists are homogenous: lists of T.

CL-USER 123 > (loop for elt in (list #\c 1 2.0d0 (/ 2 3)) collect 
(type-of elt))
(CHARACTER FIXNUM DOUBLE-FLOAT RATIO)

i.e., "heterogenous" in the common lisp sense: having different dynamic 
types, not in the H-M sense in which all lisp values are of the single 
union type T.

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


Re: What is Expressiveness in a Computer Language

2006-06-14 Thread Raffael Cavallaro
On 2006-06-14 15:04:34 -0400, Joachim Durchholz <[EMAIL PROTECTED]> said:

> Um... heterogenous lists are not necessarily a sign of expressiveness. 
> The vast majority of cases can be transformed to homogenous lists 
> (though these might then contain closures or OO objects).
> 
> As to references to nonexistent functions - heck, I never missed these, 
> not even in languages without type inference :-)
> 
> I don't hold that they are a sign of *in*expressiveness either. They 
> are just typical of highly dynamic programming environments such as 
> Lisp or Smalltalk.

This is a typical static type advocate's response when told that users 
of dynamically typed languages don't want their hands tied by a type 
checking compiler:

"*I* don't find those features expressive so *you* shouldn't want them."

You'll have to excuse us poor dynamically typed language rubes - we 
find these features expressive and we don't want to give them up just 
to silence a compiler whose static type checks are of dubious value in 
a world where user inputs of an often unpredictable nature can come at 
a program from across a potentially malicious internet making run-time 
checks a practical necessity.

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


Re: memory leak problem with arrays

2006-06-14 Thread sonjaa

Serge Orlov wrote:
> sonjaa wrote:
> > Serge Orlov wrote:
> > > sonjaa wrote:
> > > > Hi
> > > >
> > > > I'm new to programming in python and I hope that this is the problem.
> > > >
> > > > I've created a cellular automata program in python with the numpy array
> > > > extensions. After each cycle/iteration the memory used to examine and
> > > > change the array as determined by the transition rules is never freed.
> > > > I've tried using "del" on every variable possible, but that hasn't
> > > > worked.
> > >
> > > Python keeps track of number of references to every object if the
> > > object has more that one reference by the time you use "del" the object
> > > is not freed, only number of references is decremented.
> > >
> > > Print the number of references for all the objects you think should be
> > > freed after each cycle/iteration, if is not equal 2 that means you are
> > > holding extra references to those objects. You can get the number of
> > > references to any object by calling sys.getrefcount(obj)
> >
> > thanks for the info. I used this several variables/objects and
> > discovered that little counters i.e. k = k +1 have many references to
> > them, up tp 1+.
> > Is there a way to free them?
>
> Although it's looks suspicious, even if you manage to free it you will
> gain only 12 bytes. I think you should concentrate on more fat
> objects ;)


Sent message to the NumPy forum as per Roberts suggestion.
An update after implimenting the suggestions:

After doing this I see that iterative counters used to collect
occurrences
and nested loop counters (ii & jj) as seen in the code example below
are the culprits with the worst ones over 1M:

 for ii in xrange(0,40):
for jj in xrange(0,20):
try:
nc = y[a+ii,b+jj]
except IndexError: nc = 0

if nc == "1" or nc == "5":
news = news +1
if news == 100:
break
else:
pass
y[a+ii,b+jj] = 4
else:
pass


The version of python I'm using is 2.4.3 and the version of NumPy is
0.9.8

thanks again for all the help
Sonja

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


Re: Database read and write

2006-06-14 Thread Justin Ezequiel
Stan Cook wrote:
> will ope, read, and write to a Dbase 3 or 4 file?

I know I have one in VB6 that I've been meaning to translate to Python
but...
(do not have time/am lazy/does not work with indexes)

did a google search for you though

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362715
http://www.garshol.priv.no/download/software/python/dbfreader.py

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


Re: Perl XML::Simple and Data::Dumper - exists in Python?

2006-06-14 Thread Wallace Owen
Miguel Manso wrote:
> Hi there,
> 
> I'm a Perl programmer trying to get into Python. I've been reading some 
> documentation and I've choosed Python has being the "next step" to give.
> 
> Can you point me out to Python solutions for:
> 
> 1) Perl's Data::Dumper
> 
> It dumps any perl variable to the stdout in a "readable" way.

All Python objects support reflection and can be serialized to a data 
stream.  There's about four ways to do it (Kinda perl-like in that 
regard, but typically for a particular application there's one obvious 
right choice).  You control the way your objects appear as strings, by 
defining a __str__ member function that'll be invoked if the user does:

% print str(yourObject)

You can print any builtin type with just:

 >>> lst = ["one", "two", (3, 4.56), 1]
 >>> print lst
['one', 'two', (3, 4.5596), 1]
 >>>

> 
> 2) Perl's XML::Simple
> 
> It maps a XML file into a Perl data structure.

Python's got a Document Object Model lib that essentially maps an XML 
file to objects that have built-in-type behavior - you can treat a 
NodeList object as a python list, indexing into it, iterating over it's 
contents, etc.

It's also got SAX and expat bindings.

> 
> Does Python have something like these two tools? I've been googling 
> before posting this and didn't find anything.

Do your searches at python.org.


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


Re: split with "*" in string and ljust() puzzles

2006-06-14 Thread Sambo
George Sakkis wrote:
> Serge Orlov wrote:
> 
> 
>>Sambo wrote:
>>
>>>I have just (finally) realized that it is splitting and removing
>>>on single space but that seams useless, and split items
>>>1 and 2 are empty strings not spaces??
>>
>>What is useless for you is worth $1,000,000 for somebody else ;)
>>If you have comma separated list '1,,2'.split(',') naturally returns
>>['1', '', '2']. I think you can get what you want with a simple regexp.
> 
> 
> No need for regexp in this case, just use None to specify one or more
> whitespace chars as delimiter: line.split(None,3)
> 
> George
> 
AHA! Thank You.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: nested functions

2006-06-14 Thread George Sakkis
Ben Finney wrote:

> "Gregory Petrosyan" <[EMAIL PROTECTED]> writes:
>
> > I often make helper functions nested, like this:
> >
> > def f():
> > def helper():
> > ...
> > ...
> >
> > is it a good practice or not?
>
> You have my blessing. Used well, it makes for more readable code.

I'm not sure it's in general more readable; I typically use nested
functions for closures only, not helper functions, so I'd read the code
twice to check if it's a closure and if not why might have been defined
locally. I prefer to define helpers at the module level, often making
them 'private' by prepending their name with a single underscore.

> > What about performance of such constructs?
>
> What about it? Set up some examples maningful for your situation, with
> and without such constructs, and use the profiler to find out.

It shouldn't come as a surprise if it turns out to be slower, since the
nested function is redefined every time the outer is called. If you
actually call the outer function a lot, you'd better profile it.

George

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


Re: split with "*" in string and ljust() puzzles

2006-06-14 Thread George Sakkis
Serge Orlov wrote:

> Sambo wrote:
> > I have just (finally) realized that it is splitting and removing
> > on single space but that seams useless, and split items
> > 1 and 2 are empty strings not spaces??
>
> What is useless for you is worth $1,000,000 for somebody else ;)
> If you have comma separated list '1,,2'.split(',') naturally returns
> ['1', '', '2']. I think you can get what you want with a simple regexp.

No need for regexp in this case, just use None to specify one or more
whitespace chars as delimiter: line.split(None,3)

George

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


Database read and write

2006-06-14 Thread Stan Cook
Ok .  I know I'm talking ancient history, but some of us are 
stuck working with them.  Is there anything for python which 
will ope, read, and write to a Dbase 3 or 4 file?  I really 
need your assistance on this one.

Regards,

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


Re: __cmp__ method

2006-06-14 Thread George Sakkis
Jon Clements wrote:

> This probably isn't exactly what you want, but, unless you wanted to do
> something especially with your own string class, I would just pass a
> function to the sorted algorithm.
>
> eg:
>
> sorted( [a,b,c], cmp=lambda a,b: cmp(len(a),len(b)) )
>
> gives you the below in the right order...

Or even better in 2.4 or later:
sorted([a,b,c], key=len)

George

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


Re: Bundling an application with third-party modules

2006-06-14 Thread Serge Orlov
Ben Finney wrote:
> "Serge Orlov" <[EMAIL PROTECTED]> writes:
>
> > Ben Finney wrote:
> > > That's a large part of my question. How can I lay out these
> > > modules sensibly during installation so they'll be easily
> > > available to, but specific to, my application?
> >
> > Put them in a directory "lib" next to the main module and start the
> > main module with the following blurb:
> > 
> > import sys, os
> > sys.path.insert(1, os.path.join(sys.path[0],"lib"))
> > 
>
> The application consists of many separate programs to perform various
> tasks, some larger than others. There's no sensible place for a "main
> module".

Perhaps I'm using my own jargon. By "main module" I mean every module
used to start any application within your project. If you want
relocatable solution, create empty .topdir file in the top directory
and put this blurb into every application:

import sys, os
top_dir = sys.path[0]
while True:
if os.path.exists(os.path.join(top_dir,".topdir")):
break
top_dir = os.path.dirname(top_dir)
sys.path.insert(1, os.path.join(top_dir,"lib"))

I don't think you need to worry about duplication, I used this code. It
is verion 1.0 and it is final :) You won't need to change it.

> There probably will be a library directory for common code,
> though. Are you suggesting that the third-party libraries should go
> within the application-native library?

Not really. I was just feeling lazy to type a generic solution, so I
assumed one project == one application.

> What's a good way to get from upstream source code (some of which is
> eggs, some of which expects 'distutils' installation, and some of
> which is simple one-file modules) to a coherent set of application
> library code, that is automatable in an install script?

Well, I did it manually, it's not that time consuming if you keep in
mind that you also need to test new version and by testing I also mean
finding integration bugs days later. Anyway, if you feel like
automating I think you can do something using distutils command
"install --home=/temp/dir" and then copying to your common library
directory in a flat manner (--home option puts files in subdirectories
that don't make sense for a bundled lib)

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


Re: Negative hex to int

2006-06-14 Thread Ben Finney
John Machin <[EMAIL PROTECTED]> writes:

> On 15/06/2006 10:31 AM, Ben Finney wrote:
> > If you want a special interpretation of the value, you'll have to
> > calculate it.
> > 
> > Example assuming you want a one's-complement interpretation::
> 
> Given that the OP had to ask the question at all, it is doubtful
> that he knows what "one's-complement" means. He may well not be
> alone -- see later.

You've pointed out something useful: a quick attempt (by me, in this
case) to describe the algorithm isn't worth much, less so if it's
already well-documented. Hopefully the original poster can consult a
more authoritative reference on the topic. Fortunately, that was also
one of my points :-)

The implementation itself seems to do the job the OP asked. I hope
it's useful in some form.

-- 
 \  "If society were bound to invent technologies which could only |
  `\   be used entirely within the law, then we would still be sitting |
_o__)in caves sucking our feet."  -- Gene Kan, creator of Gnutella |
Ben Finney

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


Re: "groupby" is brilliant!

2006-06-14 Thread Alex Martelli
James Stroud <[EMAIL PROTECTED]> wrote:

> Alex Martelli wrote:
> > James Stroud <[EMAIL PROTECTED]> wrote:
> >...
> > 
> >>def doit(rows, doers, i=0):
> >>   for r, alist in groupby(rows, itemgetter(i)):
> >> if len(doers) > 1:
> >>   doit(alist, doers[1:], i+1)
> >> doers[0](r)
> > 
> > 
> > Isn't this making N useless slices (thus copies, for most kinds of
> > sequences) for a doers of length N?  Since you're passing i anyway, it
> > seems to me that:
> > 
> > def doit(rows, doers, i=0):
> > for r, alist in groupby(rows, itemgetter(i)):
> >   if len(doers) > i+1:
> >  doit(alist, doers, i+1)
> >   doers[i](r)
> > 
> > is equivalent to your code, but avoids these slices (thus copies).
> > 
> > 
> > Alex
> 
> Actually, I remember why I wrote it that way--because the itemgetter 
> argument may not start at zero (admitting that I haven't yet played with
> itemgetter at all). Maybe pop(0) is better than a copy?
> 
> 
> def doit(rows, doers, i=0):
>for r, alist in groupby(rows, itemgetter(i)):
>  doer = doers.pop(0)
>  if doers:  # empty list tests as False
> doit(alist, doers, i+1)
>  doer(r)

No, doers.pop(0) is O(N), just like the slicing doers[1:].

To support the indexing into itemgetter possibly being different from
that into doers (under the hypothesis that efficiency matters here, of
course!-) I'd rather do something like:

def doit(rows, doers, i=0):
L = len(doers)
def _aux(rows, j):
if L <= j: return
doer = doers[j]
for r, alist in groupby(rows, itemgetter(i+j)):
_aux(alist, j+1)
doer(r)
_aux(rows, 0)

haven't tested this, but it seems a straightforward semantics-preserving
transformation -- the hoisting out of the recursion of the computation
of len(), and out of the loop of the termination-test and indexing,
being trivial optimizations (which I'm not averse to using, even though
trivial, because I think they make the code clearer.

Whether all this is worth it, or not, is in a sense besides the point --
I like this anyway, even just as an example of how the best way to
introduce recursion may often be, not in the "official" function (the
one that gets called by client code), but in a "private" auxiliary
function inside the "official" one.


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


Re: Screen capturing on Windows

2006-06-14 Thread Roger Upole
"Rune Strand" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
>
> Is it possible by use of pyWin32 or ctypes to make a screen capture of
> an inactive, or a hidden window if the hwnd/WindowName/ClassName is
> known? I've seen dedicated screen capture software do this. While
> PIL.ImageGrab.grab() is excellent, it will only capture the foreground
> of the desktop. I've tried for hours, but I soon get helplessly lost in
> the labyrinths of the Win32API.
>

This will restore a minimized window, bring it to the top and save a bmp.

import time
import win32gui, win32ui, win32con, win32api

def window_capture(window_title):
hwnd=win32gui.FindWindow(None, window_title)
if not hwnd:
raise 'Window not found'

print hwnd
win32gui.ShowWindow(hwnd,win32con.SW_RESTORE)
win32gui.SetForegroundWindow(hwnd)
time.sleep(0.1)
l,t,r,b=win32gui.GetWindowRect(hwnd)
h=b-t
w=r-l
hwndDC = win32gui.GetWindowDC(hwnd)
mfcDC=win32ui.CreateDCFromHandle(hwndDC)
saveDC=mfcDC.CreateCompatibleDC()
saveBitMap = win32ui.CreateBitmap()
saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
saveDC.SelectObject(saveBitMap)
saveDC.BitBlt((0,0),(w, h) , mfcDC, (0,0), win32con.SRCCOPY)
temp_dir=win32api.GetTempPath()
bmpname=win32api.GetTempFileName(temp_dir,'wc')[0]+'.bmp'
saveBitMap.SaveBitmapFile(saveDC, bmpname)
return bmpname

  Roger


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


Re: How to select a folder with native windows dialog box?

2006-06-14 Thread Roger Upole
<[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
> Thanks for your answer, it's working fine!
>
> For information, the function to use to get the pathName is
> shell.SHGetPathFromIDList
> It returns an error if you select a special folder (!?!?) but otherwise
> it's working fine... And I was unable to fix this issue.

SHGetPathFromIDList only works for real filesystem folders.
Pseudo-folders like Control Panel or Network Connections
throw an error.  You can use PyIShellFolder.BindToObject
to get an interface to perform operations on these.

  Roger


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


Re: Negative hex to int

2006-06-14 Thread John Machin
On 15/06/2006 10:31 AM, Ben Finney wrote:
> [EMAIL PROTECTED] writes:
> 
>> The problem is negative values. If the unit returns the hex value
>> 'e7', it means -25, but python says it's 231:
> 
> Python is right. There is no "negative bit" in Python numbers, now
> that unification of 'long' and 'int' is complete; numbers can grow
> indefinitely large.
> 
> If you want a special interpretation of the value, you'll have to
> calculate it.
> 
> Example assuming you want a one's-complement interpretation::

Given that the OP had to ask the question at all, it is doubtful that he 
knows what "one's-complement" means. He may well not be alone -- see later.

> 
> def value_from_reading(num):
> """ Gets the integer value from the reading string.
> num is a positive hexadecimal number as a string.
> Numbers greater than 0x7F are interpreted as negative,
> with magnitude greater than 0x7F being the negative value.
> Only the lowest 15 bits are used for the magnitude.

thing & 0x7F looks like lowest 7 bits to me.

> 
> >>> value_from_reading('00')
> 0
> >>> value_from_reading('05')
> 5
> >>> value_from_reading('7f')
> 127
> >>> value_from_reading('80')
> -128
> >>> value_from_reading('e7')
> -25
> >>> value_from_reading('ff')
> -1

Looks like TWOS complement to me.

> >>> value_from_reading('100')
> -128

Same result as '80'?
In any case the OP gave no indication that he was getting more than two 
hex digits. His desired interpretation of 'e7' as -25 strongly indicates 
  that he's getting only 2 hex digits.

> >>> value_from_reading('fff')
> -1
> 
> """
> num_base = 16
> negative_threshold = 0x7F
> int_val = int(num, num_base)
> if int_val > negative_threshold:
> magnitude = (int_val & negative_threshold)
> int_val = -(1 + negative_threshold - magnitude)
> return int_val
> 
> Adjust for whatever algorithm you want to use. Consult a book of
> algorithms if you want a better implementation than my off-the-cuff
> brute-force approach.



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


Re: Bundling an application with third-party modules

2006-06-14 Thread Ben Finney
"Serge Orlov" <[EMAIL PROTECTED]> writes:

> Ben Finney wrote:
> > That's a large part of my question. How can I lay out these
> > modules sensibly during installation so they'll be easily
> > available to, but specific to, my application?
> 
> Put them in a directory "lib" next to the main module and start the
> main module with the following blurb:
> 
> import sys, os
> sys.path.insert(1, os.path.join(sys.path[0],"lib"))
> 

The application consists of many separate programs to perform various
tasks, some larger than others. There's no sensible place for a "main
module".

There probably will be a library directory for common code,
though. Are you suggesting that the third-party libraries should go
within the application-native library?

What's a good way to get from upstream source code (some of which is
eggs, some of which expects 'distutils' installation, and some of
which is simple one-file modules) to a coherent set of application
library code, that is automatable in an install script?

I could muddle through and hack something together, of course. I'm
asking what are the ways that have already been found to work well.

-- 
 \  "Friendship is born at that moment when one person says to |
  `\another, 'What!  You too?  I thought I was the only one!'"  -- |
_o__)   C.S. Lewis |
Ben Finney

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


Re: wxPython problems with Fedora Core 5

2006-06-14 Thread writeson
Frank,

Thanks for the link, that solved the problem for me with FC5! That was
a great help to me!

Doug

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


wxPython install question

2006-06-14 Thread DarkBlue
Trying to install wxPython on Suse10.1 64 with gcc4.1.0
and get
wxPython-src-2.6.3.2/wxPython # python setup.py install 
Found wx-config: /usr/local/bin/wx-config
Using flags:  --toolkit=gtk2 --unicode=no --version=2.6
Preparing CORE...
Preparing GLCANVAS...
Preparing STC...
Preparing GIZMOS...
Preparing ANIMATE...
running install
running build
running build_py
copying wx/__version__.py -> build-gtk2/lib.linux-x86_64-2.4/wx
copying wx/build/build_options.py ->
build-gtk2/lib.linux-x86_64-2.4/wx/build
running build_ext
building '_glcanvas' extension
gcc -pthread -fno-strict-aliasing -DNDEBUG -O2 -fmessage-length=0 -Wall
-D_FORTIFY_SOURCE=2 -g -fPIC -DSWIG_TYPE_TABLE=_wxPython_table
-DHAVE_CONFIG_H -DWXP_USE_THREAD=1 -UNDEBUG -DGTK_NO_CHECK_CASTS
-D__WXGTK__ -D_FILE_OFFSET_BITS=64 -D_LARGE_FILES -DNO_GCC_PRAGMA -Iinclude
-Isrc -I/usr/local/lib/wx/include/gtk2-ansi-release-2.6
-I/usr/local/include/wx-2.6 -I/usr/include/cairo -I/usr/include/freetype2
-I/usr/X11R6/include -I/usr/include/libpng12 -I/opt/gnome/include/gtk-2.0
-I/opt/gnome/lib64/gtk-2.0/include -I/opt/gnome/include/atk-1.0
-I/opt/gnome/include/pango-1.0 -I/opt/gnome/include/glib-2.0
-I/opt/gnome/lib64/glib-2.0/include -I/usr/include/python2.4 -c
contrib/glcanvas/gtk/glcanvas_wrap.cpp -o
build-gtk2/temp.linux-x86_64-2.4/contrib/glcanvas/gtk/glcanvas_wrap.o -O3
contrib/glcanvas/gtk/glcanvas_wrap.cpp: In function ‘PyObject*
_wrap_new_GLContext(PyObject*, PyObject*, PyObject*)’:
contrib/glcanvas/gtk/glcanvas_wrap.cpp:1737: error: ‘wxGLCanvas’ was not
declared in this scope
contrib/glcanvas/gtk/glcanvas_wrap.cpp:1737: error: ‘arg2’ was not declared
in this scope
contrib/glcanvas/gtk/glcanvas_wrap.cpp:1737: error: expected
primary-expression before ‘)’ token
contrib/glcanvas/gtk/glcanvas_wrap.cpp:1737: error: expected `;' before
numeric constant
contrib/glcanvas/gtk/glcanvas_wrap.cpp:1740: error: ‘wxGLContext’ was not
declared in this scope
contrib/glcanvas/gtk/glcanvas_wrap.cpp:1740: error: ‘arg4’ was not declared
in this scope 

then it errors out .
What is wrong ? The wxwidgets compiled without a hitch.

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

Re: Negative hex to int

2006-06-14 Thread James Stroud
[EMAIL PROTECTED] wrote:
> Hi!
> 
> While communicating with a monitoring unit, I get some hex values
> representing degrees celcius from its probes. The values can be
> something like '19' or '7d'. To convert it to int, I do the following:
> ---
> Python 2.4.2 (#1, Sep 28 2005, 10:25:47)
> [GCC 3.4.3 20041212 (Red Hat 3.4.3-9.EL4)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> 
int('7d', 16)
> 
> 125
> 
int('19', 16)
> 
> 25
> 
> ---
> 
> The problem is negative values. If the unit returns the hex value 'e7',
> it means -25, but python says it's 231:
> ---
> 
int('e7', 16)
> 
> 231
> ---
> 
> Does anyone have a clue a to what I need to do?
> 
> Thanks!
> 
> Andreas Lydersen
> 


py> t = lambda x: int(x, 16) - ((int(x, 16) >> 7) * 256)
py> t('e7')
-25


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

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


Re: prog1 | prog2 . How not to make prog2 block if not piped?

2006-06-14 Thread riquito

Steve Holden ha scritto:

> When you run it "standalone" you should give it some input - type some
> text then enter ^D (on Unix-like systems) or ^Z (on Windows). How else
> do you expect read() to return anything? It *has* to read to the end fo
> the file before it returns a value.
>
> regards
>   Steve

you've got reason.
I must read my command line options, if then there is still text I use
that, otherwise I read from stdin. If nothing was piped, the user must
complete the work.

Thank you all,
Riccardo

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


Re: nested functions

2006-06-14 Thread Ben Finney
"Gregory Petrosyan" <[EMAIL PROTECTED]> writes:

> I often make helper functions nested, like this:
> 
> def f():
> def helper():
> ...
> ...
> 
> is it a good practice or not?

You have my blessing. Used well, it makes for more readable code.

> What about performance of such constructs?

What about it? Set up some examples maningful for your situation, with
and without such constructs, and use the profiler to find out.

-- 
 \  "People demand freedom of speech to make up for the freedom of |
  `\thought which they avoid."  -- Soren Aabye Kierkegaard |
_o__)  (1813-1855) |
Ben Finney

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


Re: Negative hex to int

2006-06-14 Thread Ben Finney
[EMAIL PROTECTED] writes:

> The problem is negative values. If the unit returns the hex value
> 'e7', it means -25, but python says it's 231:

Python is right. There is no "negative bit" in Python numbers, now
that unification of 'long' and 'int' is complete; numbers can grow
indefinitely large.

If you want a special interpretation of the value, you'll have to
calculate it.

Example assuming you want a one's-complement interpretation::

def value_from_reading(num):
""" Gets the integer value from the reading string.
num is a positive hexadecimal number as a string.
Numbers greater than 0x7F are interpreted as negative,
with magnitude greater than 0x7F being the negative value.
Only the lowest 15 bits are used for the magnitude.

>>> value_from_reading('00')
0
>>> value_from_reading('05')
5
>>> value_from_reading('7f')
127
>>> value_from_reading('80')
-128
>>> value_from_reading('e7')
-25
>>> value_from_reading('ff')
-1
>>> value_from_reading('100')
-128
>>> value_from_reading('fff')
-1

"""
num_base = 16
negative_threshold = 0x7F
int_val = int(num, num_base)
if int_val > negative_threshold:
magnitude = (int_val & negative_threshold)
int_val = -(1 + negative_threshold - magnitude)
return int_val

Adjust for whatever algorithm you want to use. Consult a book of
algorithms if you want a better implementation than my off-the-cuff
brute-force approach.

-- 
 \   "Remorse: Regret that one waited so long to do it."  -- Henry |
  `\L. Mencken |
_o__)  |
Ben Finney

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


Re: Bundling an application with third-party modules

2006-06-14 Thread Serge Orlov
Ben Finney wrote:
> > 2. An Installshield-type installer can place files (essentially)
> > wherever you want them
>
> That's a large part of my question. How can I lay out these modules
> sensibly during installation so they'll be easily available to, but
> specific to, my application?

Put them in a directory "lib" next to the main module and start the
main module with the following blurb:

import sys, os
sys.path.insert(1, os.path.join(sys.path[0],"lib"))


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


Re: split with "*" in string and ljust() puzzles

2006-06-14 Thread Serge Orlov
Sambo wrote:
> I have just (finally) realized that it is splitting and removing
> on single space but that seams useless, and split items
> 1 and 2 are empty strings not spaces??

What is useless for you is worth $1,000,000 for somebody else ;)
If you have comma separated list '1,,2'.split(',') naturally returns
['1', '', '2']. I think you can get what you want with a simple regexp.

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


found a swftools for 2.4 - Docs anyone?

2006-06-14 Thread jmdeschamps
New to swf - interesting technology for dynamic web graphic effects
stemming from user input.

I found a working windows pre-compiled binary (0.6.2) for Python 2.4 of
rfxswf library  from swftools to generate swf files.  (flash compiled
files(?)).

No source of documentation of that api.  There are a few python
examples that I managed to make work, from swftools site but only
covers partly the api.

help(SWF) only tells of the main classes - nothings on arguments

I tried reading the C source, but I'm not very fluent in C so that
didn't amount to much.

Any help appreciated in finding help on this API.

Thanks in advance

Jean-Marc
Ref: http://www.swftools.org/
python binary :
http://lists.gnu.org/archive/html/swftools-common/2005-01/msg00066.html
(Thanks to Daichi .)

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


Re: Bundling an application with third-party modules

2006-06-14 Thread Ben Finney
"utabintarbo" <[EMAIL PROTECTED]> writes:

> 1. py2exe/csFreeze-type thing. This would even relieve the customer
> of installing python

Not really what I need. I only want to have installation control over
*some* of the modules, and leave Python and other dependencies up to
the administrator to manage. The application consists of many
programs, so bundling Python-and-many-modules with *each* one makes no
sense.

> 2. An Installshield-type installer can place files (essentially)
> wherever you want them

That's a large part of my question. How can I lay out these modules
sensibly during installation so they'll be easily available to, but
specific to, my application?

-- 
 \"Know what I hate most? Rhetorical questions."  -- Henry N. Camp |
  `\   |
_o__)  |
Ben Finney

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


Re: Writing PNG with pure Python

2006-06-14 Thread Ben Finney
"Johann C. Rocholl" <[EMAIL PROTECTED]> writes:

> Ben Finney schrieb:
> > Simplify. Please don't attempt to write yet another set of license
> > terms without expert legal assistance. You've already chosen the
> > Expat license as being acceptable; use that, and you grant all the
> > rest without even mentioning it.
> 
> Sorry for my stubborn ignorance, and thank you for your patient
> explanations.

No problems; if license proliferation can be reduced, it's worth
spending some time to do so.

> I think I finally got it: I'll put the bulk of my browsershots
> project under the GNU GPL again, and the independent library parts
> like png.py under the Expat License.

Sounds quite workable. This has the effect that the work as a whole
can be redistributed under the GNU GPL (since the Expat license allows
this), and the library parts can be redistributed independently under
just about any license.

-- 
 \ "As we enjoy great advantages from the inventions of others, we |
  `\ should be glad to serve others by any invention of ours."  -- |
_o__)Benjamin Franklin |
Ben Finney

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


Re: Numerics, NaNs, IEEE 754 and C99

2006-06-14 Thread Grant Edwards
On 2006-06-14, Nick Maclaren <[EMAIL PROTECTED]> wrote:
>
> In article <[EMAIL PROTECTED]>,
> Gary Herron <[EMAIL PROTECTED]> writes:
>|> 
>|> The IEEE standard specifies (plus or minus) infinity as the result of
>|> division by zero.  This makes sense since such is the limit of division
>|> by a quantity that goes to zero.  The IEEE standard then goes on to
>|> define reasonable results for arithmetic between infinities and real
>|> values.  The production of, and arithmetic on, infinities is a choice
>|> that any application may want allow or not.
>
> The mistake you have made (and it IS a mistake) is in assuming
> that the denominator approaches zero from the direction
> indicated by its sign.

I assume the "you" in that sentence refers to the IEEE FP
standards group.  I just try to follow the standard, but I have
found that the behavior required by the IEEE standard is
generally what works best for my applications.

> There are many reasons why it is likely to not be, but let's give only
> two:
>
> It may be a true zero - i.e. a count that is genuinely zero, or
> the result of subtracting a number from itself.

I do real-world engineering stuff with measured physical
quatities.  There generally is no such thing as "true zero".

> I fully agree that infinity arithmetic is fairly well-defined for
> most operations, but it most definitely is not in this case.  It should
> be reserved for when the operations have overflowed.

All I can say is that 1/0 => Inf sure seems to work well for
me.

-- 
Grant Edwards   grante Yow!  World War Three can
  at   be averted by adherence
   visi.comto a strictly enforced
   dress code!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Numerics, NaNs, IEEE 754 and C99

2006-06-14 Thread Grant Edwards
On 2006-06-14, Sébastien Boisgérault <[EMAIL PROTECTED]> wrote:

> Jeez, 12 posts in this IEEE 754 thread, and still no message
> from uncle timmy ? ;)
>
> Please, we need enlightenment here and *now* :)

What we need is fewer people like me who do nothing but
complain about it...

-- 
Grant Edwards   grante Yow!  I am covered with
  at   pure vegetable oil and I am
   visi.comwriting a best seller!
-- 
http://mail.python.org/mailman/listinfo/python-list


split with "*" in string and ljust() puzzles

2006-06-14 Thread Sambo
I have couple of puzzles in my code.

def load_headers( group_info ):

if os.path.isfile( group_info.pointer_file ):
ptr_file = open( group_info.pointer_file, "r" )
else:
print group_info.mess_list
return
linecount = 0
ptr_file.seek( 512 )
print ptr_file.tell()
line = ptr_file.readline()
while line != "" :
if line[0:1] == "<":
print linecount
print len(line), line
print line.split( " ", 3 )

group_info.mess_list.append( line.split( " ", 3 ) )
line = ptr_file.readline()
ptr_file.close()

when reading the following line from file:  
<[EMAIL PROTECTED]> 2338 *Re: PCB Pad 
Size for TQFP Package?? 

the split command returns
 ['<[EMAIL PROTECTED]>','','','2338 *
Re: PCB Pad Size for TQFP Package??']
   
instead of
 ['<[EMAIL PROTECTED]>, '2338','*','Re: PCB Pad 
Size for TQFP Package??']



I have just (finally) realized that it is splitting and removing on single 
space but that seams useless, and split items 1 and 2 are empty strings not 
spaces?? regex somewhere it shouldn't be?



The other problem 
is in this piece of code which is trying to pad the first 512 bytes:

line = group_info.group_name+" sf"+ group_info.first + " sl"+ \ 
group_info.last + " sc" + group_info.count + "dt" + \   
group_info.date_checked + group_info.time_checked
line = line + "\n"
line = string.ljust( line, 512 - len(os.linesep) )
print len( os.linesep )
line += "\n"
print len( line )
ptr_file.write( line )
print " "+repr(ptr_file.tell())+ " "
print "message list\n"

the ljust function returns string 511 bytes long, besides the fact that the 
logic is not exactly correct what is going on here. Is ljust trying to be smart 
about the EOL inside the string already?

I have tried the following, which should be about right ( account for the 1 
bytes added after justification and two added by file write.)

line = string.ljust( line, 512 - len(os.linesep) - len(os.linesep) - 1 )

But, in this case I end up 2 bytes short of 512.

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


Re: Negative hex to int

2006-06-14 Thread John Machin
On 15/06/2006 9:24 AM, Wojciech Muła wrote:
> [EMAIL PROTECTED] wrote:
>> The problem is negative values. If the unit returns the hex value 'e7',
>> it means -25, but python says it's 231:
>> ---
> int('e7', 16)
>> 231
>> ---
>>
>> Does anyone have a clue a to what I need to do?
> 
> def u2(x):
>   if x & 0x80: # MSB set -> neg.
>   return -((~x & 0xff) + 1)

Holy obfuscation, Batman!

>   else:
>   return x
>   
 u2(int('e7', 16))
> -25
 u2(int('12', 16))
> 18
> 
> w.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Negative hex to int

2006-06-14 Thread Wojciech Muła
[EMAIL PROTECTED] wrote:
> The problem is negative values. If the unit returns the hex value 'e7',
> it means -25, but python says it's 231:
> ---
 int('e7', 16)
> 231
> ---
>
> Does anyone have a clue a to what I need to do?

def u2(x):
if x & 0x80: # MSB set -> neg.
return -((~x & 0xff) + 1)
else:
return x

>>> u2(int('e7', 16))
-25
>>> u2(int('12', 16))
18
>>>

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


Re: __cmp__ method

2006-06-14 Thread Jon Clements
This probably isn't exactly what you want, but, unless you wanted to do
something especially with your own string class, I would just pass a
function to the sorted algorithm.

eg:

sorted( [a,b,c], cmp=lambda a,b: cmp(len(a),len(b)) )

gives you the below in the right order...

Never tried doing what you're doing, but something about builtin types,
and there's a UserString module...

Hope that helps a bit anyway,

Jon.

JH wrote:

> Hi
>
> Can anyone explain to me why the following codes do not work? I want to
> try out using __cmp__ method to change the sorting order. I subclass
> the str and override the __cmp__ method so the strings can be sorted by
> the lengh. I expect the shortest string should be in the front. Thanks
>
> >>> class myStr(str):
> def __init__(self, s):
> str.__init__(self, s) # Ensure super class is initialized
> def __cmp__(self, other):
> return cmp(len(self), len(other))
>
> >>> a = myStr('abc')
> >>> b = myStr('Personal')
> >>> c = myStr('Personal firewall')
> >>> sorted([c, b, a])
> ['Personal', 'Personal firewall', 'abc']
> >>>

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


Re: Negative hex to int

2006-06-14 Thread John Machin
On 15/06/2006 9:09 AM, [EMAIL PROTECTED] wrote:
> Hi!
> 
> While communicating with a monitoring unit, I get some hex values
> representing degrees celcius from its probes. The values can be
> something like '19' or '7d'. To convert it to int, I do the following:
> ---
> Python 2.4.2 (#1, Sep 28 2005, 10:25:47)
> [GCC 3.4.3 20041212 (Red Hat 3.4.3-9.EL4)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
 int('7d', 16)
> 125
 int('19', 16)
> 25
> ---
> 
> The problem is negative values. If the unit returns the hex value 'e7',
> it means -25, but python says it's 231:
> ---
 int('e7', 16)
> 231
> ---
> 

The Da Vinci code it aint :-)

|>> readings = ['19', 'e7']
|>> for reading in readings:
...intval = int(reading, 16)
...if intval >= 128:
...   intval -= 256
...print intval
...
25
-25

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


Re: __cmp__ method

2006-06-14 Thread marek . rocki
Python documentation says:
>__cmp__( self, other)
> Called by comparison operations if rich comparison (see above) is not defined.
So it seems you have to redefine rich comparisons __lt__, __gt__,
__eq__ etc as well.

If all you need is change sorting order, why not use appropriate
parameters of sorted() function (cmp=... or key=...)?

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


Re: memory leak problem with arrays

2006-06-14 Thread Serge Orlov
sonjaa wrote:
> Serge Orlov wrote:
> > sonjaa wrote:
> > > Hi
> > >
> > > I'm new to programming in python and I hope that this is the problem.
> > >
> > > I've created a cellular automata program in python with the numpy array
> > > extensions. After each cycle/iteration the memory used to examine and
> > > change the array as determined by the transition rules is never freed.
> > > I've tried using "del" on every variable possible, but that hasn't
> > > worked.
> >
> > Python keeps track of number of references to every object if the
> > object has more that one reference by the time you use "del" the object
> > is not freed, only number of references is decremented.
> >
> > Print the number of references for all the objects you think should be
> > freed after each cycle/iteration, if is not equal 2 that means you are
> > holding extra references to those objects. You can get the number of
> > references to any object by calling sys.getrefcount(obj)
>
> thanks for the info. I used this several variables/objects and
> discovered that little counters i.e. k = k +1 have many references to
> them, up tp 1+.
> Is there a way to free them?

Although it's looks suspicious, even if you manage to free it you will
gain only 12 bytes. I think you should concentrate on more fat
objects ;)

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


Negative hex to int

2006-06-14 Thread andreas . lydersen
Hi!

While communicating with a monitoring unit, I get some hex values
representing degrees celcius from its probes. The values can be
something like '19' or '7d'. To convert it to int, I do the following:
---
Python 2.4.2 (#1, Sep 28 2005, 10:25:47)
[GCC 3.4.3 20041212 (Red Hat 3.4.3-9.EL4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> int('7d', 16)
125
>>> int('19', 16)
25
>>>
---

The problem is negative values. If the unit returns the hex value 'e7',
it means -25, but python says it's 231:
---
>>> int('e7', 16)
231
---

Does anyone have a clue a to what I need to do?

Thanks!

Andreas Lydersen

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


Re: What is Expressiveness in a Computer Language

2006-06-14 Thread Neelakantan Krishnaswami
In article <[EMAIL PROTECTED]>, Pascal Costanza wrote:
> Torben Ægidius Mogensen wrote:
> 
>> On a similar note, is a statically typed langauge more or less
>> expressive than a dynamically typed language?  Some would say less, as
>> you can write programs in a dynamically typed language that you can't
>> compile in a statically typed language (without a lot of encoding),
>> whereas the converse isn't true.
> 
> It's important to get the levels right here: A programming language
> with a rich static type system is more expressive at the type level,
> but less expressive at the base level (for some useful notion of
> expressiveness ;).

This doesn't seem obviously the case to me. If you have static
information about your program, the compiler can use this information
to automate a lot of grunt work away.

Haskell's system of typeclasses work this way. If you tell the
compiler how to print integers, and how to print lists, then when you
call a print function on a list of list of integers, then the compiler
will automatically figure out the right print function using your base
definitions. This yields an increase in Felleisen-expressiveness over
a dynamically typed language, because you would need to globally
restructure your program to achieve a similar effect.

More dramatic are the "polytypic" programming languages, which let you
automate even more by letting you write generic map, fold, and print
functions which work at every type.

> This doesn't seem to capture what I hear from Haskell programmers
> who say that it typically takes quite a while to convince the
> Haskell compiler to accept their programs. (They perceive this to be
> worthwhile because of some benefits wrt correctness they claim to
> get in return.)

This is true, if you are a novice learning the language, or if you are
an expert programming with good style.

If you encode your invariants in the types, then type errors will
signal broken invariants. But: learning how to use the type system to
encode significantly complex invariants (eg, that an abstract syntax
tree representing an HTML document actually satisfies all of the
constraints on valid HTML) takes experience to do well.

-- 
Neel Krishnaswami
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Pb console Effbot

2006-06-14 Thread M�ta-MCI
Good evening!

I installed the Console of EFFBOT (http://effbot.org/downloads/#console).
It functions well. It's a very fun/friendly tool.

Except a detail: when I send (by console.write()) more than 53200 
characters, it does not occur anything.
I circumvented the problem, with a loop which sends ranges of 5 
characters.

But, I would like to know if somebody already encountered this problem.

@-greetings

Michel Claveau



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


Newbie wxpython staticbitmap help please

2006-06-14 Thread janama
Hi, how do i go about having my little gui (boa) app updating
(changing) the bitmap used in a StaticBitmap automatically. In the
example below when i click the button the app check checks to see if a
file exists and if so it swaps the StaticBitmap in the gui to another
bitmap.
  Can somewhone add a wx.Timer example to this to make it check
if the file exists every minute or so , instead of clicking the button
to check and update this? Or is there a better way of auto updating my
little gui apps StaticBitmap if a file exists?


Thanks for any help with this

Regards


 Frame1
# Frame 1

#Boa:Frame:Frame1

import wx
import os

def create(parent):
return Frame1(parent)


[wxID_FRAME1, wxID_FRAME1BUTTON1, wxID_FRAME1PANEL1,
wxID_FRAME1STATICBITMAP1,
] = [wx.NewId() for _init_ctrls in range(4)]

class Frame1(wx.Frame):
def _init_ctrls(self, prnt):
# generated method, don't edit
wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt,
  pos=wx.Point(535, 346), size=wx.Size(175, 109),
  style=wx.DEFAULT_FRAME_STYLE, title='Frame1')
self.SetClientSize(wx.Size(167, 75))

self.panel1 = wx.Panel(id=wxID_FRAME1PANEL1, name='panel1',
parent=self,
  pos=wx.Point(0, 0), size=wx.Size(167, 75),
  style=wx.TAB_TRAVERSAL)

self.staticBitmap1 =
wx.StaticBitmap(bitmap=wx.Bitmap('Z:/Dan/scripting/python/gui/up1.png',
  wx.BITMAP_TYPE_PNG), id=wxID_FRAME1STATICBITMAP1,
  name='staticBitmap1', parent=self.panel1,
pos=wx.Point(16, 24),
  size=wx.Size(32, 32), style=0)

self.button1 = wx.Button(id=wxID_FRAME1BUTTON1,
label='button1',
  name='button1', parent=self.panel1, pos=wx.Point(64, 24),
  size=wx.Size(88, 32), style=0)
self.button1.Bind(wx.EVT_BUTTON, self.OnButton1Button,
  id=wxID_FRAME1BUTTON1)

def __init__(self, parent):
self._init_ctrls(parent)

def OnButton1Button(self, event):
if os.path.isfile('Z:/Dan/scripting/python/gui/p1.txt'):
i = wx.Image('Z:/Dan/scripting/python/gui/up2.png',
wx.BITMAP_TYPE_PNG)
b1 = wx.BitmapFromImage(i)
self.staticBitmap1.SetBitmap(b1)


event.Skip()


 App1
#!/usr/bin/env python
#Boa:App:BoaApp

import wx

import Frame1

modules ={'Frame1': [1, 'Main frame of Application', 'Frame1.py']}

class BoaApp(wx.App):
def OnInit(self):
wx.InitAllImageHandlers()
self.main = Frame1.create(None)
self.main.Show()
self.SetTopWindow(self.main)
return True

def main():
application = BoaApp(0)
application.MainLoop()

if __name__ == '__main__':
main()

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


Re: Tiddlywiki type project in Python?

2006-06-14 Thread Paul Boddie
Diez B. Roggisch wrote:
>

[Quoting jkn...]

> > Well, that may be an/the answer, since another form of my question
> > would be 'how can I write a TiddlyWikiLike using Python instead of JS'
> > ;-). I appreciate that it might involve, for instance, a local server.
> > Does the idea of embedding python in a browser instead of Javascript
> > make any sense at all?
>
> Nope. Not really.

While I think TiddlyWiki is interesting from the perspective of
creating sites that are editable in the browser without having to
install or configure server-side Wiki software (which many people find
intimidating, even if it's a ten line program that uses
BaseHTTPServer), the drawbacks are numerous: even moderately small
Wikis are slow since browser-based DOMs aren't designed for storing and
manipulating large documents; published Wikis can be edited and saved,
but their changes remain unmerged with the original unless you install
various server-side extensions, compromising the simple "all in one
place" storage model; last time I looked, production of non-Wiki,
navigable sites from TiddlyWiki wasn't supported unless you wrote your
own tools. A lot of the effort getting around these problems is
arguably better invested in coming to terms with installing some
traditional Wiki software.

But where I don't agree with a negative assessment of Python in the
browser is in one area that TiddlyWiki inadvertently illustrates quite
nicely: the ability to conveniently distribute a sandbox to other
people which has its own rather nice, widely-supported input/output
system. People have been more enthusiastic about virtualisation
recently: "safe Python" in the browser (or with other visualisation
front-ends) would be a good lightweight virtualisation solution of
sorts, I think.

Paul

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


Re: memory leak problem with arrays

2006-06-14 Thread Robert Kern
sonjaa wrote:
> Hi
> 
> I'm new to programming in python and I hope that this is the problem.
> 
> I've created a cellular automata program in python with the numpy array
> extensions. After each cycle/iteration the memory used to examine and
> change the array as determined by the transition rules is never freed.
> I've tried using "del" on every variable possible, but that hasn't
> worked. I've read all the forums for helpful hints on what to do, but
> nothing has worked so far. I've even tried the "python memory
> verification" (beta) program, which did point to numpy.dtype and
> numpy.ndarray as increasing objects, before the whole computer crashed.

Please post to numpy-discussion:

  http://www.scipy.org/Mailing_Lists

We will need to know the version of numpy which you are using. There used to be
a bug that sounds like this, but it was fixed some time ago. Also, please try to
narrow your program down to the smallest piece of code that runs and still
displays the memory leak.

Thank you.

-- 
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


Re: memory leak problem with arrays

2006-06-14 Thread John Machin
On 15/06/2006 8:27 AM, sonjaa wrote:
> Serge Orlov wrote:
>> sonjaa wrote:
>>> Hi
>>>
>>> I'm new to programming in python and I hope that this is the problem.
>>>
>>> I've created a cellular automata program in python with the numpy array
>>> extensions. After each cycle/iteration the memory used to examine and
>>> change the array as determined by the transition rules is never freed.
>>> I've tried using "del" on every variable possible, but that hasn't
>>> worked.
>> Python keeps track of number of references to every object if the
>> object has more that one reference by the time you use "del" the object
>> is not freed, only number of references is decremented.
>>
>> Print the number of references for all the objects you think should be
>> freed after each cycle/iteration, if is not equal 2 that means you are
>> holding extra references to those objects. You can get the number of
>> references to any object by calling sys.getrefcount(obj)
> 
> thanks for the info. I used this several variables/objects and
> discovered that little counters i.e. k = k +1 have many references to
> them, up tp 1+.
> Is there a way to free them?

If (for example) k refers to the integer object 10, all that means is 
that you have 1+ objects whose value is 10. The references to them 
will be scattered throughout your data structures somewhere.

Caveat: I'm not a numpy user. Now read on:

I would have thought [by extrapolation from the built-in "array" module] 
that numpy would allow you to "declare" a homogeneous array of integers 
which would be internal integers, not python object integers, in which 
case you would not be getting 1+ references to whatever "k" refers to.

Suggested approaches: read numpy manual, publish relevant parts of your 
code, wait for a numpy guru to appear.

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


__cmp__ method

2006-06-14 Thread JH
Hi

Can anyone explain to me why the following codes do not work? I want to
try out using __cmp__ method to change the sorting order. I subclass
the str and override the __cmp__ method so the strings can be sorted by
the lengh. I expect the shortest string should be in the front. Thanks

>>> class myStr(str):
def __init__(self, s):
str.__init__(self, s) # Ensure super class is initialized
def __cmp__(self, other):
return cmp(len(self), len(other))

>>> a = myStr('abc')
>>> b = myStr('Personal')
>>> c = myStr('Personal firewall')
>>> sorted([c, b, a])
['Personal', 'Personal firewall', 'abc']
>>>

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


Re: Earthquake and Tornado Forecasting Programs June 13, 2006

2006-06-14 Thread Richard E Maine
edgrsprj <[EMAIL PROTECTED]> wrote:

> > Oh for a newsreader that can eliminate all such ugly excessively
> > cross-posted articles lacking follow-ups.  PLONK thread is the only
> > remaining answer.
> >
> 
> Posted by E.D.G.   June 14, 2006
> 
> In my opinion, even moderated Internet Newsgroups cannot provide the
> necessary control for adequately protected scientific communications.  I
> have in mind the development of a sophisticated Web site based Internet
> Bulletin Board which past experiences indicate to me should work.  The Web
> site running that bulletin board should be of interest to computer
> programmers around the globe regardless of what programming language they
> are using.

Wow. That is an impressive display of ummm understanding.  :-)

Yes, I guess plonk thread will have to do.

(My news server wouldn't even accept this as a followup until I trimmed
a few of the groups.)

-- 
Richard Maine | Good judgment comes from experience;
email: my first.last at org.domain| experience comes from bad judgment.
org: nasa, domain: gov|   -- Mark Twain
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: memory leak problem with arrays

2006-06-14 Thread sonjaa

Serge Orlov wrote:
> sonjaa wrote:
> > Hi
> >
> > I'm new to programming in python and I hope that this is the problem.
> >
> > I've created a cellular automata program in python with the numpy array
> > extensions. After each cycle/iteration the memory used to examine and
> > change the array as determined by the transition rules is never freed.
> > I've tried using "del" on every variable possible, but that hasn't
> > worked.
>
> Python keeps track of number of references to every object if the
> object has more that one reference by the time you use "del" the object
> is not freed, only number of references is decremented.
>
> Print the number of references for all the objects you think should be
> freed after each cycle/iteration, if is not equal 2 that means you are
> holding extra references to those objects. You can get the number of
> references to any object by calling sys.getrefcount(obj)

thanks for the info. I used this several variables/objects and
discovered that little counters i.e. k = k +1 have many references to
them, up tp 1+.
Is there a way to free them?

regards
Sonja

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


Re: Earthquake and Tornado Forecasting Programs June 13, 2006

2006-06-14 Thread edgrsprj
>
> Oh for a newsreader that can eliminate all such ugly excessively
> cross-posted articles lacking follow-ups.  PLONK thread is the only
> remaining answer.
>

Posted by E.D.G.   June 14, 2006

In my opinion, even moderated Internet Newsgroups cannot provide the
necessary control for adequately protected scientific communications.  I
have in mind the development of a sophisticated Web site based Internet
Bulletin Board which past experiences indicate to me should work.  The Web
site running that bulletin board should be of interest to computer
programmers around the globe regardless of what programming language they
are using.


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


Re: memory leak problem with arrays

2006-06-14 Thread Serge Orlov
sonjaa wrote:
> Hi
>
> I'm new to programming in python and I hope that this is the problem.
>
> I've created a cellular automata program in python with the numpy array
> extensions. After each cycle/iteration the memory used to examine and
> change the array as determined by the transition rules is never freed.
> I've tried using "del" on every variable possible, but that hasn't
> worked.

Python keeps track of number of references to every object if the
object has more that one reference by the time you use "del" the object
is not freed, only number of references is decremented.

Print the number of references for all the objects you think should be
freed after each cycle/iteration, if is not equal 2 that means you are
holding extra references to those objects. You can get the number of
references to any object by calling sys.getrefcount(obj)

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


Re: better Python IDE? Mimics Maya's script editor?

2006-06-14 Thread Scott David Daniels
warpcat wrote:
> I've been scripting in Maya, via mel for years now.  Recently learning
> to Python, love it.  Thing that's driving me nuts it the IDE.  I'm
> using PythonWin right now and trying to find something better, mainly
> with this functionality:

I'm not certain, but you could take a look at Komodo from ActiveState.
I do have an interactive window, edit window(s), and an output window.
You can get a free trial from them, as I remember.

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about the Exception class

2006-06-14 Thread Scott David Daniels
Carl J. Van Arsdall wrote:
> So this is probably a fairly basic question, but help me out because I'm 
> just not lining things up and I'm somewhat new to the world of exception 
> handling.
> 
> What's the benefit to inheriting an exception from and of the available 
> parent exception classes?  Does one subclass have benefits over any 
> other?  Most of what I see involves making a new class and inheriting 
> from Exception so that one can have an exception class with a name of 
> their choosing.  If you didn't care about the name would there be any 
> benefit to making a subclass versus raising StandardError or something 
> else equally vanilla?  Are there any difference to library provided 
> exceptions other than their names?
> 
> -carl
> 
If you create a new exception class that is a subclass of, say,
"ValueError,"  Your exception may have some specific data that
assists you in discovering the source of the problem.  Meanwhile,
any code that says:
 try:
 something()
 except ValueError, error:
 ...
will catch your new exception in the ValueError clause.  Subclasses
of exceptions can be seen as more specific version of the parent.

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


psycopg2, gtk and float

2006-06-14 Thread Sandro Dentella
Hi all,

while building an applycation in pygtk I noticed that psycopg2 returns the
floats rouded (eg: 4.123 -> 4.0).

This turns out to be a problem of psycopg2 (psycopg behaves correctly) when
you 'import gtk' !!! It behaves correctly with numeric/decimal, though.

I'm totally clueless. Any hints?

TIA
sandro
*:-)




import gtk
import psycopg2 as ps2

DB = "host=localhost dbname=test user=test port=5432 password=xxx"
conn = ps2.connect(DB)
cursor = conn.cursor()
cursor.executeq("SELECT DISTINCT a_float FROM numbers ")
conn.commit()

rows = cursor.fetchall()
for row in rows:
print row[0]


-- 
Sandro Dentella  *:-)
e-mail: [EMAIL PROTECTED] 
http://www.tksql.orgTkSQL Home page - My GPL work
-- 
http://mail.python.org/mailman/listinfo/python-list


WS-Security support for Python SOAP libraries

2006-06-14 Thread Satchidanand Haridas
Hi,

Do any of the existing SOAP libraries for Python have support for 
WS-Security?

thanks,
Satchit

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


nested functions

2006-06-14 Thread Gregory Petrosyan
I often make helper functions nested, like this:

def f():
def helper():
...
...

is it a good practice or not? What about performance of such
constructs?

--
Regards, Gregory.

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


Re: Simple Char-I/O Dialogs for Win32 and DOS

2006-06-14 Thread Petr Jakes
Mr Roboto wrote:
> Folks:
>
> I've already searched the group and have determined there *are*
> char I/O based input systems, ala NCURSES, that are
> Python-compatible (ie. PyNCurses, UrWid, etc.)  What I *need* is
> something that does simple dialogs under char-I/O Win32 and DOS
> w/ very little fuss or muss.  At most, I need one or two dialog
> boxes to boot my little app/util *AND* hope upon hope I don't
> need port something (which would take more days than I have
> *and* would also require a non-trivial support effort from a
> one-man show: *me*) and can simply grab something (open-source)
> off-the-shelf.  I don't need a dialog/forms designer, no
> database access, just a basic dialog box to get input from a
> couple of text boxes, check boxes, etc.
>
> Does such an animal exist and can someone offer a link to the
> kit ?  TIAMR

You can try:

Dialog
http://invisible-island.net/dialog/


HTH
Petr Jakes

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


Re: wxPython, tree Control text cutoff

2006-06-14 Thread Kiran
Ah, dang.  Nice find!

thanks a lot for your help.  Also, your note is completely called for.
I realize that my code was very complicated, and I just pasted what I
had instead of simplifying it down.  Next time, I will do so.

thanks again!
Kiran

jean-michel bain-cornu wrote:
> Kiran a écrit :
> >  Hello all,
> > I am using a tree to display stuff, and it is constantly updated, but
> > what I have noticed is in the lowest level, there is clearly noticable
> > cutoff of the text I place there. The cutoff is existent even if I do
> > not update the text inside the tree constantly. It seems that the text
> > is halfway below where it should line up. I tried placing an image to
> > see if that would correct it, but it does not. The image is perfectly
> > lined up, but the text is still misaligned.
> >
> > Any known issues of this and how to fix it? By the way, it happens in
> > both Linux and Windows.
> Hi Kiran,
> It works fine if you change :
>   x = self.tree.AppendItem(self.connections[i][j][0], "")
> to
>   x = self.tree.AppendItem(self.connections[i][j][0], " ")
> I let you imagine the explanation...
> Regards,
> jm
>
> Just a hint : it'd be helpfull to solve such a bug if you make your
> program more simple. To find out the solution, I reduced your program to
> what's following, and the light came :
>
> import wx
> import wx.gizmos as gizmos
>
> class AlarmsWindow(wx.MDIChildFrame):
>  def __init__(self, parent, title, size, pos):
>  wx.MDIChildFrame.__init__(self, parent, -1, title, size = size,
> pos =pos)
>  self.tree = gizmos.TreeListCtrl(self, -1, style =
> wx.TR_DEFAULT_STYLE| wx.TR_FULL_ROW_HIGHLIGHT)
>  # create some columns
>  self.tree.AddColumn("Connection")
>  self.tree.AddColumn("Alarm")
>  self.tree.AddColumn("Value")
>  self.tree.SetMainColumn(0)
>
>  self.root = self.tree.AddRoot("Connections")
>  self.tree.Expand(self.root)
>  self.tree.GetMainWindow().Bind(wx.EVT_RIGHT_UP, self.OnRightUp)
>  self.Show()
>
>  child = self.tree.AppendItem(self.root, 'name')
>  self.tree.SetItemText(child, 'name')
>  child2= self.tree.AppendItem(child,'name2')
> ##x = self.tree.AppendItem(child2, "")
>  x = self.tree.AppendItem(child2, "XXX")
>  self.tree.SetItemText(x, 'alarm', 1)
>  self.tree.SetItemText(x, 'value', 2)
>
>  def OnRightUp(self, evt):
>  pass
>
> class MDIFrame(wx.MDIParentFrame):
>  def __init__(self):
>  wx.MDIParentFrame.__init__(self, None, -1, "MDI Parent", size
> =(600, 400))
>  child = AlarmsWindow(self, "Alarm", (400, 300), (0, 0))
>
>
> if __name__=='__main__':
>  app = wx.PySimpleApp()
>  frame = MDIFrame()
>  frame.Show()
>  app.MainLoop()

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


__lt__ slowing the "in" operator even if not called

2006-06-14 Thread Emanuele Aina
I have some code which does a lot of "in" on lists containing objects
with no __eq__ defined.

It all goes fast until I add the __lt__() method: then I have a
slowdown comparable to the one I get using the overridden __eq__, while
the __lt__ method is never called.

Someone can explain me why?


I have here a simple program which shows the behaviour:

*---*

#!/usr/bin/env python

import timing

class State(object):
def __init__(self, value):
self.v = value

def generate(self):
return [self.__class__(self.v+1)]

class StateLT(State):
def __lt__ (self, other):
print 'Foo'
return self.v < other.v

class StateEQ(State):
def __eq__ (self, other):
return self.v == other.v


def test(state_cls):
print state_cls

timing.start()
initial = state_cls(0)
l = [initial]
for i in xrange(3000):

successors = l[i].generate()
successors = [s for s in successors if s not in l]

l += successors
timing.finish()
print timing.milli()

if __name__ == '__main__':
test(State)
print ' '
test(StateLT)
print ' '
test(StateEQ)

*---*

On my machine the output is:


406


4982


5395

Here you can see that even with only the __lt__ method it goes 10x
slower, but __lt__ is never called as "Foo" is not printed.

I use the python 2.3.5-8 package on a debian unstable, but even the
python 2.4.3-5 package shows the same behaviour.

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


Interactive Find and Replace String Patterns on Multiple Files

2006-06-14 Thread Xah Lee
Interactive Find and Replace String Patterns on Multiple Files

Xah Lee, 2006-06

Suppose you need to do find and replace of a string pattern, for all
files in a directory. However, you do not want to replace all of them.
You need to look at it in a case-by-case basis. What can you do?

Answer: emacs.

Here's how you do it.
Select Target Files

Start emacs by typing “emacs” in the command line interface prompt.

Now you need to locate the directory and files you want to
find/replace. Type “esc x find-dired”. (then press Enter) Then,
give a directory name, e.g. “/Users/mary/myfiles”

Emacs will ask you with the prompt “Run find (with args): ”. If you
need to do the replacement on all html files, then give “-name
"*html"”. If you don't care about what kind of file but simply all
files under that dir, then give “-type f”.

Now, you will be shown the list of files, and now you need to
“mark” the files you want the regex find-replace to work on. You
mark a file by moving the cursor to the file you want, then press m.
Unmark it by pressing u. To mark all files by a regex, type “% m”,
then give your pattern. Suppose you want to mark all html files, then
type “% m html$”.
Interactive Find & Replace

Now, you are ready to do the interactive find replace. For simplicity,
let's say you just want to replace the word “quick” by “super”
depending on the context. Now, type “esc x
dired-do-query-replace-regexp”. It will prompt you for the regex
string and the replacement string. Type “quick” then “super”.

Now, emacs will use your pattern and check the files, and stop and show
you whenever a match occurred. When this happens, emacs will prompt
you, and you have a choice of making the change or skip the change. To
make the change, type y. To skip, type n. If you simply want emacs to
go ahead and make all such changes to the current files, type “!”.
If you want to cancel the whole operation, type control-g.
Saving the Changed Files

Now, after you went through the above ordeal. There is one more step
you need to do, and that is saving the changed files. This you can do,
by typing “esc x list-buffer”, then move the cursor to the file you
want to save and press s. It will mark the file for later save action.
Type u to unmark. Once you are done, type x to execute the saving of
all S marked files. (in emacs, opened file is called “buffer”.
Disregard ohter things there.)

Alternatively, you can also type “esc x save-some-buffers”. Then
emacs will show each buffer for you and ask if you want it saved.

If you have emacs version 22, you can use “M-x ibuffer” to mark all
files you want to save by a regex.



PS if anyone know any tool or perl/python/lisp program that can also do
this, i'd be interested to know. Thanks.


This post is archived at:
http://xahlee.org/emacs/find_replace_inter.html

   Xah
   [EMAIL PROTECTED]
 ∑ http://xahlee.org/

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

Re: How to select a folder with native windows dialog box?

2006-06-14 Thread flaus . a
Thanks for your answer, it's working fine!

For information, the function to use to get the pathName is
shell.SHGetPathFromIDList
It returns an error if you select a special folder (!?!?) but otherwise
it's working fine... And I was unable to fix this issue.

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


Re: Earthquake and Tornado Forecasting Programs June 13, 2006

2006-06-14 Thread Aidan Karley
In article <[EMAIL PROTECTED]>, CBFalconer wrote:
> Oh for a newsreader that can eliminate all such ugly excessively
> cross-posted articles lacking follow-ups.  PLONK thread is the only
> remaining answer.
>
   See my reply posted to alt.disasters.misc and 
sci.geo.earthquakes for an alternative strategy. But yes, cross-posting 
like that is highly irritating, which makes the actual purpose of the 
original posting highly suspect.
   I don't know which of the comp.lang groups you're coming from, 
but since any of them could probably be used to write cross-post 
filtering code ... I'll leave the lot in.
-- 
 Aidan Karley, FGS
 Aberdeen, Scotland
 Written at Wed, 14 Jun 2006 08:14 +0100, but posted later.

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


Re: wxPython, tree Control text cutoff

2006-06-14 Thread jean-michel bain-cornu
Kiran a écrit :
>  Hello all,
> I am using a tree to display stuff, and it is constantly updated, but
> what I have noticed is in the lowest level, there is clearly noticable
> cutoff of the text I place there. The cutoff is existent even if I do
> not update the text inside the tree constantly. It seems that the text
> is halfway below where it should line up. I tried placing an image to
> see if that would correct it, but it does not. The image is perfectly
> lined up, but the text is still misaligned.
> 
> Any known issues of this and how to fix it? By the way, it happens in
> both Linux and Windows.
Hi Kiran,
It works fine if you change :
x = self.tree.AppendItem(self.connections[i][j][0], "")
to
x = self.tree.AppendItem(self.connections[i][j][0], " ")
I let you imagine the explanation...
Regards,
jm

Just a hint : it'd be helpfull to solve such a bug if you make your 
program more simple. To find out the solution, I reduced your program to 
what's following, and the light came :

import wx
import wx.gizmos as gizmos

class AlarmsWindow(wx.MDIChildFrame):
 def __init__(self, parent, title, size, pos):
 wx.MDIChildFrame.__init__(self, parent, -1, title, size = size, 
pos =pos)
 self.tree = gizmos.TreeListCtrl(self, -1, style = 
wx.TR_DEFAULT_STYLE| wx.TR_FULL_ROW_HIGHLIGHT)
 # create some columns
 self.tree.AddColumn("Connection")
 self.tree.AddColumn("Alarm")
 self.tree.AddColumn("Value")
 self.tree.SetMainColumn(0)

 self.root = self.tree.AddRoot("Connections")
 self.tree.Expand(self.root)
 self.tree.GetMainWindow().Bind(wx.EVT_RIGHT_UP, self.OnRightUp)
 self.Show()

 child = self.tree.AppendItem(self.root, 'name')
 self.tree.SetItemText(child, 'name')
 child2= self.tree.AppendItem(child,'name2')
##x = self.tree.AppendItem(child2, "")
 x = self.tree.AppendItem(child2, "XXX")
 self.tree.SetItemText(x, 'alarm', 1)
 self.tree.SetItemText(x, 'value', 2)

 def OnRightUp(self, evt):
 pass

class MDIFrame(wx.MDIParentFrame):
 def __init__(self):
 wx.MDIParentFrame.__init__(self, None, -1, "MDI Parent", size 
=(600, 400))
 child = AlarmsWindow(self, "Alarm", (400, 300), (0, 0))


if __name__=='__main__':
 app = wx.PySimpleApp()
 frame = MDIFrame()
 frame.Show()
 app.MainLoop()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is Expressiveness in a Computer Language

2006-06-14 Thread Pascal Bourguignon
Joachim Durchholz <[EMAIL PROTECTED]> writes:
> Raffael Cavallaro schrieb:
>> a program which would be perfectly permissible in a dynamically
>> typed language such as common lisp - for example - heterogeneous
>> lists and forward references to as yet non-existent functions.
>
> Um... heterogenous lists are not necessarily a sign of
> expressiveness. The vast majority of cases can be transformed to
> homogenous lists (though these might then contain closures or OO
> objects).

In lisp, all lists are homogenous: lists of T.


-- 
__Pascal Bourguignon__ http://www.informatimago.com/

ADVISORY: There is an extremely small but nonzero chance that,
through a process known as "tunneling," this product may
spontaneously disappear from its present location and reappear at
any random place in the universe, including your neighbor's
domicile. The manufacturer will not be responsible for any damages
or inconveniences that may result.
-- 
http://mail.python.org/mailman/listinfo/python-list


memory leak problem with arrays

2006-06-14 Thread sonjaa
Hi

I'm new to programming in python and I hope that this is the problem.

I've created a cellular automata program in python with the numpy array
extensions. After each cycle/iteration the memory used to examine and
change the array as determined by the transition rules is never freed.
I've tried using "del" on every variable possible, but that hasn't
worked. I've read all the forums for helpful hints on what to do, but
nothing has worked so far. I've even tried the "python memory
verification" (beta) program, which did point to numpy.dtype and
numpy.ndarray as increasing objects, before the whole computer crashed.


I can supply the code if needed. I'm desperate because this is part of
my thesis, and if I can't get this fixed, I'll try another programming
language.

thanks in advance
Sonja

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


Re: prog1 | prog2 . How not to make prog2 block if not piped?

2006-06-14 Thread Steve Holden
imcs ee wrote:
> yeah, forget my post ,it;s useless.
> sorry for my thoughtless
> On 14 Jun 2006 10:40:15 -0700, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> 
>>imcs ee ha scritto:
>>
>>
>>>do u really need read something even when you run the scripts2.py directly?
>>>why not just change script2.py to
>>> #script2.py
>>>if __name__ == "__main__":
>>>x=sys.stdin.read()
>>>print 'passed'
>>>else:
>>>print 'passed from else branch'
>>>
>>>is it what  you want? or anything i misunderstand.
>>
>>it won't do. clever btw.
>>Script2 is not a module, it's a program that _could_ receive input via
>>pipe.
>>
It really doesn't matter *how* it receives input, whether from a pipe, 
or a terminal or a redirected file.

When you run it "standalone" you should give it some input - type some 
text then enter ^D (on Unix-like systems) or ^Z (on Windows). How else 
do you expect read() to return anything? It *has* to read to the end fo 
the file before it returns a value.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Love me, love my blog  http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Question about the Exception class

2006-06-14 Thread Carl J. Van Arsdall
So this is probably a fairly basic question, but help me out because I'm 
just not lining things up and I'm somewhat new to the world of exception 
handling.

What's the benefit to inheriting an exception from and of the available 
parent exception classes?  Does one subclass have benefits over any 
other?  Most of what I see involves making a new class and inheriting 
from Exception so that one can have an exception class with a name of 
their choosing.  If you didn't care about the name would there be any 
benefit to making a subclass versus raising StandardError or something 
else equally vanilla?  Are there any difference to library provided 
exceptions other than their names?

-carl

-- 

Carl J. Van Arsdall
[EMAIL PROTECTED]
Build and Release
MontaVista Software

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


Re: What is Expressiveness in a Computer Language

2006-06-14 Thread Pascal Costanza
Torben Ægidius Mogensen wrote:

> On a similar note, is a statically typed langauge more or less
> expressive than a dynamically typed language?  Some would say less, as
> you can write programs in a dynamically typed language that you can't
> compile in a statically typed language (without a lot of encoding),
> whereas the converse isn't true.

It's important to get the levels right here: A programming language with 
a rich static type system is more expressive at the type level, but less 
expressive at the base level (for some useful notion of expressiveness ;).

> However, I think this is misleading,
> as it ignores the feedback issue: It takes longer for the average
> programmer to get the program working in the dynamically typed
> language.

This doesn't seem to capture what I hear from Haskell programmers who 
say that it typically takes quite a while to convince the Haskell 
compiler to accept their programs. (They perceive this to be worthwhile 
because of some benefits wrt correctness they claim to get in return.)


Pascal

-- 
3rd European Lisp Workshop
July 3 - Nantes, France - co-located with ECOOP 2006
http://lisp-ecoop06.bknr.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: better Python IDE? Mimics Maya's script editor?

2006-06-14 Thread Steve Holden
warpcat wrote:
> I'm not sure where you got "pythonwin sucks" from my text (none of
> those words are there).  Saying one aspect of a piece of software is
> clunky to "me" (if that's what you're refering too?) or saying the
> whole software "sucks" are pretty different IMO.  All I stated is that
> it's very different from how I'm used to working.  I didn't mean any
> disrespect, but I do appreciate your info!
> 
No offence taken - I was clearly reading too much into your words.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Love me, love my blog  http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: "groupby" is brilliant!

2006-06-14 Thread James Stroud
Alex Martelli wrote:
> James Stroud <[EMAIL PROTECTED]> wrote:
>...
> 
>>def doit(rows, doers, i=0):
>>   for r, alist in groupby(rows, itemgetter(i)):
>> if len(doers) > 1:
>>   doit(alist, doers[1:], i+1)
>> doers[0](r)
> 
> 
> Isn't this making N useless slices (thus copies, for most kinds of
> sequences) for a doers of length N?  Since you're passing i anyway, it
> seems to me that:
> 
> def doit(rows, doers, i=0):
> for r, alist in groupby(rows, itemgetter(i)):
>   if len(doers) > i+1:
>  doit(alist, doers, i+1)
>   doers[i](r)
> 
> is equivalent to your code, but avoids these slices (thus copies).
> 
> 
> Alex

Actually, I remember why I wrote it that way--because the itemgetter 
argument may not start at zero (admitting that I haven't yet played with 
itemgetter at all). Maybe pop(0) is better than a copy?


def doit(rows, doers, i=0):
   for r, alist in groupby(rows, itemgetter(i)):
 doer = doers.pop(0)
 if doers:  # empty list tests as False
doit(alist, doers, i+1)
 doer(r)


James

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

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


Re: determining file type

2006-06-14 Thread utabintarbo

http://www.demonseed.net/~jp/code/magic.py

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


Re: better Python IDE? Mimics Maya's script editor?

2006-06-14 Thread warpcat
I'm not sure where you got "pythonwin sucks" from my text (none of
those words are there).  Saying one aspect of a piece of software is
clunky to "me" (if that's what you're refering too?) or saying the
whole software "sucks" are pretty different IMO.  All I stated is that
it's very different from how I'm used to working.  I didn't mean any
disrespect, but I do appreciate your info!

Steve Holden wrote:

> You might also wish to reconsider your approach to the Python community.
> "PythonWin sucks" isn't my idea of how to win friends and influence
> people in a first posting to a usenet newsgroup. By and large we are a
> friendly bunch here, but you don't want to start off on the wrong foot :-)
>
> regards
>   Steve
> --
> Steve Holden   +44 150 684 7255  +1 800 494 3119
> Holden Web LLC/Ltd  http://www.holdenweb.com
> Love me, love my blog  http://holdenweb.blogspot.com
> Recent Ramblings http://del.icio.us/steve.holden

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


Re: "groupby" is brilliant!

2006-06-14 Thread James Stroud
Alex Martelli wrote:
> James Stroud <[EMAIL PROTECTED]> wrote:
>...
> 
>>def doit(rows, doers, i=0):
>>   for r, alist in groupby(rows, itemgetter(i)):
>> if len(doers) > 1:
>>   doit(alist, doers[1:], i+1)
>> doers[0](r)
> 
> 
> Isn't this making N useless slices (thus copies, for most kinds of
> sequences) for a doers of length N?  Since you're passing i anyway, it
> seems to me that:
> 
> def doit(rows, doers, i=0):
> for r, alist in groupby(rows, itemgetter(i)):
>   if len(doers) > i+1:
>  doit(alist, doers, i+1)
>   doers[i](r)
> 
> is equivalent to your code, but avoids these slices (thus copies).
> 
> 
> Alex

Yes, it does seem the copies are useless. Thank you.

James

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

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


python-list@python.org Removed

2006-06-14 Thread Gary M. Gordon
We are sorry to see you leaving Gary M. Gordon, LLC!

You will not receive news and information about Gary M. Gordon, LLC anymore.

--
If you ever want to join Gary M. Gordon, LLC again, simply visit:
http://www.garymgordon.com/easylist/easylist.cgi?action=subscribe&[EMAIL 
PROTECTED]
and you will be automatically subscribed again.

Thanks,

Gary M. Gordon, LLC Staff

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


Re: What is Expressiveness in a Computer Language

2006-06-14 Thread Joachim Durchholz
Rob Thorpe schrieb:
> 
> If a language can express constraints of one kind that is an increase
> in expressiveness.

Agreed.

> If a language requires constraint to be in one particular way thats a
> decrease in expressiveness.

Unless alternatives would be redundant.
Having redundant ways to express the same thing doesn't make a language 
more or less expressive (but programs written in it become more 
difficult to maintain).

> So I would say languages that can be statically typed and can be
> dynamically typed are the most expressive.  Languages that require
> static typing or are dynamic but cannot express static typing are less
> expressive.

Note that this is a different definition of expressiveness.
(The term is very diffuse...)

I think Felleisen's paper defines something that should be termed 
"conciseness".
Whether there's a way to express constraints or other static properties 
of the software is something different. I don't have a good word for it, 
but "expressiveness" covers too much for my taste to really fit.

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


wxPython, tree Control text cutoff

2006-06-14 Thread Kiran
 Hello all,
I am using a tree to display stuff, and it is constantly updated, but
what I have noticed is in the lowest level, there is clearly noticable
cutoff of the text I place there. The cutoff is existent even if I do
not update the text inside the tree constantly. It seems that the text
is halfway below where it should line up. I tried placing an image to
see if that would correct it, but it does not. The image is perfectly
lined up, but the text is still misaligned.

Any known issues of this and how to fix it? By the way, it happens in
both Linux and Windows.

thanks a lot for your help!



here is the code that I am using, I realize that it is a bit
convoluted, but the parts where I am setting the text should be
evident.

import wx
import wx.gizmos as gizmos

class AlarmsWindow(wx.MDIChildFrame):
def __init__(self, parent, title, size, pos):
wx.MDIChildFrame.__init__(self, parent, -1, title, size = size, 
pos =
pos)

self.tree = gizmos.TreeListCtrl(self, -1, style = 
wx.TR_DEFAULT_STYLE
| wx.TR_FULL_ROW_HIGHLIGHT)

# images of the tree
isz = (16,16)
il = wx.ImageList(isz[0], isz[1])
self.fldridx = 
il.Add(wx.ArtProvider_GetBitmap(wx.ART_FOLDER,
 wx.ART_OTHER, isz))
self.fldropenidx = 
il.Add(wx.ArtProvider_GetBitmap(wx.ART_FILE_OPEN,
 wx.ART_OTHER, isz))
self.fileidx =
il.Add(wx.ArtProvider_GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, isz))
self.selidx  = 
il.Add(wx.ArtProvider_GetBitmap(wx.ART_CROSS_MARK,
  wx.ART_OTHER, isz))

self.tree.SetImageList(il)
self.il = il

# create some columns
self.tree.AddColumn("Connection")
self.tree.AddColumn("Alarm")
self.tree.AddColumn("Value")
self.tree.SetMainColumn(0)

self.root = self.tree.AddRoot("Connections")
self.tree.SetItemImage(self.root, self.fldridx, which =
wx.TreeItemIcon_Normal)
self.tree.SetItemImage(self.root, self.fldropenidx, which =
wx.TreeItemIcon_Expanded)

self.connectionsName = []
self.connections = []
self.registers   = []

self.tree.Expand(self.root)

self.tree.GetMainWindow().Bind(wx.EVT_RIGHT_UP, self.OnRightUp)
self.Show()


# testing

self.AddConnection("Dummy")
self.AddRegister("Dummy", "R5")
self.AddAlarm("Dummy", "R5", "LOA", "10")
self.UpdateAlarm("Dummy", "R5", "LOA", "14")
self.AddAlarm("Dummy", "R5", "LOS", "1354")
self.AddRegister("Dummy", "R6")
self.AddAlarm("Dummy", "R6", "LOA", "15")
self.AddConnection("DUMMY @#2")
self.AddRegister("DUMMY @#2", "R0")
self.AddAlarm("DUMMY @#2", "R0", "LSKJDF", "S:LKJDF")


# tree control
def OnRightUp(self, evt):
pos = evt.GetPosition()
item, flags, col = self.tree.HitTest(pos)
if item:
print('Flags: %s, Col:%s, Text: %s' %
   (flags, col, self.tree.GetItemText(item,
col)))

# tree control
def OnSize(self, evt):
self.tree.SetSize(self.GetSize())

# adds a section to the logger
def AddConnection(self, name):
self.connectionsName.append(name)
self.connections.append([])
child = self.tree.AppendItem(self.root, name)
self.connections[(len(self.connectionsName)-1)].append(child)
self.tree.SetItemText(child, name)
self.tree.SetItemImage(child, self.fldridx, which =
wx.TreeItemIcon_Normal)
self.tree.SetItemImage(child, self.fldropenidx, which =
wx.TreeItemIcon_Expanded)

# adds a register
def AddRegister(self, connection, name):
# find the connection
index = -1
for i in range(len(self.connectionsName)):
if self.connectionsName[i] == connection:
index = i
break
if index != -1:

self.connections[index].append([self.tree.AppendItem(self.connections[index][0],
name)])

# adds a message to a specific section
def AddAlarm(self, connection, register, alarm, value):
# find the connection
for i in range(len(self.connectionsName)):
if self.connectionsName[i] == connection:
# find the register
for j in range(1, len(self.connections[i])):
if 
self.tree.GetItemText((self.connections[i][j])[0]) == register:

 

Re: What is Expressiveness in a Computer Language

2006-06-14 Thread Joachim Durchholz
Raffael Cavallaro schrieb:
> On 2006-06-14 09:42:25 -0400, [EMAIL PROTECTED] (Torben Ægidius 
> Mogensen) said:
> 
>> It takes longer for the average
>> programmer to get the program working in the dynamically typed
>> language.
> 
> Though I agree with much of your post I would say that many here find 
> the opposite to be true - it takes us longer to get a program working in 
> a statically typed language because we have to keep adding/changing 
> things to get the compiler to stop complaining and actually compile and 
> run

I think Torben was assuming a language with type inference. You write 
only those type annotations that really carry meaning (and some people 
let the compiler infer even these).

 > a program which would be perfectly permissible in a dynamically
> typed language such as common lisp - for example - heterogeneous lists 
> and forward references to as yet non-existent functions.

Um... heterogenous lists are not necessarily a sign of expressiveness. 
The vast majority of cases can be transformed to homogenous lists 
(though these might then contain closures or OO objects).

As to references to nonexistent functions - heck, I never missed these, 
not even in languages without type inference :-)

I don't hold that they are a sign of *in*expressiveness either. They are 
just typical of highly dynamic programming environments such as Lisp or 
Smalltalk.

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


Re: What is Expressiveness in a Computer Language

2006-06-14 Thread Joachim Durchholz
Torben Ægidius Mogensen schrieb:
> For example,
> if you have to code everything as natural numbers, untyped pure lambda
> calculus or S-expressions, there is a good chance that you can get
> nonsense past the compiler.

Also past peer review and/or debugging runs. And, most importantly, past 
your own mental review processes.

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


Simple Char-I/O Dialogs for Win32 and DOS

2006-06-14 Thread Mr Roboto
Folks:

I've already searched the group and have determined there *are*
char I/O based input systems, ala NCURSES, that are
Python-compatible (ie. PyNCurses, UrWid, etc.)  What I *need* is
something that does simple dialogs under char-I/O Win32 and DOS
w/ very little fuss or muss.  At most, I need one or two dialog
boxes to boot my little app/util *AND* hope upon hope I don't
need port something (which would take more days than I have
*and* would also require a non-trivial support effort from a
one-man show: *me*) and can simply grab something (open-source)
off-the-shelf.  I don't need a dialog/forms designer, no
database access, just a basic dialog box to get input from a
couple of text boxes, check boxes, etc.

Does such an animal exist and can someone offer a link to the
kit ?  TIAMR

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


Re: Numerics, NaNs, IEEE 754 and C99

2006-06-14 Thread Simon Brunning
On 14 Jun 2006 10:33:21 -0700, Sébastien Boisgérault
<[EMAIL PROTECTED]> wrote:
> Jeez, 12 posts in this IEEE 754 thread, and still
> no message from uncle timmy ? ;)

Somebody reboot the timbot, please. Seems to have hung.

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


Re: Correctly reading stdout/stderr from subprocess

2006-06-14 Thread Christoph Haas
On Wed, Jun 14, 2006 at 03:56:16PM +0200, Maric Michaud wrote:
> I did it just to validate my point and because i don't use threads very often 
> in python, some exercises can't hurt :)
 
Since you are familiar with threads I believe that my excercises are a
tad bit more low-level compared to yours. :)

> def run(command):
> 
>import subprocess
> 
>run = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, 
> stderr=subprocess.PIPE)
> 
># Wait for the process to return
>import thread, threading
>out, err = [], []
>out_ended, err_ended = threading.Event(), threading.Event()
> 
>def getOutput(output, lines, ended_event) :
>for i in output.readlines() : lines.append(i.rstrip('\n'))
>ended_event.set()
> 
>out_thread = thread.start_new_thread(getOutput, (run.stdout, out, 
> out_ended))
>err_thread = thread.start_new_thread(getOutput, (run.stderr, err, 
> err_ended))
> 
>out_ended.wait()
>err_ended.wait()
> 
>returncode = run.wait()
> 
>return returncode, out, err

Quite interesting. I dived into /usr/lib/python2.4/subprocess.py and
found out that the "communicate()" method actually works similarly. I
might even prefer your version because I get the returncode from
run.wait() what "communicate()" does not.

Great work. Thanks for your time.

Kindly
 Christoph

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


Re: Numerics, NaNs, IEEE 754 and C99

2006-06-14 Thread Nick Maclaren

In article <[EMAIL PROTECTED]>,
Gary Herron <[EMAIL PROTECTED]> writes:
|> 
|> The IEEE standard specifies (plus or minus) infinity as the result of
|> division by zero.  This makes sense since such is the limit of division
|> by a quantity that goes to zero.  The IEEE standard then goes on to
|> define reasonable results for arithmetic between infinities and real
|> values.  The production of, and arithmetic on, infinities is a choice
|> that any application may want allow or not.

The mistake you have made (and it IS a mistake) is in assuming that the
denominator approaches zero from the direction indicated by its sign.
There are many reasons why it is likely to not be, but let's give only
two:

It may be a true zero - i.e. a count that is genuinely zero, or
the result of subtracting a number from itself.

It may be a negative zero that has had its sign flipped by an
aritfact of the code.  For example:

lim(x->0 from above) 0.001*b/(a-1.001*a)

I fully agree that infinity arithmetic is fairly well-defined for
most operations, but it most definitely is not in this case.  It should
be reserved for when the operations have overflowed.


Regards,
Nick Maclaren.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: prog1 | prog2 . How not to make prog2 block if not piped?

2006-06-14 Thread imcs ee
yeah, forget my post ,it;s useless.
sorry for my thoughtless
On 14 Jun 2006 10:40:15 -0700, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
> imcs ee ha scritto:
>
> > do u really need read something even when you run the scripts2.py directly?
> > why not just change script2.py to
> >  #script2.py
> > if __name__ == "__main__":
> > x=sys.stdin.read()
> > print 'passed'
> > else:
> > print 'passed from else branch'
> >
> > is it what  you want? or anything i misunderstand.
>
> it won't do. clever btw.
> Script2 is not a module, it's a program that _could_ receive input via
> pipe.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: prog1 | prog2 . How not to make prog2 block if not piped?

2006-06-14 Thread riquito

imcs ee ha scritto:

> do u really need read something even when you run the scripts2.py directly?
> why not just change script2.py to
>  #script2.py
> if __name__ == "__main__":
> x=sys.stdin.read()
> print 'passed'
> else:
> print 'passed from else branch'
>
> is it what  you want? or anything i misunderstand.

it won't do. clever btw.
Script2 is not a module, it's a program that _could_ receive input via
pipe.

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


Re: Numerics, NaNs, IEEE 754 and C99

2006-06-14 Thread Sébastien Boisgérault
Jeez, 12 posts in this IEEE 754 thread, and still
no message from uncle timmy ? ;)

Please, we need enlightenment here and *now* :)

platform-dependent accident'ly yours,

SB

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


Re: Numerics, NaNs, IEEE 754 and C99

2006-06-14 Thread Grant Edwards
On 2006-06-14, Christophe <[EMAIL PROTECTED]> wrote:

The division by zero trap is really annoying.  In my world the
right thing to do is to return Inf.
>>>
>>>Your world is flawed then, this is a big mistake. NaN is the
>>>only aceptable return value for a division by zero.
>> 
>> You're probably right if you're talking about math, but I'm not
>> doing math.  I'm doing engineering.  In all of the situations
>> I've ever encountered, Inf was a much better choice.
>
> You should have been more precise then : "In my ideal world, when 
> dividing a non zero value by a zero value, the result should be +Inf or 
> -Inf according the the sign rules"

True.  I've been dealing with IEEE 754 so long that I assume
things like that go without saying.

> On that point, you should also note that +0 and -0 are sometimes 
> considered two different floating point numbers in Python :)

Different but equal.

[Don't tell the Supreme Court.]

-- 
Grant Edwards   grante Yow!  I just had a NOSE
  at   JOB!!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Numerics, NaNs, IEEE 754 and C99

2006-06-14 Thread Nick Maclaren

In article <[EMAIL PROTECTED]>,
Scott David Daniels <[EMAIL PROTECTED]> writes:
|> Grant Edwards wrote:
|> 
|> > While you're at it, the pickle modules need to be fixed so they
|> > support NaN and Inf. ;)
|> 
|> The NaN problem is portability -- NaN values are not standard, and
|> pretending they are won't help.  There are many possible NaNs, several
|> of which have desirable behaviors, and different processors (and 
|> Floating Point settings) choose different bit representations for
|> those NaNs.  There are at least: Inf, -Inf, NaN, Ind (Indeterminant).

The main meaning of NaN is Indeterminate (i.e. it could be anything).
If you mean 'Missing', that is what was and is done in statistical
packages, and it follows very different rules.  There are several other
meanings of NaN, but let's not go there, here.  Though I have document
I could post if people are interested.

|> Being able to pickle some of these will produce values that "don't
|> behave right" on a different machine.  Up until now, I think you can
|> send a pickle of a data structure and unpickle it on a different
|> processor to get equivalent data.

No, it could be done right.  The unpickling would need to detect those
values and raise an exception.  You have to allow for it even on the
same 'systems' because one Python might have been compiled with hard
underflow and one with soft.   Your really DON'T want to import denorms
into programs that don't expect them.


Regards,
Nick Maclaren.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Trace KeyboardInterrupt exception?

2006-06-14 Thread Tony Nelson
In article <[EMAIL PROTECTED]>,
 [EMAIL PROTECTED] wrote:

> Tony Nelson wrote:
> > I'm trying to find out what is eating some KeyboardInterrupt exceptions
> > in a fairly large program (yum).  My KeyboardInterrupt handler is called
> > for some Ctl-C presses, but for others nothing seems to happen.
> 
> >  ... I'd like to use a debugger to trace
> > KeyboardInterrupt exceptions, make sure that they're happening, and see
> > what is handling them.
> 
> I don't know how to do that in Idle.  You can replace the default
> Ctrl-C interrupt handler with your own and use that to inspect the
> current stack.

Thanky you, that helps.  Interestingly, some Ctl-Cs don't get caught.  
Presumably they're happening in a subprocess.

Now to see if I can get into that situation again where Ctl-C is 
ignored.  I need to know what's eating the exceptions.  I don't think 
it's a subprocess in the case I'm concerned with.  I don't think yum is 
threaded, but apparantly importing the tread module anywhere should keep 
KeyboardInterrupt on the main thread anyway (?).

It would be nice if I could inspect the stack and find the exception 
handlers.  I'm using trace handlers, but their output seems somewhat 
spotty and inconsistent, or maybe just confusing.

TonyN.:'[EMAIL PROTECTED]
  '  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: prog1 | prog2 . How not to make prog2 block if not piped?

2006-06-14 Thread imcs ee
do u really need read something even when you run the scripts2.py directly?
why not just change script2.py to
 #script2.py
if __name__ == "__main__":
x=sys.stdin.read()
print 'passed'
else:
print 'passed from else branch'

is it what  you want? or anything i misunderstand.

On 14 Jun 2006 08:13:04 -0700, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> I googled around, but couldn't understand how to solve this problem.
> I have 2 scripts
>
> # script1.py #
> print 'something'
>
> #script2.py
> x=sys.stdin.read()
> print 'passed'
>
> if I run
> script1.py | script2.py
> all goes well.
>
> But if I run just
> script2.py
> the program blocks waiting forever for input.
>
> On *nix I used select.select to solve this problem, but on windows?
> I read that maybe I should use, from win32api, GetStdHandle and
> WaitForMultipleObjects, but how to do it it's far from my knowledge.
>
> Any help?
>
> Thank you,
> Riccardo
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Numerics, NaNs, IEEE 754 and C99

2006-06-14 Thread Nick Maclaren

In article <[EMAIL PROTECTED]>,
Gary Herron <[EMAIL PROTECTED]> writes:
|> Christophe wrote:
|> > Grant Edwards a =E9crit :
|> >
|> >> The division by zero trap is really annoying.  In my world the
|> >> right thing to do is to return Inf.
|> >
|> > Your world is flawed then, this is a big mistake. NaN is the only=20
|> > aceptable return value for a division by zero.
|> >
|> Sorry, but this is not true.
|> 
|> The IEEE standard specifies (plus or minus) infinity as the result of
|> division by zero.  This makes sense since such is the limit of division
|> by a quantity that goes to zero.  The IEEE standard then goes on to
|> define reasonable results for arithmetic between infinities and real
|> values.  The production of, and arithmetic on, infinities is a choice
|> that any application may want allow or not.

That is true, and it is numerical nonsense.  Christophe is right.  Despite
Kahan's eminence as a numerical analyst, he is no software engineer.  And
I am amazed at ANY engineer that can believe that inverting zero should
give infinity - while there ARE circumstances where it is correct, it is
NEVER a safe thing to do by default.

The reason is that it is correct only when you know for certain that the
sign of zero is meaningful.  IEEE 754 gets this wrong by conflating true
zero, sign-unknown zero and positive zero.  Inter alia, it means that
you get situations like:

A = 0.0; B = -A; C = B+0.0; A == B == C; 1/A != 1/B != 1/C;


Regards,
Nick Maclaren.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wxpython: how do i write this without the id parameter?

2006-06-14 Thread Scott David Daniels
John Salerno wrote:
> Scott David Daniels wrote:
> 
>> class InputForm(wx.Frame):
>> def __init__(self, parent=None, id=-1, title=__file__):
> 
> Also, is there a way to define parent and id with defaults, but not 
> title? Is it good to change the order around to do this?
No, too many things know the first couple of args are parent and id.
If __file__ doesn't work for you, just stick in something for title
and remember to replace it.

 class InputForm(wx.Frame):
 def __init__(self, parent=None, id=-1, title='Input Form"):

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: convert floats to their 4 byte representation

2006-06-14 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
godavemon <[EMAIL PROTECTED]> wrote:
>I've been a member for a while but I had no idea how helpful this form
>is.  I had a one hour meeting and when I came back there were 4
>replies.  Thanks for your help!
>
>
>Scott David Daniels wrote:
>> godavemon wrote:
>> > I need to take floats and dump out their 4 byte hex representation.
.
.
.
>>  import array
>>
>>  def eights(number, swap=False):
>>  data = array.array('d', [number])
>>  if swap:
>>  data.byteswap()
>>  return ' '.join(hexx(ord(char), 2) for char in data.tostring())
>>
>>  def fours(number, swap=False):
>>  data = array.array('f', [number])
>>  if swap:
>>  data.byteswap()
>>  return ' '.join(hexx(ord(char), 2) for char in data.tostring())
.
.
.
I want to reinforce and refine a bit of what's been written.

comp.lang.python *is* unusually useful.  Note, by the way, that,
among the four replies you first found, ALL FOUR were accurate
and pertinent.  In a world where a discussion group is better-than-
average when *one* out of four of its replies is trustworthy, clp
rates high.

Please be aware that "their ... hex representation" is ambiguous.
At the very least, you need to be sensitive--as perhaps you already
are--to the possibility that a float's (or double's) representation
in memory is hardware-dependent (and, depending on what you mean,
potentially dependent on the version of Python implementation).  If
you pursue this area, you'll want to be on the look-out for "IEEE
754", the standard which ... well, is most standard http://en.wikipedia.org/wiki/IEEE_floating-point_standard >.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Help

2006-06-14 Thread Tim Chase
> I have recently downloaded Python 2.4.3 on Windows XP. The
> program does not recongnize when I type in python:" name
> 'python' is not defined". Please tell me how to correct this.


Sounds like you don't have it in your path.

In XP, use Win+Break to pull up your system properties (the same 
as right-clicking on "My Computer" and chosing "Properties").  On 
the "Advanced" tab, press the "Environment Variables" button.

If you want the change to be just for your user, add a new 
variable under the top section, named "PATH", with a value of 
"%PATH%;c:\Program Files\Python24" (or wherever the path to 
python.exe resides).  If a PATH variable already exists, you can 
just edit it, appending a semicolon followed by the path to the 
directory containing python.exe

If you want to make python accessible for all users on the 
machine, you can do the same sort of process in the bottom pane 
of that window.

Restart your command-shell and you should be good to go.  Or, if 
you've got stuff in your command shell you don't want to lose, 
you can just use

c:\> path %PATH%;c:\Progra~1\Python24\

which will set the path for that particular command window, but 
this change will be forgotten when you close the window.

-tkc


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


Re: Numerics, NaNs, IEEE 754 and C99

2006-06-14 Thread Christophe
Grant Edwards a écrit :
> On 2006-06-14, Christophe <[EMAIL PROTECTED]> wrote:
> 
>>Grant Edwards a écrit :
>>
>>>The division by zero trap is really annoying.  In my world the
>>>right thing to do is to return Inf.
>>
>>Your world is flawed then, this is a big mistake. NaN is the
>>only aceptable return value for a division by zero.
> 
> 
> You're probably right if you're talking about math, but I'm not
> doing math.  I'm doing engineering.  In all of the situations
> I've ever encountered, Inf was a much better choice.

You should have been more precise then : "In my ideal world, when 
dividing a non zero value by a zero value, the result should be +Inf or 
-Inf according the the sign rules"

On that point, you should also note that +0 and -0 are sometimes 
considered two different floating point numbers in Python :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Numerics, NaNs, IEEE 754 and C99

2006-06-14 Thread Gary Herron
Christophe wrote:
> Grant Edwards a écrit :
>   
>> The division by zero trap is really annoying.  In my world the
>> right thing to do is to return Inf.
>> 
>
> Your world is flawed then, this is a big mistake. NaN is the only 
> aceptable return value for a division by zero.
>   
Sorry, but this is not true.

The IEEE standard specifies (plus or minus) infinity as the result of
division by zero.  This makes sense since such is the limit of division
by a quantity that goes to zero.  The IEEE standard then goes on to
define reasonable results for arithmetic between infinities and real
values.  The production of, and arithmetic on, infinities is a choice
that any application may want allow or not.

Gary Herron


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


Re: Numerics, NaNs, IEEE 754 and C99

2006-06-14 Thread Grant Edwards
On 2006-06-14, Scott David Daniels <[EMAIL PROTECTED]> wrote:
> Grant Edwards wrote:
>
>> While you're at it, the pickle modules need to be fixed so they
>> support NaN and Inf. ;)

> The NaN problem is portability -- NaN values are not standard,

My copy of IEEE 754 defines them quite precisely. :)

> and pretending they are won't help.  There are many possible
> NaNs, several of which have desirable behaviors, and different
> processors (and Floating Point settings) choose different bit
> representations for those NaNs.  There are at least: Inf,
> -Inf, NaN, Ind (Indeterminant).

I don't think +Inf and -Inf aren't NaNs (in IEEE 754
terminology).  I think Pickle ought to handle them as well.

> Being able to pickle some of these will produce values that
> "don't behave right" on a different machine.

The values "don't behave right" now.  Having them "behave
right" on 99.9% of the hosts in the world would be a vast
improvement.

> Up until now, I think you can send a pickle of a data
> structure and unpickle it on a different processor to get
> equivalent data.

No, you can't.  Nan, Inf, and Ind floating point values don't
work.

-- 
Grant Edwards   grante Yow!  Yow! STYROFOAM...
  at   
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Numerics, NaNs, IEEE 754 and C99

2006-06-14 Thread Grant Edwards
On 2006-06-14, Christophe <[EMAIL PROTECTED]> wrote:
> Grant Edwards a écrit :
>> The division by zero trap is really annoying.  In my world the
>> right thing to do is to return Inf.
>
> Your world is flawed then, this is a big mistake. NaN is the
> only aceptable return value for a division by zero.

You're probably right if you're talking about math, but I'm not
doing math.  I'm doing engineering.  In all of the situations
I've ever encountered, Inf was a much better choice.

Aside from Python, every FP library or processor I've ever used
returned Inf for divide by zero (which is the behavior required
by IEEE 754).

I need my Python programs to work the same way as everything
else.


http://standards.ieee.org/reading/ieee/interp/754-1985.html

  In IEEE Std 754-1985, subclause 7.2- Division by Zero, it says:

 "If the divisor is zero and the dividend is a finite nonzero
  number, then the division by zero shall be signaled. The
  result, when no trap occurs, shall be a correctly signed
  (infinity symbol)(6.3)."

  While this is apparently the convention decided on by the
  committee, it is mathematically incorrect and it seems as if
  it should have been designated as Not-a-Number, since
  division by zero is mathematically undefined and implies that
  0*infinity=1, which is patently absurd.

  Why was this convention chosen instead of NaN, since it leads
  to a further degradation of our children's math abilities,
  given that the IEEE floating-point standard would be considered
  to be authoritative on this subject, yet produces an erroneous
  results.

  Interpretation for IEEE Std 754-1985
  
  When a non-zero number is divided by a zero number, that is a
  divide by zero. It is interpreted as an attempt to
  take a limit of the ratio of two numbers as the denominator
  becomes too small to be represented in the number system
  while the numerator remains representable. Such a limit is best
  represented by an infinity of the appropriate sign.
  
  When zero is divided by zero, no such extrapolation can be
  made. If it is caused by an attempt to take the limit of
  the ratio of two numbers when both become two small to be
  represented, then the limit cannot be determined. If it
  is caused by some mistake in the programming, then no limit
  exists. Thus, this case is thought to be invalid and a NaN
  of appropriate sign is returned. (The sign is the only bit of
  information that can be determined.)
  
  While counter examples to the mathematical interpretation of
  both of these results can be constructed they tend to be either
  the result of extreme scaling or an attempt to evaluate a
  non-analytic function. The former can be resolved by
  rescaling. But, as the latter involve functions that cannot
  (formally) be evaluated on a computer (without extreme effort
  anyway) in the region of their non-analyticity, usually no good
  solution exists.

-- 
Grant Edwards   grante Yow!  I represent a
  at   sardine!!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >