Re: Problem redirecting stdin on Windows

2005-05-25 Thread vincent wehren
"aurora" <[EMAIL PROTECTED]> schrieb im Newsbeitrag 
news:[EMAIL PROTECTED]
| On Windows (XP) with win32 extension installed, a Python script can be
| launched from the command line directly since the .py extension is
| associated with python. However it fails if the stdin is piped or
| redirected.
|
| Assume there is an echo.py that read from stdin and echo the input.
|
|
|
| Launching from command line directly, this echos input from keyboard:
|
|   echo.py
|
|
|
| But it causes an error if the stdin is redirected
|
|   echo.py http://mail.python.org/pipermail/python-bugs-list/2004-August/024920.html

--
Vincent Wehren


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


Re: Improve the performance of a loop

2005-05-25 Thread Peter Otten
[EMAIL PROTECTED] wrote:

> What is the fastest way to code this particular block of code below..
> I used numeric for this currently and I thought it should be really
> fast..
> But, for large sets of data (bx and vbox) it takes a long time and I
> would like to improve.
> 
> vbox = array(m) (size: 1000x1000 approx)
> for b in bx:
> vbox[ b[1], b[0]:b[2] ] = 0
> vbox[ b[3], b[0]:b[2] ] = 0
> vbox[ b[1]:b[3], b[0] ] = 0
> vbox[ b[1]:b[3], b[2] ] = 0
> 
> and vbox is a 2D array
> where bx is of form [( int,int,int,int),() ]

You can try

for b0, b1, b2, b3 in bx:
vbox[b1:b3, b0:b2+1:b2-b0] = 0
vbox[b1:b3+1:b3-b1, b0:b2] = 0

By the way, the bottom/right cell of your box remains nonzero. Is that
intentional?

Peter

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


Weekly Python Patch/Bug Summary

2005-05-25 Thread Kurt B. Kaiser
Patch / Bug Summary
___

Patches :  342 open ( +3) /  2839 closed ( +1) /  3181 total ( +4)
Bugs:  936 open ( -2) /  4974 closed (+12) /  5910 total (+10)
RFE :  189 open ( +2) /   159 closed ( +2) /   348 total ( +4)

New / Reopened Patches
__

optparse documentation bug fixes  (2005-05-18)
   http://python.org/sf/1204347  opened by  Barry A. Warsaw

Bugfix for signal-handler on x64 Platform  (2005-05-20)
   http://python.org/sf/1205436  opened by  André Fritzsche

updates for the compiler package  (2005-05-21)
   http://python.org/sf/1206077  opened by  Stelios

An URL for UnicodeData File Format 3.2 has changed.  (2005-05-24)
   http://python.org/sf/1207985  opened by  Darek Suchojad

Patches Closed
__

workaround deprecated ostat structure in   (2005-05-17)
   http://python.org/sf/1203329  closed by  loewis

New / Reopened Bugs
___

Documentation error?  (2005-05-18)
   http://python.org/sf/1204734  opened by  John Eikenberry

urllib has spurious print statement  (2005-05-20)
   http://python.org/sf/1205544  opened by  Stuart Wray

Compile fails on Darwin8 with --with-cxx=g++  (2005-05-20)
   http://python.org/sf/1205568  opened by  Robert M. Zigweid

wrong location for math lib with --prefix  (2005-05-20)
   http://python.org/sf/1205736  opened by  Thomas Richter

IDLE 1.0.5 (Python 2.3.5) crashes under Windows  (2005-05-21)
   http://python.org/sf/1206232  opened by  Torsten Bronger

weakref cannot handle bound methods (in contrast to docu)  (2005-05-22)
   http://python.org/sf/1206537  opened by  Raik Gruenberg

class property fset not working  (2005-05-24)
   http://python.org/sf/1207379  opened by  Master_Jaf

installer ignores changed installation directory  (2005-05-24)
   http://python.org/sf/1207466  opened by  Blubb Fallo

Issue in grammar  (2005-05-24)
   http://python.org/sf/1207501  opened by  venkat manian

Issue in grammar  (2005-05-24)
CLOSED http://python.org/sf/1207509  opened by  venkat manian

Bugs Closed
___

Problem with recursion in dict (crash with core dump)  (2005-05-13)
   http://python.org/sf/1201456  closed by  vys

Windows msi installer fails on virtual drives  (2005-05-12)
   http://python.org/sf/1200287  closed by  loewis

urllib2 authentication redirection error(?)  (2004-11-21)
   http://python.org/sf/1070735  closed by  allanbwilson

No documentation for urllib2 exception classes  (2004-04-29)
   http://python.org/sf/944407  closed by  fresh

file("foo", "wU") is silently accepted  (2004-06-05)
   http://python.org/sf/967182  closed by  montanaro

UnboundLocalError in cgitb.py  (2003-12-16)
   http://python.org/sf/861340  closed by  montanaro

Python 2.4.1 Installer ended prematurely  (2005-05-11)
   http://python.org/sf/1199947  closed by  loewis

xml.dom.minidom.Node.removeChild() doesn't remove  (2005-03-06)
   http://python.org/sf/1157901  closed by  mkempka

csv writer bug on windows  (2004-04-29)
   http://python.org/sf/944890  closed by  montanaro

Importing anydbm generates exception if _bsddb unavailable  (2003-05-02)
   http://python.org/sf/731501  closed by  montanaro

Explicit interp reference during build fails  (2003-07-08)
   http://python.org/sf/768068  closed by  montanaro

Issue in grammar  (2005-05-24)
   http://python.org/sf/1207509  closed by  mwh

New / Reopened RFE
__

Let shift operators take any integer value  (2005-05-19)
   http://python.org/sf/1205239  opened by  David Albert Torpey

Right Click Context Menu  (2005-05-24)
   http://python.org/sf/1207589  opened by  Mike Foord

Clipboard Cleared on Close  (2005-05-24)
   http://python.org/sf/1207592  opened by  Mike Foord

Bottom Scroll Bar  (2005-05-24)
   http://python.org/sf/1207613  opened by  Mike Foord

RFE Closed
__

enhancing os.chown functionality  (2005-05-12)
   http://python.org/sf/1200804  closed by  loewis

"replace" function should accept lists.  (2005-04-17)
   http://python.org/sf/1184678  closed by  loewis

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


Re: evaluated function defaults: stored where?

2005-05-25 Thread John Machin
David Isaac wrote:
> Default parameter values are evaluated once when the function definition is
> executed.
> Where are they stored?

A good bet for where to start looking for the storage would be as an 
attribute of the function object. From this point, there are two paths:

(a) Make a function and inspect it:

 >>> def fun(a,b=42,c=666):
...pass
...
 >>> dir(fun)
['__call__', '__class__', '__delattr__', '__dict__', '__doc__', 
'__get__', '__getattribute__', '__hash__', '__init__', '__module__',
  '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', 
'__setattr__', '__str__', 'func_closure', 'func_code', 'func_defa
ults', 'func_dict', 'func_doc', 'func_globals', 'func_name']
 >>> fun.func_defaults
(42, 666)
 >>>


(b) Become familiar with the general structure of the manuals.
By process of elimination, the Python Reference Manual would be a good 
place to start for a question of this type.
Inside that manual, this is a likely candidate:
"""
3.2 The standard type hierarchy
Below is a list of the types that are built into Python.
"""

I'll leave you to read further ...

>  (A guess: in a dictionary local to the function.)

As you've seen the default values are contained in a tuple. So where are 
the keys of the mapping {'b': 42, 'c': 666} that you expected? Suppose 
*you* do the extra research and report back ...

> Where is this documented?

See above.

> 
> As a Python newbie I found this behavior quite surprising.

Surprisingly good, bad or just different? Do you have alternate 
non-surprising behaviours in mind?

> Is it common in many other languages?

That makes two of us who don't know and haven't done any research :-)
My impression based on a limited number of different languages that I've 
worked with or looked at is that Python's apparatus is the best I've 
seen; YMMV.

> Is it unsurprising if I look at it right?

Yes; in general this is true across many domains for a very large number 
of referents of "it" :-)

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


Re: vim configuration for python

2005-05-25 Thread Gary Johnson
In comp.editors Leonard J. Reder <[EMAIL PROTECTED]> wrote:
> Hello,
> 
> I am looking at configuring vim for Python.  Most importantly I
> need 4 spaces when the tab is hit.  I am searching and getting
> a bit confused.  Does anyone know where I can find a set of
> ready made .vimrc and ~/.vim/syntax/python.vim.  If could find
> c.vim and cpp.vim these would be useful also.

The vim distribution already contains python.vim files for syntax, 
indenting and general configuration.  It also contains a similar set 
of c.vim and cpp.vim files.  These should all be in the appropriate 
subdirectories under $VIMRUNTIME.  You might take a look at

:help ftplugins
:help filetype-indent-on
:help filetype-overview
:help usr_43.txt
:help usr_06.txt

If the files supplied with vim for Python don't do what you want, 
you might also search the scripts and tips at vim.sf.net for 
"python".

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


Re: __init__() not called automatically

2005-05-25 Thread Sakesun Roykiattisak
Does c++ call base class constructor automatically ??
If I'm not wrong, in c++ you also have to call base class constructor 
explicitly.
Python just do not enforce the rule. You can leave it as desire.

BTW, I've once been an C++ expert.  Knowing python kill that skill.
However, I'm not regret.  I have c++ compiler installed, but I don't even
bother validate my last paragraph assertion.  Too disgusting.  ;)

Sriek wrote:

>Tim pointed out  rightly that i missed out the most crucial part of my
>question.
>i should have said that __init__() is not called automatically only for
>the inheritance hierarchy. we must explicitly call all the base class
>__init__() fuctions explicitly.
> i wanted a reason for that.
>Thanks Tim.
>  
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Checking for a full house

2005-05-25 Thread Paul Rubin
"Raymond Hettinger" <[EMAIL PROTECTED]> writes:
> Your use case for gathering roll statistics probably needs a more
> general solution:
> 
> hands = {
> (1,1,1,1,1): 'nothing',
> (1,1,1,2): 'one pair',
> (1,2,2): 'two pair',
> (1,1,3): 'three of a kind',
> (2,3): 'full house',
> (1,4): 'four of a kind',
> (5): 'flush (five of a kind)'
> }
> 
> def eval_hand(hand):
> counts = tuple(sorted(hand.count(card) for card in set(hand)))
> return hands.get(counts, 'misdeal')

1. "Flush" means 5 cards of the same suit (i.e. all hearts), not 5 of
   a kind.

2. That code doesn't detect flushes or straights.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: evaluated function defaults: stored where?

2005-05-25 Thread alex23
I wrote: (some guff on default parameters)

Of course, it helps if I actually include the alternative function's
code:

>>> def foo(a, b = None):
... if b == None: b = []
... b.append(a)
... return b

Sorry about that :)

-alex23

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


Strange Execution Times

2005-05-25 Thread curi42
I am running two functions in a row that do the same thing.  One runs
in .14 seconds, the other 56.  I'm confused.  I wrote another version
of the program and couldn't get the slow behavior again, only the fast.
 I'm not sure what is causing it.  Can anyone figure it out?

