Re: reduce to be removed?

2006-11-12 Thread Ben Finney
"Dustan" <[EMAIL PROTECTED]> writes:

> Steven D'Aprano wrote:
> > Repeat after me:
> >
> > "Not everything has to be a one-liner."
>
> Not everything has to be a one-liner. But readability helps.

Indeed. Complex one-liners are rarely as readable as a well-named
function call, implemented with several explicit readable lines in
one place, and then re-used as many times as necessary.

-- 
 \  "Anyone who believes exponential growth can go on forever in a |
  `\ finite world is either a madman or an economist."  -- Kenneth |
_o__) Boulding |
Ben Finney

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


Re: Decimal() instead of float?

2006-11-12 Thread Ben Finney
"Steven D'Aprano" <[EMAIL PROTECTED]> writes:

> On Sun, 12 Nov 2006 02:31:04 +0100, Fredrik Lundh wrote:
> > (who uses fractional ZIP codes, btw?)
>
> Well, I can't speak for Americans, but here in Australia we
> typically give our post codes to six decimal places:
>
> Melbourne 3000.00
> Brunswick 3056.00
> Clifton Hill 3068.00
> Sydney 2000.00
> St Johns Park 2176.00

Yeah, I know. As soon as that legislation came in, I started giving
the *precision* they asked for, with my own choice of *accuracy*, just
to mess with their damned totalitarian databases.

Melbourne 3000.00
Brunswick 3000.00
Clifton Hill 3000.00

But you try to tell people overseas about this legislation, and they
just don't believe you.

-- 
 \  "It is well to remember that the entire universe, with one |
  `\   trifling exception, is composed of others."  -- John Andrew |
_o__)   Holmes |
Ben Finney

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


Python as default Lexer in SciTE

2006-11-12 Thread egbert
Is it possible to set Python as the default language in SciTE?
Not all my python scripts have the .py extension, 
only the to_be_imported ones. And I use SciTE only for Python.
e.
-- 
Egbert Bouwman - Keizersgracht 197 II - 1016 DS  Amsterdam - 020 6257991

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


Fredrik Lundh [was "Re: explicit self revisited"]

2006-11-12 Thread Doug

Fredrik Lundh wrote:
> Doug wrote:
>>
>> Fredrik Lundh wrote:
>>> Fredrik Lundh wrote:
>>> > cannot all you clueless trolls who cannot think of a single useful thing
>>> > to contribute to Python start your own newsgroup?
>>
>>> and before anyone complains; please note that they're working through
>>
>>>  http://www.effbot.org/pyfaq/design-index.htm
>>
>> That site is a bunch of FUD -
>> The explicit self is there simply because OOP was tacked onto python as
>> an afterthought.
>> Why not just be honest about it.  It's too late to change Python's
>> syntax.  It just means a little extra typing.  If it really bothers
>> someone, use "s" instead of "self" or else use Ruby.
>
> the official FAQ is a bunch of FUD?  are you sure you know what FUD means?
>
> 

You idiot.  Putting the word "official" in front of something doesn't
mean it can't be FUD.  Especially when it is written by people such as
yourself.  Have you not paid attention to anything happening in
politics around the world during your lifetime?
And yes, actually, the dash after FUD was where I was going to link to
a definition of FUD to show I really meant to use that term.  It
doesn't appear that you believe anything that isn't on your own effbot
site, however.

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


Re: Py3K idea: why not drop the colon?

2006-11-12 Thread Doug

Michael Hobbs wrote:
> Can anyone find a flaw with this change in syntax?
>
> Instead of dividing a compound statement with a colon, why not divide it
> on a newline? For example, the colon could be dropped from this statement:
> if self.hungry:
> self.eat()
> to
> if self.hungry
> self.eat()
>
> Python is already sensitive to whitespace and the newline anyway, so why
> not put it to good use? For example, Python rejects this statement
> because of the newline present:
> if self.hungry or
>   self.depressed:
> self.eat()
> You need to use the backslash to continue the expression on the next line:
> if self.hungry or \
>   self.depressed:
> self.eat()
> The colon that divides the statement therefore seems redundant. The
> colon could continue to be used for single-line statements:
> if self.hungry: self.eat()
>
> I think the colon could be omitted from every type of compound
> statement: 'if', 'for', 'def', 'class', whatever. Am I missing anything?
>
> Thanks,
> - Mike

It is a very good idea as the colon is technically redundant (not
necessary for parsing, aside from one liners) and actually hurts
readability (and writeability).  The "evidence" people cite for the
advantage of using a colon is research done by users of the ABC
language, python's predecessor.  They forget that A) that was like 20
years ago, B) the language was designed for children, and C) the
keywords in ABC are IN ALL CAPS LIKE THIS (hurting readability and
writeability) and thus adding a colon obviously helps restore some
readability for users in that case but not in python's.

However, python is far too old to accept any fundamental changes to
syntax at this point.

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


Re: Decimal() instead of float?

2006-11-12 Thread John Machin

Steven D'Aprano wrote:
> On Sun, 12 Nov 2006 02:31:04 +0100, Fredrik Lundh wrote:
>
> >> For example, I have a ZIP code
> >> database that can do some processing on its numbers, and the numbers are
> >> stored as floating point values (exactly) but Python doesn't get them
> >> right
> >
> > sounds odd.  are you sure you don't mean "stored as strings containing
> > decimal numbers" ?
> >
> > (who uses fractional ZIP codes, btw?)
>
> Well, I can't speak for Americans, but here in Australia we typically give
> our post codes to six decimal places:
>
> Melbourne 3000.00
> Brunswick 3056.00
> Clifton Hill 3068.00
> Sydney 2000.00
> St Johns Park 2176.00
>
> and so forth. You can't have too much precision with those floating point
> post/ZIP codes!

Here in Austraila, (I expect this is common to most countries), there
are people who are utterly clueless about elementary data model rules,
like identification "numbers" should be kept as strings.

E.g. (1) National grief started over twenty years ago when the Post
Office started using postcodes with leading zeroes, and continues to
the present. The postcode for Darwin can be stored as 800, "800", or
"0800".

E.g. (2) Many Australians have a Tax File Number (TFN) which is a
9-digit number with an "officially kept secret" check digit algorithm
(you need to sign an NDA with the Tax Office). Storing this as an
integer allows the TFN be negative -- if the data entry for say
123456789 is actually 123456789-, you don't check for anything (length,
allowable characters, check digit) and an old-fashioned
trailing-minus-allowed conversion-to-integer routine is used.

Cheers,
John

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


Re: explicit self revisited

2006-11-12 Thread Duncan Booth
Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:

> On Sun, 12 Nov 2006 01:55:35 +0100, Fredrik Lundh
><[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
> 
> 
>> 
>> ah, good point.  I've updated the FAQ.
>>
>  Ah, but do we dare update the Wikipedia link to include Python as a
> language capable of COMEFROM? 

Somebody definitely should. The current wikipedia article contains an 
example in a hypothetical dialect of BASIC ('because an actual example in 
INTERCAL would be too difficult to read'). Somebody should enhance the 
article with the equivalent example in Python which is both easy to read 
and can actually be run:

from goto import goto, comefrom, label

comefrom .repeat
name = raw_input('what is your name? ')
if name:
print "Hello",name
label .repeat

print "Goodbye!"

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


Re: Decimal() instead of float?

2006-11-12 Thread Steven D'Aprano
On Sun, 12 Nov 2006 20:38:31 +1100, Ben Finney wrote:

> But you try to tell people overseas about this legislation, and they
> just don't believe you.

Ha! You were lucky. When I was a lad, we had to write our postcodes on
envelopes in balanced ternary.


-- 
Steven.

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


ANN: version 3.9.2 of eric3 available

2006-11-12 Thread Detlev Offenbach
Hi,

this is to informe you about the availability of eric3 v 3.9.2. This is
bug fix release with some new features. It is available via

http://www.die-offenbachs.de/detlev/eric.html

Changelog:
- bug fixes
- added support for new QScintilla stuff 
  (e.g. autocomplete from document and APIs)
- extended debugger to not set the encoding (configurable)
- added keyboard shortcuts for the shell
  -- to clear the shell
  -- for all zoom aczions (zoom in, zoom out, zoom)
- added the tool eric3-configure to setup eric3 without the need
  to start the IDE

Regards,
Detlev
-- 
Detlev Offenbach
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Find interface associated with default route?

2006-11-12 Thread Neal Becker
Any thoughts on howto find the interface associated with the default route
(this is on linux)?

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


Re: Find interface associated with default route?

2006-11-12 Thread Fredrik Lundh
Neal Becker wrote:

> Any thoughts on howto find the interface associated with the default route
> (this is on linux)?

are you sure you sent this to the right newsgroup ?

is this what you want ?

 >>> import os
 >>> for line in os.popen("/sbin/route"):
... line = line.split()
... if line[0] == "default":
... print line[-1]
...
eth0



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


Re: Fredrik Lundh [was "Re: explicit self revisited"]

2006-11-12 Thread Alan G Isaac
On Sun, 12 Nov 2006 02:14:32 -0500, Doug <[EMAIL PROTECTED]> wrote:
> I was going to link to
> a definition of FUD to show I really meant to use that term.

Oooh.
If you had just mentioned your dyslogia,
it would have saved us all some time.
Thanks!
Alan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Py3K idea: why not drop the colon?

2006-11-12 Thread Hendrik van Rooyen
"Dan Lenski" <[EMAIL PROTECTED]> wrote:


> Hendrik van Rooyen wrote:
> > "Fredrik Lundh" <[EMAIL PROTECTED]> wrote:
> >
> > 8<---
> > >  >>> color = "blue"
> > >  >>> if color == "red" or "green" or "yellow":
> > > ... print color, "is red or green or yellow"
> > > ...
> > > blue is red or green or yellow
> >
> > *grin* - this can be construed as a weakness in Python -
> >
> > Even COBOL compilers in the sixties would "add in" the implied
> > "if color = " after each 'or', instead of bloody - mindedly thinking:
> 
> How the heck could this be considered a weakness in Python?  I *like*
> the fact that Python does not do anything "automagical" and rewrite
> expressions, thinking it's smarter than the programmer.  That's one
> reason I got sick of Perl.
> 
> There are plenty of cases where I might want to use an expression like
> "color == red or foo or bar" with the semantics it actually implies in
> Python.  Making an exception for literal strings specifically seems
> reallly dubious given the fact that Python already has an easy way to
> do what you want with the "color in (red, green, blue)" construct.
> This supposedly lacking feature would only be desired by people who
> have been brain-damaged by programming languages like BASIC and
> COBOL... or newbies who haven't programmed enough to really "get"
> Boolean logic.  
> 
> Dan

I am amazed by the reaction my grin and weakness comment has drawn - 
it looks as if both you and the effbot did not bother to read and try to 
understand the rest of that post, which gave an example of why the python
way is in fact good...

I apologise if my example is meaningless to people whose brains have not been
damaged by experience yet.

- Hendrik



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


Re: Python component model

2006-11-12 Thread Jacob Hallen
In article <[EMAIL PROTECTED]>,
Peter Wang <[EMAIL PROTECTED]> wrote:
...
>functions at ever higher levels of abstraction, or to have a
>proliferation of nebulously-defined "manager" objects.)  IMHO once you
>cross this chasm and are able to model your problem domain with live
>objects that go off and automatically respond to the runtime
>environment and Do the Right Thing, it's very hard to go back to a dead
>object mindset.  I can understand, however, that until one makes this
>leap, it might seem like an academic and useless distinction.

I'm not disagreeing with the blessings of components reacting to events
and going off Doing the Right Thing. However, there is a huge with
components going off Doing the Wrong Thing. It becomes exceedingly
hard to debug for several reasons. The first one is that it is difficult
to trace the callbacks generated, since the point where they were
registered is no longer trackable when your problem occurs. The second
and most serious problem is that erroneous behaviour in two components
can interact in extremely mysterious ways that are really difficult to
debug.

In part these problems can be reduced by much rigorous testing of each
component than is the norm today, but for the really tough problems we
need tools that have not been invented yet, that track the history
of each callback. Since these tools have to understand the details
of the calling conventions and registration mechanism for events, they
have to be custom built for each component framework and should therefore
be part of the framework distribution.

Jacob Hallén

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

Re: Find interface associated with default route?

2006-11-12 Thread Neal Becker
Fredrik Lundh wrote:

> Neal Becker wrote:
> 
>> Any thoughts on howto find the interface associated with the default
>> route (this is on linux)?
> 
> are you sure you sent this to the right newsgroup ?
> 
> is this what you want ?
> 
>  >>> import os
>  >>> for line in os.popen("/sbin/route"):
> ... line = line.split()
> ... if line[0] == "default":
> ... print line[-1]
> ...
> eth0
> 

Well, I was hoping for something more 'elegant' - meaning relying on library
calls rather than calling programs.  Obviously, /sbin/route has some
library calls to obtain this info, and maybe python has a wrapper for it.

Yes, this is the right group - I want a python solution.

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


Re: Why does this code crash python?

2006-11-12 Thread Martin Blume
<[EMAIL PROTECTED]> schrieb 
> I am trying to make a program that will basically simulate 
> a chess clock in python. ...
> ... it crashes shortly after. 

Can't help you on why it crashes, but

> 
> class eventMonitor (Thread):
> def run ( self ):
> [snipped]
> if event.keycode == 32:
> if turn == 1: turn = 0
> if turn == 0: turn = 1
>

looks wrong to me. This is supposed to switch between the 
players (0 and 1), but the first if changes turn to 0, the
second changes it immediately back to 1.

I'd do:
  if turn == 1:  turn = 0
  else:  turn = 1

HTH
Martin


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


Re: Close program built with py2exe

2006-11-12 Thread Fredrik Lundh
Steve Ingram wrote:

> I've got a problem with a program I've written and want to distribute. It
> uses a wxPython dialog and I've built a distribution version with py2exe.
> Problem is when I run the .exe under windows I can only stop the program
> completely using the task manager. When I close the dialog and check the
> task manager, there is still a running process. I think this is probably
> the python interpreter that is still running.
> 
> Can't find any help anywhere, does anyone know how to get the dialog to
> kill the process properly??

have you checked if any exceptions occur during application shutdown?

it could be that the GUI toolkit manages to remove all windows, but that 
something goes wrong at the application level before the GUI gets around 
to shut down the message loop.



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


Re: FAQ: How do I calculate what quoted strings and numbers mean?

2006-11-12 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> But those objections miss the point.  Having had those troubles
> explained to me now, I'm still leaving my code unchanged - it still
> does what I mean.  That is,
> 
> eval(source, {'builtins': {}}) works enough like an evaluator of
> literals to let you duck the work of writing that evaluator until you
> need it.  Yagni.

until you forget about it, and someone uses the security hole to take 
down your company's site, or steal all the customer data from your 
database, or some such thing.

I think the PHP "I don't really get bound parameters; let's explain how 
to build SQL statements by hand first" shows that you should avoid doing 
things in stupid ways in documentation that's likely to be read by 
inexperienced programmers...

 > eval(source, {'builtins': {}}) works enough like an evaluator of
 > literals to l

eval(source, {'builtins': {}}) doesn't prevent you from using built-ins, 
though.  it's spelled __builtins__, not builtins:

 >>> eval("len('10')", {"builtins": {}})
2
 >>> eval("len('10')", {"__builtins__": {}}
Traceback (most recent call last):
   File "", line 1, in 
   File "", line 1, in 
NameError: name 'len' is not defined

 > That's useful, and likely an FAQ.

A FAQ that discusses good ways to handle Python-like literals and 
expressions would definitely be a useful addition to the FAQ.  if nobody 
else does anything about it, I'll get there sooner or later.



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


Re: service windows avec py2exe

2006-11-12 Thread DarkPearl
 ok,

It's this line who crash the service :

self.WMIService
=win32com.client.GetObject(r"winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")


why this function goes when it is not a service?

with IDLE -> ok
with py2exe executable (no windows service) -> ok
with py2exe service option true (windows service) -> CRASH

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


python(abi)

2006-11-12 Thread Ioannis Vranos
OS: Scientific Linux 4.4 (http://www.scientificlinux.org) which is a Red Hat 
Enterprise 
Linux 4 derivative (http://www.redhat.com/rhel/), like CentOS 
(http://www.centos.org), 
White Box Linux (http://www.whiteboxlinux.org) etc.

Python version built and installed from sources: 2.4.4.


I am trying to install BitTorrent 5.0 prerequisites, and when I am trying to 
install 
wxPython-common-gtk2-unicode-2.6.3.3-fc4_py2.4.i386.rpm, I am getting the 
message that it 
requires python(abi):

[EMAIL PROTECTED] download]# rpm -ivh 
wxPython-common-gtk2-unicode-2.6.3.3-fc4_py2.4.i386.rpm
error: Failed dependencies:
 python(abi) = 2.4 is needed by 
wxPython-common-gtk2-unicode-2.6.3.3-fc4_py2.4.i386

[EMAIL PROTECTED] download]#



I have found in some message logs, that it is a pseudo-requirement, but where 
can I 
download this for Python 2.4.4? (The Python version that comes with my 
distribution is 
currently 2.3.4).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Find interface associated with default route?

2006-11-12 Thread Neal Becker
Neal Becker wrote:

> Fredrik Lundh wrote:
> 
>> Neal Becker wrote:
>> 
>>> Any thoughts on howto find the interface associated with the default
>>> route (this is on linux)?
>> 
>> are you sure you sent this to the right newsgroup ?
>> 
>> is this what you want ?
>> 
>>  >>> import os
>>  >>> for line in os.popen("/sbin/route"):
>> ... line = line.split()
>> ... if line[0] == "default":
>> ... print line[-1]
>> ...
>> eth0
>> 
> 
> Well, I was hoping for something more 'elegant' - meaning relying on
> library
> calls rather than calling programs.  Obviously, /sbin/route has some
> library calls to obtain this info, and maybe python has a wrapper for it.
> 
> Yes, this is the right group - I want a python solution.
> 

A quick strace reveals that 'route' just reads /proc/net/route, so:

def get_default_if():
f = open ('/proc/net/route', 'r')
for line in f:
words = string.split (line)
dest = words[1]
try:
if (int (dest) == 0):
interf = words[0]
break
except ValueError:
pass
return interf


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


writing wx code in emacs - how to make easier?

2006-11-12 Thread Seweryn Kokot
Hello,

I would like to write wx code in emacs. For now I'm using python-mode
but I hope they are stuff which make it easier. I mean some
autocompletion or abbrevs of such things as wx.ALIGN* wx.EVT_* ... 

Any ideas?
regards,
SK

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


Re: python(abi)

2006-11-12 Thread Fredrik Lundh
Ioannis Vranos wrote:

> [EMAIL PROTECTED] download]# rpm -ivh 
> wxPython-common-gtk2-unicode-2.6.3.3-fc4_py2.4.i386.rpm
> error: Failed dependencies:
>  python(abi) = 2.4 is needed by 
> wxPython-common-gtk2-unicode-2.6.3.3-fc4_py2.4.i386
> 
> I have found in some message logs, that it is a pseudo-requirement, but where 
> can I 
> download this for Python 2.4.4? (The Python version that comes with my 
> distribution is 
> currently 2.3.4).

something like this could work:

http://rpmfind.net//linux/RPM/fedora/updates/4/i386/python-2.4.3-8.FC4.i386.html



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


Help with gateway

2006-11-12 Thread Cameron Laird
Who knows and/or manages bag.python.org?  My e-mail server
and the clp gateway are having a configuration disagreement
that I'd like to solve.  Please e-mail me privately.

I'll report back to the group as appropriate.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: range syntax

2006-11-12 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Colin J. Williams <[EMAIL PROTECTED]> wrote:
.
.
.
>Your point about iterators is well taken, but it seems that the range is 
>used sufficiently frequently that some syntactic form would be helpful.
>
>Colin W.
>

A personal reaction:  part of the judgment guiding 
Python now and for some time in the past is a bias
toward NOT "multiplying entities".  I believe Guido
and his lieutenants think in terms of, "if a syntax
*might* be helpful, leave it out; only if it's
compelling/necessary/... do we change the language."

Perhaps you know this already.  In any case, Python
leadership is wary that pursuit of local
optimizations--like your range suggestion--can
damage global prospects for the language.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: service windows avec py2exe

2006-11-12 Thread Tim Golden

DarkPearl wrote:
> ok,
>
> It's this line who crash the service :
>
> self.WMIService
> =win32com.client.GetObject(r"winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
>
>
> why this function goes when it is not a service?
>
> with IDLE -> ok
> with py2exe executable (no windows service) -> ok
> with py2exe service option true (windows service) -> CRASH

OK. I think I can help here. WMI is a COM/DCOM-based technology.
Windows services are inherently multithreaded. Therefore you need to
Initialize a COM threading model specifically even though you're not
really using threads yourself.

Try putting:

import pythoncom
pythoncom.CoInitialize ()

somewhere before the line which instantiates the WMI
object (the one you quoted above).

I have no idea why this usually manifests itself as a
"Syntax Error" but it does!

TJG

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


Re: Python Parallel Paradigm

2006-11-12 Thread Paul Boddie
Sandy wrote:
>
> A higher-level system of concurrency, not based on monitors and
> locks and great programmer discipline, will ultimately require making
> "Python 3000" a reality.

It would surprise me if Python 3000 introduced anything substantially
more than what Python 2.x provides in the area of concurrency.

> In the meantime, is there anywhere, or any thing, that discusses the
> various concurrency options related to Python?  There's Stackless Python
> (which I can't make head or tail of; I have been unable to find any
> lucid overview, or genuine explanation of the purpose of the design.)

What about this introduction...?

http://members.verizon.net/olsongt/stackless/why_stackless.html

>  I know that there's a package for an Erlang system for Python, somewhere
> ("Parnassus" probably).  There's probably a Py-CSP somewhere too.  Lots
> of trees, but where's the Wood?

Here are some fairly similar projects in Python:

http://kamaelia.sourceforge.net/
 - a way of making general concurrency easy to work with, and fun

http://candygram.sourceforge.net/
 - a Python implementation of Erlang concurrency primitives

http://www.python.org/pypi/parallel
 - process forking and channel-based communication (using pickles)

> Where are concurrency/distributed models compared and discussed?

In the following article and comments there are some opinions expressed
on Python concurrency (along with the usual dose of Ruby vapourware
promotion):

http://www.oreillynet.com/onlamp/blog/2005/10/does_python_have_a_concurrency.html

Meanwhile, the topic has been discussed on python-dev:

http://mail.python.org/pipermail/python-dev/2005-September/056801.html

That discussion led to a description of something which isn't so far
from parallel/pprocess, at least:

http://mail.python.org/pipermail/python-dev/2005-September/056829.html

Other searching yielded this interesting paper about PyPy and "hardware
transactional memory":

http://portal.acm.org/citation.cfm?id=1176617.1176758&coll=ACM&dl=ACM&type=series&idx=1176617&part=Proceedings&WantType=Proceedings&title=Conference%20on%20Object%20Oriented%20Programming%20Systems%20Languages%20and%20Applications&CFID=15151515&CFTOKEN=6184618

Paul

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


Re: numpy/scipy: correlation

2006-11-12 Thread robert
Robert Kern wrote:
> robert wrote:
>> Is there a ready made function in numpy/scipy to compute the correlation 
>> y=mx+o of an X and Y fast: 
>> m, m-err, o, o-err, r-coef,r-coef-err ?
> 
> And of course, those three parameters are not particularly meaningful 
> together.
> If your model is truly "y is a linear response given x with normal noise" then
> "y=m*x+o" is correct, and all of the information that you can get from the 
> data
> will be found in the estimates of m and o and the covariance matrix of the
> estimates.
> 
> On the other hand, if your model is that "(x, y) is distributed as a bivariate
> normal distribution" then "y=m*x+o" is not a particularly good representation 
> of
> the model. You should instead estimate the mean vector and covariance matrix 
> of
> (x, y). Your correlation coefficient will be the off-diagonal term after
> dividing out the marginal standard deviations.
> 
> The difference between the two models is that the first places no restrictions
> on the distribution of x. The second does; both the x and y marginal
> distributions need to be normal. Under the first model, the correlation
> coefficient has no meaning.

Think the difference is little in practice - when you head for usable 
diagonals. 
Looking at the bivar. coef first before going on to any models, seems to be a 
more stable approach for the first step in data mining. ( before you proceed to 
a model or to class-learning .. )

Basically the first need is to analyse lots of x,y data and check for linear 
dependencies. No real model so far. I'd need a quality measure (coef**2) and to 
know how much I can rely on it (coef-err). coef alone is not enough. You get a 
perfect 1.0 with 2 ( or 3 - see below ) points.
With big coef's and lots of distributed data the coef is very good by itself  - 
its error range err(N) only approx ~ 1/sqrt(N)

One would expect the error range to drop simply with # of points. Yet it 
depends more complexly on the mean value of the coef and on the distribution at 
all. 
More interesting realworld cases: For example I see a lower correlation on lots 
of points - maybe coef=0.05 . Got it - or not?  Thus lower coefs require 
naturally a coef-err to be useful in practice.

Now think of adding 'boring data':

>>> X=[1.,2,3,4]
>>> Y=[1.,2,3,5]
>>> sd.correlation((X,Y)) # my old func 
(1.3, -0.5, 0.982707629824)   # m,o,coef
>>> numpy.corrcoef((X,Y))
array([[ 1.,  0.98270763],
   [ 0.98270763,  1.]])
>>> XX=[1.,1,1,1,1,2,3,4]
>>> YY=[1.,1,1,1,1,2,3,5]
>>> sd.correlation((XX,YY))
(1.23684210526, -0.289473684211, 0.988433774639)
>>> 

I'd expect: the little increase of r is ok. But this 'boring data' should not 
make the error to go down simply ~1/sqrt(N) ...

I remember once I saw somewhere a formula for an error range of the corrcoef. 
but cannot find it anymore. 

http://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient#Trivia
says:
  In MATLAB, corr(X) calculates Pearsons correlation coefficient along with 
p-value.

Does anybody know how this prob.-value is computed/motivated? Such thing would 
be very helpful for numpy/scipy too.

http://links.jstor.org/sici?sici=0162-1459(192906)24%3A166%3C170%3AFFPEOC%3E2.0.CO%3B2-Y
tells:  

probable error of r = 0.6745*(1-r**2)/sqrt(N)

A simple function of r and N - quite what I expected above roughly for the 
N-only dep.. But thus it is not sensitive to above considerations about 
'boring' data. With above example it would spit a decrease of this probable 
coef-err from 

0.0115628571429 to 0.00548453410954 !

And the absolute size of this error measure seems to be too low for just 4 
points of data!

The other formula which I remember seeing once was much more sophisticated and 
used things like sum_xxy etc...


Robert



PS:

my old func is simply hands-on based on 
n,sum_x,sum_y,sum_xy,sum_xx,sum_yy=len(vx),vx.sum(),vy.sum(),(vx*vy).sum(),(vx*vx).sum(),(vy*vy).sum()
Guess its already fast for large data?


Note: numpy.corrcoef strikes on 2 points:
>>> numpy.corrcoef(([1,2],[1,2]))
array([[  -1.#IND,   -1.#IND],
   [  -1.#IND,   -1.#IND]])
>>> sd.correlation(([1,2],[1,2]))
(1, 0, 1.0)
>>> 
>>> numpy.corrcoef(([1,2,3],[1,2,3]))
array([[ 1.,  1.],
   [ 1.,  1.]])
>>> sd.correlation(([1,2,3],[1,2,3]))
(1, 0, 1.0)


PPS:

A compatible scipy binary (0.5.2?) for numpy 1.0 was announced some weeks back. 
Think currently many users suffer when trying to get started with incompatible 
most-recent libs of scipy and numpy.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: numpy/scipy: correlation

2006-11-12 Thread sturlamolden

Robert Kern wrote:

> The difference between the two models is that the first places no restrictions
> on the distribution of x. The second does; both the x and y marginal
> distributions need to be normal. Under the first model, the correlation
> coefficient has no meaning.

That is not correct. The correlation coefficient is meaningful in both
models, but must be interpreted differently. However, in both cases a
correlation coefficient of 1 or -1 indicates an exact linear
relationship between x and y.

Under the first model ("linear regression"), the squared correlation
coefficient is the "explained variance", i.e. the the proportion of y's
variance accounted for by the model y = m*x  + o.

Under the second model ("multivariate normal distribution"), the
correlation coefficient is the covariance of y and x divided by the
product of the standard deviations, cov(x,y)/(std(x)*std(y)).

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


Re: reduce to be removed?

2006-11-12 Thread Dustan
Alright, I can see I'm a bit outvoted here. I tried your suggestions
and it worked fine.

I'll also try to consider in the future that part of the problem might
be lack of information conveyed on my part.

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


Re: numpy/scipy: correlation

2006-11-12 Thread robert
robert wrote:
> Robert Kern wrote:
> http://links.jstor.org/sici?sici=0162-1459(192906)24%3A166%3C170%3AFFPEOC%3E2.0.CO%3B2-Y
>  
> 
> tells: 
> probable error of r = 0.6745*(1-r**2)/sqrt(N)
> 
> A simple function of r and N - quite what I expected above roughly for 
> the N-only dep.. But thus it is not sensitive to above considerations 
> about 'boring' data. With above example it would spit a decrease of this 
> probable coef-err from
> 0.0115628571429 to 0.00548453410954 !

This 1929 formula for estimating the error of correlation coefficient seems to 
make some sense for r=0 . 
I do monte carlo on correlating random series:

>>> X=numpy.random.random(1)
>>> l=[]
>>> for i in range(200): 
... Z=numpy.random.random(1)
... l.append( sd.correlation((X,Z))[2] )   #collect coef's
... 
>>> mean(l)
0.000327657082234
>>> std(l)
0.0109120766158  # thats how the coef jitters
>>> std(l)/sqrt(len(l))
0.000771600337185
>>> len(l)
200

# now
# 0.6745*(1-r**2)/sqrt(N) = 0.0067440015079
# vs M.C.   0.0109120766158 ± 0.000771600337185


but the fancy factor of 0.6745 is significantly just fancy for r=0.

then for a higher (0.5) correlation:

>>> l=[]
>>> for i in range(200): 
... Z=numpy.random.random(1)+array(range(1))/1.0
... l.append( sd.correlation((X+array(range(1))/1.0,Z))[2] )
... 
>>> mean(l)
0.498905642552
>>> std(l)
0.00546979583163
>>> std(l)/sqrt(len(l))
0.000386772972425

#now:
# 0.6745*(1-r**2)/sqrt(N) = 0.00512173224849)
# vs M.C.   0.00546979583163 ± 0.000386772972425

=> there the 0.6745 factor and (1-r**2) seem to get the main effect ! There is 
something in it.

--

Now adding boring data:

>>> boring=ones(10001)*0.5
>>> X=numpy.random.random(1)
>>> l=[]
>>> for i in range(200): 
... 
Z=concatenate((numpy.random.random(1)+array(range(1))/1.0,boring))
... l.append( 
sd.correlation((concatenate((X+array(range(1))/1.0,boring)),Z))[2] )
... 
>>> mean(l)
0.712753628489 # r
>>> std(l)
0.00316163649888   # r_err
>>> std(l)/sqrt(len(l))
0.0002235614608

# now:
# 0.6745*(1-r**2)/sqrt(N) = 0.00234459971461   #N=2
# vs M.C. streuung  0.00316163649888 ± 0.0002235614608

=> the boring data has an effect on coef-err which is significantly not 
reflected by the formula 0.6745*(1-r**2)/sqrt(N) 

=> I'll use this formula to get a downside error estimate for the correlation 
coefficient:

--
|  r_err_down ~= 1.0 * (1-r**2)/sqrt(N)  |
--

(until I find a better one respecting the actual distribution of data)

Would be interesting what MATLAB & Octave say ...


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

Re: writing wx code in emacs - how to make easier?

2006-11-12 Thread Diez B. Roggisch
> I would like to write wx code in emacs. For now I'm using python-mode
> but I hope they are stuff which make it easier. I mean some
> autocompletion or abbrevs of such things as wx.ALIGN* wx.EVT_* ... 

Create a TAGS-file using e.g.

find  -type f | xargs -L1 etags --append

Then use the emacs completion-feature M-/

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


Re: Python component model

2006-11-12 Thread sturlamolden

[EMAIL PROTECTED] wrote:

> Having never used java or .NET I'm not sure what you're looking for.

There is a whole generation of computer users out there scared stiff of
using the keyboard. Soon, computers will not have a keyboard at all.
The trend is perhaps more pronounced among managers not writing code
themselves, but "taking decisions" about which tools to use.

The answer to these needs are so-called "RAD tools" like Borland
Delphi, Visual Basic, Visual C# .NET, and perhaps Java's NetBeans.
Instead of writing code, a "programmer" selects "components" from a
menu, drags the component over a "form" and then drops it onto the
"form". A form can e.g. be a web page, a GUI window or just an
invisible abstract container in case the program doesn't have a visual
interface. Components can be visual GUI widgets like buttons and
sliders, but also "invisible" objects like files and sockets. Instead
of creating a file by typing "open" one would "drag 'n drop" a "file
component" from a menu onto the form, and then type in the name in some
sort of "property menu" for the component. If one needs a tcp socket,
one don't type "s = socket(...)" in the code but select an socket from
a menu and drop it over a form.

In order to do this, a RAD tool need some sort of standardised
component model. Sure, it must be able to inspect the component, but
also interpret the methods and members that it finds. The RAD tool must
be able to inspect the model to find out what to "publish" in the
property menu, what event it generates, etc. Typical component
standards used for this is ActiveX (in Visual Basic), .NET in Visual
C#, VCL in Delphi, and JavaBeans in NetBeans. If you build a component
that does not follow the standard, the RAD tool can't use it. For
example in JavaBeans, every pair of method that looks like
"component.setSomething(...)" and "component.getSomething(...)" is
parsed by the RAD tool as the property "Something" and put into the
property meny for the component. The programmer can change the value of
this property by typing into the property menu.

The most extreme RAD tool is LabView, where no code is written at all,
not even event handlers which are still hand coded in the other RAD
tools. In labView, everything is "dragged and dropped", and the dropped
components are connected by "cables" just like a circuit board. There
are even "components" encapsulating for and while loops. If you need a
while loop, you drop a while loop onto the form. If you need a
subroutine, you drop a subroutine onto the form, etc. Nothing is typed.

Does Python need a standard component model like ActiveX, VCL, .NET or
JavaBeans?

First, there are GUI designer's for Python. These include GLADE, QT
Designer and wxGlade. We don't need a Python object model to support
GUI designers. Second, are we really that scared of writing code? Some
obviously are. Why is dropping a socket component preferred over typing
"socket"? Those that want LabView or Visual Basic knows where to find
it.

Python already has "properties". What Python don't have is "events",
but that can be easily implemented (and is implemented in all GUI
toolkits) e.g. using exceptions and references to functions. En event
can be raised by raising an exception. Perhaps we should define an
standard "event" interface just to shut them up? Then we have a
"component model".

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


Re: Fredrik Lundh [was "Re: explicit self revisited"]

2006-11-12 Thread Carsten Haese
On Sat, 2006-11-11 at 23:14 -0800, Doug wrote:
> Fredrik Lundh wrote:
> > Doug wrote:
> >>
> >> Fredrik Lundh wrote:
> >>> Fredrik Lundh wrote:
> >>> > cannot all you clueless trolls who cannot think of a single useful thing
> >>> > to contribute to Python start your own newsgroup?
> >>
> >>> and before anyone complains; please note that they're working through
> >>
> >>>  http://www.effbot.org/pyfaq/design-index.htm
> >>
> >> That site is a bunch of FUD -
> >> The explicit self is there simply because OOP was tacked onto python as
> >> an afterthought.
> >> Why not just be honest about it.  It's too late to change Python's
> >> syntax.  It just means a little extra typing.  If it really bothers
> >> someone, use "s" instead of "self" or else use Ruby.
> >
> > the official FAQ is a bunch of FUD?  are you sure you know what FUD means?
> >
> > 
> 
> You idiot. Putting the word "official" in front of something doesn't
> mean it can't be FUD.

Fredrik doesn't have to prove that the official FAQ isn't FUD. You,
Doug, have to prove that it is, because you accused it of being FUD. 

By your logic, I can prove that you are a piece of cheddar cheese. I
will simply assert that you are a piece of cheddar cheese. You might
respond by making a surprisingly lucid (for a piece of cheddar) argument
that you are a sentient being. To this I will respond "You idiot,
proving that you are a sentient being doesn't mean you can't be a piece
of cheddar." QED.

Since you are too lazy to post the wikipedia link, please allow me:
http://en.wikipedia.org/wiki/Fear%2C_uncertainty_and_doubt

According to that definition, FUD is "a sales or marketing strategy of
disseminating negative (and vague) information on a competitor's
product."

Even if the FAQ could, by a stretch of the imagination, be considered a
sales or marketing strategy, you'd be hard-pressed to find evidence of
it disseminating negative information on a competitor's product. Hence,
it's not FUD.

-Carsten


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


Re: numpy/scipy: correlation

2006-11-12 Thread sturlamolden

First, are you talking about rounding error (due to floating point
arithmetics) or statistical sampling error?

If you are talking about the latter, I suggest you look it up in a
statistics text book. E.g. if x and y are normally distributed, then

t = r * sqrt( (n-2)/(1-r**2) )

has a Student t-distribution with n-2 degrees of freedom. And if you
don't know how to get the p-value from that, you should not be messing
with statistics anyway.

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


Re: explicit self revisited

2006-11-12 Thread Fredrik Lundh
Carsten Haese wrote:

> According to that definition, FUD is "a sales or marketing strategy of
> disseminating negative (and vague) information on a competitor's
> product."

Doug "cheddar cheese" Holton (who has a long history of posting 
seriously confused and/or abusive stuff under a number of aliases) is
a developer of a "competing" language named Boo.

I suppose that in his view, language advocacy is a zero-sum game, so 
positive comments about Python can be considered as FUD against his own 
project.  He's even invented his own del.icio.us tag for this purpose:

 http://del.icio.us/tag/pythonfud



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


Re: How to choose the right GUI toolkit ?

2006-11-12 Thread John Henry
Nice example.


Jussi Salmela wrote:
> John Henry wrote:
> > BTW: I did a search and found the testnotebook example from:
> >
> > http://prdownloads.sourceforge.net/pythoncard/testNotebook.zip?download
> >
> > and tried it out.  There is one error in the widget.py that I have to
> > get around.  Changed from:
> >
> > canvas.setFillColor('gray')
> >
> > to:
> >
> > try:
> > canvas.setFillColor('gray')
> > except:
> > pass
> >
> > and then ran it.   Works!
> >
> > So, yes, you can do Notebook in Python.  I believe what they are saying
> > is that Notebook isn't supported fully (yet) in the resourceeditor.
>
> It's true that the notebook and grid components of wxPython are not
> completely integrated into PythonCard but they can still be used quite
> easily once you figure out how.
>
> The process of figuring out can be made easier by a working example. The
> real life application Blood Pressure Monitor
>
> http://personal.inet.fi/cool/operator/BPMDownload.html
>
> can be used as an example of using the notebook, grid and htmlwin
> widgets in PythonCard.
>
> I use this application to input the pressure values I've registered with
> my own meter and to produce a PDF page with PyChart to hand to my doctor
> to inspect when I visit him twice a year.
>
> Cheers,
> Jussi
> 
> --
> Jussi Salmela
> http://personal.inet.fi/cool/operator/

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


Re: Py3K idea: why not drop the colon?

2006-11-12 Thread Carsten Haese
On Sat, 2006-11-11 at 23:18 -0800, Doug wrote:
> Michael Hobbs wrote:
> > I think the colon could be omitted from every type of compound
> > statement: 'if', 'for', 'def', 'class', whatever. Am I missing anything?
> >
> > Thanks,
> > - Mike
> 
> It is a very good idea as the colon is technically redundant (not
> necessary for parsing, aside from one liners) and actually hurts
> readability (and writeability).  The "evidence" people cite for the
> advantage of using a colon is research done by users of the ABC
> language, python's predecessor.  They forget that A) that was like 20
> years ago,

Research being old does not automatically invalidate it. Old research is
invalidated by newer research that invalidates it.

>  B) the language was designed for children,

http://www.cwi.nl/archive/projects/abc.html does not mention children:
"Originally intended as a language for beginners, it has evolved into a
powerful tool for beginners and experts alike."

>  and C) the
> keywords in ABC are IN ALL CAPS LIKE THIS (hurting readability and
> writeability) and thus adding a colon obviously helps restore some
> readability for users in that case but not in python's.

So what are you saying? In a programming language that doesn't use all
caps keywords, adding colons to block-beginning lines hurts readability,
or it doesn't add any readability?

In any case, that's an assertion that should be backed up by citing
relevant research.

> However, python is far too old to accept any fundamental changes to
> syntax at this point.

The source code for Python is openly available. If you are so convinced
of the added readability from removing the colons, do the world a favor
and make the necessary change, or hire somebody to make the change, to
Python.

-Carsten


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


MemoryError

2006-11-12 Thread Bugra Cakir
Hi,Within a Python program how can we avoid getting "MemoryError" problem ?
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: MemoryError

2006-11-12 Thread Fredrik Lundh
Bugra Cakir wrote:

> Within a Python program how can we avoid getting "MemoryError" problem ?

since you still haven't told us what your program is doing, and where in 
the program you're getting the error, it's a bit hard to tell.



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


Re: numpy/scipy: correlation

2006-11-12 Thread robert
sturlamolden wrote:
> First, are you talking about rounding error (due to floating point
> arithmetics) or statistical sampling error?

About measured data. rounding and sampling errors with special distrutions are 
neglegible. Thus by default assuming gaussian noise in x and y. 
(This may explain that factor of ~0.7 in the rectangle M.C. test)
The (x,y) points may not distribute "nicely" along the assumed regression 
diagonale.

> If you are talking about the latter, I suggest you look it up in a
> statistics text book. E.g. if x and y are normally distributed, then
> 
> t = r * sqrt( (n-2)/(1-r**2) )
> 
> has a Student t-distribution with n-2 degrees of freedom. And if you
> don't know how to get the p-value from that, you should not be messing
> with statistics anyway.

yet too lazy/practical for digging these things from there. You obviously got 
it - out of that, what would be a final estimate for an error range of r (n 
big) ?   
that same "const. * (1-r**2)/sqrt(n)" which I found in that other document ?

The const. ~1 is less the problem. 

My main concern is, how to respect the fact, that the (x,y) points may not 
distribute well along the regression line. E.g. due to the nature of the 
experiment more points are around (0,0) but only few distribute along the 
interesting part of the diagonale and thus few points have great effect on m & 
r. above formulas will possibly not respect that.
I could try a weighting technique, but maybe there is a (commonly used) speedy 
formula for r/r_err respecting that directly?


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


Random image text generation?

2006-11-12 Thread skip

Is there a module out there that will generate an image with a random text
string such as the confirmation images you see on various websites?  I'm
thinking I'm going to have to add that to the forms on the Mojam websites.
Over the past couple weeks we've begun to get lots of spam submission crap.

Thx,

Skip

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


Re: Random image text generation?

2006-11-12 Thread Mitja Trampus
[EMAIL PROTECTED] wrote:
> Is there a module out there that will generate an image with a random text
> string such as the confirmation images you see on various websites?

They're called captcha images or captchas for short.
Googling for "python captcha" returns several hits; see what you like...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Random image text generation?

2006-11-12 Thread Jorge Godoy
[EMAIL PROTECTED] writes:

> Is there a module out there that will generate an image with a random text
> string such as the confirmation images you see on various websites?  I'm
> thinking I'm going to have to add that to the forms on the Mojam websites.
> Over the past couple weeks we've begun to get lots of spam submission crap.

http://captchas.net/sample/python/
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440588

There are specific implementations for Zope, TurboGears and other frameworks. 

-- 
Jorge Godoy  <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Close program built with py2exe

2006-11-12 Thread Steve Ingram
Found out what I'd done, and it wasn't py2exe causug the problem. I wasn't
 closing the main dialog properly, I was calling Close() instead of
Destroy(), so the dialog stayed in memory, basically it was still running.

Thanks for your help,

steve

-Original Message-
From: Fredrik Lundh [mailto:[EMAIL PROTECTED]
Sent: 12 November 2006 12:50
To: [email protected]
Subject: Re: Close program built with py2exe

Steve Ingram wrote:

> I've got a problem with a program I've written and want to distribute.
> It uses a wxPython dialog and I've built a distribution version with
py2exe.
> Problem is when I run the .exe under windows I can only stop the
> program completely using the task manager. When I close the dialog and
> check the task manager, there is still a running process. I think this
> is probably the python interpreter that is still running.
>
> Can't find any help anywhere, does anyone know how to get the dialog
> to kill the process properly??

have you checked if any exceptions occur during application shutdown?

it could be that the GUI toolkit manages to remove all windows, but that
something goes wrong at the application level before the GUI gets around
to shut down the message loop.






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


Re: Random image text generation?

2006-11-12 Thread skip

>> Is there a module out there that will generate an image with a random
>> text string such as the confirmation images you see on various
>> websites?

Mitja> They're called captcha images or captchas for short.  Googling
Mitja> for "python captcha" returns several hits; see what you like...

Thanks.  I'd never heard that term before.  Assuming I can get PIL installed
with freetype support on my Mac the ASPN recipe looks like it will do the
trick.

Skip

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


Re: numpy/scipy: correlation

2006-11-12 Thread Ramon Diaz-Uriarte
On 11/12/06, robert <[EMAIL PROTECTED]> wrote:
> Robert Kern wrote:
> > robert wrote:

(...)
> One would expect the error range to drop simply with # of points. Yet it 
> depends more complexly on the mean value of the coef and on the distribution 
> at all.
> More interesting realworld cases: For example I see a lower correlation on 
> lots of points - maybe coef=0.05 . Got it - or not?  Thus lower coefs require 
> naturally a coef-err to be useful in practice.
>

(...)

> I remember once I saw somewhere a formula for an error range of the corrcoef. 
> but cannot find it anymore.
>
(...)
>
> Does anybody know how this prob.-value is computed/motivated? Such thing 
> would be very helpful for numpy/scipy too.
>
>

There is a transformation of the correlation coefficient that is
distributed as a t-statistic under the null. This was derived a long
way back, and is the usual, standard, way to test for significance of
(attach a p-value to) correlation coefficients.  I do not recall the
formula from top of my head, but I am sure any google search will find
it. And of course, any decent intro stats textbook will also provide
it. You can look in your nearby library for popular textbooks such as
Snedecor & Cochran, or Sokal & Rohlf, or the wonderful "Beyond Anova"
by Miller, which do have the expression.

Since this is such a common procedure all stats programs do provide
for tests of significance of correlation coefficients. A whole bunch
of them are free, and one is widely used: R (check
http://cran.r-project.org). This is an easy way for you to test the
output of your stats code in Python.

Now, since you can do a significance test, you can invert the
procedure and obtain a confidence interval (of whichever width you
want) for your correlation coefficients. This CI will (almost always)
be assymmetric. (And recall that CI do have a not-obvious
interpretation). CI of correlation coefficients are not as common as
p-values, but this is doable too.

The expression (and "improved versions" of it, I think Sokal & Rohlf
show several) is easy to compute. And I bet obtaining the density of a
t-distribution with k d.f. is also available already for Python. So
this part is definitely doable.


Best,

R.

(...)
> Now think of adding 'boring data':
>
> >>> X=[1.,2,3,4]
> >>> Y=[1.,2,3,5]
> >>> sd.correlation((X,Y)) # my old func
> (1.3, -0.5, 0.982707629824)   # m,o,coef
> >>> numpy.corrcoef((X,Y))
> array([[ 1.,  0.98270763],
>[ 0.98270763,  1.]])
> >>> XX=[1.,1,1,1,1,2,3,4]
> >>> YY=[1.,1,1,1,1,2,3,5]
> >>> sd.correlation((XX,YY))
> (1.23684210526, -0.289473684211, 0.988433774639)
> >>>
>
> I'd expect: the little increase of r is ok. But this 'boring data' should not 
> make the error to go down simply ~1/sqrt(N) ...
>
> http://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient#Trivia
> says:
>   In MATLAB, corr(X) calculates Pearsons correlation coefficient along with 
> p-value.
http://links.jstor.org/sici?sici=0162-1459(192906)24%3A166%3C170%3AFFPEOC%3E2.0.CO%3B2-Y
> tells:
>
> probable error of r = 0.6745*(1-r**2)/sqrt(N)
>
> A simple function of r and N - quite what I expected above roughly for the 
> N-only dep.. But thus it is not sensitive to above considerations about 
> 'boring' data. With above example it would spit a decrease of this probable 
> coef-err from
>
> 0.0115628571429 to 0.00548453410954 !
>
> And the absolute size of this error measure seems to be too low for just 4 
> points of data!
>
> The other formula which I remember seeing once was much more sophisticated 
> and used things like sum_xxy etc...
>
>
> Robert
>
>
>
> PS:
>
> my old func is simply hands-on based on
> n,sum_x,sum_y,sum_xy,sum_xx,sum_yy=len(vx),vx.sum(),vy.sum(),(vx*vy).sum(),(vx*vx).sum(),(vy*vy).sum()
> Guess its already fast for large data?
>
>
> Note: numpy.corrcoef strikes on 2 points:
> >>> numpy.corrcoef(([1,2],[1,2]))
> array([[  -1.#IND,   -1.#IND],
>[  -1.#IND,   -1.#IND]])
> >>> sd.correlation(([1,2],[1,2]))
> (1, 0, 1.0)
> >>>
> >>> numpy.corrcoef(([1,2,3],[1,2,3]))
> array([[ 1.,  1.],
>[ 1.,  1.]])
> >>> sd.correlation(([1,2,3],[1,2,3]))
> (1, 0, 1.0)
>
>
> PPS:
>
> A compatible scipy binary (0.5.2?) for numpy 1.0 was announced some weeks 
> back. Think currently many users suffer when trying to get started with 
> incompatible most-recent libs of scipy and numpy.
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
Ramon Diaz-Uriarte
Statistical Computing Team
Structural Biology and Biocomputing Programme
Spanish National Cancer Centre (CNIO)
http://ligarto.org/rdiaz
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Random image text generation?

2006-11-12 Thread Steven D'Aprano
On Sun, 12 Nov 2006 14:56:49 -0600, skip wrote:

> 
> >> Is there a module out there that will generate an image with a random
> >> text string such as the confirmation images you see on various
> >> websites?
> 
> Mitja> They're called captcha images or captchas for short.  Googling
> Mitja> for "python captcha" returns several hits; see what you like...
> 
> Thanks.  I'd never heard that term before.  Assuming I can get PIL installed
> with freetype support on my Mac the ASPN recipe looks like it will do the
> trick.

Keep in mind two serious problems with captchas:

- they're impossible for the blind or people using text-only browsers to
see -- even mere colour blindness can make some captchas impossible to
solve;

- sometimes they're too difficult for even those with perfect vision to
decipher.


Two alternatives:

Instead of displaying an obfuscated image of a nonsense word, display six
randomly chosen photos, where five are of the same thing but not the same
image. E.g. you might show five different kittens and a horse. The user
has to click on the image that is not the same as the others.
State-of-the-art horse-recognition software is not yet in widespread use
by spammers *wink*

For a text only solution, consider putting up a natural language question
such as:

What is the third letter of 'national'?
What is four plus two?
How many eggs in a dozen?
Fill in the blank: Mary had a little  its fleece was white as snow.
Cat, Dog, Apple, Bird. One of those words is a fruit. Which one?

Beware of making the questions too difficult or too specific:

In the third season of Babylon Five, what did Mr Morden ask Lando? 

Also, keep in mind that all captchas are vulnerable to the old
distributed hybrid human-machine network trick: "We'll give you a free
account on our porn site if you spend fifteen minutes a day solving
captchas for our bot network." The only solution to that, I fear, is open
season on spammers and anyone who buys from a spammer.



-- 
Steven.

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


Re: Random image text generation?

2006-11-12 Thread Leif K-Brooks
Steven D'Aprano wrote:
> For a text only solution, consider putting up a natural language question
> such as:
> 
> What is the third letter of 'national'?
> What is four plus two?
> How many eggs in a dozen?
> Fill in the blank: Mary had a little  its fleece was white as snow.
> Cat, Dog, Apple, Bird. One of those words is a fruit. Which one?

That wouldn't work as a true CAPTCHA (Completely Automated *Public* 
Turing test to tell Computers and Humans Apart), since making the list 
of questions and answers public would defeat its purpose.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Random image text generation?

2006-11-12 Thread skip

Steven> Keep in mind two serious problems with captchas:

Steven> - they're impossible for the blind or people using text-only
Steven>   browsers to see -- even mere colour blindness can make some
Steven>   captchas impossible to solve;

Steven> - sometimes they're too difficult for even those with perfect
Steven>   vision to decipher.

Sure, but I'm more concerned in the immediate term with people not
submitting random crap advertising cheap drugs into my concert database.
(I've been running the Musi-Cal concert database for nearly 12 years.  This
is the first time I've ever had to consider resorting to something like
this, and it really pisses me off that I have to.)  I can deal with visual
impairment in other ways (like asking users who can't respond to the captcha
by simply emailing their concert data directly to me).

Steven> Instead of displaying an obfuscated image of a nonsense word,
...

Thanks for the suggestions.  I'll keep them in mind.

Another possibility is to run the submissions through SpamBayes and silently
direct any which score as "unsure" or "spam" to me for review.  Users
wouldn't even need to know their submissions were being scrutinized.

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


Re: numpy/scipy: correlation

2006-11-12 Thread Robert Kern
sturlamolden wrote:
> Robert Kern wrote:
> 
>> The difference between the two models is that the first places no 
>> restrictions
>> on the distribution of x. The second does; both the x and y marginal
>> distributions need to be normal. Under the first model, the correlation
>> coefficient has no meaning.
> 
> That is not correct. The correlation coefficient is meaningful in both
> models, but must be interpreted differently. However, in both cases a
> correlation coefficient of 1 or -1 indicates an exact linear
> relationship between x and y.
> 
> Under the first model ("linear regression"), the squared correlation
> coefficient is the "explained variance", i.e. the the proportion of y's
> variance accounted for by the model y = m*x  + o.

Point.

-- 
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: Random image text generation?

2006-11-12 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> Another possibility is to run the submissions through SpamBayes and silently
> direct any which score as "unsure" or "spam" to me for review.  Users
> wouldn't even need to know their submissions were being scrutinized.

there's also:

 http://akismet.com/

python interface here:

 http://kemayo.wordpress.com/2005/12/02/akismet-py/



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


Re: numpy/scipy: correlation

2006-11-12 Thread Robert Kern
robert wrote:

> I remember once I saw somewhere a formula for an error range of the corrcoef. 
> but cannot find it anymore. 

There is no such thing as "a formula for an error range" in a vacuum like that.
Each formula has a model attached to it. If your data does not follow that
model, then any such estimate of the error of your estimate is meaningless.

sturlamolden pointed out to me that I was wrong in thinking that the correlation
coefficient was meaningless in the linear regression case. However, the error
estimate that is used for bivariate normal correlation coefficients will almost
certainly not apply to "correlation coefficient qua sqare root of the fraction
of y's variance explained by the linear model". In that context, the
"correlation coefficient" is not an estimate of some parameter. It has no
uncertainty attached to it.

> http://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient#Trivia
> says:
>   In MATLAB, corr(X) calculates Pearsons correlation coefficient along with 
> p-value.
> 
> Does anybody know how this prob.-value is computed/motivated? Such thing 
> would be very helpful for numpy/scipy too.

scipy.stats.pearsonr()

As with all such frequentist hypothesis testing nonsense, one takes the null
hypothesis (in this case, a bivariate normal distribution of points with 0
correlation), finds the distribution of the test statistic given the number of
points sampled, and then finds the probability of getting a test statistic "at
least as extreme" as the test statistic you actually got.

> my old func is simply hands-on based on 
> n,sum_x,sum_y,sum_xy,sum_xx,sum_yy=len(vx),vx.sum(),vy.sum(),(vx*vy).sum(),(vx*vx).sum(),(vy*vy).sum()
> Guess its already fast for large data?

You really want to use a 2-pass algorithm to avoid numerical problems.

> Note: numpy.corrcoef strikes on 2 points:
 numpy.corrcoef(([1,2],[1,2]))
> array([[  -1.#IND,   -1.#IND],
>[  -1.#IND,   -1.#IND]])

This was fixed in SVN.

> PPS:
> 
> A compatible scipy binary (0.5.2?) for numpy 1.0 was announced some weeks 
> back. Think currently many users suffer when trying to get started with 
> incompatible most-recent libs of scipy and numpy.

Well, go ahead and poke the people that said they would have a Windows binary
ready. Or provide one yourself.

-- 
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: numpy/scipy: correlation

2006-11-12 Thread sturlamolden

robert wrote:

> > t = r * sqrt( (n-2)/(1-r**2) )

> yet too lazy/practical for digging these things from there. You obviously got 
> it - out of that, what would be a final estimate for an error range of r (n 
> big) ?
> that same "const. * (1-r**2)/sqrt(n)" which I found in that other document ?

I gave you th formula. Solve for r and you get the confidence interval.
You will need to use the inverse cumulative Student t distribution.

Another quick-and-dirty solution is to use bootstrapping.

from numpy import mean, std, sum, sqrt, sort
from numpy.random import randint

def bootstrap_correlation(x,y):
   idx = randint(len(x),size=(1000,len(x)))
   bx = x[idx] # reasmples x with replacement
   by = y[idx] # resamples y with replacement
   mx = mean(bx,1)
   my = mean(by,1)
   sx = std(bx,1)
   sy = std(by,1)
   r = sort(sum( (bx - mx.repeat(len(x),0).reshape(bx.shape)) *
  (by - my.repeat(len(y),0).reshape(by.shape)), 1) /
((len(x)-1)*sx*sy))
   #bootstrap confidence interval (NB! biased)
   return (r[25],r[975])


> My main concern is, how to respect the fact, that the (x,y) points may not 
> distribute well along the regression line.

The bootstrap is "non-parametric" in the sense that it is distribution
free.

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


Re: Random image text generation?

2006-11-12 Thread Ben Finney
Leif K-Brooks <[EMAIL PROTECTED]> writes:

> Steven D'Aprano wrote:
> > For a text only solution, consider putting up a natural language
> > question such as:
> > 
> > What is the third letter of 'national'?
> > What is four plus two?
> > How many eggs in a dozen?
> > Fill in the blank: Mary had a little  its fleece was white as snow.
> > Cat, Dog, Apple, Bird. One of those words is a fruit. Which one?
>
> That wouldn't work as a true CAPTCHA (Completely Automated *Public*
> Turing test to tell Computers and Humans Apart), since making the
> list of questions and answers public would defeat its purpose.

The "Public" part of a CAPTCHA is the algorithm. The data consumed and
produced by the algorithm don't need to be publicly correlated -- and
indeed shouldn't be, for exactly the reason you state.

-- 
 \"To me, boxing is like a ballet, except there's no music, no |
  `\choreography, and the dancers hit each other."  -- Jack Handey |
_o__)  |
Ben Finney

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


Re: numpy/scipy: correlation

2006-11-12 Thread sturlamolden

While I am at it, lets add the bootstrap estimate of the standard error
as well.




from numpy import mean, std, sum, sqrt, sort, corrcoef, tanh, arctanh
from numpy.random import randint

def bootstrap_correlation(x,y):
   idx = randint(len(x),size=(1000,len(x)))
   bx = x[idx]
   by = y[idx]
   mx = mean(bx,1)
   my = mean(by,1)
   sx = std(bx,1)
   sy = std(by,1)
   r = sort(sum( (bx - mx.repeat(len(x),0).reshape(bx.shape)) *
   (by - my.repeat(len(y),0).reshape(by.shape)), 1)
/ ((len(x)-1)*sx*sy))
   #bootstrap confidence interval (NB! biased)
   conf_interval = (r[25],r[975])
   #bootstrap standard error using Fisher's z-transform  (NB! biased)
   std_err = tanh(std(arctanh(r))*(len(r)/(len(r)-1.0)))
   return (std_err, conf_interval)

Since we are not using bias corrected and accelerated bootstrap, the
standard error are more meaningful, although both estimates are biased.

I said that the boostrap is "distribution free". That is not quite the
case either. The assumed distribution is the provided sample
distribution, i.e. a sum of Dirac delta functions. Often this is not a
very sound assumption, and the bootstrap must then be improved e.g.
using the BCA procedure. That is particularly important for confidence
intervals, but not so much for standard errors. However for a
quick-and-dirty standard error estimate, we can just ignore the small
bias.

Now, if you wonder why I used the standard deviation to obtain the
standard error (without dividing by sqrt(n) ), the answer is that the
standard error is the standard deviation of an estimator. As we have
1000 samples from the correlation's sampling distribution in r, we get
the "standard error of the correlation" by taking the standard
deviation of r. The z-transform is required before we can compute mean
and standard deviations of correlations.

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


Re: Random image text generation?

2006-11-12 Thread Ben Finney
[EMAIL PROTECTED] writes:

> Is there a module out there that will generate an image with a random text
> string such as the confirmation images you see on various websites?

The W3C recommends more-accessible alternatives to vision-based CAPTCHAs:

http://www.w3.org/TR/turingtest/>

-- 
 \   "A free society is one where it is safe to be unpopular."  -- |
  `\ Adlai Ewing Stevenson |
_o__)  |
Ben Finney

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


Re: Random image text generation?

2006-11-12 Thread Leif K-Brooks
Ben Finney wrote:
> Leif K-Brooks <[EMAIL PROTECTED]> writes:
> 
>> Steven D'Aprano wrote:
>>> For a text only solution, consider putting up a natural language
>>> question 
>> That wouldn't work as a true CAPTCHA (Completely Automated *Public*
>> Turing test to tell Computers and Humans Apart), since making the
>> list of questions and answers public would defeat its purpose.
> 
> The "Public" part of a CAPTCHA is the algorithm. The data consumed and
> produced by the algorithm don't need to be publicly correlated -- and
> indeed shouldn't be, for exactly the reason you state.

When the CAPTCHA is based entirely on a fixed list of questions and 
answers, I think it's reasonable to treat that list as part of the 
algorithm, since the CAPTCHA couldn't function without it. Similarly, I 
think most people would consider an image-based CAPTCHA for which the 
algorithm but not the fonts were available to be non-public
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Find interface associated with default route?

2006-11-12 Thread Giovanni Bajo
Neal Becker wrote:

> A quick strace reveals that 'route' just reads /proc/net/route, so:
>
> def get_default_if():
> f = open ('/proc/net/route', 'r')
> for line in f:
> words = string.split (line)
> dest = words[1]
> try:
> if (int (dest) == 0):
> interf = words[0]
> break
> except ValueError:
> pass
> return interf

And if you acknowledge that /proc/net/route is a CSV file, you can be more
terse and clear:

>>> import csv
>>> def get_default_if():
... f = open('/proc/net/route')
... for i in csv.DictReader(f, delimiter="\t"):
... if long(i['Destination'], 16) == 0:
... return i['Iface']
... return None
...
>>>
>>> get_default_if()
'ppp0'

-- 
Giovanni Bajo


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


Re: explicit self revisited

2006-11-12 Thread Fredrik Lundh

> I suppose that in his view, language advocacy is a zero-sum game, so 
> positive comments about Python can be considered as FUD against his own 
> project.  He's even invented his own del.icio.us tag for this purpose:
> 
>  http://del.icio.us/tag/pythonfud

now at:

 http://del.icio.us/tag/python-fud



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


format requires a mapping?

2006-11-12 Thread ronrsr
what is python trying to tell me here?  does it have to do with
formatting the string.

Keywords and Zinger are fields in my database.

print """
Keywords
Zinger





TypeError:  format requires a mapping




thanks much in advance, 

-rsr-

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


Re: format requires a mapping?

2006-11-12 Thread Fredrik Lundh
ronrsr wrote:

> what is python trying to tell me here?  does it have to do with
> formatting the string.
> 
> Keywords and Zinger are fields in my database.
> 
> print """
> Keywords
> Zinger
> 
> 
> 
> 
> 
> TypeError:  format requires a mapping

portions of your code and the traceback appears to be missing, so it's a 
bit hard to tell what you're really doing here, but that error message 
usually means that you're using the % string formatting operator with 
named placeholders in the string template, but with something that's not 
a dictionary as the data.  an example:

 >>> "%(name)s" % 10
Traceback (most recent call last):
   File "", line 1, in 
TypeError: format requires a mapping

either switch to positional markers, or put the data in a dictionary (or 
any other object that implements the mapping interface).



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


Re: reduce to be removed?

2006-11-12 Thread George Sakkis
Dustan wrote:

> Alright, I can see I'm a bit outvoted here. I tried your suggestions
> and it worked fine.
>
> I'll also try to consider in the future that part of the problem might
> be lack of information conveyed on my part.

If you insist on one-liners, it can be done without sum(), though it
probably doesn't buy you much in readability:

from itertools import chain
[list(chain(*row)) for row in foo]

By the way, if this was not a toy example and you're doing serious work
with n-dimensional arrays, make yourself a favor and install NumPy;
it's usually both faster and more elegant for array manipulations than
pure python.

George

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


Python 3000 idea -- + on iterables -> itertools.chain

2006-11-12 Thread John Reese
It seems like it would be clear and mostly backwards compatible if the
+ operator on any iterables created a new iterable that iterated
throught first its left operand and then its right, in the style of
itertools.chain.  This would allow summation of generator expressions,
among other things, to have the obvious meaning.

Any thoughts?  Has this been discussed before?  I didn't see it
mentioned in PEP 3100.

The exception to the compatibility argument is of course those
iterables for which + is already defined, like tuples and lists, for
that set of code that assumes that the result is of that same type,
explicitly or implicitly by calling len or indexing or whathaveyou.
In those cases, you could call tuple or list on the result.  There are
any number of other things in Python 3000 switching from lists to
one-at-a-time iterators, like dict.items(), so presumably this form of
incompatibility isn't a showstopper.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does this code crash python?

2006-11-12 Thread Scott David Daniels
[EMAIL PROTECTED] wrote:
>...

>>> if float(seconds[0]) < 10: seconds[0] = '0' +
>>> seconds[0][:-1]
>>> if float(seconds[1]) < 10: seconds[1] = '0' +
>>> seconds[1][:-1]I've not handled leading 0s on the seconds field (I 
>>> tried, but can't
>> figure out how to specify zero-filled field width for floats -- works
>> for integers)
> 
> I ran into the same problem, thats why I did it the way I did, instead
> of continuing to wrestle with python's string formatting.

For this portion, you could quite simply:

  totalsecs = int(whatever)
  print '%02d:%02d' % divmod(totalsecs, 60)

Or, depending on your leading zero requirements:

  totalsecs = int(whatever)
  print '%2d:%02d' % divmod(totalsecs, 60)

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


Re: Python 3000 idea -- + on iterables -> itertools.chain

2006-11-12 Thread Fredrik Lundh
John Reese wrote:

> It seems like it would be clear and mostly backwards compatible if the
> + operator on any iterables created a new iterable that iterated
> throught first its left operand and then its right, in the style of
> itertools.chain. 

you do know that "iterable" is an informal interface, right?  to what 
class would you add this operation?



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


article on Python 2.5 features

2006-11-12 Thread Beliavsky
A Parade of New Features Debuts in Python 2.5
by Gigi Sayfan
"Python 2.5 still has the smell of fresh paint but it's the perfect
time to drill down on the most important new features in this
comprehensive release. Read on for detailed explanations and examples
of exception handling, resource management, conditional expressions,
and more."

The full article is at
http://www.devx.com/webdev/Article/33005/0/page/1 .

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


Re: Python 3000 idea -- + on iterables -> itertools.chain

2006-11-12 Thread George Sakkis
Fredrik Lundh wrote:

> John Reese wrote:
>
> > It seems like it would be clear and mostly backwards compatible if the
> > + operator on any iterables created a new iterable that iterated
> > throught first its left operand and then its right, in the style of
> > itertools.chain.
>
> you do know that "iterable" is an informal interface, right?  to what
> class would you add this operation?
>
> 

The base object class would be one candidate, similarly to the way
__nonzero__ is defined to use __len__, or __contains__ to use __iter__.

Alternatively, iter() could be a wrapper type (or perhaps mixin)
instead of a function, something like:

from itertools import chain, tee, islice

import __builtin__
_builtin_iter = __builtin__.iter

class iter(object):

def __init__(self, iterable):
self._it = _builtin_iter(iterable)

def __iter__(self):
return self
def next(self):
return self._it.next()

def __getitem__(self, index):
if isinstance(index, int):
try: return islice(self._it, index, index+1).next()
except StopIteration:
raise IndexError('Index %d out of range' % index)
else:
start,stop,step = index.start, index.stop, index.step
if start is None: start = 0
if step is None: step = 1
return islice(self._it, start, stop, step)

def __add__(self, other):
return chain(self._it, other)
def __radd__(self,other):
return chain(other, self._it)

def __mul__(self, num):
return chain(*tee(self._it,num))

__rmul__ = __mul__

__builtin__.iter = iter


if __name__ == '__main__':
def irange(*args):
return iter(xrange(*args))

assert list(irange(5)[:3]) == range(5)[:3]
assert list(irange(5)[3:])  == range(5)[3:]
assert list(irange(5)[1:3]) == range(5)[1:3]
assert list(irange(5)[3:1]) == range(5)[3:1]
assert list(irange(5)[:])   == range(5)[:]
assert irange(5)[3] == range(5)[3]

s = range(5) + range(7,9)
assert list(irange(5) + irange(7,9)) == s
assert list(irange(5) +  range(7,9)) == s
assert list(range(5)  + irange(7,9)) == s

s = range(5) * 3
assert list(irange(5) * 3) == s
assert list(3 * irange(5)) == s


George

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


boost::python embedding example running error

2006-11-12 Thread could . net
I use boost 1.33_1, there's an example on boost::python named
embedding.cpp. When I tried to build and run it in visual studio 2005,
I got an error on this line:

std::string hello() { return python::call_method(self,
"hello"); }

It's a back ptr error.

I don't know where to ask this question so I came to python group. Has
anyone run this example successfully? Thanks in advance.

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


how do i map this?

2006-11-12 Thread ronrsr
I think I am passing the wrong argument to the Print_row routine:



Traceback (most recent call last):
  File "index.py", line 91, in ?
zhtml.print_row(record)
  File "/usr/www/users/homebase/realprogress/zingers/zhtml.py", line
154, in pri
nt_row
print """
TypeError: format requires a mapping
[EMAIL PROTECTED]



routine from zhtml.py:

#row is a dictionary with keys: zid, keywords, citation, quotation
def print_row(row):
   print """
  %(keywords)s
  
  %(quotation)s
  
  %(citation)s
  
  
  
  
  """


code from index.py:


cursor.execute(querystring);
# get the resultset as a tuple
result = cursor.fetchall()
# iterate through resultset
for record in result:
  print record[0] , "-->", record[1]

#zq = zc.query(querystring).dictresult()

#HTML

import zhtml
zhtml.print_start_html()
zhtml.print_header("Frankie's Zingers")

if form.has_key("printview"):
   print ("thenxx")
   zhtml.printp_start_table()
   zhtml.printp_title_row()
   for record in result:
  zhtml.printp_row(record[row])
else:
#   print ("xelsex",record[1]);
   zhtml.print_top_controls(k=k,c=c,q=q)
   zhtml.print_start_table()
   zhtml.print_title_row()
   zhtml.print_search_row(k=k,c=c,q=q)
   for record in result:


  print(record);
  zhtml.print_row(record)

zhtml.print_end_table()
zhtml.print_end_html()






how do i go about mapping that, if tha'ts what I need to do.
thanks again for your help.

bests, 

-rsr-

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


Re: how do i map this?

2006-11-12 Thread Ben Finney
"ronrsr" <[EMAIL PROTECTED]> writes:

> #row is a dictionary with keys: zid, keywords, citation, quotation
> def print_row(row):
>print """
>   %(keywords)s
>   
>   %(quotation)s
>   
>   %(citation)s
>   
>name="updateform" enctype="application/x-www-form-urlencoded"
> method="GET"> type="submit" value="Edit">
>   
>   
>   """

You're printing a string, and never using that 'row' parameter.

Perhaps this will help illustrate:

>>> print "spam %(foo)s eggs"
spam %(foo)s eggs
>>> print "spam %(foo)s eggs" % {'foo': "Wortle"}
spam Wortle eggs

The 'print' statement doesn't care about the format specifiers; it
just wants a string expression. It's the formatting operator, '%',
that looks for them.

http://docs.python.org/lib/typesseq-strings.html>

-- 
 \   "When I was little, my grandfather used to make me stand in a |
  `\   closet for five minutes without moving. He said it was elevator |
_o__) practice."  -- Steven Wright |
Ben Finney

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


Re: how do i map this?

2006-11-12 Thread John Machin

Ben Finney wrote:
> "ronrsr" <[EMAIL PROTECTED]> writes:
>
> > #row is a dictionary with keys: zid, keywords, citation, quotation
> > def print_row(row):
> >print """
> >   %(keywords)s
> >   
> >   %(quotation)s
> >   
> >   %(citation)s
> >   
> >> name="updateform" enctype="application/x-www-form-urlencoded"
> > method="GET"> > type="submit" value="Edit">
> >   
> >   
> >   """
>
> You're printing a string, and never using that 'row' parameter.

If that is so, why is he getting that message "TypeError: format
requires a mapping"?

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


Re: how do i map this?

2006-11-12 Thread Gabriel G

At Monday 13/11/2006 01:55, John Machin wrote:


Ben Finney wrote:
> "ronrsr" <[EMAIL PROTECTED]> writes:
>
> > #row is a dictionary with keys: zid, keywords, citation, quotation
> > def print_row(row):
> >print """
> >   [...]
> >   """
>
> You're printing a string, and never using that 'row' parameter.

If that is so, why is he getting that message "TypeError: format
requires a mapping"?


Apparently the posted code doesn't match the actual code. If that 
print_row() matched the stack trace, should say % row at the end.

Perhaps there is another function print_row?
Or you cut something from the end?


--
Gabriel Genellina
Softlab SRL 


__
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis! 
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: how do i map this?

2006-11-12 Thread John Machin
ronrsr wrote:
> I think I am passing the wrong argument to the Print_row routine:

Well, yes,  that is what the error message is telling you.
It is also what Fredrik Lundh told you only a couple of hours ago.
He also told you what to do to fix it, at a high level.
Below is my attempt to explain at a lower level.
If you don't understand, please *reply* to my message; *don't* start a
new topic as though it were a totally fresh problem.

Now read on ...

>
>
>
> Traceback (most recent call last):
>   File "index.py", line 91, in ?
> zhtml.print_row(record)
>   File "/usr/www/users/homebase/realprogress/zingers/zhtml.py", line
> 154, in pri
> nt_row
> print """
> TypeError: format requires a mapping
> [EMAIL PROTECTED]
>
>
>
> routine from zhtml.py:
>
> #row is a dictionary with keys: zid, keywords, citation, quotation
> def print_row(row):
>print """
>   %(keywords)s
>   
>   %(quotation)s
>   
>   %(citation)s
>   
>name="updateform" enctype="application/x-www-form-urlencoded"
> method="GET"> type="submit" value="Edit">
>   
>   
>   """

This cannot be the code that was executed -- it would need to be
followed by
% row
for it to produce the error message that you received.

>
>
> code from index.py:
>
>
> cursor.execute(querystring);
> # get the resultset as a tuple
> result = cursor.fetchall()
> # iterate through resultset
> for record in result:
>   print record[0] , "-->", record[1]

"record" looks like a tuple, not a dictionary.

>
> #zq = zc.query(querystring).dictresult()
>
> #HTML
>
> import zhtml
> zhtml.print_start_html()
> zhtml.print_header("Frankie's Zingers")
>
> if form.has_key("printview"):
>print ("thenxx")
>zhtml.printp_start_table()
>zhtml.printp_title_row()
>for record in result:
>   zhtml.printp_row(record[row])
> else:
> #   print ("xelsex",record[1]);
>zhtml.print_top_controls(k=k,c=c,q=q)
>zhtml.print_start_table()
>zhtml.print_title_row()
>zhtml.print_search_row(k=k,c=c,q=q)
>for record in result:
>
>
>   print(record);

print is a statement, not a function; you meant
print record
Instead of that, do this
print type(record)
print repr(record)

You will find that "record" is a tuple, not a dictionary
Without changing the code in the zhtml module, you need to make a
dictionary, for example (untested):

adict = {}
for key, inx in zip("zid keywords citation quotation".split(), (0, 1,
2, 3)):
adict[key] = record[inx]
zhtml.print_row(adict)
where (0, 1, 2, 3) are the positions of the 4 fields in record --
change the numbers as necessary to match reality.

Alternatively (sketch):

(1) unpack the tuple e.g.
 zid, keywords, citation, quotation = record
# Add names for any other fields that exist.
# Change the order as necessary to match reality.
(2) call a changed zhtml routine:
zhtml.print_row(zid, keywords, citation, quotation)
(3) re-jig the zhtml.print_row routine
 def print_row(zid, keywords, citation, quotation):
print """
   %s
   
   %s
etc etc
""" % (keywords, quotation, citation, zid)

>   zhtml.print_row(record)
> 
> zhtml.print_end_table()
> zhtml.print_end_html()

HTH,
John

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


Re: how do i map this?

2006-11-12 Thread Ben Finney
"John Machin" <[EMAIL PROTECTED]> writes:

> Ben Finney wrote:
> > You're printing a string, and never using that 'row' parameter.
>
> If that is so, why is he getting that message "TypeError: format
> requires a mapping"?

No idea. Probably because what the poster showed us is not code that
shows the problem described.

Original poster (and everyone who wants help with their program
behaving unexpectedly): please ensure that you post a complete,
minimal example of code that exhibits the unexpected behaviour.

-- 
 \ "Room service? Send up a larger room."  -- Groucho Marx |
  `\   |
_o__)  |
Ben Finney

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


Re: boost::python embedding example running error

2006-11-12 Thread Roman Yakovenko
On 12 Nov 2006 19:10:24 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> I use boost 1.33_1, there's an example on boost::python named
> embedding.cpp. When I tried to build and run it in visual studio 2005,
> I got an error on this line:
>
> std::string hello() { return python::call_method(self,
> "hello"); }
>
> It's a back ptr error.
>
> I don't know where to ask this question so I came to python group.

Boost.Python mailing list: http://mail.python.org/mailman/listinfo/c++-sig/

More resources: http://www.language-binding.net/pyplusplus/links.html


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


-- 
Roman Yakovenko
C++ Python language binding
http://www.language-binding.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3000 idea -- + on iterables -> itertools.chain

2006-11-12 Thread Fredrik Lundh
George Sakkis wrote:

> The base object class would be one candidate, similarly to the way
> __nonzero__ is defined to use __len__, or __contains__ to use __iter__.
> 
> Alternatively, iter() could be a wrapper type (or perhaps mixin)
> instead of a function, something like:

so you're proposing to either make *all* objects respond to "+", or 
introduce limited *iterator* algebra.

not sure how that matches the OP's wish for "mostly backwards 
compatible" support for *iterable* algebra, really...

(iirc, GvR has shot down a few earlier "let's provide sugar for iter- 
tools" proposals.  no time to dig up the links right now, but it's in 
the python-dev archives, somewhere...)



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


logging

2006-11-12 Thread [EMAIL PROTECTED]
Hi all !
How to remove a logger ?
There si no logging.removeLogger(name) method.
I've a lot of objects that create loging.
When objects are destroyed, associated logger are not. This create
memory leak...

Thanks for any idea.

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