Here is my code (sorry it's a bit of a mess, but my cleaned up version
isn't slow!).  Just skim to the bottom where the timing is.  The first
time printed out is .14, the seond is 56.56.


f = open("/Users/curi/data.xml")


o = open("/Users/curi/out2.xml", "w")


import md5
import array


p1 = ""
p2 = ""

cnt = 0

m = md5.new
jo = "".join


adjust = len(p1) - 1

i = 1
s = f.read()
a = array.array('c', s).tolist()
spot = 0
k = 0
find = s.find

starts = []
ends = []

while k != -1:

#print len(s)
k = find(p2, spot)
if k != -1:
starts.append(find(p1, spot) + adjust)
ends.append(k)
spot = k + 1

#s = "".join([s[:j+1], md5.new(s[j+1:k-1]).hexdigest(), s[k:]])

#if k != -1: a[j+1:k-1] = m(jo(a[j+1:k-1])).hexdigest()



r = range(len(starts))
#r = range(20)
r.reverse()
import time


data = a[:]

md5 = m
join = jo





t1 = time.clock()
for j in r:
#print jo(s[starts[j]+1:ends[j]])
digest = m(jo(s[starts[j]+1:ends[j]])).hexdigest()

a[starts[j]+1:ends[j]] = digest
#cnt += 1
#if cnt % 100 == 0: print cnt


t2 = time.clock()
print "time is", round(t2-t1, 5)



t1 = time.clock()
for i in r:
data[starts[i]:ends[i]] =
md5(join(s[starts[i]:ends[i]])).hexdigest()
t2 = time.clock()
print "second time is", round(t2-t1, 5)


o.write(jo(a))

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


Re: evaluated function defaults: stored where?

2005-05-25 Thread alex23
David Isaac wrote:
> As a Python newbie I found this behavior quite surprising.

It can be even more surprising if a default value is mutable:

>>> def foo(a, b=[]):
... b.append(a)
... return b

>>> foo(3,[1,2])
[1, 2, 3]

>>> foo('c',['a','b'])
['a', 'b', 'c']

>>> foo(1)
[1]

So far, everything is behaving much as you'd expect, but then:

>>> foo(2)
[1, 2]

>>> foo(3)
[1, 2, 3]

The parameter is bound to the list at creation time and, being mutable,
is modifiable each time the function is called.

This can be avoided by modifying your function slightly:

>>> foo(3, [1,2])
[1, 2, 3]

>>> foo('c', ['a','b'])
['a', 'b', 'c']

>>> foo(1)
[1]

>>> foo(2)
[2]

>>> foo(3)
[3]

-alex23

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


Re: Running in Release or Debug version of the python interpreter?

2005-05-25 Thread Raphael Zulliger
Thanks for your answers!
I prefer the proposal of Thomas Heller by using a small helper function 
like this:

def IsDebugVersionRunning():
import imp
for suffix in imp.get_suffixes():
if suffix[0] == '_d.pyd':
return True
return False

This works well for me. The
  _ctypes.__file__
trick didn't work for me - I guess I've done something wrong...

One more question: Under linux this doesn't seam to work - as there is 
always returned '.so' (not '_d.so') at least in my tests. Are there no 
debug/release version issues like on windows? doesn't import the 
python2.4-dbg (debian) binary different modules than python2.4?

Raphael Zulliger

Thomas Heller wrote:
> Raphael Zulliger schrieb:
> 
>> Hi
>>
>> I have to check wheter a .py script is run within the debug or the 
>> release version of an embedded python interpreter (in short, wheter 
>> python24_d.dll or python24.dll is in use).
>>
>> long version: I'm using ctypes to load my own dll. There exists 2 
>> version of this dll - a debug and a release version (where one is 
>> linked against debug C runtime dll and the other to release C runtime 
>> dll). Now
>> I have to change the name of the dll I want to be loaded by ctypes... 
>> But how can I find out which of the dll I have to load?!
>>
>> Thanks in advance!
>> Raphael Zulliger
> 
> 
> You could use imp.get_suffixes(). In a release build the returned list 
> will contain these entries
> ('.pyd', 'rb', 3), ('.dll', 'rb', 3)
> in a debug build that will be
> ('_d.pyd', 'rb', 3), ('_d.dll', 'rb', 3)
> 
> Another way would be to look at the filename of any binary extension 
> module.  _ctypes.__file__, for example:  '.\\_ctypes.pyd' vs. 
> '\\_ctypes_d.pyd'.
> 
> Thomas
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing 2 similar strings?

2005-05-25 Thread Roger Binns
<[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
> ***Check out difflib, it's in the library.***  Perfect package for what
> the OP wants AFAICT.

The method in difflib is okay, but doesn't do that good a job.  It
is also relatively slow.  My need for this was matching records in
BitPim (eg which entries just read from a cell phone correspond to
which entries just read from Outlook)

Here are some links for the OP as well as ready to run code at the
end.

A paper on various algorithms and their effectiveness on various data
sets.

http://www.isi.edu/info-agents/workshops/ijcai03/papers/Cohen-p.pdf

They do have a Java library of all the algorithms by the same authors.

http://secondstring.sourceforge.net/

There is a group at the Australian National University with a project named
Febrl - Freely extensible biomedical record linkage.  The idea is to be able
to work out if two records from the same or different sources are the same
person.  All their code is in Python:

http://datamining.anu.edu.au/software/febrl/febrldoc/

The solution I settled on is using Jaro-Winkler. This is a quote from the
paper above:

  A surprisingly good distance metric is a fast heuristic scheme, proposed
  by Jaro (Jaro 1995; 1989) and later extended by Winkler (Winkler 1999).
  This works almost as well as the Monge-Elkan scheme, but
  is an order of magnitude faster

I did find a Python module that implemented this (it is part of the
python-levenshtein package).  Unfortunately there were some issues
at the time dealing with some strings that may be unicode and some
not.  There was one implementation I saw that took copies of both
strings and was replacing characters with asterisks.  My data sets
include meaningful asterisks so that seriously munged things.

Ultimately I wrote my own implementation with the following properties:

 - The arguments can be any combination of unicode and ordinary strings
 - There are no special characters nor ones used internally as replacements
 - A bitset is used for tracking so you use an eigth of the memory
 - There is both Python and C code implementations so you don't have
   to compile anything but can if you want

The code can be grabbed from:

http://cvs.sf.net/viewcvs.py/bitpim/bitpim/native/strings/

There is a detailed description at the begining of the Python implementation:

http://cvs.sf.net/viewcvs.py/bitpim/bitpim/native/strings/jarowpy.py?view=markup

Roger 


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


Re: Checking for a full house

2005-05-25 Thread Raymond Hettinger
Your use case for gathering roll statistics probably needs a more
general solution:

hands = {
(1,1,1,1,1): 'nothing',
(1,1,1,2): 'one pair',
(1,2,2): 'two pair',
(1,1,3): 'three of a kind',
(2,3): 'full house',
(1,4): 'four of a kind',
(5): 'flush (five of a kind)'
}

def eval_hand(hand):
counts = tuple(sorted(hand.count(card) for card in set(hand)))
return hands.get(counts, 'misdeal')


Raymond Hettinger

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


Re: Checking for a full house

2005-05-25 Thread Raymond Hettinger
[mwdsmith]
> Below is my code for checking for a full house (when rolling
> with 5 dice).

There are many ways to do this.  Here's one:

.def isfullHouse(hand):
.counts = [hand.count(card) for card in set(hand)]
.return (3 in counts) and (2 in counts) and len(hand)==5


And here's a one-liner:

.def isfullHouse(hand):
.return sorted(hand.count(card) for card in set(hand)) == [2,3]


Raymond Hettinger

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


Re: __init__() not called automatically

2005-05-25 Thread Steven Bethard
Paul McNett wrote:
> Sriek wrote:
>> i come from a c++ background. i ws happy to find myself on quite
>> familiar grounds with Python. But, what surprised me was the fact that
>> the __init__(), which is said to be the equivlent of the constructor in
>> c++, is not automatically called. 
> 
[snip]
> 
> It is true that if 
> you derive from A and override __init__, A.__init__ won't be called 
> unless done so explicitly like:
> 
> class B(A):
> def __init__(self):
> print "in B.__init__()"
> super(B, self).__init__()
> 
>> I'm sure there must be ample reason
>> for this. I would like to know why this is so? This is my view is more
>> burden on the programmer.
> 
> It isn't that much practical burden, and IMO it makes perfect sense. 
> When you override a method of a class, you want to have to explicitly 
> call superclass code, not have it run automatically, else you lose 
> control of the flow.

I'd like to reiterate this point.  Say I have a class like:

class A(object):
 def __init__(self, x):
 self.x = x
 print 'A.__init__'

and an inheriting class like:

class B(A):
 def __init__(self, y):
 ...
 print 'B.__init__'
 ...

If 'y' is the same thing as 'x', then I probably want to write B like:

class B(A):
 def __init__(self, y):
 super(B, self).__init__(y)
 print 'B.__init__'

But what if 'x' has to be computed from 'y'?  Then I don't want the 
super call first.  I probably want it last (or at least later), e.g.:

class B(A):
 def __init__(self, y):
 print 'B.__init__'
 x = self._compute_x(y)
 super(B, self).__init__(x)

If the superclass constructor is automatically called, how will it know 
which meaning I want for 'y'?  Is 'y' equivalent to 'x', or is it 
something different?  Since Python can't possibly know this for sure, it 
refuses the temptation to guess, instead requiring the user to be explicit.

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


Re: urllib2 and SSL

2005-05-25 Thread flamesrock
don't you need to install openSSL?

I'm not sure.

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


Re: evaluated function defaults: stored where?

2005-05-25 Thread Raymond Hettinger
[Alan Isaac]
> Default parameter values are evaluated once when the function definition is
> executed.  Where are they stored?


>>> def f(a, b=10, c=20):
.   pass
>>> f.func_defaults
(10, 20)


> Where is this documented?

http://docs.python.org/ref/types.html#l2h-78



Raymond Hettinger

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


Re: __init__() not called automatically

2005-05-25 Thread Sriek
Tim pointed out  rightly that i missed out the most crucial part of my
question.
i should have said that __init__() is not called automatically only for
the inheritance hierarchy. we must explicitly call all the base class
__init__() fuctions explicitly.
 i wanted a reason for that.
Thanks Tim.

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


Re: __init__() not called automatically

2005-05-25 Thread Paul McNett
Sriek wrote:
> hi,
> i come from a c++ background. i ws happy to find myself on quite
> familiar grounds with Python. But, what surprised me was the fact that
> the __init__(), which is said to be the equivlent of the constructor in
> c++, is not automatically called. 

What do you mean by automatically? :

Python 2.4.1 (#2, May  5 2005, 09:45:41)
[GCC 4.0.0 20050413 (prerelease) (Debian 4.0-0pre11)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> class A(object):
... def __init__(self):
... print "in __init__"
...
 >>> a = A()
in __init__

So __init__ is definitely called upon instantiation.  It is true that if 
you derive from A and override __init__, A.__init__ won't be called 
unless done so explicitly like:

class B(A):
def __init__(self):
print "in B.__init__()"
super(B, self).__init__()

> I'm sure there must be ample reason
> for this. I would like to know why this is so? This is my view is more
> burden on the programmer.

It isn't that much practical burden, and IMO it makes perfect sense. 
When you override a method of a class, you want to have to explicitly 
call superclass code, not have it run automatically, else you lose 
control of the flow.


> Similarly, why do we have to explicitly use the 'self' keyword
> everytime?

This is closer to a wart, IMO, but once you've used Python for a while 
you'll come to understand why this is so. Basically, everything in 
Python is either a namespace or a name in a namespace. In the case of 
the self reference which Python sends as the first arg automatically, 
the method needs to bind that to a local name which is, by convention 
only, 'self'.


> Every kind of help would be welcome.

You've found the right place to hang out. Welcome!


-- 
pkm ~ http://paulmcnett.com

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


Re: __init__() not called automatically

2005-05-25 Thread Tim Leslie
On 25 May 2005 21:31:57 -0700, Sriek <[EMAIL PROTECTED]> wrote:
> hi,
> i come from a c++ background. i ws happy to find myself on quite
> familiar grounds with Python. But, what surprised me was the fact that
> the __init__(), which is said to be the equivlent of the constructor in
> c++, is not automatically called. I'm sure there must be ample reason
> for this. I would like to know why this is so? This is my view is more
> burden on the programmer.

>>> class C:
... def __init__(self): print "Hello"
...
>>> c = C()
Hello

This looks like __init__ being called automatically to me. Are you
doing something different?

> Similarly, why do we have to explicitly use the 'self' keyword
> everytime?

http://www.python.org/doc/faq/general.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls

> 
> Every kind of help would be welcome.

No worries,

Tim

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


__init__() not called automatically

2005-05-25 Thread Sriek
hi,
i come from a c++ background. i ws happy to find myself on quite
familiar grounds with Python. But, what surprised me was the fact that
the __init__(), which is said to be the equivlent of the constructor in
c++, is not automatically called. I'm sure there must be ample reason
for this. I would like to know why this is so? This is my view is more
burden on the programmer.
Similarly, why do we have to explicitly use the 'self' keyword
everytime?

Every kind of help would be welcome.

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


win32clipboard.GetClipboardData() return string with null characters

2005-05-25 Thread aurora
I was using win32clipboard.GetClipboardData() to retrieve the Windows  
clipboard using code similar to the message below:

http://groups-beta.google.com/group/comp.lang.python/msg/3722ba3afb209314?hl=en

Some how I notice the data returned includes \0 and some characters that  
shouldn't be there after the null character. It is easy enough to truncate  
them. But why does it get there in the first place? Is the data length  
somehow calculated wrong?

I'm using Windows XP SP2 with Python 2.4 and pywin32-203.

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


Design problem...need some ideas

2005-05-25 Thread Mudcat
Howdy,

I'm trying to create a selection helper, just like in Google or other
places where a drop-down menu appears below the text selection box when
you enter some text. As you type, the choices are narrowed based on the
characters entered.

I have everything worked out but the actual menu which is giving me
problems. My first attempt was using a Pmw.ScrolledListBox and taking
advantage of the inherent drop-down menu. I was attempting to invoke
the menu and change the list as characters were typed.

However, I found I was getting focus problems. When the menu is
invoked, focus in the entry box is lost which makes it impossible for
the user to continue typing his selection. When focus is returned to
the entry box, the drop-down menu disappears. Is there a way to make
this work?

Or, is there a better way? My Plan B was to create a new toplevel
window and place it using screen geometry to appear right below the
entry box. The window was going to contain just a listbox that
contained the selections. But I fear this may pose many more problems,
focus just being one of them.

Thanks ahead of time for the help,
Marc

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


evaluated function defaults: stored where?

2005-05-25 Thread David Isaac
Default parameter values are evaluated once when the function definition is
executed.
Where are they stored?  (A guess: in a dictionary local to the function.)
Where is this documented?

As a Python newbie I found this behavior quite surprising.
Is it common in many other languages?
Is it unsurprising if I look at it right?

Thanks,
Alan Isaac


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


Re: Q: "...Learning with Python" ...a property that addition and multiplication have...

2005-05-25 Thread Dan Sommers
On 25 May 2005 17:23:45 -0700,
[EMAIL PROTECTED] wrote:

> I'm reading "How to think like a computer scientist: Learning with
> Python" and there's a question regarding string operations. The
> question is, "Can you think of a property that addition and
> multiplication have that string concatenation and repetition do not?"

> I thought it was the commutative property but ""*3 is
> equivalent to 3*"". Any ideas?

Thinking like an old embedded systems programmer, for many types of
numbers (ints and floats, but not longs), multiplication and addition
are constant time, constant space operations.  String concatenation and
repetition are not.

As already mentioned, there are no inverses.  Similarly, there aren't
even inverse operations (e.g., it makes little sense to divide a string
by a number, let alone a number by a string).

For floating point numbers (and integers that can overflow),
multiplication and addition are not necessarily exact.  Unless your
strings get too big for the memory manager, concatenation and
replication are exact.

And now that I reread the question, "a property that addition and
multiplication have" is "the distributive property," but the
distributive property of multiplcation over addition does not translate
to a distributive property of repetition over concatenation:

2 * ( 3 + 4 ) == 14
2 * 3 + 2 * 4 == 14

but

2 * ( "ABC" + "DEFG" ) == "ABCDEFGABCDEFG"
2 * "ABC" + 2 * "DEFG" == "ABCABCDEFGDEFG"

Regards,
Dan

-- 
Dan Sommers

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


urllib2 and SSL

2005-05-25 Thread rbt
urllib2 handles https request flawlessly on my Linux machines, but errors out 
on 
Windows like this:

PythonWin 2.4 (#60, Nov 30 2004, 09:34:21) [MSC v.1310 32 bit (Intel)] on win32.
Portions Copyright 1994-2004 Mark Hammond ([EMAIL PROTECTED]) - see 
'Help/About PythonWin' for further copyright information.
working_0...

working_2...


Is SSL not supported on win32?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Checking for a full house

2005-05-25 Thread Robert Kern
Tony Meyer wrote:
> [Tony Meyer]
> 
>>>def isfullHouse(roll):
>>>return len(set(roll)) != 2
> 
> [Robert Kern]
> 
>>[1, 1, 1, 1, 2] is not a full house.
> 
> Opps.  I did say it was untested (that should have been == not !=, too).
> What about:
> 
> def isfullHouse(roll):
> return len(set(roll)) == 2 and roll.count(min(roll)) != 1 and
> roll.count(max(roll)) != 1
> 
> Although your solution looks a lot nicer than this (though it may use more
> memory, and might be slower).

It *is* slower as written, although a more optimized version using 
itertools and sets (left as an exercise for the bored) gets close to 
yours. I don't think memory is an issue with 5-element lists of small 
integers.

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter

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


Re: Python Impact Analysis Tool ?

2005-05-25 Thread Stephen Prinster
Paul McNett wrote:
> Terry Hancock wrote:
> 
>> On Wednesday 25 May 2005 08:27 am, [EMAIL PROTECTED] wrote:
>>
>>> Is there an impact analysis tool out there that can cross reference
>>> python -- VB has a couple of these tools (eg. Visual Expert)
>>
>>
>> I could be wrong, but my first impression is that that must be
>> VB jargon for something we might know under another name.
> 
> 
> Yep, I think we know it as 'unit testing'.
> 
> From the Visual Expert site (http://visual-expert.com), impact analysis
> refers to taking a given variable or function name, and finding
> everywhere in the project where that name is referenced, for the purpose
> of determining what bad things will happen when that variable or
> function is changed somehow. The tool won't tell you what bad things
> will happen, just list other code segments that depend on the name in
> question.

This also sounds a little bit like "refactoring."
The OP may want to look at Bicycle Repair Man:

http://bicyclerepair.sourceforge.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Checking for a full house

2005-05-25 Thread Tony Meyer
[Tony Meyer]
>> def isfullHouse(roll):
>> return len(set(roll)) != 2

[Robert Kern]
> [1, 1, 1, 1, 2] is not a full house.

Opps.  I did say it was untested (that should have been == not !=, too).
What about:

def isfullHouse(roll):
return len(set(roll)) == 2 and roll.count(min(roll)) != 1 and
roll.count(max(roll)) != 1

Although your solution looks a lot nicer than this (though it may use more
memory, and might be slower).

=Tony.Meyer

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


Re: Checking for a full house

2005-05-25 Thread Roy Smith
"mwdsmith" <[EMAIL PROTECTED]> wrote:
> Hi, I'm new to python, and I'm not sure if this is the place to post
> this kind of question; so feel free to tell me if I should take this
> elsewhere.

Well, that depends.  Are we doing your homework assignment for you? :-)

> So, to start me off on python, I decided to put together a little
> script to test the probabilities of rolling certain combinations of
> dice.  Below is my code for checking for a full house (when rolling
> with 5 dice).  A roll is a list, eg [1, 3, 5, 1, 4] (this example is
> not a full house)
> 
> def removeAll(element, num2Rem, list):
> l = list[:]
> for num in range(0, num2Rem):
> l.remove(element)
> return l
> 
> def isfullHouse(roll):
> for die in range(1,7):
> if roll.count(die)==3:
> l = removeAll(die, 3, roll)
> if l[0]==l[1]:
> return 1
> return 0
> 
> My questions is this: is there a better way to do this?  A way that's
> more natural to python, or just more efficient perhaps?

Well, I think I might do two trips through a dictionary.  Something like 
the following.  The arguments to the two dict() constructors are list 
comprehensions.  I don't normally use them a lot, and I don't normally like 
complicated expressions like this, but I tried a few ways, and this just 
seems to be the most compact way by far to do the counting.  So, even 
though I'm not convinced this is the clearest way to write it, you did ask 
for the most pythonic way, and I think this might be that :-)

#!/usr/bin/env python   
   

def isFullHouse (roll):
# count how many of each value you have, i.e. how many 1's,
# how many 2's, etc
valueDict = dict ([(x, 0) for x in range(1,7)])
for die in roll:
valueDict[die] += 1

# count how many of each set size you have, i.e. how many
# voids, how many singletons, how many pairs, etc.
setDict = dict ([(x, 0) for x in range(0,6)])
for setSize in valueDict.values():
setDict[setSize] += 1

# A full house is one pair and one three-of-a-kind
return setDict[2] == 1 and setDict[3] == 1

print isFullHouse ([1, 1, 1, 2, 2]) == True
print isFullHouse ([1, 1, 1, 1, 1]) == False
print isFullHouse ([1, 2, 3, 4, 5]) == False
print isFullHouse ([3, 4, 3, 3, 4]) == True
print isFullHouse ([1, 2, 1, 1, 1]) == False
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python analog of Ruby on Rails?

2005-05-25 Thread George Sakkis
"Christopher J. Bottaro" wrote:

> Cool signature, can anyone do a Python one that I can leech?  =)
>
> -- C
>

Here's the transliteration in python for your address:

python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')])
 for p in '[EMAIL PROTECTED]'.split('@')])"

Cheers,
George

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


Problem redirecting stdin on Windows

2005-05-25 Thread aurora
On Windows (XP) with win32 extension installed, a Python script can be  
launched from the command line directly since the .py extension is  
associated with python. However it fails if the stdin is piped or  
redirected.

Assume there is an echo.py that read from stdin and echo the input.



Launching from command line directly, this echos input from keyboard:

   echo.py



But it causes an error if the stdin is redirected

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


Re: Checking for a full house

2005-05-25 Thread Robert Kern
Tony Meyer wrote:

> def isfullHouse(roll):
> return len(set(roll)) != 2

[1, 1, 1, 1, 2] is not a full house.

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter

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


how to import a module from a arbitraty path?

2005-05-25 Thread Andy Leszczynski
I have a program which is going to dynamicly load components from some 
arbitrary defined paths. How to do that?

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


RE: Checking for a full house

2005-05-25 Thread Tony Meyer
> def removeAll(element, num2Rem, list):
> l = list[:]
> for num in range(0, num2Rem):
> l.remove(element)
> return l
> 
> def isfullHouse(roll):
> for die in range(1,7):
> if roll.count(die)==3:
> l = removeAll(die, 3, roll)
> if l[0]==l[1]:
> return 1
> return 0
> 
> My questions is this: is there a better way to do this?  A way that's
> more natural to python, or just more efficient perhaps?

This is an alternative that doesn't muck about making a second list:

def isfullHouse(roll):
has_pair = False
has_triple = False
for die in xrange(1,7):
if has_pair and has_triple:
return True
count = roll.count(die)
if count > 3:
return False # easy out; can't have four/five and full house
if count == 2:
has_pair = True
elif count == 3:
has_triple = True
return False

If you want it in one line (and have Python 2.4):

def isfullHouse(roll):
return len(set(roll)) != 2

If you create a set from the list, it will remove duplicates.  If there are
3,4, or 5 different numbers, then you don't have a triplet.  (I assume that
[1,1,1,1,1] isn't a full house, or this answer is wrong, since that will
have the length be 1).

(These are both untested).

=Tony.Meyer

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


Re: Checking for a full house

2005-05-25 Thread Robert Kern
mwdsmith wrote:
> Hi, I'm new to python, and I'm not sure if this is the place to post
> this kind of question; so feel free to tell me if I should take this
> elsewhere.
> 
> So, to start me off on python, I decided to put together a little
> script to test the probabilities of rolling certain combinations of
> dice.  Below is my code for checking for a full house (when rolling
> with 5 dice).  A roll is a list, eg [1, 3, 5, 1, 4] (this example is
> not a full house)
> 
> def removeAll(element, num2Rem, list):
> l = list[:]
> for num in range(0, num2Rem):
> l.remove(element)
> return l
> 
> def isfullHouse(roll):
> for die in range(1,7):
> if roll.count(die)==3:
> l = removeAll(die, 3, roll)
> if l[0]==l[1]:
> return 1
> return 0
> 
> My questions is this: is there a better way to do this?  A way that's
> more natural to python, or just more efficient perhaps?
> 
> ps. A roll of [1, 2, 1, 1, 2] is a full house (three of one kind and
> two of another)

def isFullHouse(roll):
 counts = [roll.count(die) for die in range(1,7)]
 counts.sort()
 return counts == [0, 0, 0, 0, 2, 3]

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter

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


Re: "...Learning with Python" ...a property that addition andmultiplication have...

2005-05-25 Thread Terry Reedy

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Greetings.
>
> I'm reading "How to think like a computer scientist: Learning with
> Python" and there's a question regarding string operations. The
> question is, "Can you think of a property that addition and
> multiplication have that string concatenation and repetition do not?"
>
> I thought it was the commutative property but ""*3 is
> equivalent to 3*"". Any ideas?

Go back to concatenation instead of repetition.

TJR



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


Checking for a full house

2005-05-25 Thread mwdsmith
Hi, I'm new to python, and I'm not sure if this is the place to post
this kind of question; so feel free to tell me if I should take this
elsewhere.

So, to start me off on python, I decided to put together a little
script to test the probabilities of rolling certain combinations of
dice.  Below is my code for checking for a full house (when rolling
with 5 dice).  A roll is a list, eg [1, 3, 5, 1, 4] (this example is
not a full house)

def removeAll(element, num2Rem, list):
l = list[:]
for num in range(0, num2Rem):
l.remove(element)
return l

def isfullHouse(roll):
for die in range(1,7):
if roll.count(die)==3:
l = removeAll(die, 3, roll)
if l[0]==l[1]:
return 1
return 0

My questions is this: is there a better way to do this?  A way that's
more natural to python, or just more efficient perhaps?

ps. A roll of [1, 2, 1, 1, 2] is a full house (three of one kind and
two of another)

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


Re: Automatically populate and submit HTML Forms

2005-05-25 Thread alex23
Hey rbt,

You should take a look at mechanize:
http://wwwsearch.sourceforge.net/mechanize/

One of its listed features is 'Easy HTML form filling, using ClientForm
interface'.

A more recent option which came up on this group a few days ago is
twill: http://www.idyll.org/~t/www-tools/twill.html

twill combines pyparsing & mechanize to provide a way of scripting
tests for web applications. While it might not offer the functionality
you're after (I haven't had call to use either of these), it looks very
accessible, and could provide some good examples for using mechanize
with your own scripts.

-alex23

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


Re: Q: "...Learning with Python" ...a property that addition and multiplication have...

2005-05-25 Thread Greg Ewing
[EMAIL PROTECTED] wrote:
> "Can you think of a property that addition and
> multiplication have that string concatenation and repetition do not?"

Existence of inverses?

E.g. the additive inverse of 3 is -3, but there are
no "concatenative inverses" of strings.

(BTW, I would consider this more about thinking like a
mathematician than a computer scientist!)

-- 
Greg Ewing, Computer Science Dept,
University of Canterbury,   
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Q: "...Learning with Python" ...a property that addition and multiplication have...

2005-05-25 Thread [EMAIL PROTECTED]


[EMAIL PROTECTED] wrote:
> Greetings.
>
> I'm reading "How to think like a computer scientist: Learning with
> Python" and there's a question regarding string operations. The
> question is, "Can you think of a property that addition and
> multiplication have that string concatenation and repetition do not?"
>
> I thought it was the commutative property but ""*3 is
> equivalent to 3*"". Any ideas?

>>> 3.3*1
3.2998

>>> 3.3*'1'

Traceback (most recent call last):
  File "", line 1, in -toplevel-
3.3*'1'
TypeError: can't multiply sequence to non-int

> 
> Thanks,
> 
> Jeff

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


Re: Using properties

2005-05-25 Thread alex23
[EMAIL PROTECTED] wrote:
> Thanks for the help. I now understand it better. As Bruno points out, I
> really don't need a property in this case, as my attribute is public,
> and I will remove it.

Should you need it to be a property at a latter date, it's worth noting
that you can achieve what you were initially after by wrapping the
property's get/set around the objects '__dict__' attribute:

def getname(self): return self.__dict__['name']
def setname(self): self.__dict__['name'] =newname

Hope this helps.

-alex23

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


how to accomplish dl progress bars?

2005-05-25 Thread flamesrock
Certain web applications, everything from wget to downloader for X has
this nifty feature I'd like to accomplish in python.

Its the progress bar/time elapsed/time remaining scheme

Filename  | Progress| Speed (kB/s) | T/Elapsed | T/Remaining

blah.bin  |-->45%   | 56.6 |   02:39   |   02:45
file2.bz2 |--->33%  | 35.0 |   05:22   |   11:24
etc   |>60% | 47.5 |   00:14   |   00:08

(could be either text or a gui..)

So where would one begin to accomplish this sort of thing efficiently?

I've searched the web and there are plenty of resources on network
programming in python, but how could I
1) keep track of download speed
2) calculate t/elapsed/remaining
3) output that to a progress bar

w/o spawning countless threads to do the many calculations and avoid
eating up the entire CPU.

This seems like it would require a lot of resources and easily go out
of sync with the real world file transfer. To compound problems, I have
a very limited understanding of threads and using multiple threads that
rely on eachother doesn't make very much sense.

Can anyone point me in the right direction?

-thanks in advance

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


Re: vim configuration for python

2005-05-25 Thread Stephen Thorne
On 26/05/05, Leonard J. Reder <[EMAIL PROTECTED]> wrote:
> Hello,
> 
> I am looking at configuring vim for Python.  Most importantly I
> need 4 spaces when the tab is hit.  I am searching and getting
> a bit confused.  Does anyone know where I can find a set of
> ready made .vimrc and ~/.vim/syntax/python.vim.  If could find
> c.vim and cpp.vim these would be useful also.

The default python.vim in the /usr/share/vim/vim63/ftplugin/ directory
automatically set the shiftwidth to 4 wide (i.e. a  keypress
makes 4 spaces) and automatically uses spaces instead of tab
characters. A tab character in your file will be rendered as 8 wide.

-- 
Stephen Thorne
Development Engineer
-- 
http://mail.python.org/mailman/listinfo/python-list


Q: "...Learning with Python" ...a property that addition and multiplication have...

2005-05-25 Thread jeffbernstein
Greetings.

I'm reading "How to think like a computer scientist: Learning with
Python" and there's a question regarding string operations. The
question is, "Can you think of a property that addition and
multiplication have that string concatenation and repetition do not?"

I thought it was the commutative property but ""*3 is
equivalent to 3*"". Any ideas?

Thanks,

Jeff

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


Re: setting up scipy in windows

2005-05-25 Thread hawkesed
Thanks to both you guys. I got scipy up and running yesterday. Here are
the steps I went through:
1. I un-installed some non-official pythons. (Plone and ActiveState)
2. I loaded STANDARD Python 2.3.5
3. I loaded Python for Windows extensions.
4. I Loaded Numeric
5. Loaded SCIPY
6. Tested it by typing in pythonwin
>>> from scipy import *
>>>
Then played around with some of the methods. Pretty cool stuff. Thanks
all!



Frithiof Andreas Jensen wrote:
> "hawkesed" <[EMAIL PROTECTED]> skrev i en meddelelse
> news:[EMAIL PROTECTED]
>
>
> > Scipy looks like just the thing I want, if anyone has got it running on
> > a Windows box I would like to hear how you did it.
>
> With STANDARD Python 2.3 it installs from the Python 2.3 win 32 installers
> and runs.
>
> The only problem I had was that "Numeric" needs to be installed before
> "Scipy" or Scipy will chrash.

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


Re: vim configuration for python

2005-05-25 Thread Simon Percivall
I don't know if the binary editions include the Misc directory, but if
you download the Python source you'll find a directory called Misc. In
it, there's a vimrc file.

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


Re: vim configuration for python

2005-05-25 Thread haihui guo
I think you can do

set tabstop=4

also, it's better to

set expandtab

so, the tab will be expanded as space.

HG
On Wed, 25 May 2005 16:36:04 -0700, Leonard J. Reder <[EMAIL PROTECTED]>  
wrote:

> Hello,
>
> I am looking at configuring vim for Python.  Most importantly I
> need 4 spaces when the tab is hit.  I am searching and getting
> a bit confused.  Does anyone know where I can find a set of
> ready made .vimrc and ~/.vim/syntax/python.vim.  If could find
> c.vim and cpp.vim these would be useful also.
>
> Thanks for any pointer.
> Len



-- 
Using Opera's revolutionary e-mail client: http://www.opera.com/m2/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pyvm -- faster python

2005-05-25 Thread Stelios Xanthakis
Hi Michael

[...]
> 
> Releasing open source means that people *may* fix their own bugs, or
> abandon the code.
[...]

I agree with all the points made.

Moreover let me add that "code is one expression of a set of good
ideas", and ideas want to be free!  ;)

I've decided to release the source code of pyvm as soon as it's ready.

Right now *it doesn't* make much sense to give the source because it is
still at an early development stage.  Even if I did and people sent
patches they wouldn't apply because I still make big changes to the
architecture of it.  I'd like to keep it in this status where I can
modify the structure of the program until it becomes really
developer-friendly.  And IMO it doesn't make sense to release incomplete
open source projects: either give something that's good and people can
happily hack, or don't do it at all.  Giving out the source of an
unstable project will most likely harm it (see CherryOS incidents).

The bottomline is that I estimate that pyvm will be ready within
the summer.


Thanks,

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


vim configuration for python

2005-05-25 Thread Leonard J. Reder
Hello,

I am looking at configuring vim for Python.  Most importantly I
need 4 spaces when the tab is hit.  I am searching and getting
a bit confused.  Does anyone know where I can find a set of
ready made .vimrc and ~/.vim/syntax/python.vim.  If could find
c.vim and cpp.vim these would be useful also.

Thanks for any pointer.
Len
-- 

Leonard J. Reder
Jet Propulsion Laboratory
Interferometry Systems and Technology Section 383
Email: [EMAIL PROTECTED]
Phone (Voice): 818-354-3639
Phone (FAX): 818-354-4357
Mail Address:
Mail Stop: 171-113
4800 Oak Grove Dr.
Pasadena, CA. 91109
---
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What are OOP's Jargons and Complexities?

2005-05-25 Thread David Formosa (aka ? the Platypus)
On Tue, 24 May 2005 09:16:02 +0200, Tassilo v. Parseval
<[EMAIL PROTECTED]> wrote: 
> Also sprach John W. Kennedy:
[...]

> Most often, languages with strong typing can be found on the functional
> front (such as ML and Haskell). These languages have a dynamic typing
> system. I haven't yet come across a language that is both statically and
> strongly typed, in the strictest sense of the words. I wonder whether
> such a language would be usable at all.

Modula2 claims to be both statically typed and strongly typed.  And
your wonder at its usablity is justified.

-- 
Please excuse my spelling as I suffer from agraphia. See
http://dformosa.zeta.org.au/~dformosa/Spelling.html to find out more.
Free the Memes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Improve the performance of a loop

2005-05-25 Thread Steven Bethard
[EMAIL PROTECTED] wrote:
> vbox = array(m) (size: 1000x1000 approx)
> for b in bx:
> vbox[ b[1], b[0]:b[2] ] = 0
> vbox[ b[3], b[0]:b[2] ] = 0
> vbox[ b[1]:b[3], b[0] ] = 0
> vbox[ b[1]:b[3], b[2] ] = 0

This may not help, but you could try to minimize the number of times you 
call b's __getitem__, e.g.:

for b0, b1, b2, b3 in bx:
 vbox[b1, b0:b2] = 0
 vbox[b3, b0:b2] = 0
 vbox[b1:b3, b0] = 0
 vbox[b1:b3, b2] = 0

If it helps, I wouldn't expect it to help a lot though.  You could also try:

for b0, b1, b2, b3 in bx:
 b0_2 = slice(b0, b2)
 b1_3 = slice(b1, b3)
 vbox[b1, b0_2] = 0
 vbox[b3, b0_2] = 0
 vbox[b1_3, b0] = 0
 vbox[b1_3, b2] = 0

But again, I wouldn't expect dramatic improvements...

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


Re: regexp for sequence of quoted strings

2005-05-25 Thread Steven Bethard
Paul McGuire wrote:
text = r"'the','dog\'s','bite'"
def unquote(s,l,t):
> 
> ... t2 = t[0][1:-1]
> ... return t2.replace("\\'","'")
> ...

Note also, that the codec 'string-escape' can be used to do what's done 
with str.replace in this example:

py> s
"'the','dog\\'s','bite'"
py> s.replace("\\'", "'")
"'the','dog's','bite'"
py> s.decode('string-escape')
"'the','dog's','bite'"

Using str.decode() is a little more general as it will also decode other 
escaped characters.  This may be good or bad depending on your needs.

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


Re: import cx_Oracle fails!

2005-05-25 Thread Daniel
Hi Bernard

My system is a PA 8K series with 4096 MB and 2 processors, running 64
bit mode OS.

I only created the recipe above after 1 week of mistakes :-), but I
don't know if it will work with your branch of patches @ 11.23 version.


I really hate HP-UX >-(, god bless BSD!!! :-D

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


Improve the performance of a loop

2005-05-25 Thread querypk
What is the fastest way to code this particular block of code below..
I used numeric for this currently and I thought it should be really
fast..
But, for large sets of data (bx and vbox) it takes a long time and I
would like to improve.

vbox = array(m) (size: 1000x1000 approx)
for b in bx:
vbox[ b[1], b[0]:b[2] ] = 0
vbox[ b[3], b[0]:b[2] ] = 0
vbox[ b[1]:b[3], b[0] ] = 0
vbox[ b[1]:b[3], b[2] ] = 0

and vbox is a 2D array
where bx is of form [( int,int,int,int),() ]

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


Re: regexp for sequence of quoted strings

2005-05-25 Thread Paul McGuire
Pyparsing includes some built-in quoted string support that might
simplify this problem.  Of course, if you prefer regexp's, I'm by no
means offended!

Check out my Python console session below.  (You may need to expand the
unquote method to do more handling of backslash escapes.)

-- Paul
(Download pyparsing at http://pyparsing.sourceforge.net.)

>>> from pyparsing import delimitedList, sglQuotedString
>>> text = r"'the','dog\'s','bite'"
>>> def unquote(s,l,t):
... t2 = t[0][1:-1]
... return t2.replace("\\'","'")
...
>>> sglQuotedString.setParseAction(unquote)
>>> g = delimitedList( sglQuotedString )
>>> g.parseString(text).asList()
['the', "dog's", 'bite']

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


py2exe problems with win32com [ EnsureDispatch('ADODB.Connection') ]

2005-05-25 Thread list . repository
Problem:

Works fine when running python test.py but fails when executing
test.exe.


test.py:

conn = win32com.client.gencache.EnsureDispatch('ADODB.Connection')
conn.Open("Provider='SQLOLEDB';Data Source='.';Initial
Catalog='mydatabase';User ID='user';Password='pwd';")
.
.
.

setup.py:(same KeyError)

from distutils.core import setup
import py2exe

setup(console=['test.pyw'],
  options = { "py2exe": { "typelibs":
[('{0550--0010-8000-00AA006D2EA4}', 0, 2, 8)]
 }
 }
 )

(Doesn't work since its not registered or need to get the

setup.py:  (same KeyError)

from distutils.core import setup
import py2exe

setup(console=['test.pyw'])


Generated error when running test.exe:

Traceback (most recent call last):
  File "test.py", line 66, in ?
  File "test.py", line 57, in main
  File "test.py", line 16, in test_status
  File "win32com\client\gencache.pyc", line 540, in EnsureDispatch
  File "win32com\client\CLSIDToClass.pyc", line 50, in GetClass
KeyError: '{0550--0010-8000-00AA006D2EA4}'


Solution:

Use a registered typelib that has ADODB.Connection functionality :)



Any suggestions...

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


Re: SSL (HTTPS) with 2.4

2005-05-25 Thread pyguy2
After failed attempts at trying to get my code to work with squid.

I did some research into this and came up with some info.

http://www.python.org/peps/pep-0320.txt

"- It would be nice if the built-in SSL socket type
could be used for non-blocking SSL I/O.  Currently
packages such as Twisted  which implement async
servers using SSL have to require third-party packages
such as pyopenssl. "

My guess is that the squid proxy server uses
non-blocking sockets which python ssl does not
support.

And, of course after looking at the squid site, I found this:

"Unlike traditional caching software, Squid handles
all requests in a single, non-blocking, I/O-driven
process."

Now, I haven't had time to verify this. But, it  can explain why the
non-ssl proxy authentication works and the ssl partially works. And,
also why I get success with a different type of proxy server.

For a clue as to why there is this problem I would also recommend
looking at  http://www.openssl.org/support/faq.html, specifically the
section on non-blocking i/o.

It looks like pyopenssl would be an option:
http://pyopenssl.sourceforge.net/

It's docs comment that it was written because m2crypto error handeling
was not finished for non-blocking i/o:

http://pyopenssl.sourceforge.net/pyOpenSSL.txt

The reason this module exists at all is that the SSL support in the
   socket module in the Python 2.1 distribution (which is what we used,
   of course I cannot speak for later versions) is severely limited.

   When asking about SSL on the comp.lang.python newsgroup (or on
   python-list@python.org) people usually pointed you to the M2Crypto
   package. The M2Crypto.SSL module does implement a lot of OpenSSL's
   functionality but unfortunately its error handling system does not
   seem to be finished, especially for non-blocking I/O. I think that
   much of the reason for this is that M2Crypto^1 is developed using
   SWIG^2. This makes it awkward to create functions that e.g. can
return
   both an integer and NULL since (as far as I know) you basically
write
   C functions and SWIG makes wrapper functions that parses the Python
   argument list and calls your C function, and finally transforms your
   return value to a Python object.

john

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


Re: regexp for sequence of quoted strings

2005-05-25 Thread Alexander Schmolck
gry@ll.mit.edu writes:

> I have a string like:
>  {'the','dog\'s','bite'}
> or maybe:
>  {'the'}
> or sometimes:
>  {}
>
> [FYI: this is postgresql database "array" field output format]
>
> which I'm trying to parse with the re module.
> A single quoted string would, I think, be:
>  r"\{'([^']|\\')*'\}"

what about {'dog \\', ...} ?

If you don't need to validate anything you can just forget about the commas
etc and extract all the 'strings' with findall,

The regexp below is a bit too complicated (adapted from something else) but I
think will work:

In [90]:rex = 
re.compile(r"'(?:[^\n]|(?http://mail.python.org/mailman/listinfo/python-list


using a com automation object (how do I avoid crash?)

2005-05-25 Thread James Carroll
I'm trying to call functions on an automation object, and I've run
makepy to generate a wrapper, and 99% of the calls I make on the
wrapper work great.

my question is: Is my [''] * 10  as close as I can come to a variant
array of pre-allocated empty strings?

I'm trying to call a function called EnumerateCameras

m.ShowLiveWindow(True)<--- this works
cams = [''] * 10
m.EnumerateCameras(cams)


The documentation that I have for the function says:

HRESULT EnumerateCameras
(
[in,out] VARIANT * pvBstrArray, 
[out,retval] VARIANT_BOOL *pbSuccess 
);

Parameters

pvBstrArray - Location of VARIANT array to read list of MicroFIRE
cameras into.  Array must   be pre-allocated with empty strings before
calling this function.


Is my [''] * 10  as close as I can come to a variant array of
pre-allocated empty strings?

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


Re: Python Impact Analysis Tool ?

2005-05-25 Thread Paul McNett
Terry Hancock wrote:
> On Wednesday 25 May 2005 08:27 am, [EMAIL PROTECTED] wrote:
> 
>>Is there an impact analysis tool out there that can cross reference
>>python -- VB has a couple of these tools (eg. Visual Expert)
> 
> I could be wrong, but my first impression is that that must be
> VB jargon for something we might know under another name.

Yep, I think we know it as 'unit testing'.

 From the Visual Expert site (http://visual-expert.com), impact analysis 
refers to taking a given variable or function name, and finding 
everywhere in the project where that name is referenced, for the purpose 
of determining what bad things will happen when that variable or 
function is changed somehow. The tool won't tell you what bad things 
will happen, just list other code segments that depend on the name in 
question.

While such a tool may indeed be helpful in quickly understanding a 
project, and there may indeed be such a tool for Python, I think that 
most Pythonistas would find unit testing has a better impact on 
developer productivity, for the common case of wanting to make a change 
and also fix any dependent structures: just do it and then discover/fix 
any repercussions!


-- 
pkm ~ http://paulmcnett.com

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


Re: Tkinter Text Question

2005-05-25 Thread Fredrik Lundh
James Stroud wrote:

> Thank you Fredrik, this worked beautifully. I had no idea about the "@"
> prefix. Incidentally, I had to change the code to
>
> w.index("@%s,%s" % (e.x, e.y))
>
> Maybe the x,y is a python 2.4 thing.

no, it's a think-before-cutting-and-pasting thing.  should have
been "@%d,%d"





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


Re: regexp for sequence of quoted strings

2005-05-25 Thread Steven Bethard
gry@ll.mit.edu wrote:
> I have a string like:
>  {'the','dog\'s','bite'}
> or maybe:
>  {'the'}
> or sometimes:
>  {}
>
[snip]
> 
> I want to end up with a python array of strings like:
> 
> ['the', "dog's", 'bite']
> 
> Any simple clear way of parsing this in python would be
> great; I just assume that "re" is the appropriate technique.
> Performance is not an issue.


py> s = "{'the','dog\'s','bite'}"
py> s
"{'the','dog's','bite'}"
py> s[1:-1]
"'the','dog's','bite'"
py> s[1:-1].split(',')
["'the'", "'dog's'", "'bite'"]
py> [item[1:-1] for item in s[1:-1].split(',')]
['the', "dog's", 'bite']

py> s = "{'the'}"
py> [item[1:-1] for item in s[1:-1].split(',')]
['the']

py> s = "{}"
py> [item[1:-1] for item in s[1:-1].split(',')]
['']

Not sure what you want in the last case, but if you want an empty list, 
you can probably add a simple if-statement to check if s[1:-1] is non-empty.

HTH,

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


Re: Has ComboBox ctrl in Tkinter?

2005-05-25 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Fredrik Lundh <[EMAIL PROTECTED]> wrote:
>"ÒÊÃÉɽÈË" <[EMAIL PROTECTED]> wrote:
>
>>i have not find the ComboBox in Tkinter,has it? where to get the doc about
>> how to use combobox ctrl?
>
>the Tix add-on contains a combobox:
>
>http://docs.python.org/lib/node727.html
>
>see
>
>http://docs.python.org/lib/node725.html
>
>for some information on how to check for a working Tix install.
>
>if you cannot get Tix to work (or don't want to use it), there's a combobox in
>the bwidgets package as well:
>
>http://tkinter.unpythonic.net/bwidget/
>
> 
>
>
>

There are also several pure-Tk implementations http://wiki.tcl.tk/combobox >, including Bryan Oakley's
popular one, all of which can be used directly from 
Tkinter.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Tkinter Text Question

2005-05-25 Thread James Stroud
Thank you Fredrik, this worked beautifully. I had no idea about the "@" 
prefix. Incidentally, I had to change the code to 

w.index("@%s,%s" % (e.x, e.y))

Maybe the x,y is a python 2.4 thing. I'm still stuck in 2.3.

James

On Wednesday 25 May 2005 12:18 am, Fredrik Lundh wrote:
> w.index("@x,y" % (event.x, event.y))

-- 
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: Python analog of Ruby on Rails?

2005-05-25 Thread Christopher J. Bottaro
bruno modulix wrote:

> Christopher J. Bottaro wrote:
>> Hello fellow Pythonists,
>>   Is there such a thing?
> 
> As what ?
> Oops, sorry, the question is in the subject... May be helpful to repeat
> it in the body.
> 
> You may want to have a look at Subway

Cool, that looks like what I'm looking for, thanks.

>> My work is thinking of maybe experimenting with
>> Ruby on Rails for some lesser projects.  Naturally, I wonder if Python
>> can do as good a job or better...
> 
> Doing 'as good or better' does not mean 'doing the same'.

Hmm.

Cool signature, can anyone do a Python one that I can leech?  =)

-- C

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


Re: Python Impact Analysis Tool ?

2005-05-25 Thread Terry Hancock
On Wednesday 25 May 2005 08:27 am, [EMAIL PROTECTED] wrote:
> Is there an impact analysis tool out there that can cross reference
> python -- VB has a couple of these tools (eg. Visual Expert)

I could be wrong, but my first impression is that that must be
VB jargon for something we might know under another name.

What *is* an "impact analysis tool".  Something tells me it has
little to do with the physics of craters, though that's the first
thing that comes to mind. There are a lots of self-documentation
tools for Python, though, starting with the interpreter itself.

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

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


regexp for sequence of quoted strings

2005-05-25 Thread gry
I have a string like:
 {'the','dog\'s','bite'}
or maybe:
 {'the'}
or sometimes:
 {}

[FYI: this is postgresql database "array" field output format]

which I'm trying to parse with the re module.
A single quoted string would, I think, be:
 r"\{'([^']|\\')*'\}"

but how do I represent a *sequence* of these separated
by commas?  I guess I can artificially tack a comma on the
end of the input string and do:

 r"\{('([^']|\\')*',)\}"

but that seems like an ugly hack...

I want to end up with a python array of strings like:

['the', "dog's", 'bite']

Any simple clear way of parsing this in python would be
great; I just assume that "re" is the appropriate technique.
Performance is not an issue.

-- George

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


Re: Using properties

2005-05-25 Thread Terry Reedy

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Thanks for the help. I now understand it better. As Bruno points out, I
> really don't need a property in this case, as my attribute is public,
> and I will remove it.

As much to the point is that your name attribute is static in the sense of 
being a fixed object between settings.  Should you later want to make it 
dynamic (or perhaps lazy) in the sense of being computed on demand, then 
you can do so with property() *without* changing the external interface to 
the class.

A third reason for property() is when you want to do something in addition 
to the access, such as reporting the access to something else.

Terry J. Reedy



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


Re: Where do I find the dispatch name?

2005-05-25 Thread James Carroll


I looked through all the IIDs in:  PythonWin, Tools, COM Object
Browser, RegisteredCategories, Automation Objects.

After looking through all the IIDs I saw one that looked like it might
work... and it did.

-Jim





On 5/25/05, James Carroll <[EMAIL PROTECTED]> wrote:
> I just ran makepy to create a wrapper for my com object, and it
> generated the wrapper with the CLSID.py under
> site-packages/win32com/gen_py/
> 
> Now, I'm trying to figure out how to invoke it.  How do I figure out
> what string to give Dispatch?
> 
> For instance:
> xl = win32com.client.Dispatch("Excel.Application")
> 
> If I understand right would give me an instance of the wrapper
> Do I give it the entire classID?
> 
> -Jim
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: namespaces in eval(): spot error in 3 line program

2005-05-25 Thread Terry Reedy

"pasa" <[EMAIL PROTECTED]> wrote in message

> Do functions carry their own pointer to global namespace,
> which gets defined at function compile time, or what is
> happening here?

To expand on Just's answer:

For lexical scoping --  resolution of globals in the definition context --  
some reference to that context is required.  The alternative of dynamic 
scoping -- resolution of globals in the calling context -- has been tried 
in other languages and found wanting.  For instance, if you call a function 
in the math module that uses pi, sin, or cos, one almost certainly wants it 
to use the object defined and bound to pi, sin, or cos in the math module. 
That happens automatically with lexical scoping.  With dynamic scoping, one 
would have to do 'from math import *' first.  And so on for everything 
else.

Terry J. Reedy



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


Automatically populate and submit HTML Forms

2005-05-25 Thread rbt
How can I make a python client script connect to a Web server and 
automatically populate form fields and then submit the form?

For example, say I wanted to check and see if 1924 was a leap year... 
how would I populate the 'year' field and then submit it for processing? 
I have no control of the server... just the client script.


  Enter a year and find out if it's a leap year:
  
  
  


Many thanks,

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


Re: Pyro2.3 problem

2005-05-25 Thread Irmen de Jong
Golawala, Moiz M (GE Infrastructure) wrote:
> Hi All,
> 
> I am seeing some interesting behavior with Pyro 2.3. I created a server using 
> Pyro2.2
> and a client on a different machine with Python2.2 and communication was just 
> fine (I
> am not using a Name server). However when I upgraded the client to Pyro2.3 
> (the
> server was sill on Pyro2.2) and try and communicate with the server, I get a 
> bunch of
> exception telling me that there is a problem with the URI etc..
[...]

Why are you still using this ancient version?! Pyro 2.2/2.3 is
almost 4 (four) years old! There have been uncountable improvements
and fixes in the versions after that!

Please upgrade to a later version, 3.4 or 3.5beta (released last february).

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


Pyro2.3 problem

2005-05-25 Thread Golawala, Moiz M (GE Infrastructure)
Hi All, 

I am seeing some interesting behavior with Pyro 2.3. I created a server using 
Pyro2.2 and a client on a different machine with Python2.2 and communication 
was just fine (I am not using a Name server).
However when I upgraded the client to Pyro2.3 (the server was sill on Pyro2.2) 
and try and communicate with the server, I get a bunch of exception telling me 
that there is a problem with the URI etc..

My server code is simple:
 
import MyClass
from Pyro.ext import remote_nons

remote_nons.provide_server_object(MyClass.MyClass(), 'myhost', 'myhost', 9199)
sys.exit(remote_nons.handle_request())


My client code is:

from Pyro.ext import remote_nons
s = remote_nons.get_server_object('Myhost','Myhost',9199)
s.helloWorld()

Please can someone tell me why the above code would work when both client and 
server are running Pyro2.2 but not when server is on Pyro2.2 and client is on 
Pyro2.3

Any help is greatly appreciated.

Thanks,
Moiz Golawala
GE Infrastructure, Security
Software Engineer
Enterprise Solutions

T 561 912 5972
F 561 994 6572
E [EMAIL PROTECTED] 
www.gesecurity.com

791 Park of Commerce Blvd., Suite 100
Boca Raton, FL, 33487, U.S.A.
GE Security, Inc.

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


Where do I find the dispatch name?

2005-05-25 Thread James Carroll
I just ran makepy to create a wrapper for my com object, and it
generated the wrapper with the CLSID.py under
site-packages/win32com/gen_py/

Now, I'm trying to figure out how to invoke it.  How do I figure out
what string to give Dispatch?

For instance:
xl = win32com.client.Dispatch("Excel.Application")

If I understand right would give me an instance of the wrapper
Do I give it the entire classID?

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


Re: Using properties

2005-05-25 Thread tkpmep
Thanks for the help. I now understand it better. As Bruno points out, I
really don't need a property in this case, as my attribute is public,
and I will remove it.

Thomas Philips

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


Re: Unusable outer edge of Tkinter canvases?

2005-05-25 Thread Dave Opstad
In article <[EMAIL PROTECTED]>,
 "Fredrik Lundh" <[EMAIL PROTECTED]> wrote:

> to fix this, you can either set the border width to zero, add scrollbars
> to the widget (this fixes the coordinate system), or explicitly reset the
> coordinate system:
> 
> w.xview_moveto(0)
> w.yview_moveto(0)

The canvas's border width was already zero, but when I moved the origin 
to (0,0) via xview_moveto and yview_moveto I was able to successfully 
draw all three rectangles.

Just out of curiosity, why aren't these zeroed to start with when the 
widget is created, given the default border width is zero? And is there 
a way of determining what they're set at, something like a xview_get() 
method? I looked at all the canvas's attributes (calling configure()) 
but nothing in there referred to xview or yview.

Thanks for the help!
Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python analog of Ruby on Rails?

2005-05-25 Thread bruno modulix
Christopher J. Bottaro wrote:
> Hello fellow Pythonists,
>   Is there such a thing? 

As what ?
Oops, sorry, the question is in the subject... May be helpful to repeat
it in the body.

You may want to have a look at Subway

> My work is thinking of maybe experimenting with
> Ruby on Rails for some lesser projects.  Naturally, I wonder if Python can
> do as good a job or better...

Doing 'as good or better' does not mean 'doing the same'.

-- 
bruno desthuilliers
ruby -e "print '[EMAIL PROTECTED]'.split('@').collect{|p|
p.split('.').collect{|w| w.reverse}.join('.')}.join('@')"
-- 
http://mail.python.org/mailman/listinfo/python-list


Python analog of Ruby on Rails?

2005-05-25 Thread Christopher J. Bottaro
Hello fellow Pythonists,
  Is there such a thing?  My work is thinking of maybe experimenting with
Ruby on Rails for some lesser projects.  Naturally, I wonder if Python can
do as good a job or better...

Thanks for the info,
-- C

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


Re: namespaces in eval(): spot error in 3 line program

2005-05-25 Thread Just
In article <[EMAIL PROTECTED]>,
 "pasa" <[EMAIL PROTECTED]> wrote:

> I'm an old time python user, but just got bitten by namespaces in eval.
> If this is an old discussion somewhere, feel free to point me there.
> 
> Based on the documentation, I would have expected the following to
> work:
> 
> def foo(k): print k; print a
> 
> ns = {'a':1, 'foo': foo}
> eval('foo(2)', ns)
> 
> But it does not, complete session:
> 
> [EMAIL PROTECTED] ~]$ python
> Python 2.4 (#2, Feb 13 2005, 22:08:03)
> [GCC 3.4.3 (Mandrakelinux 10.1 3.4.3-3mdk)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> def foo(k): print k; print a
> ...
> >>> ns = {'a':1, 'foo': foo}
> >>> eval('foo(2)', ns)
> 2
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "", line 0, in ?
>   File "", line 1, in foo
> NameError: global name 'a' is not defined
> >>>
> 
> huh?  I'd almost be tempted to call this a bug?
> 
> Playing with locals() and globals() I see that this one works,
> which I would not have expected to work:
> 
> def foo(k): print k; print ns['a']
> 
> ns = {'a':1, 'foo': foo}
> eval('foo(2)', ns)
> 
> Prints out
> 2
> 1
> 
> Do functions carry their own pointer to global namespace,
> which gets defined at function compile time, or what is
> happening here?

Function definition time. Your code is more or less equivalent to:

  # A.py:
  def foo(k): print k; print a

  # B.py:
  from A import foo
  a = 1
  foo()

That will fail with a NameError just the same.

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


Re: Trouble with regexes

2005-05-25 Thread Fredrik Lundh
Fernando Rodriguez wrote:

> I'm trying to write a regex that matches a \r char if and only if it
> is not followed by a \n (I want to translate text files from unix
> newlines to windows\dos).

Unix uses \n and Windows uses \r\n, so matching lone \r isn't
going to help you the slighest... (read on)

> I tried this, but it doesn't work:
> p = re.compile(r'(\r)[^\n]', re.IGNORECASE)
>
> it still matches a string such as r'\r\n'

really?

>>> import re
>>> p = re.compile(r'(\r)[^\n]', re.IGNORECASE)
>>> print p.match('\r\n')
None
>>> print p.match(r'\r\n')
None

on the other hand,

<_sre.SRE_Match object at 0x0083B160>
>>> print p.match('\rx')
<_sre.SRE_Match object at 0x0083B120>
>>> print p.match(r'\rx')

it might be a good idea to play a little more with ''-literals and r''-
literals (and print x and print repr(x)) until you understand exactly
how things work...

:::

> I want to translate text files from unix newlines to windows\dos

you don't need regular expressions for that; the easiest way to
convert any kind of line endings to the local format is to open the
source file with the "U" flag:

infile = open(filename, "rU") # universal line endings
outfile = open(outfilename, "w") # text mode is default

s = infile.readline()
outfile.write(s)

:::

if you're converting files from Unix format to Windows format on a
Windows box, you don't have to do anything -- just open the files
in text mode, and Python's file I/O layer will fix the rest for you.





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


Re: IRIX MipsPro compiler chokes on Python.h

2005-05-25 Thread Bram Stolk
Andrew MacIntyre wrote:

> My suspicion would be directed to a #define that is incorrect, as the
> snippet above suggests that select() appears in two system headers
> (/usr/include/sys/time.h & /usr/include/unistd.h).

thanks for the info.
I need to undef the following from my pyconfig.h to make it pass the
compiler:

HAVE_SYS_TIME_H
TIME_WITH_SYS_TIME

   Bram


> That is ./configure got something wrong and may need to be modified for
> your platform to sort this out properly, but modifying pyconfig.h to
> correct the incorrect definitions should get you out of trouble.
> 
> -
> Andrew I MacIntyre "These thoughts are mine alone..."
> E-mail: [EMAIL PROTECTED]  (pref) | Snail: PO Box 370
>[EMAIL PROTECTED] (alt) |Belconnen ACT 2616
> Web:http://www.andymac.org/   |Australia
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unusable outer edge of Tkinter canvases?

2005-05-25 Thread Fredrik Lundh
Dave Opstad wrote:

> When drawing rectangles in Tkinter canvases I've noticed the outer edges
> (say 3-5 pixels) don't always draw. For instance, try typing this in an
> interactive session (Terminal in OS X or Command Prompt in Windows XP):
>
> >>> import Tkinter as T
> >>> root = T.Tk()
> >>> f = T.Frame(root)
> >>> f.grid()
> >>> c = T.Canvas(f, width = 300, height = 300)
> >>> c.grid()
> >>> c.create_rectangle(1, 1, 299, 299)
> >>> c.create_rectangle(3, 3, 297, 297)
> >>> c.create_rectangle(5, 5, 295, 295)
>
> On the Mac, the first two rectangles only partly show up (two sides for
> the first one and three for the second), while the third one draws
> completely. On Windows the first rectangle appears partially and the
> final two appear completely.
>
> Is there some simple setting I'm missing? I've tried gridding the canvas
> with padx, pady and also ipadx, ipady values but nothing seems to help
> make the whole rectangle (1, 1, 299, 299) appear.

by default, the coordinate system is aligned with the widget's upper
left corner, which means that things you draw will be covered by the
inner border.

to fix this, you can either set the border width to zero, add scrollbars
to the widget (this fixes the coordinate system), or explicitly reset the
coordinate system:

w.xview_moveto(0)
w.yview_moveto(0)





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


RE: Build error Python 2.4.1 - stat problem?

2005-05-25 Thread Brandt, Servatius
Hello,

I found the solution of my problems.  The configure script decided to
switch on large file support, but the #defines set in pyconfig.h caused
an inconsistency between the stat function calls (32 bit versions) and
the stat structures used (64 bit versions).  After I switched off the
large file support manually in pyconfig.h, all works fine.

Maybe someone could change the configure script so that it tests whether
the large files support really works (create a file of a few bytes and
test its size)?

- Servatius


Servatius Brandt Phone: +49 89 636-41504
Fujitsu Siemens ComputersFax:   +49 89 636-48716
EP SW AD C++ Email: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


ReWrite Request Within SocketServer?

2005-05-25 Thread John Abel
Hi!

I may be missing something simple, but is there a way to have 
verify_request change the request before it gets processed by the 
RequestHandlerClass?

Regards

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


Re: pygame 1.6 for windows (python2.4)

2005-05-25 Thread bc
Got it!  Thank you so much for your much appreciated help.

Bill Carey

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


Trouble with regexes

2005-05-25 Thread Fernando Rodriguez
Hi,

I'm trying to write a regex that matches a \r char if and only if it
is not followed by a \n (I want to translate text files from unix
newlines to windows\dos).

I tried this, but it doesn't work:
p = re.compile(r'(\r)[^\n]', re.IGNORECASE)

it still matches a string such as r'\r\n'

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


namespaces in eval(): spot error in 3 line program

2005-05-25 Thread pasa
I'm an old time python user, but just got bitten by namespaces in eval.
If this is an old discussion somewhere, feel free to point me there.

Based on the documentation, I would have expected the following to
work:

def foo(k): print k; print a

ns = {'a':1, 'foo': foo}
eval('foo(2)', ns)

But it does not, complete session:

[EMAIL PROTECTED] ~]$ python
Python 2.4 (#2, Feb 13 2005, 22:08:03)
[GCC 3.4.3 (Mandrakelinux 10.1 3.4.3-3mdk)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def foo(k): print k; print a
...
>>> ns = {'a':1, 'foo': foo}
>>> eval('foo(2)', ns)
2
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 0, in ?
  File "", line 1, in foo
NameError: global name 'a' is not defined
>>>

huh?  I'd almost be tempted to call this a bug?

Playing with locals() and globals() I see that this one works,
which I would not have expected to work:

def foo(k): print k; print ns['a']

ns = {'a':1, 'foo': foo}
eval('foo(2)', ns)

Prints out
2
1

Do functions carry their own pointer to global namespace,
which gets defined at function compile time, or what is
happening here?

-Harri

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


Unusable outer edge of Tkinter canvases?

2005-05-25 Thread Dave Opstad
When drawing rectangles in Tkinter canvases I've noticed the outer edges 
(say 3-5 pixels) don't always draw. For instance, try typing this in an 
interactive session (Terminal in OS X or Command Prompt in Windows XP):

>>> import Tkinter as T
>>> root = T.Tk()
>>> f = T.Frame(root)
>>> f.grid()
>>> c = T.Canvas(f, width = 300, height = 300)
>>> c.grid()
>>> c.create_rectangle(1, 1, 299, 299)
>>> c.create_rectangle(3, 3, 297, 297)
>>> c.create_rectangle(5, 5, 295, 295)

On the Mac, the first two rectangles only partly show up (two sides for 
the first one and three for the second), while the third one draws 
completely. On Windows the first rectangle appears partially and the 
final two appear completely.

Is there some simple setting I'm missing? I've tried gridding the canvas 
with padx, pady and also ipadx, ipady values but nothing seems to help 
make the whole rectangle (1, 1, 299, 299) appear.

I'm using Python 2.4.1 and TclTkAqua 8.4.9 on Mac OS X 10.3.7, and 
Python 2.3.4 on Windows XP (which comes with a Tcl/Tk whose version I 
don't know).

Thanks for any insights,
Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using properties

2005-05-25 Thread bruno modulix
[EMAIL PROTECTED] wrote:
> I have a class with a name attribute, which I want to modify using
> property.The following code works just fine:
> 
> class Portfolio(object):
> 
> def __init__( self, name="Port1"):
> self.name=name

This may not do what you think it does (see below)

> 
> def getname(self):
> return self._name
> def setname(self,newname="Port2"):
> self._name=newname
> 
> name=property(getname,setname,None,None)
> 
> However, it no longer works if I modify getname and setname to
> 
> def getname(self):
> return self.name
> 
> def setname(self,newname="Port2"):

what's the use of putting a default value here ?

> self.name=newname

How could this work, since self.name is now a property object that calls
 on setname() and getname() ?

> Why is it so critical to have getname and setname modify _name and not
> name? 

because 'name' is how you named your property...

> The constructor does not make name a private attribute, 

Note that there is in fact no notion of private/public in Python (I mean
: in the language). The underscore stuff is nothing more than a convention.

Now you don't seem to understand what happens when __init__ is called.
Try this:

8<
class Portfolio(object):

def __init__( self, name="Port1"):
self.name=name
print "self._name is %s" % self._name
print "self.__class__.name is %s" % self.__class__.name

def _getname(self):
print "in getname"
return self._name

def _setname(self, newname):
print "in setname"
try:
print "self._name is %s" % self._name
except AttributeError, e:
print "got AttributeError %s" % e
print "when trying to access self._name"
self._name=newname

name=property(fget=_getname, fset=_setname)
print "in Portfolio class definition : name is %s" % name

p = Portfolio()
8<

As you can see, the 'name=property(...)' statement at the end of your
class definition is executed when the class definition is first eval'd
(this is when the code is loaded in the interpreter). So when __init__
is called, the statement 'self.name = name' does not create an instance
variable 'name', but calls the existing property, which in turn creates
the instance variable '_name'.

> so why do
> getname and setname have to treat it as such?

>From a technical POV, we don't care if the attribute accessed by a
property is 'private' or whatever. The only thing is that it can't have
the same name as the property...

>From a conceptual POV, it makes no sense (well, IMHO) to use a property
for a 'public' (by convention...) attribute. Either you want a property
(think : a computed attribute) and then you hide the implementation
details, or you're ok with a plain old 'public' attribute and then you
don't use a property.

BTW, this is also true of the setter and getter used by the property:
they are implementation details, and as such should not be exposed as
part of the interface.

HTH
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Problem in Building a Simple EXE

2005-05-25 Thread ParE
Hello,

   I wrote a small script which I have been trying to
convert to an Executable.  I have tried py2exe and
McMillians.  Both will convert it just fine but when I
run it on a machine that does not have Python
installed it will run the script twice. Any ideas on
how I may fix this?

Paras



__ 
Do you Yahoo!? 
Yahoo! Small Business - Try our new Resources site
http://smallbusiness.yahoo.com/resources/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using properties

2005-05-25 Thread Leif K-Brooks
[EMAIL PROTECTED] wrote:
> name=property(getname,setname,None,None)
> 
> However, it no longer works if I modify getname and setname to
> 
> def getname(self):
> return self.name
> 
> def setname(self,newname="Port2"):
> self.name=newname

That's because you're actually modifying the property in setname instead
of modifying the normal attribute. It's equivalent to doing:

def setname(self, newname="Port2"):
self.setname(newname)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using properties

2005-05-25 Thread Terry Reedy

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>I have a class with a name attribute, which I want to modify using
> property.The following code works just fine:
>
> class Portfolio(object):
>
>def __init__( self, name="Port1"):
>self.name=name
>
>def getname(self):
>return self._name
>
>def setname(self,newname="Port2"):
>self._name=newname
>
>name=property(getname,setname,None,None)
>
> However, it no longer works if I modify getname and setname to

What does 'no longer works' mean?  Do you get and exception and traceback? 
If so, what?

>def getname(self):
>return self.name

>def setname(self,newname="Port2"):
>self.name=newname

These both look like infinite loops.  Did you got the related exceptions?
>
> Why is it so critical to have getname and setname modify _name and not
> name? The constructor does not make name a private attribute, so why do
> getname and setname have to treat it as such?

I believe because getting and setting name calls getname and setname.  The 
initializer (not constructor) setting of name results in a call to setname.

Terry J. Reedy



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


distutils, install_data and RPM distributions

2005-05-25 Thread bwooster47

I have a simple python script that I need to create a kit for, and it
has one config file.
This is for Unix only, and very restricted use, so here's my relevant
setup.py:

setup(., scripts=['myscript.py'],
  data_files=[('/etc', ['myscript.cfg'])],...)

My problem is that when I repeatedly run "python setup.py install", it
will always overwrite the exising myscript.py, but if a
/etc/myscript.cfg file exists, it will not overwrite it.

I can use the --force option, or I can add force = 1 in [install_data]
in the setup.cfg - but that does not seem to help me with the RPM
packaging.

I looked at the bdist_rpm create .spec file, and for install it says:
python setup.py install --root=$RPM_BUILD_ROOT --record=INSTALLED_FILES

Two questions:
1) Is there a way to customize the %install line created by bdist_rpm
option of the setup.py script?

2) Or, is there a way I can avoid using a setup.cfg, and put all that
info in the setup.py script itself? I would like to add a --force
option to the "data_files" line in the setup() call...

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


ºô­¶±H¦sªA°È­p¹º¶R¤Q°e¤G..............................................................................................................................................................................................................................................................................................

2005-05-25 Thread dsafl
UHOSTNET.COM 
[EMAIL PROTECTED] 
²{±À¥X¥þ·sÀu´f

ªA°È­p¹º¶R¤Q°e¤G¡A¤Z¹wú¤Q­Ó¤ëªA°È¤ë¶O¡A¦h°e¨â­Ó¤ë¡C
²{§Y¥Ñ¨ä¥¦¤½¥qÂà¥Î§Ú­Ì¡A§Y¦h°e±z¤T­Ó¤ëªA°È¡C
(¥ô¦ó°ì¦WÂಾ)
¤ä´© PHP+MySQL, Access+ASP, ASP.NET, CGI, SSI ¹q¶l¯f¬r¹LÂo, ©U§£¹q¶l¹LÂo ¤Î 
WebMail µ¥..

¥»¤ë§C«e¥Ó½ÐW1000§Y°e­º¦¸¦w¸ËÁʪ«¨®µ{¦¡ osc.
http://shop2.uhostnet.com

¨C¤ë¥u»Ý $20 °_

ªþ°e¹ê¥Îµ{¦¡
ASP ¯d¨¥Ã¯,²á¤Ñ«Ç,ASP ¤H¼Æ¾¹,PHP ¤H¼Æ¾¹,ASP ºô¤W¹q¶lªí®æ,ASP 
Àɮ׺޲zµ{¦¡,ºô¤W°Ó©±,©ç½æ¨t²Î¤Î¦U´Ú½×¾Âµ{¦¡..

¸Ô±¡½Ð°Ñ¾\\¥»¤½¥qºô¯¸
http://www.uhostnet.com
©Î
[EMAIL PROTECTED]@[EMAIL PROTECTED]@¢¶¢µ¢µ¢¸
©Î
[EMAIL PROTECTED]@¬d¸ß
.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Localized Type Inference of Atomic Types in Python

2005-05-25 Thread Blake Garretson
On 5/24/05, Brett C. <[EMAIL PROTECTED]> wrote:
My thesis, "Localized Type Inference of Atomic Types in Python", wassuccessfully defended today for my MS in Computer Science at the CaliforniaPolytechnic State University, San Luis Obispo.  With that stamp of approval I
am releasing it to the world.  You can grab a copy athttp://www.drifty.org/thesis.pdf .

That is one beautiful document.  Seriously nice LaTeX work
here.  The content is nice too (mostly over my head), but I
thoroughly enjoyed the beautiful typesetting, TOC, PDF outline, links,
footnotes, etc.-- Blake T. Garretson  ---  http://blakeg.net
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: uploading files to a webdav SSL enabled server

2005-05-25 Thread Peter Hansen
rbt wrote:
> Has anyone used pure python to upload files to a webdav server over SSL? 

We were not using SSL at the time (since it wasn't supported in standard 
Python, as I recall), but we successfully used the webdav client that 
was part of Zope a few years ago.  I suspect you could adapt it to use 
the new SSL support relatively easily.  Check back for version 2.4 or so 
if you can't find it in the latest Zopes. (I haven't looked at Zope for 
a few years now, so I don't know whether it's still included.)

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


Re: Parsing XML - Newbie help

2005-05-25 Thread Fredrik Lundh
"rh0dium" wrote:

> Ok so up to here I am ok.  I find ( If you want the full xml let me
> know) two blocks of system memory.  It MUST be "System Memory" only.
> Now how do I get a list of all of the children "nodes" of this.  They
> are named bank:N  ( i.e bank:0, bank:1 etc [see below] ).  For each one
> of those there may ( or may not ) have some memory stuck in it.  I can
> tell if there is memory because a size is given.  I want to a list of
> all of the sizes.  From there I can say you have sum(memory) in
> len(memory) banks of total banks.

once you've found a memory node, you should be able to simply loop
over all node children, optionally filter on the id attribute, and look for
size elements.

sizes = []

for elem in tree.findall(".//node"):
if elem.get("class") == "memory":
if elem.findtext("description") == "System Memory":
print "Found system memory bank"
# loop over subnodes
for node in elem:
size = node.findtext("size")
if size:
sizes.append(int(size))

print len(sizes), sum(sizes)

note that this assumes that the size is always in bytes.  if not,
you have to check the units attribute; e.g.

size_elem = node.find("size")
if size_elem is not None:
unit = size_elem.get("units", "bytes")
size = int(size_elem.text)
...





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


Re: python24.zip

2005-05-25 Thread Scott David Daniels
Dieter Maurer wrote:
> "Martin v. Löwis" <[EMAIL PROTECTED]> writes on Sun, 22 May 2005 21:24:41 
> +0200:
>>...
>>>The application was Zope importing about 2.500 modules
>>>from 2 zip files "zope.zip" and "python24.zip".
>>>This resulted in about 12.500 opens -- about 4 times more
>>>than would be expected -- about 10.000 of them failing opens.

I'll bet this means that the 'zope.zip', 'python24.zip' would drop
you to "about 12500 - 1 = 2500" failing opens.  That should be
an easy test: sys.path.insert(0, 'zope.zip') or whatever.
If that works and you want to drop even more, make a copy of zope.zip,
update it with python24.zip, and call the result python24.zip.

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


uploading files to a webdav SSL enabled server

2005-05-25 Thread rbt
Has anyone used pure python to upload files to a webdav server over SSL? 
  I have no control over the server. I can access it with all of the 
various webdav GUIs such as Konqueror, Cadaver, etc. by using a URL like 
this:

webdavs://dav.hostname.com/user_name/uploads

My goal is to upload files automatically with a python script. The 
server requires authentication over SSL which I can do with urllib2 like 
this:

def auth_against_url(url, username, password):

 # This is a slightly modified version that I found here:
 # http://simon.incutio.com/archive/2004/07/15/instant

 import urllib2
 import base64
 request = urllib2.Request(url)
 b64 = base64.encodestring('%s:%s' % (username, password))[:-1]
 request.add_header('Authorization', 'Basic %s' % b64)
 try:
 f = urllib2.urlopen(request)
print f.read()
f.close()
return True
 except urllib2.HTTPError, e:
print e
 return False

auth_against_url('https://dav.hostname.com/user_name/uploads',\
   str.strip(raw_input('Enter User ID: ')),\
  str.strip(raw_input('Enter Password: ')))

If urllib2 supported webdav, I think I'd be in business, but it doesn't. 
Any one who can provide pointers on this? I've googled around to no 
avail. I've began playing with Perl's HTTP::DAV and somone reccomended 
PHP's curl functions as well, but I wanted to try this in Python first.

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


  1   2   >