Re: Sorting a list depending of the indexes of another sorted list

2008-01-21 Thread J. Peng
J. Peng 写道:

>k = (i.split())[3]
>y = (i.split())[1]

btw, why can't I write the above two into one statement?

(k,y) = (i.split())[3,1]
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Bug in __init__?

2008-01-21 Thread cokofreedom
Is there no way of adding a possible warning message (that obviously
could be turned off) to warn users of possible problems linked to
using mutable types as parameters?

Seems to me this could save users a few minutes/hours of headaches and
headscratching. (The biggest issue affecting new programmers these
days!)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorting a list depending of the indexes of another sorted list

2008-01-21 Thread J. Peng
I tried to write it below,it can work,:)

v= """preference 10 host mx1.domain.com
preference 30 host anotherhost.domain.com
preference 20 host mx2.domain.com"""

x=v.split("\n")

li =[]
for i in x:
   k = (i.split())[3]
   y = (i.split())[1]
   li.append((y,k))

li.sort()
print li


the output is:
[('10', 'mx1.domain.com'), ('20', 'mx2.domain.com'), ('30', 
'anotherhost.domain.com')]



Santiago Romero 写道:
>  Hi ...
> 
>  I have the following DNS MX records info:
> 
> domain.com
> preference 10 host mx1.domain.com
> preference 30 host anotherhost.domain.com
> preference 20 host mx2.domain.com
> 
>  I'm storing this info in 2 lists:
> 
> preferences = [10, 30, 20]
> hosts = [ "mx1.domain.com", "anotherhost.domain.com",
> "mx2.domain.com"]
> 
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt

2008-01-21 Thread pythonewbie
On 21 jan, 05:31, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On Sun, 20 Jan 2008 13:58:13 -0800 (PST), pythonewbie
> <[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
>
> > I just would like to know if I would ALWAYS find the install directory
> > in sys.path[6] and site-packages directory in sys.path[7] on any Win32
> > platform and sys.path[2] and site-packages directory in sys.path[6] on
> > any Linux platform.
>
> Unlikely...
>
> >>> sys.path[6]
>
> 'E:\\Python24\\lib\\site-packages\\decoratortools-1.4-py2.4.egg'>>> 
> sys.path[2]
>
> 'E:\\Python24\\lib\\site-packages\\ctypes-1.0.1-py2.4-win32.egg'>>> sys.path
>
> ['', 'E:\\Python24\\lib\\site-packages\\pyopengl-3.0.0a5-py2.4.egg',
> 'E:\\Python24\\lib\\site-packages\\ctypes-1.0.1-py2.4-win32.egg',
> 'E:\\Python24\\lib\\site-packages\\sqlobject-0.7.6-py2.4.egg',
> 'E:\\Python24\\lib\\site-packages\\celementtree-1.0.5_20051216-py2.4-win32.egg',
> 'E:\\Python24\\lib\\site-packages\\configobj-4.4.0-py2.4.egg',
> 'E:\\Python24\\lib\\site-packages\\decoratortools-1.4-py2.4.egg',
> 'E:\\Python24\\lib\\site-packages\\ruledispatch-0.5a0.dev_r2306-py2.4-win32.egg',
> 'E:\\Python24\\lib\\site-packages\\formencode-0.7.1-py2.4.egg',
> 'E:\\Python24\\lib\\site-packages\\pastescript-1.3.4-py2.4.egg',
> 'E:\\Python24\\lib\\site-packages\\elementtree-1.2.6_20050316-py2.4-win32.egg',
> 'E:\\Python24\\lib\\site-packages\\simplejson-1.7.1-py2.4.egg',
> 'E:\\Python24\\lib\\site-packages\\cherrypy-2.2.1-py2.4.egg',
> 'E:\\Python24\\lib\\site-packages\\turbocheetah-0.9.5-py2.4.egg',
> 'E:\\Python24\\lib\\site-packages\\turbojson-1.0-py2.4.egg',
> 'E:\\Python24\\lib\\site-packages\\pyprotocols-1.0a0dev_r2302-py2.4-win32.egg',
> 'E:\\Python24\\lib\\site-packages\\pastedeploy-1.3-py2.4.egg',
> 'E:\\Python24\\lib\\site-packages\\paste-1.3-py2.4.egg',
> 'E:\\Python24\\lib\\site-packages\\cheetah-2.0rc8-py2.4.egg',
> 'E:\\Python24\\lib\\site-packages\\setuptools-0.6c6-py2.4.egg',
> 'E:\\Python24\\lib\\site-packages\\turbogears-1.0.3.2-py2.4.egg',
> 'E:\\Python24\\lib\\site-packages\\turbokid-1.0.2-py2.4.egg',
> 'E:\\Python24\\lib\\site-packages\\kid-0.9.6-py2.4.egg',
> 'e:\\python24\\lib\\site-packages\\scipy',
> 'C:\\WINDOWS\\system32\\python24.zip', 'e:\\UserData\\Dennis Lee
> Bieber\\My Documents', 'E:\\Python24\\DLLs', 'E:\\Python24\\lib',
> 'E:\\Python24\\lib\\plat-win', 'E:\\Python24\\lib\\lib-tk',
> 'E:\\Python24\\Lib\\site-packages\\pythonwin', 'E:\\Python24',
> 'E:\\Python24\\lib\\site-packages',
> 'E:\\Python24\\lib\\site-packages\\Numeric',
> 'E:\\Python24\\lib\\site-packages\\PIL',
> 'E:\\Python24\\lib\\site-packages\\win32',
> 'E:\\Python24\\lib\\site-packages\\win32\\lib',
> 'E:\\Python24\\lib\\site-packages\\wx-2.8-msw-unicode']
>
> >>> os.environ["PATH"]
>
> 'E:\\Python24\\;C:\\GNAT\\bin;C:\\bin;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\PROGRA~1\\MySQL\\MySQL
> Server 5.0\\bin;C:\\Program Files\\SciTE;C:\\Program
> Files\\Java\\jre1.6.0_03\\bin;C:\\Program
> Files\\Java\\jdk1.6.0_03\\bin;C:\\Program Files\\Common
> Files\\Adobe\\AGL;C:\\MSSQL7\\BINN;c:\\PROGRA~1\\sdb\\programs\\bin;c:\\PROGRA~1\\sdb\\programs\\pgm;C:\\Tcl\\bin;C:\\Program
> Files\\Common Files\\Roxio Shared\\DLLShared\\;C:\\Program Files\\Common
> Files\\Roxio Shared\\9.0\\DLLShared\\;e:\\Python24\\Scripts;c:\\Regina'
>
> --
> WulfraedDennis Lee Bieber   KD6MOG
> [EMAIL PROTECTED]  [EMAIL PROTECTED]
> HTTP://wlfraed.home.netcom.com/
> (Bestiaria Support Staff:   [EMAIL PROTECTED])
> HTTP://www.bestiaria.com/

OK Denis Lee, I see now. I appreciate your clear and simple to
understand reply.

All posts on this topic, have been appreciated a lot... Thanks to all
helpers.

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


Re: Just for fun: Countdown numbers game solver

2008-01-21 Thread Paul Rubin
Arnaud Delobelle <[EMAIL PROTECTED]> writes:
> Update: 2, 4, 5, 8, 9, 25 can reach any target between 100 and 999.

Are you sure?  What expression do you get for target = 758?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Just for fun: Countdown numbers game solver

2008-01-21 Thread dg . google . groups
Hi all,

It's great how many different sorts of solutions (or almost solutions)
this puzzle has generated. Speedwise, for reference my solution posted
above takes about 40 seconds on my 1.8GHz laptop, and the less elegant
version (on my webpage linked to in the original post) takes about 15
seconds. It seems to me like surely this problem can be more
efficiently solved than that?

My version isn't very Pythonic (it could almost be written in C++ the
way I've done it) so I liked the idea of the first solution, but I
don't think it can be fixed. I adapted it so that it doesn't use the
same number more than once, but it still has some problems. Firstly,
it only finds solution ((a op b) op c) op d etc. and won't find (for
example (1+2)*(3+4). Secondly, it stores a dictionary value->how to
get to value which is fine if you can re-use numbers because one way
to get to a given value is as good as another, but sometimes you can
get to the same number in two different ways using different numbers,
so it misses solutions.

Paul: 758 = 8+(5*((2+4)*25))

Arnaud: I haven't had time to play with your solution yet - how quick
does it run?

My fantasy is that there is a solution that isn't TOO slow where you
can just look at the code and go 'Oh yes, of course that works!' and
understand it immediately. Maybe that's too much to ask even of
Python! ;-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: When is min(a, b) != min(b, a)?

2008-01-21 Thread Steven D'Aprano
On Sun, 20 Jan 2008 21:15:02 -0600, Albert Hopkins wrote:

> This issue may have been referred to in
> news:<[EMAIL PROTECTED]> but I didn't
> entirely understand the explanation.  Basically I have this:
> 
> >>> a = float(6)
> >>> b = float('nan')
> >>> min(a, b)
> 6.0
> >>> min(b, a)
> nan
> >>> max(a, b)
> 6.0
> >>> max(b, a)
> nan
> 
> Before I did not know what to expect, but I certainly didn't expect
> this.  So my question is what is the min/max of a number and NaN or is
> it not defined (for which I would have expected either an exception to
> be raised or NaN returned in each case).


According to the IEEE-754 standard the usual trichotomy of "x is less 
than y, x is equal to y, or x is greater than y" has to be extended to 
include "x and y are unordered". Comparisons with NaNs are unordered, and 
so expressions like "x < nan" should signal an exception.

(However both == and != do not signal exceptions, they return False and 
True respectively.)

Unfortunately, the standard conflicts with Python's requirement that 
comparisons should always return True or False, so the next "least bad" 
alternative is to have comparisons with NaN to return False. That is:

>>> 5 < float('nan')
False
>>> 5 >= float('nan')
False

So BEWARE of assuming that if x < y returns False, y >= x must return 
True. That does not hold for floats.

Aside: Apple's Power PC Numerics math library extended the usual six 
comparison operators to fourteen. I don't judge whether this was a good 
idea or not.

http://developer.apple.com/documentation/mac/PPCNumerics/PPCNumerics-37.html#MARKER-9-1


Given that NaNs are unordered, the "right" thing for max() and min() to 
do is raise an exception. But failing that, the next best thing would be 
for them to ignore any NaNs. Any way you look at it, for min or max to 
return a nan is a mistake. Possibly even a bug.



> As a corrollary would I be able to rely on the above behavior or is it
> subject to change (to fix a bug in min/max perhaps :-)?

Presently, you can't rely on *any* behaviour of NaNs and INFs in Python, 
since they all depend on the underlying C library. Even whether or not 
you can create them is not defined in Python.



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


Re: Just for fun: Countdown numbers game solver

2008-01-21 Thread Terry Jones
> "Arnaud" == Arnaud Delobelle <[EMAIL PROTECTED]> writes:
Arnaud> In countdown you are not required to use all numbers to reach the
Arnaud> target.  This means you are missing solutions, e.g.  (1, 3, 6,
Arnaud> 'mul', 'add', 7 , 'add', 9, 'mul')

Hi Arnaud.

Thanks, I didn't know that. The fix is a simple change to the first if my
function below.

WRT to the missing solution, note that my code only allowed multiplication
by 1 if it was the last thing done. That was because you can multiply by 1
at any time, and I didn't want to see those trivially equivalent solutions
(same goes for adding 0). Seeing as you're allowed to omit numbers, I've
now gotten rid of those trivial operations altogether in my solution.

Code and output below.

Terry


from operator import *

def countdown(target, nums, numsAvail, value, partialSolution, solutions, 
ops=(add, mul, sub, div)):
if value == target or not any(numsAvail):
# Ran out of available numbers. Add the solution, if we're right.
if value == target:
solutions.add(tuple(partialSolution))
elif value is None:
# Use each distinct number as a starting value.
used = set()
for i, num in enumerate(nums):
if num not in used:
numsAvail[i] = False
used.add(num)
partialSolution.append(num)
countdown(target, nums, numsAvail, num, partialSolution, 
solutions, ops)
numsAvail[i] = True
partialSolution.pop()
else:
for op in ops:
for i, num in enumerate(nums):
if numsAvail[i]:
numsAvail[i] = False
moreAvail = any(numsAvail)
try:
lastNum, lastOp = partialSolution[-2:]
except ValueError:
lastNum, lastOp = partialSolution[-1], None
# Don't allow any of:
if not any((
# Div: after mul, by 1, by 0, producing a fraction.
(op == div and (lastOp == 'mul' or num <= 1 or value % 
num != 0)),
# If initial mul/add, canonicalize to 2nd operator 
biggest.
((op == mul or op == add) and lastOp is None and num > 
lastNum),
# Don't allow add or sub of 0.
((op == add or op == sub) and num == 0),
# Don't allow mult by 1.
(op == mul and num == 1),
# Don't allow sub after add (allow add after sub).
(op == sub and lastOp == 'add'),
# If same op twice in a row, canonicalize operand order.
(lastOp == op.__name__ and num > lastNum)
)):
partialSolution.extend([num, op.__name__])
countdown(target, nums, numsAvail, op(value, num), 
partialSolution, solutions, ops)
del partialSolution[-2:]
numsAvail[i] = True

for nums, target in (((100, 9, 7, 6, 3, 1), 253),
 ((100, 9, 7, 6, 3, 1), 234),
 ((2, 3, 5), 21),
 ((7, 8, 50, 8, 1, 3), 923),
 ((8, 8), 16),
 ((8, 8, 8), 8),
 ((8, 0), 8),
 ((7,), 8),
 ((), 8),
 ((8, 8, 8, 8), 32)):
solutions = set()
countdown(target, nums, [True,] * len(nums), value=None, 
partialSolution=[], solutions=solutions)
print "%d solutions to: target %d, numbers = %s" % (len(solutions), target, 
nums)
for s in sorted(solutions, cmp=lambda a, b: cmp(len(a), len(b)) or cmp(a, 
b)):
print '\t', s


$ time countdown.py 
8 solutions to: target 253, numbers = (100, 9, 7, 6, 3, 1)
(6, 3, 'mul', 1, 'sub', 9, 'mul', 100, 'add')
(7, 6, 'mul', 9, 'add', 3, 'mul', 100, 'add')
(9, 3, 'sub', 7, 'mul', 6, 'mul', 1, 'add')
(100, 9, 'sub', 7, 'sub', 3, 'mul', 1, 'add')
(3, 1, 'add', 6, 'mul', 7, 'sub', 9, 'mul', 100, 'add')
(7, 1, 'add', 6, 'mul', 3, 'mul', 100, 'add', 9, 'add')
(7, 6, 'add', 3, 'add', 1, 'add', 9, 'mul', 100, 'add')
(100, 7, 'sub', 6, 'sub', 3, 'mul', 9, 'sub', 1, 'add')
19 solutions to: target 234, numbers = (100, 9, 7, 6, 3, 1)
(6, 3, 'mul', 7, 'add', 1, 'add', 9, 'mul')
(7, 1, 'add', 9, 'mul', 6, 'add', 3, 'mul')
(7, 3, 'mul', 1, 'sub', 6, 'add', 9, 'mul')
(7, 6, 'mul', 3, 'mul', 100, 'sub', 9, 'mul')
(100, 1, 'sub', 3, 'div', 7, 'sub', 9, 'mul')
(100, 1, 'sub', 7, 'mul', 9, 'add', 3, 'div')
(100, 7, 'mul', 3, 'mul', 6, 'add', 9, 'div')
(100, 9, 'sub', 7, 'div', 6, 'mul', 3, 'mul')
(100, 9, 'sub', 7, 'sub', 6, 'sub', 3, 'mul')
(6, 1, 'add', 100, 'mul', 7, 'sub', 9, 'add', 3, 'div')

Re: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt

2008-01-21 Thread pythonewbie
On 21 jan, 09:53, pythonewbie <[EMAIL PROTECTED]> wrote:
> On 21 jan, 05:31, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Sun, 20 Jan 2008 13:58:13 -0800 (PST), pythonewbie
> > <[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
>
> > > I just would like to know if I would ALWAYS find the install directory
> > > in sys.path[6] and site-packages directory in sys.path[7] on any Win32
> > > platform and sys.path[2] and site-packages directory in sys.path[6] on
> > > any Linux platform.
>
> > Unlikely...
>
> > >>> sys.path[6]
>
> > 'E:\\Python24\\lib\\site-packages\\decoratortools-1.4-py2.4.egg'>>> 
> > sys.path[2]
>
> > 'E:\\Python24\\lib\\site-packages\\ctypes-1.0.1-py2.4-win32.egg'>>> sys.path
>
> > ['', 'E:\\Python24\\lib\\site-packages\\pyopengl-3.0.0a5-py2.4.egg',
> > 'E:\\Python24\\lib\\site-packages\\ctypes-1.0.1-py2.4-win32.egg',
> > 'E:\\Python24\\lib\\site-packages\\sqlobject-0.7.6-py2.4.egg',
> > 'E:\\Python24\\lib\\site-packages\\celementtree-1.0.5_20051216-py2.4-win32.egg',
> > 'E:\\Python24\\lib\\site-packages\\configobj-4.4.0-py2.4.egg',
> > 'E:\\Python24\\lib\\site-packages\\decoratortools-1.4-py2.4.egg',
> > 'E:\\Python24\\lib\\site-packages\\ruledispatch-0.5a0.dev_r2306-py2.4-win32.egg',
> > 'E:\\Python24\\lib\\site-packages\\formencode-0.7.1-py2.4.egg',
> > 'E:\\Python24\\lib\\site-packages\\pastescript-1.3.4-py2.4.egg',
> > 'E:\\Python24\\lib\\site-packages\\elementtree-1.2.6_20050316-py2.4-win32.egg',
> > 'E:\\Python24\\lib\\site-packages\\simplejson-1.7.1-py2.4.egg',
> > 'E:\\Python24\\lib\\site-packages\\cherrypy-2.2.1-py2.4.egg',
> > 'E:\\Python24\\lib\\site-packages\\turbocheetah-0.9.5-py2.4.egg',
> > 'E:\\Python24\\lib\\site-packages\\turbojson-1.0-py2.4.egg',
> > 'E:\\Python24\\lib\\site-packages\\pyprotocols-1.0a0dev_r2302-py2.4-win32.egg',
> > 'E:\\Python24\\lib\\site-packages\\pastedeploy-1.3-py2.4.egg',
> > 'E:\\Python24\\lib\\site-packages\\paste-1.3-py2.4.egg',
> > 'E:\\Python24\\lib\\site-packages\\cheetah-2.0rc8-py2.4.egg',
> > 'E:\\Python24\\lib\\site-packages\\setuptools-0.6c6-py2.4.egg',
> > 'E:\\Python24\\lib\\site-packages\\turbogears-1.0.3.2-py2.4.egg',
> > 'E:\\Python24\\lib\\site-packages\\turbokid-1.0.2-py2.4.egg',
> > 'E:\\Python24\\lib\\site-packages\\kid-0.9.6-py2.4.egg',
> > 'e:\\python24\\lib\\site-packages\\scipy',
> > 'C:\\WINDOWS\\system32\\python24.zip', 'e:\\UserData\\Dennis Lee
> > Bieber\\My Documents', 'E:\\Python24\\DLLs', 'E:\\Python24\\lib',
> > 'E:\\Python24\\lib\\plat-win', 'E:\\Python24\\lib\\lib-tk',
> > 'E:\\Python24\\Lib\\site-packages\\pythonwin', 'E:\\Python24',
> > 'E:\\Python24\\lib\\site-packages',
> > 'E:\\Python24\\lib\\site-packages\\Numeric',
> > 'E:\\Python24\\lib\\site-packages\\PIL',
> > 'E:\\Python24\\lib\\site-packages\\win32',
> > 'E:\\Python24\\lib\\site-packages\\win32\\lib',
> > 'E:\\Python24\\lib\\site-packages\\wx-2.8-msw-unicode']
>
> > >>> os.environ["PATH"]
>
> > 'E:\\Python24\\;C:\\GNAT\\bin;C:\\bin;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\PROGRA~1\\MySQL\\MySQL
> > Server 5.0\\bin;C:\\Program Files\\SciTE;C:\\Program
> > Files\\Java\\jre1.6.0_03\\bin;C:\\Program
> > Files\\Java\\jdk1.6.0_03\\bin;C:\\Program Files\\Common
> > Files\\Adobe\\AGL;C:\\MSSQL7\\BINN;c:\\PROGRA~1\\sdb\\programs\\bin;c:\\PROGRA~1\\sdb\\programs\\pgm;C:\\Tcl\\bin;C:\\Program
> > Files\\Common Files\\Roxio Shared\\DLLShared\\;C:\\Program Files\\Common
> > Files\\Roxio Shared\\9.0\\DLLShared\\;e:\\Python24\\Scripts;c:\\Regina'
>
> > --
> > WulfraedDennis Lee Bieber   KD6MOG
> > [EMAIL PROTECTED]  [EMAIL PROTECTED]
> > HTTP://wlfraed.home.netcom.com/
> > (Bestiaria Support Staff:   [EMAIL PROTECTED])
> > HTTP://www.bestiaria.com/
>
> OK Denis Lee, I see now. I appreciate your clear and simple to
> understand reply.
>
> All posts on this topic, have been appreciated a lot... Thanks to all
> helpers.
>
> Cheers

Hi John Machin,

Your code :
>>> import sys, re
>>> for p in sys.path:

...m = re.match(r'(.*)[\\/][Ll]ib[\\/]site-packages$', p)
...if m:
...   print m.group(1, 0)
...   break
... else:
...raise Exception('Huh?')
...

Does not work on my PC : Traceback (most recent call last):
  File "/home/eproust/john-machin_recup_rep_site-packages.py", line 9,
in 
raise Exception('Huh?')
Exception: Huh?

Even if I remove all code below the else: part of the script...

-

Thanks for your advice to read : 
http://www.python.org/community/sigs/current/distutils-sig/

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


Re: Just for fun: Countdown numbers game solver

2008-01-21 Thread Terry Jones
> "Paul" == Paul Rubin <"http://phr.cx"@NOSPAM.invalid> writes:

Hi Paul

Paul> Here's my latest, which I think is exhaustive, but it is very slow.
Paul> It prints a progress message now and then just to give the user some
Paul> sign of life.  It should print a total of 256-8 = 248 of those
Paul> messages and it takes around 20 minutes on my old 1 Ghz Pentium 3.
Paul> It does find plenty of solutions for 234, e.g.

Paul> 234 mul(9,sub(mul(mul(6,mul(3,1)),7),100))

Paul> There are some obvious clunky ways to speed it up through memoizing
Paul> and symmetry folding but I can't help thinking there's a concise
Paul> elegant way to do that too.

The symmetry folding is important, you can cut off many recursive calls. My
code runs in 0.5 seconds for the 234 problem, but I have a MacBook Pro :-)

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


Re: eucledian dist calculations

2008-01-21 Thread John Machin
On Jan 21, 6:44 pm, nodrogbrown <[EMAIL PROTECTED]> wrote:
> hi
> i am using python to do some image data calculations..I use the
> following numpy.ndarrays ,(i have given their shapes and ranks)
>
> weights=ndarray :shape(100,30),ndim=2   will have vals like
> 2458121847.49 (of  type 'numpy.float64')
> input_weight=ndarray :shape(30,),ndim=1 (similar to above but diff
> vals)
> distance =ndarray :shape(30,),ndim=1
> mindistance==ndarray :shape(30,),ndim=1
>
> now i am calculating the euclidian distance of 'input_weight' from
> 'weight'
> since this is the cumulative diff i do this in this way
>
> 
> for image in range(100):
>temp=0.0
>for j in range(30):
> distance[j]=abs(input_weight[j]-weights[image,j])
>
>if(image==0):
> #at the start copy from distance to mindistance
> mindistance=distance.copy()
>if (sum(mindistance) > sum(distance)):
> imgindex=image # i use this  later to access a list
> mindistance=distance.copy()
>
> # now normalise the mindistance
> array
> if (max(mindistance) > 0.0):
> mindistance=mindistance/(max(mindistance))
>
> dist=sum(mindistance)
>
> 
>
> this gives me the correct results

Are you sure? What happens if the vector with the smallest
sum(distance) is the first one?

> but i am worried if this is a bit
> unpythonish?
> (been a java programmer for a long time..) i wd like to know if there
> is a better way

1. 'temp' is not used
2. Lose the superfluous parentheses in 'if' statements
3. Put space around operators
4. I've never used any of numpy & friends, but:
(a) Can't you replace the inner loop with something like this:
   distance = abs(input_weight - weights[image, :])
(b) I doubt that you need the .copy()
5. Lose the hard-wired numbers like 30 and 100
6. Put it inside a function and *TEST* it

The word you were looking for is 'unpythonic', but the principles
behind the above apply to any language.

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


Re: Sorting a list depending of the indexes of another sorted list

2008-01-21 Thread Steven D'Aprano
On Mon, 21 Jan 2008 16:23:50 +0800, J. Peng wrote:

> J. Peng 写道:
> 
>>k = (i.split())[3]
>>y = (i.split())[1]
> 
> btw, why can't I write the above two into one statement?
> 
> (k,y) = (i.split())[3,1]

I don't know. What's "i"?

I'm guessing "i" is a string (and what a horrible choice of a name for a 
string!) So i.split() will return a list. List indexing with multiple 
arguments isn't defined, which is why you can't write 

k, y = (i.split())[3,1]


BTW, the outermost set of brackets is unnecessary. You can write:

i.split()[3] 

instead of (i.split())[3]


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

Re: Sorting a list depending of the indexes of another sorted list

2008-01-21 Thread Peter Otten
Santiago  Romero wrote:

>  I'm trying to sort both lists so that they end like this:
> 
> preferences = [10, 20, 30]
> hosts = [ "mx1.domain.com", "mx2.domain.com",
> "anotherhost.domain.com" ]
> 
>  I want to sort hosts list depending on the numeric order of
> "preferences".

The following relies on undocumented (I hope) behaviour:

>>> preferences = [10, 30, 20]
>>> hosts = [ "mx1.domain.com", "anotherhost.domain.com", "mx2.domain.com"]
>>> hosts.sort(key=lambda x, p=iter(preferences).next: p())
>>> preferences.sort()
>>> hosts
['mx1.domain.com', 'mx2.domain.com', 'anotherhost.domain.com']
>>> preferences
[10, 20, 30]

Don't do it, use a list of tuples as already suggested.

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


Re: Just for fun: Countdown numbers game solver

2008-01-21 Thread dg . google . groups
Decided I may as well post my other solution while I'm at it. The neat
trick here is redefining the add, mul, etc. functions so that they
raise exceptions for example if x>y then add(x,y) raises an exception
which is handled by the search algorithm to mean don't continue that
computation - this stops you from having to evaluate x+y AND y+x, etc.

sub = lambda x,y:x-y
def add(x,y):
if x<=y: return x+y
raise ValueError
def mul(x,y):
if x<=y or x==1 or y==1: return x*y
raise ValueError
def div(x,y):
if not y or x%y or y==1:
raise ValueError
return x/y

add.disp = '+'
mul.disp = '*'
sub.disp = '-'
div.disp = '/'

standard_ops = [ add, sub, mul, div ]

def strexpression(e):
if len(e)==3:
return '('+strexpression(e[1])+e[0].disp+strexpression(e[2])
+')'
elif len(e)==1:
return str(e[0])

# I don't like this function, it's nice and short but is it clear
# what it's doing just from looking at it?
def expressions(sources,ops=standard_ops,minremsources=0):
for i in range(len(sources)):
yield ([sources[i]],sources[:i]+sources[i+1:],sources[i])
if len(sources)>=2+minremsources:
for e1, rs1, v1 in expressions(sources,ops,minremsources+1):
for e2, rs2, v2 in expressions(rs1,ops,minremsources):
for o in ops:
try: yield ([o,e1,e2],rs2,o(v1,v2))
except ValueError: pass

def findfirsttarget(target,sources,ops=standard_ops):
for e,s,v in expressions(sources,ops):
if v==target:
return strexpression(e)
return None

print findfirsttarget(923,[7,8,50,8,1,3])

gives:

((7*(((8*50)-1)/3))-8)

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


Re: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt

2008-01-21 Thread John Machin
On Jan 21, 8:12 pm, pythonewbie <[EMAIL PROTECTED]> wrote:
> On 21 jan, 09:53, pythonewbie <[EMAIL PROTECTED]> wrote:
>
>
>
> > On 21 jan, 05:31, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
>
> > > On Sun, 20 Jan 2008 13:58:13 -0800 (PST), pythonewbie
> > > <[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
>
> > > > I just would like to know if I would ALWAYS find the install directory
> > > > in sys.path[6] and site-packages directory in sys.path[7] on any Win32
> > > > platform and sys.path[2] and site-packages directory in sys.path[6] on
> > > > any Linux platform.
>
> > > Unlikely...
>
> > > >>> sys.path[6]
>
> > > 'E:\\Python24\\lib\\site-packages\\decoratortools-1.4-py2.4.egg'>>> 
> > > sys.path[2]
>
> > > 'E:\\Python24\\lib\\site-packages\\ctypes-1.0.1-py2.4-win32.egg'>>> 
> > > sys.path
>
> > > ['', 'E:\\Python24\\lib\\site-packages\\pyopengl-3.0.0a5-py2.4.egg',
> > > 'E:\\Python24\\lib\\site-packages\\ctypes-1.0.1-py2.4-win32.egg',
> > > 'E:\\Python24\\lib\\site-packages\\sqlobject-0.7.6-py2.4.egg',
> > > 'E:\\Python24\\lib\\site-packages\\celementtree-1.0.5_20051216-py2.4-win32.egg',
> > > 'E:\\Python24\\lib\\site-packages\\configobj-4.4.0-py2.4.egg',
> > > 'E:\\Python24\\lib\\site-packages\\decoratortools-1.4-py2.4.egg',
> > > 'E:\\Python24\\lib\\site-packages\\ruledispatch-0.5a0.dev_r2306-py2.4-win32.egg',
> > > 'E:\\Python24\\lib\\site-packages\\formencode-0.7.1-py2.4.egg',
> > > 'E:\\Python24\\lib\\site-packages\\pastescript-1.3.4-py2.4.egg',
> > > 'E:\\Python24\\lib\\site-packages\\elementtree-1.2.6_20050316-py2.4-win32.egg',
> > > 'E:\\Python24\\lib\\site-packages\\simplejson-1.7.1-py2.4.egg',
> > > 'E:\\Python24\\lib\\site-packages\\cherrypy-2.2.1-py2.4.egg',
> > > 'E:\\Python24\\lib\\site-packages\\turbocheetah-0.9.5-py2.4.egg',
> > > 'E:\\Python24\\lib\\site-packages\\turbojson-1.0-py2.4.egg',
> > > 'E:\\Python24\\lib\\site-packages\\pyprotocols-1.0a0dev_r2302-py2.4-win32.egg',
> > > 'E:\\Python24\\lib\\site-packages\\pastedeploy-1.3-py2.4.egg',
> > > 'E:\\Python24\\lib\\site-packages\\paste-1.3-py2.4.egg',
> > > 'E:\\Python24\\lib\\site-packages\\cheetah-2.0rc8-py2.4.egg',
> > > 'E:\\Python24\\lib\\site-packages\\setuptools-0.6c6-py2.4.egg',
> > > 'E:\\Python24\\lib\\site-packages\\turbogears-1.0.3.2-py2.4.egg',
> > > 'E:\\Python24\\lib\\site-packages\\turbokid-1.0.2-py2.4.egg',
> > > 'E:\\Python24\\lib\\site-packages\\kid-0.9.6-py2.4.egg',
> > > 'e:\\python24\\lib\\site-packages\\scipy',
> > > 'C:\\WINDOWS\\system32\\python24.zip', 'e:\\UserData\\Dennis Lee
> > > Bieber\\My Documents', 'E:\\Python24\\DLLs', 'E:\\Python24\\lib',
> > > 'E:\\Python24\\lib\\plat-win', 'E:\\Python24\\lib\\lib-tk',
> > > 'E:\\Python24\\Lib\\site-packages\\pythonwin', 'E:\\Python24',
> > > 'E:\\Python24\\lib\\site-packages',
> > > 'E:\\Python24\\lib\\site-packages\\Numeric',
> > > 'E:\\Python24\\lib\\site-packages\\PIL',
> > > 'E:\\Python24\\lib\\site-packages\\win32',
> > > 'E:\\Python24\\lib\\site-packages\\win32\\lib',
> > > 'E:\\Python24\\lib\\site-packages\\wx-2.8-msw-unicode']
>
> > > >>> os.environ["PATH"]
>
> > > 'E:\\Python24\\;C:\\GNAT\\bin;C:\\bin;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\PROGRA~1\\MySQL\\MySQL
> > > Server 5.0\\bin;C:\\Program Files\\SciTE;C:\\Program
> > > Files\\Java\\jre1.6.0_03\\bin;C:\\Program
> > > Files\\Java\\jdk1.6.0_03\\bin;C:\\Program Files\\Common
> > > Files\\Adobe\\AGL;C:\\MSSQL7\\BINN;c:\\PROGRA~1\\sdb\\programs\\bin;c:\\PROGRA~1\\sdb\\programs\\pgm;C:\\Tcl\\bin;C:\\Program
> > > Files\\Common Files\\Roxio Shared\\DLLShared\\;C:\\Program Files\\Common
> > > Files\\Roxio Shared\\9.0\\DLLShared\\;e:\\Python24\\Scripts;c:\\Regina'
>
> > > --
> > > WulfraedDennis Lee Bieber   KD6MOG
> > > [EMAIL PROTECTED]  [EMAIL PROTECTED]
> > > HTTP://wlfraed.home.netcom.com/
> > > (Bestiaria Support Staff:   [EMAIL PROTECTED])
> > > HTTP://www.bestiaria.com/
>
> > OK Denis Lee, I see now. I appreciate your clear and simple to
> > understand reply.
>
> > All posts on this topic, have been appreciated a lot... Thanks to all
> > helpers.
>
> > Cheers
>
> Hi John Machin,
>
> Your code :
>
> >>> import sys, re
> >>> for p in sys.path:
>
> ...m = re.match(r'(.*)[\\/][Ll]ib[\\/]site-packages$', p)
> ...if m:
> ...   print m.group(1, 0)
> ...   break
> ... else:
> ...raise Exception('Huh?')
> ...
>
> Does not work on my PC : Traceback (most recent call last):
>   File "/home/eproust/john-machin_recup_rep_site-packages.py", line 9,
> in 
> raise Exception('Huh?')
> Exception: Huh?

My palantir is in the workshop, so you'll have to tell me what's in
sys.path on your machine.

>
> Even if I remove all code below the else: part of the script...

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


Re: Just for fun: Countdown numbers game solver

2008-01-21 Thread Steven D'Aprano
On Mon, 21 Jan 2008 01:15:50 -0800, dg.google.groups wrote:

> Decided I may as well post my other solution while I'm at it. The neat
> trick here is redefining the add, mul, etc. functions so that they raise
> exceptions for example if x>y then add(x,y) raises an exception which is
> handled by the search algorithm to mean don't continue that computation
> - this stops you from having to evaluate x+y AND y+x, etc.

Setting up a try...except block is very fast, but actually responding to 
an exception is very slow. You _might_ find that it is quicker to 
evaluate both expressions than it is to catch the exception.

Better still is to find another way of avoiding both the exception and 
the symmetrical calls.


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


Re: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt

2008-01-21 Thread Diez B. Roggisch
pythonewbie 

> 
> Because the solution using distutils.sysconfig.get_python_lib() is
> very smart !

Depending on your goal. You said 

"""
My goal is to verify if an/several extension(s) are installed and to
automatically install the missing ones on Linux or Win32.
"""

This goal can't be reached with only the site-packages - because I can
install packages somewhere else (matter of factly, this happens on debian
for example, they've split the install-dirs and created a bunch of dirs
under /usr/share)

So having a method that gives you the installation root doesn't help much
here.

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


Re: Default attribute values pattern

2008-01-21 Thread Bruno Desthuilliers
David Tweet a écrit :
(please, don't top-post)
> 
> def Grab(argdict, key, default):

cf pep08 for naming conventions...

>   """Like argdict.get(key, default), but also deletes key from argdict."""
>   if key in argdict:
> retval = argdict["key"]
> del(argdict[key])
>   else:
> retval = default
>   return retval

def grab(kw, key, default=None):
   try:
 return kw.pop(key)
   except KeyError:
 return default

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


Re: Sorting a list depending of the indexes of another sorted list

2008-01-21 Thread J. Peng
Steven D'Aprano 写道:
> On Mon, 21 Jan 2008 16:23:50 +0800, J. Peng wrote:
> 
>> J. Peng 写道:
>>
>>>k = (i.split())[3]
>>>y = (i.split())[1]
>> btw, why can't I write the above two into one statement?
>>
>> (k,y) = (i.split())[3,1]
> 
> I don't know. What's "i"?
> 
> I'm guessing "i" is a string (and what a horrible choice of a name for a 
> string!) So i.split() will return a list. List indexing with multiple 
> arguments isn't defined, which is why you can't write 
> 
> k, y = (i.split())[3,1]
> 

Thanks.
Then one have to split the list twice.Given the list is large,it's maybe 
not good for performance.Is it a more effective split way?
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Sorting a list depending of the indexes of another sorted list

2008-01-21 Thread Santiago Romero

 Thanks all for the answers ... I'll use a tuple as you said :)

 Anyway, is interesting to know how to sort 2 lists when you dont want
to use tuples, so thanks also to Peter :)

> Then one have to split the list twice.Given the list is large,it's maybe
> not good for performance.Is it a more effective split way?

 Well, I just use:

 rows = i.split(' ')
 a = rows[3]
 b = rows[5]

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


Re: Default attribute values pattern

2008-01-21 Thread cokofreedom
> Grab(argdict, key, default) is argdict.pop(key, default)

"pop() raises a KeyError when no default value is given and the key is
not found."

> def grab(kw, key, default=None):
>try:
>  return kw.pop(key)
>except KeyError:
>  return default

So Bruno's technique seems to me to be the correct one as it catches
the KeyError.
-- 
http://mail.python.org/mailman/listinfo/python-list


building psycopg2 on windows using mingw, "cannot find -lpq"

2008-01-21 Thread GHUM
The compile works, BUT linking fails:

2.5\Release\psycopg\_psycopg.def -Lc:\python25\libs -Lc:
\python25\PCBuild -Lc:/p
ostgres/83RC2/lib -lpython25 -lpq -lws2_32 -ladvapi32 -o build
\lib.win32-2.5\psy
copg2\_psycopg.pyd
c:\mingw\bin\..\lib\gcc\mingw32\3.4.5\..\..\..\..\mingw32\bin\ld.exe:
cannot find -lpq
collect2: ld returned 1 exit status
error: command 'gcc' failed with exit status 1

if I google for the error

"ld.exe: cannot find -lpq"

there is allways the information that the lib-dir of libpq is missing;
but :

 -Lc:/postgres/83RC2/lib

is clearly in the commandline, and within c:/postgres/83RC2/lib
there is one libqp.lib

What am I missing? any hints?

Best wishes,

Harald

(complete output:
c:\mingw\bin\gcc.exe -mno-cygwin -shared -s build
\temp.win32-2.5\Release\psycopg
\psycopgmodule.o build\temp.win32-2.5\Release\psycopg\pqpath.o build
\temp.win32-
2.5\Release\psycopg\typecast.o build\temp.win32-2.5\Release\psycopg
\microprotoco
ls.o build\temp.win32-2.5\Release\psycopg\microprotocols_proto.o build
\temp.win3
2-2.5\Release\psycopg\connection_type.o build\temp.win32-2.5\Release
\psycopg\con
nection_int.o build\temp.win32-2.5\Release\psycopg\cursor_type.o build
\temp.win3
2-2.5\Release\psycopg\cursor_int.o build\temp.win32-2.5\Release\psycopg
\lobject_
type.o build\temp.win32-2.5\Release\psycopg\lobject_int.o build
\temp.win32-2.5\R
elease\psycopg\adapter_qstring.o build\temp.win32-2.5\Release\psycopg
\adapter_pb
oolean.o build\temp.win32-2.5\Release\psycopg\adapter_binary.o build
\temp.win32-
2.5\Release\psycopg\adapter_asis.o build\temp.win32-2.5\Release\psycopg
\adapter_
list.o build\temp.win32-2.5\Release\psycopg\adapter_datetime.o build
\temp.win32-
2.5\Release\psycopg\_psycopg.def -Lc:\python25\libs -Lc:
\python25\PCBuild -Lc:/p
ostgres/83RC2/lib -lpython25 -lpq -lws2_32 -ladvapi32 -o build
\lib.win32-2.5\psy
copg2\_psycopg.pyd
c:\mingw\bin\..\lib\gcc\mingw32\3.4.5\..\..\..\..\mingw32\bin\ld.exe:
cannot find -lpq
collect2: ld returned 1 exit status
error: command 'gcc' failed with exit status 1
)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt

2008-01-21 Thread pythonewbie
On 21 jan, 10:34, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> pythonewbie
>
>
>
> > Because the solution using distutils.sysconfig.get_python_lib() is
> > very smart !
>
> Depending on your goal. You said
>
> """
> My goal is to verify if an/several extension(s) are installed and to
> automatically install the missing ones on Linux or Win32.
> """
>
> This goal can't be reached with only the site-packages - because I can
> install packages somewhere else (matter of factly, this happens on debian
> for example, they've split the install-dirs and created a bunch of dirs
> under /usr/share)
>
> So having a method that gives you the installation root doesn't help much
> here.
>
> Diez

To John Machin,

>>> sys.path
['', '/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/
python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/
python2.5/lib-dynload', '/usr/local/lib/python2.5/site-packages', '/
usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/
Numeric', '/usr/lib/python2.5/site-packages/gst-0.10', '/var/lib/
python-support/python2.5', '/usr/lib/python2.5/site-packages/gtk-2.0',
'/var/lib/python-support/python2.5/gtk-2.0', '/usr/lib/python2.5/site-
packages/wx-2.8-gtk2-unicode']
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Just for fun: Countdown numbers game solver

2008-01-21 Thread Terry Jones
> "dg" == dg google groups <[EMAIL PROTECTED]> writes:

dg> It's great how many different sorts of solutions (or almost solutions)
dg> this puzzle has generated. Speedwise, for reference my solution posted
dg> above takes about 40 seconds on my 1.8GHz laptop, and the less elegant
dg> version (on my webpage linked to in the original post) takes about 15
dg> seconds. It seems to me like surely this problem can be more
dg> efficiently solved than that?

dg> Paul: 758 = 8+(5*((2+4)*25))

For this I get:

2 solutions to: target 758, numbers = (2, 4, 5, 8, 25)
(4, 2, 'add', 25, 'mul', 5, 'mul', 8, 'add')
(25, 4, 'mul', 5, 'sub', 8, 'mul', 2, 'sub')

real0m0.118s
user0m0.074s
sys 0m0.044s


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


Re: problem with 'global'

2008-01-21 Thread Duncan Booth
Mel <[EMAIL PROTECTED]> wrote:

> oyster wrote:
>> why the following 2 prg give different results? a.py is ok, but b.py
>> is 'undefiend a'
>> I am using Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC
>> v.1310 32 bit (Intel)] on win32
>> #a.py
>> def run():
>> if 1==2:# note, it always False
>> global a
>> a=1
>> 
>> run()
>> a
>> 
>> #b.py
>> def run():
>> a=1
>> 
>> run()
>> a
> 
> The docs seem to be in  
> but don't look all that helpful.

Why are you reading Python 2.4 docs? Try 
http://docs.python.org/ref/global.html

The first sentence (which hasn't changed since 2.4) describing the global 
statement seems clear enough to me: "The global statement is a declaration 
which holds for the entire current code block."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt

2008-01-21 Thread pythonewbie
On 21 jan, 10:34, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> pythonewbie
>
>
>
> > Because the solution using distutils.sysconfig.get_python_lib() is
> > very smart !
>
> Depending on your goal. You said
>
> """
> My goal is to verify if an/several extension(s) are installed and to
> automatically install the missing ones on Linux or Win32.
> """
>
> This goal can't be reached with only the site-packages - because I can
> install packages somewhere else (matter of factly, this happens on debian
> for example, they've split the install-dirs and created a bunch of dirs
> under /usr/share)
>
> So having a method that gives you the installation root doesn't help much
> here.
>
> Diez

Diez,

I repeat I am a newbie, so please don't be angry against me, if I say
something stupid or if I propose a method not efficient.

An easy way to get the absolute path of site-packages seems very
useful to me, in order to check anything (all extensions available and
not provided by sys.path, etc.) related to the files on the
filesystem, if necessary.

For the automatic installation of missing extensions (using admin
rights), I think that it is not difficult to do it on both
platforms...


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


Re: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt

2008-01-21 Thread John Machin
On Jan 21, 9:05 pm, pythonewbie <[EMAIL PROTECTED]> wrote:
> On 21 jan, 10:34, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
[snip]
> > Diez
>
> To John Machin,

Get a clue #1: read the instructions for your news client ... like the
bit that says "click on the message/posting that you want to reply to"

>
> >>> sys.path
>
> ['', '/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/
> python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/
> python2.5/lib-dynload', '/usr/local/lib/python2.5/site-packages', '/
> usr/lib/python2.5/site-packages',

Get a clue #2: it "doesn't work" because it needs a different pattern
on *x platforms.

Consider proceeding in this order:
1. get some clues
2. write an app, test it, etc
3. do the setup.py thingie for Windows & Linux
4. persuade some people to install it and test it
5. then and only then look into "verify if an/several extension(s) are
installed and to automatically install the missing ones"

By the way, I understand "extensions" to mean modules/packages written
substantially or wholly in C or C++. Is that what you mean? If so, do
1-5 above with a Python-only module first.

BTW#2 ... for Windows users of an app you'd need to be able to package
the app up with py2exe, which involves _including_ all the third-party
libraries called by the app.

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


Re: Just for fun: Countdown numbers game solver

2008-01-21 Thread Arnaud Delobelle
On Jan 21, 9:01 am, [EMAIL PROTECTED] wrote:
> Hi all,
>
> It's great how many different sorts of solutions (or almost solutions)
> this puzzle has generated. Speedwise, for reference my solution posted
> above takes about 40 seconds on my 1.8GHz laptop, and the less elegant
> version (on my webpage linked to in the original post) takes about 15
> seconds. It seems to me like surely this problem can be more
> efficiently solved than that?

I haven't had the time to look at your solution yet.  I wanted to have
a go without being influenced.

> Arnaud: I haven't had time to play with your solution yet - how quick
> does it run?

I can't run test from here (work) but last night it seemed of the
order of a second on my 2GHz MacBook Pro (it was late and I was quite
tired so I didn't have the energy to time anything...).  It depends if
you stop when you hit the first solution or you want to go through all
of them.  I guess it will run quicker if I don't build a string
representation of each calculation.

You should run a test on your own machine though to make comparisons
meaningful.

> My fantasy is that there is a solution that isn't TOO slow where you
> can just look at the code and go 'Oh yes, of course that works!' and
> understand it immediately. Maybe that's too much to ask even of
> Python! ;-)

It's a laudable goal.  We might get there :)

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


Re: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt

2008-01-21 Thread Diez B. Roggisch
> 
> Diez,
> 
> I repeat I am a newbie, so please don't be angry against me, if I say
> something stupid or if I propose a method not efficient.

Where did I sound angry? 
 
> An easy way to get the absolute path of site-packages seems very
> useful to me, in order to check anything (all extensions available and
> not provided by sys.path, etc.) related to the files on the
> filesystem, if necessary.

As I said - this is a wrong assumption. The whole purpose of the sys.path is
to specify locations where modules/packages are installed. Note the plural.

And matter of factly (as I told you in the last post already), this happens
in e.g. debian based distributions install certain packages
under /usr/share, which is by no means a prefix of /usr/python2.5 where the
site-packages are.

So if you want to find out if something is already installed, you need to
consider ALL the contents of sys.path.

Besides, I don't understand why you want to do it that way anyway. If you
need a certain package,  do

try:
  import package
except ImportError:
  do_install_package()

This should/could be part of your installer script (most probably setup.py)

And have you heard of setuptools? They do actually manage and install
pytthon packages with dependencies. Before reinventing another wheel...

> For the automatic installation of missing extensions (using admin
> rights), I think that it is not difficult to do it on both
> platforms...

You are underestimating that task. It is, on both platforms. There are many
discussions about this, why some people don't like setuptools because it
works with python as center of it's perspective whereas linux often has
package management for the whole system.

I suggest you start acquainting yourself with setuptools and how and what
they did to essentially solve what you seem to be wanting. And try and see
if that's not a route you can go - just using setuptools.

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


Re: Just for fun: Countdown numbers game solver

2008-01-21 Thread cokofreedom
On Jan 21, 11:29 am, Terry Jones <[EMAIL PROTECTED]> wrote:
> > "dg" == dg google groups <[EMAIL PROTECTED]> writes:
>
> dg> It's great how many different sorts of solutions (or almost solutions)
> dg> this puzzle has generated. Speedwise, for reference my solution posted
> dg> above takes about 40 seconds on my 1.8GHz laptop, and the less elegant
> dg> version (on my webpage linked to in the original post) takes about 15
> dg> seconds. It seems to me like surely this problem can be more
> dg> efficiently solved than that?
>
> dg> Paul: 758 = 8+(5*((2+4)*25))
>
> For this I get:
>
> 2 solutions to: target 758, numbers = (2, 4, 5, 8, 25)
> (4, 2, 'add', 25, 'mul', 5, 'mul', 8, 'add')
> (25, 4, 'mul', 5, 'sub', 8, 'mul', 2, 'sub')
>
> real0m0.118s
> user0m0.074s
> sys 0m0.044s
>
> Terry

Terry, your technique is efficient and pretty readable! All that could
be added now is a way to output the data in a more user-friendly
print. (it currently reminds me of Lisp operands done backwards :) )

Also perhaps the creation of a random generator for the 6 numbers and
the target :)

I do not remember if countdown enforced that it must be possible to
actually get the target, you could also get close to it. (I believe
you would get different points depending on this)

Will have to read up on how many large numbers you can have, as well
as small. Currently I think it is you can take up to 4 large numbers,
and up to 6 small numbers to a total of 6. (you must always have 6
numbers to work with)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Linux/Win32 func. to get Python instdir (not exedir) + site-packages => extensions mgmt

2008-01-21 Thread pythonewbie
On 21 jan, 11:49, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> > Diez,
>
> > I repeat I am a newbie, so please don't be angry against me, if I say
> > something stupid or if I propose a method not efficient.
>
> Where did I sound angry?
>
> > An easy way to get the absolute path of site-packages seems very
> > useful to me, in order to check anything (all extensions available and
> > not provided by sys.path, etc.) related to the files on the
> > filesystem, if necessary.
>
> As I said - this is a wrong assumption. The whole purpose of the sys.path is
> to specify locations where modules/packages are installed. Note the plural.
>
> And matter of factly (as I told you in the last post already), this happens
> in e.g. debian based distributions install certain packages
> under /usr/share, which is by no means a prefix of /usr/python2.5 where the
> site-packages are.
>
> So if you want to find out if something is already installed, you need to
> consider ALL the contents of sys.path.
>
> Besides, I don't understand why you want to do it that way anyway. If you
> need a certain package,  do
>
> try:
>   import package
> except ImportError:
>   do_install_package()
>
> This should/could be part of your installer script (most probably setup.py)
>
> And have you heard of setuptools? They do actually manage and install
> pytthon packages with dependencies. Before reinventing another wheel...
>
> > For the automatic installation of missing extensions (using admin
> > rights), I think that it is not difficult to do it on both
> > platforms...
>
> You are underestimating that task. It is, on both platforms. There are many
> discussions about this, why some people don't like setuptools because it
> works with python as center of it's perspective whereas linux often has
> package management for the whole system.
>
> I suggest you start acquainting yourself with setuptools and how and what
> they did to essentially solve what you seem to be wanting. And try and see
> if that's not a route you can go - just using setuptools.
>
> Diez

OK 5/5, I will follow your advices !

I will read the manuals distutils and setuptools...

I use Ubuntu 7.10 and I have seen a package named python-setuptools
0.6c6-1 ready to install. The description of this package is Python
Distutils Enhancements
Extensions to the python-distutils for large or complex distributions.

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


Re: Just for fun: Countdown numbers game solver

2008-01-21 Thread Arnaud Delobelle
On Jan 21, 9:12 am, Terry Jones <[EMAIL PROTECTED]> wrote:
[...]
> Hi Arnaud.

Hi Terry

[...]
> WRT to the missing solution, note that my code only allowed multiplication
> by 1 if it was the last thing done. That was because you can multiply by 1
> at any time, and I didn't want to see those trivially equivalent solutions
> (same goes for adding 0). Seeing as you're allowed to omit numbers, I've
> now gotten rid of those trivial operations altogether in my solution.

Sorry I gave an incorrect example to illustrate my question last night
(I blame this on baby-induced sleep deprivation ;), so I'll have
another go:

Say I have 2, 3, 4, 100 and I want to make 406.  AFAICS there is only
one way: (2*3)+(4*100), i.e. in postfix notation:

2 3 * 4 100 * +

It seemed to me that your function wouldn't generate that sort of
solution (as you always extend partialSolution by [num, op] making the
subsequence [mul, add] impossible).  Am I wrong?

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


Re: Default attribute values pattern

2008-01-21 Thread Arnaud Delobelle
On Jan 21, 10:09 am, [EMAIL PROTECTED] wrote:
> > Grab(argdict, key, default) is argdict.pop(key, default)
>
> "pop() raises a KeyError when no default value is given and the key is
> not found."

And it doesn't if a default is provided, which is always the case in
the uses of Grab(...), so it seems the right tool for the job.

> > def grab(kw, key, default=None):
> >    try:
> >      return kw.pop(key)
> >    except KeyError:
> >      return default
>
> So Bruno's technique seems to me to be the correct one as it catches
> the KeyError.

If you really really want to write a grab function (IMHO pop is good
enough):

def grab(kw, key, default=None):
return kw.pop(key, default)

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


Re: Just for fun: Countdown numbers game solver

2008-01-21 Thread Terry Jones
> "cokofreedom" == cokofreedom  <[EMAIL PROTECTED]> writes:

cokofreedom> Terry, your technique is efficient and pretty readable! All
cokofreedom> that could be added now is a way to output the data in a more
cokofreedom> user-friendly print.

Yes, and a fix for the bug Arnaud just pointed out :-)
Below is code to print things more nicely for you.

Terry


from operator import *
from itertools import izip

def countdown(target, nums, numsAvail, value, partialSolution, solutions, 
ops=(add, mul, sub, div)):
if value == target or not any(numsAvail):
# Add the solution, if we're right.
if value == target:
solutions.add(tuple(partialSolution))
elif value is None:
# Use each distinct number as a starting value.
used = set()
for i, num in enumerate(nums):
if num not in used:
numsAvail[i] = False
used.add(num)
partialSolution.append(num)
countdown(target, nums, numsAvail, num, partialSolution, 
solutions, ops)
numsAvail[i] = True
partialSolution.pop()
else:
for op in ops:
for i, num in enumerate(nums):
if numsAvail[i]:
numsAvail[i] = False
moreAvail = any(numsAvail)
try:
lastNum, lastOp = partialSolution[-2:]
except ValueError:
lastNum, lastOp = partialSolution[-1], None
# Don't allow any of:
if not (
# Div: after mul, by 1, by 0, producing a fraction.
(op == div and (lastOp == 'mul' or num <= 1 or value % 
num != 0)) or
# If initial mul/add, canonicalize to 2nd operator 
biggest.
((op == mul or op == add) and lastOp is None and num > 
lastNum) or
# Don't allow add or sub of 0.
((op == add or op == sub) and num == 0) or
# Don't allow mult by 1.
(op == mul and num == 1) or
# Don't allow sub after add (allow add after sub).
(op == sub and lastOp == 'add') or
# If same op twice in a row, canonicalize operand order.
(lastOp == op.__name__ and num > lastNum)
):
partialSolution.extend([num, op.__name__])
countdown(target, nums, numsAvail, op(value, num), 
partialSolution, solutions, ops)
del partialSolution[-2:]
numsAvail[i] = True

op2sym = { 'add' : '+', 'sub' : '-', 'mul' : '*', 'div': '/', }

def pretty(s):
out = [str(s[0])]
lastOp = None
for value, op in izip(*(iter(s[1:]),) * 2):
if (op == 'mul' or op == 'div') and (lastOp == 'add' or lastOp == 
'sub'):
out.insert(0, '(')
out.append(')')
out.append(op2sym[op])
out.append(str(value))
lastOp = op
return ''.join(out)

for nums, target in (
((100, 9, 7, 6, 3, 1), 253),
((100, 9, 7, 6, 3, 1), 234),
((2, 3, 5), 21),
((7, 8, 50, 8, 1, 3), 923),
((8, 8), 16),
((8, 8, 8), 8),
((8, 0), 8),
((7,), 8),
((), 8),
((8, 8, 8, 8), 32),
((2, 4, 5, 8, 25), 758),
((2, 3, 4, 100), 406),
):
solutions = set()
countdown(target, nums, [True,] * len(nums), value=None, 
partialSolution=[], solutions=solutions)
print "%d solutions to: target %d, numbers = %s" % (len(solutions), target, 
nums)
for s in sorted(solutions, cmp=lambda a, b: cmp(len(a), len(b)) or cmp(a, 
b)):
print '\t', pretty(s)


Sample output:

8 solutions to: target 253, numbers = (100, 9, 7, 6, 3, 1)
(6*3-1)*9+100
(7*6+9)*3+100
(9-3)*7*6+1
(100-9-7)*3+1
((3+1)*6-7)*9+100
(7+1)*6*3+100+9
(7+6+3+1)*9+100
(100-7-6)*3-9+1
19 solutions to: target 234, numbers = (100, 9, 7, 6, 3, 1)
(6*3+7+1)*9
((7+1)*9+6)*3
(7*3-1+6)*9
(7*6*3-100)*9
((100-1)/3-7)*9
((100-1)*7+9)/3
(100*7*3+6)/9
(100-9)/7*6*3
(100-9-7-6)*3
((6+1)*100-7+9)/3
((6-9)*7-1+100)*3
(7*3-6)*9-1+100
7*6*3-1+100+9
(100-1)/3*7-6+9
((100-1)*7-9)/3+6
(100*7-6-1+9)/3
((100-7)/3-1+9)*6
((100-7)/3-6+1)*9
(100+9+7+1)/3*6
-- 
http://mail.python.org/mailman/listinfo/python-list


Q: paramiko/SSH/ how to get a remote host_key

2008-01-21 Thread DHR
I'm trying to run the simpliest example form paramiko readme(Homepage:
http://www.lag.net/paramiko/), and
cannot find out how to get the remote SSH server host_key.


This is the code. It is supposed to connect to a remote SSH host and
execute an 'ls' command:

import paramiko, base64

key = paramiko.RSAKey(data=base64.decodestring('AAA...'))
client = paramiko.SSHClient()
client.get_host_keys().add('ssh.example.com', 'ssh-rsa', key)
client.connect('227.112.168.273', username='uname', password='pass')
stdin, stdout, stderr = client.exec_command('ls')
for line in stdout:
print '... ' + line.strip('\n')

client.close()

Now, if I understand it correctly I need to get somehow the host_key
from the server and
write it insted of the 'AAA...' thing. Is there a command to get the
host_key from a remote SSH
server?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Just for fun: Countdown numbers game solver

2008-01-21 Thread Terry Jones
> "Arnaud" == Arnaud Delobelle <[EMAIL PROTECTED]> writes:

Arnaud> Sorry I gave an incorrect example to illustrate my question last
Arnaud> night (I blame this on baby-induced sleep deprivation ;), so I'll
Arnaud> have another go:

Arnaud> Say I have 2, 3, 4, 100 and I want to make 406.  AFAICS there is only
Arnaud> one way: (2*3)+(4*100), i.e. in postfix notation:
Arnaud> 2 3 * 4 100 * +

Arnaud> It seemed to me that your function wouldn't generate that sort of
Arnaud> solution (as you always extend partialSolution by [num, op] making
Arnaud> the subsequence [mul, add] impossible).  Am I wrong?

No, you're right.  I actually started out with a stack solution, and then
switched to something simpler (too simple). I'm going to redo it, but maybe
not right now...

Thanks!

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


Re: How to use py2exe ...

2008-01-21 Thread DHR
Here is how I am creating my win32 exe with py2exe:
1. create a setup.py file with the following:
from distutils.core import setup
import py2exe

#setup(console=['main_script.py'])
setup(windows=['main_script.py'] )

2. run the following command from console: 'python setup.py py2exe'

Hope this helps.

On Jan 21, 9:45 am, Santiago  Romero <[EMAIL PROTECTED]> wrote:
>  Hi...
>
>  I'm a Linux user, and I would like some windows-friends to test a
> game I'm writing with python+pygame without they needing to install
> python, pygame, and so on.
>
>  I've heard about py2exe and pygame2exe, but I'm not sure on how to
> use them to create:
>
> a.- standalone exe files with a single .py program.
> Example: myprogram.py
>
> or
>
> b.- exe files containing all my source code + data directories (png
> files, data files, and so).
> Example: main.py, doc/README, src/*.py and data/*
>
>  The problem is I'm not sure on how to use py2exe and pygame2exe to
> build the executables...
>
>  And finally, a question: if I want to provide source code
> separately ... can I include .pyc files instead of .py files?

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


Re: Q: paramiko/SSH/ how to get a remote host_key

2008-01-21 Thread Guilherme Polo
2008/1/21, DHR <[EMAIL PROTECTED]>:
> I'm trying to run the simpliest example form paramiko readme(Homepage:
> http://www.lag.net/paramiko/), and
> cannot find out how to get the remote SSH server host_key.
>
>
> This is the code. It is supposed to connect to a remote SSH host and
> execute an 'ls' command:
>
> import paramiko, base64
>
> key = paramiko.RSAKey(data=base64.decodestring('AAA...'))
> client = paramiko.SSHClient()
> client.get_host_keys().add('ssh.example.com', 'ssh-rsa', key)
> client.connect('227.112.168.273', username='uname', password='pass')
> stdin, stdout, stderr = client.exec_command('ls')
> for line in stdout:
> print '... ' + line.strip('\n')
>
> client.close()
>
> Now, if I understand it correctly I need to get somehow the host_key
> from the server and
> write it insted of the 'AAA...' thing. Is there a command to get the
> host_key from a remote SSH
> server?
> --
> http://mail.python.org/mailman/listinfo/python-list
>

You need a key to connect to that server, so you should want this:

keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))

Then keys[hostname] should contain a RSAKey object that you are looking for


-- 
-- Guilherme H. Polo Goncalves
-- 
http://mail.python.org/mailman/listinfo/python-list


[HELP] SMTPlib not sending my mail

2008-01-21 Thread ornto
Hi, I'm trying to create an application which checks a 
dynamic web site and on certain events sends an email to me. 
My problem though is with the email task. By now I made this 
  simple test code:

#prova invio email
smtpserver = smtplib.SMTP(mailserver)
messaggio= "Messaggio di prova"
print mail
print messaggio
smtpresult=smtpserver.sendmail("Watcher",mail,messaggio)
if smtpresult:
 print smtpresult
smtpserver.quit()

"mailserver" and "mail" values are loaded from a ini file 
and they're correct.
The call to smtpserver gives back no errors (smtpresult 
remains empty).
The running enviroment gives no error.
So, it looks like that the program works alloright, sending 
the mail- BUT, I receive no mail! I've tried to change the 
smtp server with another one which still works with my isp, 
with no luck. If I try a smtp which doesn't give me access, 
I correctly receive an error from the program.
What might be the problem?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorting a list depending of the indexes of another sorted list

2008-01-21 Thread Steven D'Aprano
On Mon, 21 Jan 2008 17:32:42 +0800, J. Peng wrote:

> Steven D'Aprano 写道:
>> On Mon, 21 Jan 2008 16:23:50 +0800, J. Peng wrote:
>> 
>>> J. Peng 写道:
>>>
k = (i.split())[3]
y = (i.split())[1]
>>> btw, why can't I write the above two into one statement?
>>>
>>> (k,y) = (i.split())[3,1]
>> 
>> I don't know. What's "i"?
>> 
>> I'm guessing "i" is a string (and what a horrible choice of a name for
>> a string!) So i.split() will return a list. List indexing with multiple
>> arguments isn't defined, which is why you can't write
>> 
>> k, y = (i.split())[3,1]
>> 
>> 
> Thanks.
> Then one have to split the list twice.Given the list is large,it's maybe
> not good for performance.Is it a more effective split way?

Yes, split the string once and store it.

words = "Nobody expects the Spanish Inquisition!"
alist = words.split()
k = alist[3]  # "Spanish"
y = alist[1]  # "expects"



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

Re: Basic inheritance question

2008-01-21 Thread Bruno Desthuilliers
Lie a écrit :
> On Jan 16, 9:23 pm, Bjoern Schliessmann  [EMAIL PROTECTED]> wrote:
>> Lie wrote:
>>> [EMAIL PROTECTED]> wrote:
 I used to systematically use it - like I've always systematically
 used 'this' in C++  and Java.
>>> And that is what reduces readability.
>> IMHO not, IOPHO not. This is the nth time (n >> 1) this discussion
>> comes up here. If I have learned one thing from those very lengthy
>> discussions, it's that Python's "self" handling is not going to
>> change.
> 
> And ah... yes, I don't wish it go away either. In VB, excessive Me
> reduces readability, but in Python it doesn't.
> 
>>> A proficient VB/C/Java programmer would frown upon the extra,
>>> unneeded garbage as they thought it was clear already that the
>>> variable refers to a class-level variable.
>> C programmers surely have no opinion concerning C because it has no
>> native classes.
> 
> C-family, ok?

Well... I'm not sure what "C-family" means, but to me it would consist 
in C, C++, Objective C, and D.

> Please stop taking my words to its letters.

So we're supposed to actually guess what you really mean ???

>> Personally, I've seen many C++ programs with complex class designs
>> where it definitely helps to consistently use "this->". I cannot
>> remember all local (and global) variables in bigger methods.
> 
> In that case, you have the _option_ to do it.

Make no sens when maintaining code wrote by someone that didn't use this 
'option'.

(snip)

 it's the first argument of the function - which usually happens to be
 the current instance when the function is used as a method.
>>> And that's the point, self (or anything you name it) is almost always
>>> the current instance
>> # this is a plain function. In this function,
>> # 'obj' can be whatever that happens to have a (numeric)
>> # 'stuff' attribute
>> def func(obj, arg):
>>return (obj.stuff + arg) / 2.0
>>
>> # this is a class with an instance attribute 'stuff'
>> class Foo(object):
>> def __init__(self, bar):
>>   self.stuff = bar + 42
>>
>> # this is another (mostly unrelated) class
>> # with a class attribute 'stuff'
>> class Bar(object):
>>stuff = 42
>>
>> # this is a dummy container class:
>> class Dummy(object): pass
>>
>> # now let's play:
>> import new
>>
>> d = Dummy()
>> d.stuff = 84
>> print func(d, 1)
>>
>> d.baaz = new.instancemethod(func, d, type(d))
>> print d.baaz(2)
>>
>> f = Foo(33)
>> print func(f, 3)
>> Foo.baaz = func
>> f.baaz(4)
>>
>> print func(Bar, 5)
>> Bar.baaz = classmethod(func)
>> Bar.baaz(6)
>>
>>>  and that makes it functionally the same as Me and
>>> this in VB and Java.
>> Depends on the context, cf above !-)
> 
> Please again, stop taking letters to the words, I don't meant them to
> be exactly the same, rather the same would meant that they generally
> can be considered equal,

If you still think that way after having read the above code, then I 
can't help. We obviously don't share the same mental model here.

> exceptions exists of course. And btw, I don't
> understand what you meant by your example, they seemed to be a
> completely OK program for me,

Indeed it's ok (even if totally useless by itself). The point is that 
'self' (or whatever you name it) is just and only the first argument of 
a function, period.

> even though it's a bit confusing to
> follow[2].

Nothing in it should be confusing to anyone having a decent knowledge of 
Python's object model IMHO.

> [2] btw, the reason it's a bit confusing to follow is one of my
> points: It is a Bad Thing(tm) to use the same name for different
> variables

Where do I "use the same name for different variables" here ?

> even in a language like Python that enforce explicit naming
> of classes

Python doesn't "enforce" explicit name of classes - IIRC, there are ways 
to instanciate anonymous class objects. But I definitively don't see how 
this relate to this discussion.

Yes, I know, "please guess what I mean" !-) but sorry, there's no sens 
discussing a technical point without using accurate and appropriate 
technical naming of technical concepts invlved.

> Most other languages
> 1) automatically assign the containing class' object
 s/containing class' object/current instance/
> in a keyword
> (Java: this, VB: Me) behind the screen,
 That's not very far from what a Python method object does -
 automatically assign the current instance to something. The difference
 is that Python uses functions to implement methods (instead of having
 two distinct contructs), so the only reliable way to "inject" the
 reference to the current instance is to pass it as an argument to the
 function (instead of making it pop from pure air).
>>> It isn't very far, but Python makes it obvious about the assignment
>>> (not behind the screen).
>> Exactly. And given both the simplicity of the solution and what it let
>> you do, that's a *very* GoodThing(tm) IMHO.
> 
> I agree, it's a Good Thing but it doesn't make the point 

Re: Q: paramiko/SSH/ how to get a remote host_key

2008-01-21 Thread DHR
I am connecting from a WindowsXP SP2 machine. When using Putty as an
SSH client, if you connect for the first time then you get somethign
like this:

''' The server's host key is not cached in the registry. You
have no guarantee that the server is the computer you
think it is.
The server's rsa2 key fingerprint is:
ssh-rsa 1024 7b:e5:6f:a7:f4:f9:81:62:5c:e3:1f:bf:8b:57:6c:5a
If you trust this host, hit Yes to add the key to
PuTTY's cache and carry on connecting.
If you want to carry on connecting just once, without
adding the key to the cache, hit No.
If you do not trust this host, hit Cancel to abandon the
connection. '''

If I get it correctly, Putty is using such a command to recieve the
host_key the first time it connects to a remote SSH server. Then it
stores it into the registry. The question is how can I do it from
Python?


Guilherme Polo wrote:
> 2008/1/21, DHR <[EMAIL PROTECTED]>:
> > I'm trying to run the simpliest example form paramiko readme(Homepage:
> > http://www.lag.net/paramiko/), and
> > cannot find out how to get the remote SSH server host_key.
> >
> >
> > This is the code. It is supposed to connect to a remote SSH host and
> > execute an 'ls' command:
> >
> > import paramiko, base64
> >
> > key = paramiko.RSAKey(data=base64.decodestring('AAA...'))
> > client = paramiko.SSHClient()
> > client.get_host_keys().add('ssh.example.com', 'ssh-rsa', key)
> > client.connect('227.112.168.273', username='uname', password='pass')
> > stdin, stdout, stderr = client.exec_command('ls')
> > for line in stdout:
> > print '... ' + line.strip('\n')
> >
> > client.close()
> >
> > Now, if I understand it correctly I need to get somehow the host_key
> > from the server and
> > write it insted of the 'AAA...' thing. Is there a command to get the
> > host_key from a remote SSH
> > server?
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >
>
> You need a key to connect to that server, so you should want this:
>
> keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
>
> Then keys[hostname] should contain a RSAKey object that you are looking for
>
>
> --
> -- Guilherme H. Polo Goncalves
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Q: paramiko/SSH/ how to get a remote host_key

2008-01-21 Thread Guilherme Polo
2008/1/21, DHR <[EMAIL PROTECTED]>:
> I am connecting from a WindowsXP SP2 machine. When using Putty as an
> SSH client, if you connect for the first time then you get somethign
> like this:
>
> ''' The server's host key is not cached in the registry. You
> have no guarantee that the server is the computer you
> think it is.
> The server's rsa2 key fingerprint is:
> ssh-rsa 1024 7b:e5:6f:a7:f4:f9:81:62:5c:e3:1f:bf:8b:57:6c:5a
> If you trust this host, hit Yes to add the key to
> PuTTY's cache and carry on connecting.
> If you want to carry on connecting just once, without
> adding the key to the cache, hit No.
> If you do not trust this host, hit Cancel to abandon the
> connection. '''
>
> If I get it correctly, Putty is using such a command to recieve the
> host_key the first time it connects to a remote SSH server. Then it
> stores it into the registry. The question is how can I do it from
> Python?

When you call method connect of SSHClient it checks if server's
hostname is in system_hot_keys or any local host keys, if it is not,
the missing host key policy is used. The default policy is to reject
the key and raise an SSHException, but you can change that default
policy to AutoAddPolicy

>
>
> Guilherme Polo wrote:
> > 2008/1/21, DHR <[EMAIL PROTECTED]>:
> > > I'm trying to run the simpliest example form paramiko readme(Homepage:
> > > http://www.lag.net/paramiko/), and
> > > cannot find out how to get the remote SSH server host_key.
> > >
> > >
> > > This is the code. It is supposed to connect to a remote SSH host and
> > > execute an 'ls' command:
> > >
> > > import paramiko, base64
> > >
> > > key = paramiko.RSAKey(data=base64.decodestring('AAA...'))
> > > client = paramiko.SSHClient()
> > > client.get_host_keys().add('ssh.example.com', 'ssh-rsa', key)
> > > client.connect('227.112.168.273', username='uname', password='pass')
> > > stdin, stdout, stderr = client.exec_command('ls')
> > > for line in stdout:
> > > print '... ' + line.strip('\n')
> > >
> > > client.close()
> > >
> > > Now, if I understand it correctly I need to get somehow the host_key
> > > from the server and
> > > write it insted of the 'AAA...' thing. Is there a command to get the
> > > host_key from a remote SSH
> > > server?
> > > --
> > > http://mail.python.org/mailman/listinfo/python-list
> > >
> >
> > You need a key to connect to that server, so you should want this:
> >
> > keys = 
> > paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
> >
> > Then keys[hostname] should contain a RSAKey object that you are looking for
> >
> >
> > --
> > -- Guilherme H. Polo Goncalves
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
-- Guilherme H. Polo Goncalves
-- 
http://mail.python.org/mailman/listinfo/python-list


where to join a open project in Python

2008-01-21 Thread scsoce sc
hi,all:
 as a newbie, i found that finding a suitable open project in Python seems
hard, well, i has tried sourceforge and google code, python project is just
rare or not fit for me. so i want to get any suggestion or experience from
you dear pythonmates.
thank you
scsoce
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Q: paramiko/SSH/ how to get a remote host_key

2008-01-21 Thread DHR
Thank you! Now it works and the code looks like this:

import paramiko
import base64
from paramiko import AutoAddPolicy, SSHClient

client = paramiko.SSHClient()
client.set_missing_host_key_policy(AutoAddPolicy())
client.connect('hostIP', username='uname', password='pass')
stdin, stdout, stderr = client.exec_command('ls')
for line in stdout:
print '... ' + line.strip('\n')

client.close()

On Jan 21, 3:10 pm, "Guilherme Polo" <[EMAIL PROTECTED]> wrote:
> 2008/1/21, DHR <[EMAIL PROTECTED]>:
>
>
>
> > I am connecting from a WindowsXP SP2 machine. When using Putty as an
> > SSH client, if you connect for the first time then you get somethign
> > like this:
>
> > ''' The server's host key is not cached in the registry. You
> > have no guarantee that the server is the computer you
> > think it is.
> > The server's rsa2 key fingerprint is:
> > ssh-rsa 1024 7b:e5:6f:a7:f4:f9:81:62:5c:e3:1f:bf:8b:57:6c:5a
> > If you trust this host, hit Yes to add the key to
> > PuTTY's cache and carry on connecting.
> > If you want to carry on connecting just once, without
> > adding the key to the cache, hit No.
> > If you do not trust this host, hit Cancel to abandon the
> > connection. '''
>
> > If I get it correctly, Putty is using such a command to recieve the
> > host_key the first time it connects to a remote SSH server. Then it
> > stores it into the registry. The question is how can I do it from
> > Python?
>
> When you call method connect of SSHClient it checks if server's
> hostname is in system_hot_keys or any local host keys, if it is not,
> the missing host key policy is used. The default policy is to reject
> the key and raise an SSHException, but you can change that default
> policy to AutoAddPolicy
>
>
>
>
>
> > Guilherme Polo wrote:
> > > 2008/1/21, DHR <[EMAIL PROTECTED]>:
> > > > I'm trying to run the simpliest example form paramiko readme(Homepage:
> > > >http://www.lag.net/paramiko/), and
> > > > cannot find out how to get the remote SSH server host_key.
>
> > > > This is the code. It is supposed to connect to a remote SSH host and
> > > > execute an 'ls' command:
>
> > > > import paramiko, base64
>
> > > > key = paramiko.RSAKey(data=base64.decodestring('AAA...'))
> > > > client = paramiko.SSHClient()
> > > > client.get_host_keys().add('ssh.example.com', 'ssh-rsa', key)
> > > > client.connect('227.112.168.273', username='uname', password='pass')
> > > > stdin, stdout, stderr = client.exec_command('ls')
> > > > for line in stdout:
> > > > print '... ' + line.strip('\n')
>
> > > > client.close()
>
> > > > Now, if I understand it correctly I need to get somehow the host_key
> > > > from the server and
> > > > write it insted of the 'AAA...' thing. Is there a command to get the
> > > > host_key from a remote SSH
> > > > server?
> > > > --
> > > >http://mail.python.org/mailman/listinfo/python-list
>
> > > You need a key to connect to that server, so you should want this:
>
> > > keys = 
> > > paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
>
> > > Then keys[hostname] should contain a RSAKey object that you are looking 
> > > for
>
> > > --
> > > -- Guilherme H. Polo Goncalves
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> --
> -- Guilherme H. Polo Goncalves

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


Re: problem with 'global'

2008-01-21 Thread Mel
Duncan Booth wrote:
> Mel <[EMAIL PROTECTED]> wrote:
> 
>> oyster wrote:
>>> why the following 2 prg give different results? a.py is ok, but b.py
>>> is 'undefiend a'
>>> I am using Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC
>>> v.1310 32 bit (Intel)] on win32
>>> #a.py
>>> def run():
>>> if 1==2:# note, it always False
>>> global a
>>> a=1
>>>
>>> run()
>>> a
>>>
>>> #b.py
>>> def run():
>>> a=1
>>>
>>> run()
>>> a
>> The docs seem to be in  
>> but don't look all that helpful.
> 
> Why are you reading Python 2.4 docs? Try 
> http://docs.python.org/ref/global.html
> 
> The first sentence (which hasn't changed since 2.4) describing the global 
> statement seems clear enough to me: "The global statement is a declaration 
> which holds for the entire current code block."

I don't think that would stop the OP from thinking the global 
statement had to be executed.  In the code example, it seems to have 
been stuck in a

 if 1==2: global a

and it still worked.



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


Re: Memory errors with imaplib

2008-01-21 Thread Christian Heimes
Grant Edwards wrote:
> If the solution shown in the bug report is correct, I'd be more
> than happy to generate a patch.

The solution seems fine but IMO it should be fixed in the ssl socket and
not in imaplib. I like to get it *fixed* and not *worked around*. :)

Christian



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


[OT] Valid Mail addresses modifications (WAS: Re: Looping through the gmail dot trick)

2008-01-21 Thread Martin Marcher
Martin Vilcans wrote:

> Try the SMTP spec. IIRC there's a passage there that says that the
> server should try to make sense of addresses that don't map directly
> to a user name. Specifically, it says that firstname.lastname should
> be mapped to the user with those first and last names.

Short story long:

there aren't any!

FYI:

https://mail.google.com/support/bin/answer.py?answer=10313&topic=1564

that was the only reference i found, http://www.ietf.org/rfc/rfc0821.txt
doesn't mention anything beside EXPN which still treats the localpart
literally and checks for a mailbox (or alias) as literally found in the
localpart.

Personally I think google's doing wrong here. Just don't do it anywhere
else, as it's unlikely your mail will reach the person you intended to send
it.

-- 
http://noneisyours.marcher.name
http://feeds.feedburner.com/NoneIsYours

You are not free to read this message,
by doing so, you have violated my licence
and are required to urinate publicly. Thank you.

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


Re: Sorting a list depending of the indexes of another sorted list

2008-01-21 Thread Steven D'Aprano
On Mon, 21 Jan 2008 09:53:10 +0100, Peter Otten wrote:

> Santiago  Romero wrote:
> 
>>  I'm trying to sort both lists so that they end like this:
>> 
>> preferences = [10, 20, 30]
>> hosts = [ "mx1.domain.com", "mx2.domain.com", "anotherhost.domain.com"
>> ]
>> 
>>  I want to sort hosts list depending on the numeric order of
>> "preferences".
> 
> The following relies on undocumented (I hope) behaviour:


What bit are you suggesting is undocumented?


 preferences = [10, 30, 20]
 hosts = [ "mx1.domain.com", "anotherhost.domain.com", 
>... "mx2.domain.com"] 
 hosts.sort(key=lambda x, p=iter(preferences).next: p())
 preferences.sort()
 hosts
> ['mx1.domain.com', 'mx2.domain.com', 'anotherhost.domain.com']
 preferences
> [10, 20, 30]

Now if you wanted to claim it was opaque and confusing, I'd agree with 
you :-)


Here's a function that uses the Decorate-Sort-Undecorate technique to 
sort one list by the contents of another:



from sys import maxint
_indices = xrange(maxint)

def sorterDSU(alist, blist):
"""Return a copy of alist sorted by the contents of blist."""
assert len(alist) == len(blist)
decorated = zip(blist, _indices, alist)
decorated.sort()
return [avalue for (bvalue, i, avalue) in decorated]



Here's another version:

def sorter(alist, blist):
assert len(alist) == len(blist)
table = sorted(range(len(alist)), key=blist.__getitem__)
return [alist[i] for i in table]



>>> alist = "John Eric Michael Graham Terry-J Terry-G".split()
>>> blist = [5, 0, 4, 1, 3, 2]
>>> sorter(alist, blist)
['Eric', 'Graham', 'Terry-G', 'Terry-J', 'Michael', 'John']



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


stdin, stdout, redmon

2008-01-21 Thread Bernard Desnoues
Hi,

I've got a problem with the use of Redmon (redirection port monitor). I 
intend to develop a virtual printer so that I can modify data sent to 
the printer.
Redmon send the data flow to the standard input and lauchs the Python 
program which send modified data to the standard output (Windows XP and 
Python 2.5 context).
I can manipulate the standard output.

"import sys
sys.stdout.write(data)"

it works.
But how to manipulate standard input so that I can store data in a 
string or in an object file ? There's no "read" method.

"a = sys.stdin.read()" doesn't work.
"f = open(sys.stdin)" doesn't work.

I don't find anything in the documentation. How to do that ?
Thanks in advance.

Bernard Desnoues
Librarian
Bibliothèque de géographie - Sorbonne
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Q: paramiko/SSH/ how to get a remote host_key

2008-01-21 Thread Guilherme Polo
2008/1/21, DHR <[EMAIL PROTECTED]>:
> Thank you! Now it works and the code looks like this:
>
> import paramiko
> import base64
> from paramiko import AutoAddPolicy, SSHClient
>
> client = paramiko.SSHClient()
> client.set_missing_host_key_policy(AutoAddPolicy())
> client.connect('hostIP', username='uname', password='pass')
> stdin, stdout, stderr = client.exec_command('ls')
> for line in stdout:
> print '... ' + line.strip('\n')
>
> client.close()

Very nice =)

Just an advice, you dont need to import base64. Method decode of
strings allows you to specify encoding as 'base64' to perform needed
operations.

>
> On Jan 21, 3:10 pm, "Guilherme Polo" <[EMAIL PROTECTED]> wrote:
> > 2008/1/21, DHR <[EMAIL PROTECTED]>:
> >
> >
> >
> > > I am connecting from a WindowsXP SP2 machine. When using Putty as an
> > > SSH client, if you connect for the first time then you get somethign
> > > like this:
> >
> > > ''' The server's host key is not cached in the registry. You
> > > have no guarantee that the server is the computer you
> > > think it is.
> > > The server's rsa2 key fingerprint is:
> > > ssh-rsa 1024 7b:e5:6f:a7:f4:f9:81:62:5c:e3:1f:bf:8b:57:6c:5a
> > > If you trust this host, hit Yes to add the key to
> > > PuTTY's cache and carry on connecting.
> > > If you want to carry on connecting just once, without
> > > adding the key to the cache, hit No.
> > > If you do not trust this host, hit Cancel to abandon the
> > > connection. '''
> >
> > > If I get it correctly, Putty is using such a command to recieve the
> > > host_key the first time it connects to a remote SSH server. Then it
> > > stores it into the registry. The question is how can I do it from
> > > Python?
> >
> > When you call method connect of SSHClient it checks if server's
> > hostname is in system_hot_keys or any local host keys, if it is not,
> > the missing host key policy is used. The default policy is to reject
> > the key and raise an SSHException, but you can change that default
> > policy to AutoAddPolicy
> >
> >
> >
> >
> >
> > > Guilherme Polo wrote:
> > > > 2008/1/21, DHR <[EMAIL PROTECTED]>:
> > > > > I'm trying to run the simpliest example form paramiko readme(Homepage:
> > > > >http://www.lag.net/paramiko/), and
> > > > > cannot find out how to get the remote SSH server host_key.
> >
> > > > > This is the code. It is supposed to connect to a remote SSH host and
> > > > > execute an 'ls' command:
> >
> > > > > import paramiko, base64
> >
> > > > > key = paramiko.RSAKey(data=base64.decodestring('AAA...'))
> > > > > client = paramiko.SSHClient()
> > > > > client.get_host_keys().add('ssh.example.com', 'ssh-rsa', key)
> > > > > client.connect('227.112.168.273', username='uname', password='pass')
> > > > > stdin, stdout, stderr = client.exec_command('ls')
> > > > > for line in stdout:
> > > > > print '... ' + line.strip('\n')
> >
> > > > > client.close()
> >
> > > > > Now, if I understand it correctly I need to get somehow the host_key
> > > > > from the server and
> > > > > write it insted of the 'AAA...' thing. Is there a command to get the
> > > > > host_key from a remote SSH
> > > > > server?
> > > > > --
> > > > >http://mail.python.org/mailman/listinfo/python-list
> >
> > > > You need a key to connect to that server, so you should want this:
> >
> > > > keys = 
> > > > paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
> >
> > > > Then keys[hostname] should contain a RSAKey object that you are looking 
> > > > for
> >
> > > > --
> > > > -- Guilherme H. Polo Goncalves
> > > --
> > >http://mail.python.org/mailman/listinfo/python-list
> >
> > --
> > -- Guilherme H. Polo Goncalves
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
-- Guilherme H. Polo Goncalves
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: stdin, stdout, redmon

2008-01-21 Thread Rolf van de Krol
According to various tutorials this should work.


|import sys
data = sys.stdin.readlines()
print "Counted", len(data), "lines."|


Please use google before asking such questions. This was found with only 
one search for the terms 'python read stdin'

Rolf

Bernard Desnoues wrote:
> Hi,
>
> I've got a problem with the use of Redmon (redirection port monitor). I 
> intend to develop a virtual printer so that I can modify data sent to 
> the printer.
> Redmon send the data flow to the standard input and lauchs the Python 
> program which send modified data to the standard output (Windows XP and 
> Python 2.5 context).
> I can manipulate the standard output.
>
> "import sys
> sys.stdout.write(data)"
>
> it works.
> But how to manipulate standard input so that I can store data in a 
> string or in an object file ? There's no "read" method.
>
> "a = sys.stdin.read()" doesn't work.
> "f = open(sys.stdin)" doesn't work.
>
> I don't find anything in the documentation. How to do that ?
> Thanks in advance.
>
> Bernard Desnoues
> Librarian
> Bibliothèque de géographie - Sorbonne
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to use py2exe ...

2008-01-21 Thread Mike Driscoll
On Jan 21, 1:45 am, Santiago  Romero <[EMAIL PROTECTED]> wrote:
>  Hi...
>
>  I'm a Linux user, and I would like some windows-friends to test a
> game I'm writing with python+pygame without they needing to install
> python, pygame, and so on.
>
>  I've heard about py2exe and pygame2exe, but I'm not sure on how to
> use them to create:
>
> a.- standalone exe files with a single .py program.
> Example: myprogram.py
>
> or
>
> b.- exe files containing all my source code + data directories (png
> files, data files, and so).
> Example: main.py, doc/README, src/*.py and data/*
>
>  The problem is I'm not sure on how to use py2exe and pygame2exe to
> build the executables...
>
>  And finally, a question: if I want to provide source code
> separately ... can I include .pyc files instead of .py files?

You should also check out the py2exe website as it has a tutorial, a
link to their mailing list, etc:

http://www.py2exe.org/

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


Re: stdin, stdout, redmon

2008-01-21 Thread Bernard Desnoues
Rolf van de Krol a écrit :
> According to various tutorials this should work.
> 
> 
> |import sys
> data = sys.stdin.readlines()
> print "Counted", len(data), "lines."|
> 
> 
> Please use google before asking such questions. This was found with only 
> one search for the terms 'python read stdin'
> 
> Rolf
> 
> Bernard Desnoues wrote:
>> Hi,
>>
>> I've got a problem with the use of Redmon (redirection port monitor). 
>> I intend to develop a virtual printer so that I can modify data sent 
>> to the printer.
>> Redmon send the data flow to the standard input and lauchs the Python 
>> program which send modified data to the standard output (Windows XP 
>> and Python 2.5 context).
>> I can manipulate the standard output.
>>
>> "import sys
>> sys.stdout.write(data)"
>>
>> it works.
>> But how to manipulate standard input so that I can store data in a 
>> string or in an object file ? There's no "read" method.
>>
>> "a = sys.stdin.read()" doesn't work.
>> "f = open(sys.stdin)" doesn't work.
>>
>> I don't find anything in the documentation. How to do that ?
>> Thanks in advance.
>>
>> Bernard Desnoues
>> Librarian
>> Bibliothèque de géographie - Sorbonne

Hello Rolf,

I know this code because I have search a solution !
Your google code doesn't work ! No attribute "readlines".

 >>> import sys
 >>> data = sys.stdin.readlines()

Traceback (most recent call last):
   File "", line 1, in 
 data = sys.stdin.readlines()
AttributeError: readlines
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: stdin, stdout, redmon

2008-01-21 Thread Rolf van de Krol
I don't know what you did with your Python installation, but for me this 
works perfectly.

test3.py contains:

import sys

print sys.stdin.readlines()


test.txt contains:

Testline1
Testline2


Output of 'python test3.py < test.txt' is:

['Testline1\n', 'Testline2']


Just plain simple and just works.

Rolf



Bernard Desnoues wrote:
> Rolf van de Krol a écrit :
>   
>> According to various tutorials this should work.
>>
>> 
>> |import sys
>> data = sys.stdin.readlines()
>> print "Counted", len(data), "lines."|
>> 
>>
>> Please use google before asking such questions. This was found with only 
>> one search for the terms 'python read stdin'
>>
>> Rolf
>>
>> Bernard Desnoues wrote:
>> 
>>> Hi,
>>>
>>> I've got a problem with the use of Redmon (redirection port monitor). 
>>> I intend to develop a virtual printer so that I can modify data sent 
>>> to the printer.
>>> Redmon send the data flow to the standard input and lauchs the Python 
>>> program which send modified data to the standard output (Windows XP 
>>> and Python 2.5 context).
>>> I can manipulate the standard output.
>>>
>>> "import sys
>>> sys.stdout.write(data)"
>>>
>>> it works.
>>> But how to manipulate standard input so that I can store data in a 
>>> string or in an object file ? There's no "read" method.
>>>
>>> "a = sys.stdin.read()" doesn't work.
>>> "f = open(sys.stdin)" doesn't work.
>>>
>>> I don't find anything in the documentation. How to do that ?
>>> Thanks in advance.
>>>
>>> Bernard Desnoues
>>> Librarian
>>> Bibliothèque de géographie - Sorbonne
>>>   
>
> Hello Rolf,
>
> I know this code because I have search a solution !
> Your google code doesn't work ! No attribute "readlines".
>
>  >>> import sys
>  >>> data = sys.stdin.readlines()
>
> Traceback (most recent call last):
>File "", line 1, in 
>  data = sys.stdin.readlines()
> AttributeError: readlines
>   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: When is min(a, b) != min(b, a)?

2008-01-21 Thread Jason
On Jan 21, 12:00 am, Albert Hopkins <[EMAIL PROTECTED]> wrote:
> On Sun, 20 Jan 2008 20:16:18 -0800, Paddy wrote:
> > I am definitely NOT a floating point expert, but I did find this:
> >http://en.wikipedia.org/wiki/IEEE_754r#min_and_max
>
> > P.S. What platform /Compiler are you using for Python?
>
> Linux with GCC 4
>
> -a

Please note that NaN's are very funky and platform dependent.  They
depend on their underlying platform's C library for creation and
display.  On windows, "float('nan')" will cause an exception, as there
are no valid string representations of NAN that can be converted to
the special floating point value.  Also, if you manage to create a nan
under Windows, it displays as "1.#QNAN".

Infinite values are also problematic.  In almost all cases, it is far
better to avoid infinite and NaN values.

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


Re: Sorting a list depending of the indexes of another sorted list

2008-01-21 Thread Peter Otten
Steven D'Aprano wrote:

>> The following relies on undocumented (I hope) behaviour:

> preferences = [10, 30, 20]
> hosts = [ "mx1.domain.com", "anotherhost.domain.com", 
>>... "mx2.domain.com"] 
> hosts.sort(key=lambda x, p=iter(preferences).next: p())
> preferences.sort()
> hosts
>> ['mx1.domain.com', 'mx2.domain.com', 'anotherhost.domain.com']

> What bit are you suggesting is undocumented?

The lambda spits out the items in preferences in the same order as they
occur in that list. If hosts.sort(key=...) in its C-implemented decoration
phase would iterate over the items in hosts in, say, reverse order hosts
would not be sorted correctly. Here's an illustration in Python:

>>> def dsu(items, key, reorder=lambda x: x):
... for i in reorder(range(len(items))):
... items[i] = key(items[i]), items[i]
... items.sort()
... items[:] = [v for k, v in items]
... return items
... 
>>> dsu([1,2,3], lambda x, n=iter("acb").next: n())
[1, 3, 2]
>>> dsu([1,2,3], lambda x, n=iter("acb").next: n(), reversed)
[3, 1, 2]

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


Re: Looping through the gmail dot trick

2008-01-21 Thread Martin Marcher
Steven D'Aprano wrote:
> Postfix, I think, interpets "foo+bar" the same as "foo".

yup it does, but "foo" has to be a valid localpart so

"foo+bar" -> foo
foo+baz -> foo
f+oobar -> f - which is a different user (aliases set aside)

famous call on plus addressing, and you it's just a default you can specify
anything you want but it has to be _after_ the full localpart without
address extensions.

-- 
http://noneisyours.marcher.name
http://feeds.feedburner.com/NoneIsYours

You are not free to read this message,
by doing so, you have violated my licence
and are required to urinate publicly. Thank you.

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


Re: Memory errors with imaplib

2008-01-21 Thread Grant Edwards
On 2008-01-21, Christian Heimes <[EMAIL PROTECTED]> wrote:
> Grant Edwards wrote:
>
>> If the solution shown in the bug report is correct, I'd be
>> more than happy to generate a patch.
>
> The solution seems fine but IMO it should be fixed in the ssl
> socket and not in imaplib. I like to get it *fixed* and not
> *worked around*. :)

I've always been taught that you can't assume that a read on a
socket (ssl or otherwise) will return the number of bytes you
request.  You've always got to code for the case where read()
returns smaller chunks.  Maybe I've been taught wrongly, but
under Unix at least I've found that it's always a good practice
to assume that network reads will often return smaller chunks
than requested.

-- 
Grant Edwards   grante Yow! Are we on STRIKE yet?
  at   
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dynamic type variable

2008-01-21 Thread Grant Edwards
On 2008-01-21, J. Peng <[EMAIL PROTECTED]> wrote:

> Python's variable is dynamic type,is it?
> But why this can't work?
>
 3 + 'a'

It can't work because the compiler has no way of knowing
whether the correct answer is '3a', 0x0d, the color purple, or
to reboot.

> So I see the number 3 can't be converted to string type automacially.

Because I wanted the string 'a' to be converted to an integer
automatically.

-- 
Grant Edwards   grante Yow! A can of ASPARAGUS,
  at   73 pigeons, some LIVE ammo,
   visi.comand a FROZEN DAQUIRI!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eucledian dist calculations

2008-01-21 Thread nodrogbrown

>
> 1. 'temp' is not used
> 2. Lose the superfluous parentheses in 'if' statements
> 3. Put space around operators
> 4. I've never used any of numpy & friends, but:
> (a) Can't you replace the inner loop with something like this:
>distance = abs(input_weight - weights[image, :])
> (b) I doubt that you need the .copy()
> 5. Lose the hard-wired numbers like 30 and 100
> 6. Put it inside a function and *TEST* it
>

thanx John , will go thru those and do the cleanup
gordon
-- 
http://mail.python.org/mailman/listinfo/python-list


Help with cPAMIE

2008-01-21 Thread romo20350
Hi, I'm in need of help with cPAMIE. I'm currently trying to submit
this form on a webpage:



Submit Coupon
Coupon Code:



Submit Coupon



I can fill in the textboxes alright but I'm having trouble submitting
it. I've tried using:
ie.buttonClick('action') but It returns some thing about it being
hidden...
Ive also tried:
ie.buttonClick('Submit Coupon') but it says it can't find the string
anywhere...
Any help would be greatly appreciated! Thank you so much!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: building psycopg2 on windows using mingw, "cannot find -lpq"

2008-01-21 Thread Tom Brown
On Mon, 2008-01-21 at 01:57 -0800, GHUM wrote:
> What am I missing? any hints?

I use psycopg2 all the time on windows. I use the binary installer
instead of source. Works great for me.

-Tom

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


Trouble writing to database: RSS-reader

2008-01-21 Thread Arne
Hi!

I try to make a rss-reader in python just for fun, and I'm almost
finished. I don't have any syntax-errors, but when i run my program,
nothing happends.

This program is supposed to download a .xml-file, save the contents in
a buffer-file(buffer.txt) and parse the file looking for start-tags.
When it has found a start tag, it asumes that the content (between the
start-tag and the end-tag) is on the same line, so then it removes the
start-tag and the end-tag and saves the content and put it into a
database.

The problem is that i cant find the data in the database! If i watch
my program while im running it, i can see that it sucsessfuly
downloads the .xml-file from the web and saves it in the buffer.

But I dont think that i save the data in the correct way, so it would
be nice if someone had some time to help me.

Full code: http://pastebin.com/m56487698
Saving to database: http://pastebin.com/m7ec69e1b
Retrieving from database: http://pastebin.com/m714c3ef8

And yes, I know that there is rss-parseres already built, but this is
only for learning.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: When is min(a, b) != min(b, a)?

2008-01-21 Thread Mark Dickinson
On Jan 21, 9:55 am, Jason <[EMAIL PROTECTED]> wrote:
> display.  On windows, "float('nan')" will cause an exception, as there
> are no valid string representations of NAN that can be converted to
> the special floating point value.  Also, if you manage to create a nan
> under Windows, it displays as "1.#QNAN".

I believe this will be fixed in Python 2.6  :)

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


How to solve "TypeError: list indices must be integers".

2008-01-21 Thread 顏灝
This is more details about my problem, which I running my py script
for my project. Programming in pythoncard that we can develop a GUI
based application easily.

I was assigned dialog.colorDialog(self) return value to a result
object, but I suspect that result.color is the attribute of the result
object that can assign to a string variable.

There is a error prompt from python console "TypeError: list indices
must be integers".
Have any suggestion to solve this problem?

When I print  result.color, it is print out something like (255,0,0).
How to covert result.color into a string?  How to convert a string to
result.color type?

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


Re: When is min(a, b) != min(b, a)?

2008-01-21 Thread Grant Edwards
On 2008-01-21, Albert Hopkins <[EMAIL PROTECTED]> wrote:
> This issue may have been referred to in 
> news:<[EMAIL PROTECTED]> but I didn't 
> entirely understand the explanation.  Basically I have this:
>
> >>> a = float(6)
> >>> b = float('nan')
> >>> min(a, b)
> 6.0
> >>> min(b, a)
> nan
> >>> max(a, b)
> 6.0
> >>> max(b, a)
> nan
>
> Before I did not know what to expect, but I certainly didn't expect 
> this.  So my question is what is the min/max of a number and NaN or is it 
> not defined (for which I would have expected either an exception to be 
> raised or NaN returned in each case).

For applications I work on, it should be NaN.  But I think the
result of comparing a Normal to a NaN is undefined, so the
above behavior is allowed by the IEEE spec.

> As a corrollary would I be able to rely on the above behavior or is it 
> subject to change (to fix a bug in min/max perhaps :-)?

According to Wikipedia:

  In the proposed IEEE 754r revision of that standard the same
  rule applies, except that a few anomalous functions (such as
  the maxnum function, which returns the maximum of two
  operands which are expected to be numbers) favour numbers --
  if just one of the operands is a NaN then the value of the
  other operand is returned.

  A different approach has been implemented in the NaN
  'toolbox' for GNU Octave and MATLAB. In that toolbox, NaNs
  are assumed to represent missing values and so the
  statistical functions ignore NaNs in the data instead of
  propagating them. Every computation in the NaN toolbox is
  based on the data values only, which can be useful if it is
  known that NaNs cannot be produced by errors.
  

-- 
Grant Edwards   grante Yow! Remember, in 2039,
  at   MOUSSE & PASTA will
   visi.combe available ONLY by
   prescription!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: When is min(a, b) != min(b, a)?

2008-01-21 Thread Grant Edwards
On 2008-01-21, Jason <[EMAIL PROTECTED]> wrote:

> Infinite values are also problematic.  In almost all cases, it is far
> better to avoid infinite and NaN values.

In many applications (e.g. process control) propogating NaN
values are way too useful to avoid.  Avoiding NaN would make a
lot of code far more complicated than would using them.

-- 
Grant Edwards   grante Yow! How's the wife?
  at   Is she at home enjoying
   visi.comcapitalism?
-- 
http://mail.python.org/mailman/listinfo/python-list


Python-URL! - weekly Python news and links (Jan 21)

2008-01-21 Thread Gabriel Genellina
QOTW:  "I'd say Java was never sexy, but dressed up in expensive lingerie by
marketing maniacs..." - Diez B. Roggisch
http://groups.google.com/group/comp.lang.python/msg/ae0463c921077f7f

"I must say that the richness that list comprehensions, generators and
iterators have brought to Python are well nigh immeasurable." - Uche Ogbuji


Four newbie questions:
* What are __new__ and __init__?:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/3fcb1673e25cdfe8/
* call-by-object and assignment explained (two threads):

http://groups.google.com/group/comp.lang.python/browse_thread/thread/6acd8387adbbb7f2/

http://groups.google.com/group/comp.lang.python/browse_thread/thread/f113debd4032c712/
* Why the name "list" is used instead of "array"?

http://groups.google.com/group/comp.lang.python/browse_thread/thread/d95bae7bd6c73670/
* Useful comments about a simple program: counting repeated
numbers from a file:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/b3ded6d0f494d06/

A short explanation about Unicode and encodings, by Martin Löwis:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/983f2f84f1f70320/

Computing all combinations from multiple lists - several
alternatives discussed:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/998a10a65128c96e/

APyB[1], the Brazilian Python Association, proudly announces
that the upcoming International Free Software Forum[2], one of
the biggest FLOSS events in the world, with more than 5 thousand
participants in 2007, will have a dedicated Python track this
year, with 14 talks[3] related to Python and 3 training sessions:
   [1] http://associacao.pythonbrasil.org/
   [2] http://fisl.softwarelivre.org/
   [3] http://www.pythonbrasil.com.br/moin.cgi/PropostasFISL9

Pairing two lists: from simple to rather complex answers:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/9fe4347ae4f0b4ac/

Tips to find memory leaks:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/7249eee28515bb92/

Python playes games, and more:
http://www.mechanicalcat.net/richard/log/Python/pyglet_1_0_is_out

Arguments in a function call are evaluated before checking its
number - a missing comma is very significant!

http://groups.google.com/group/comp.lang.python/browse_thread/thread/1fa85946f0947023/

Django is available for Jython, if you use the right branches:
http://jython.svn.sourceforge.net/viewvc/jython/
Much the same is true for TurboGears ...



Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

Just beginning with Python?  This page is a great place to start:
http://wiki.python.org/moin/BeginnersGuide/Programmers

The Python Papers aims to publish "the efforts of Python enthusiats":
http://pythonpapers.org/
The Python Magazine is a technical monthly devoted to Python:
http://pythonmagazine.com

Readers have recommended the "Planet" sites:
http://planetpython.org
http://planet.python.org

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce

Python411 indexes "podcasts ... to help people learn Python ..."
Updates appear more-than-weekly:
http://www.awaretek.com/python/index.html

Steve Bethard continues the marvelous tradition early borne by
Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim
Lesher of intelligently summarizing action on the python-dev mailing
list once every other week.
http://www.python.org/dev/summary/

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/

Re: building psycopg2 on windows using mingw, "cannot find -lpq"

2008-01-21 Thread Diez B. Roggisch
GHUM wrote:

> The compile works, BUT linking fails:
> 
> 2.5\Release\psycopg\_psycopg.def -Lc:\python25\libs -Lc:
> \python25\PCBuild -Lc:/p
> ostgres/83RC2/lib -lpython25 -lpq -lws2_32 -ladvapi32 -o build
> \lib.win32-2.5\psy
> copg2\_psycopg.pyd
> c:\mingw\bin\..\lib\gcc\mingw32\3.4.5\..\..\..\..\mingw32\bin\ld.exe:
> cannot find -lpq
> collect2: ld returned 1 exit status
> error: command 'gcc' failed with exit status 1
> 
> if I google for the error
> 
> "ld.exe: cannot find -lpq"
> 
> there is allways the information that the lib-dir of libpq is missing;
> but :
> 
>  -Lc:/postgres/83RC2/lib
> 
> is clearly in the commandline, and within c:/postgres/83RC2/lib
> there is one libqp.lib
> 
> What am I missing? any hints?

Are you sure using forward slashes in the path works here?

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


Re: Just for fun: Countdown numbers game solver

2008-01-21 Thread Arnaud Delobelle
On Jan 21, 9:01 am, [EMAIL PROTECTED] wrote:

> Arnaud: I haven't had time to play with your solution yet - how quick
> does it run?

Ok I've done some quick timings, it's faster than I remembered it:

numbers = [2, 4, 5, 8, 25]
target = 758

Average time to find
(1) best solution (in terms of length of repr): 0.0418s
(2) first solution: 0.00421s

(2.2GHz MacBook Pro, done with the timeit module)

(1) involves working out all possible calculations with the 6 numbers.

--
Arnaud

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


ctypes CDLL - which paths are searched?

2008-01-21 Thread Helmut Jarausch
Hi,

how can I specify the paths to be searched for a dynamic library
to be loaded by ctypes' CDLL class on a Linux system.

Do I have to set os.environment['LD_LIBRARY_PATH'] ?

Many thanks for a hint,
Helmut.

-- 
Helmut Jarausch

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


is it possible to set namespace to an object.

2008-01-21 Thread glomde
Hi,

is it somehow possible to set the current namespace so that is in an
object.
Somthing like.

class Test():
  

testObj = Test()

set namespace testObj
Name = "Test"

Name would set testObj.Name to "Test".

I was thinking this could be done with the with statement somehow
(without using as) in the __enter__
function.

Is the above possible?

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


Re: Basic inheritance question

2008-01-21 Thread Lie
> > Please stop taking my words to its letters.
>
> So we're supposed to actually guess what you really mean ???

That's what human does, otherwise you'll "Fail the Turing Test".

> >> Personally, I've seen many C++ programs with complex class designs
> >> where it definitely helps to consistently use "this->". I cannot
> >> remember all local (and global) variables in bigger methods.
>
> > In that case, you have the _option_ to do it.
>
> Make no sens when maintaining code wrote by someone that didn't use this
> 'option'.
>
> (snip)
>
>
>
>  it's the first argument of the function - which usually happens to be
>  the current instance when the function is used as a method.
> >>> And that's the point, self (or anything you name it) is almost always
> >>> the current instance
> >> # this is a plain function. In this function,
> >> # 'obj' can be whatever that happens to have a (numeric)
> >> # 'stuff' attribute
> >> def func(obj, arg):
> >>    return (obj.stuff + arg) / 2.0
>
> >> # this is a class with an instance attribute 'stuff'
> >> class Foo(object):
> >>     def __init__(self, bar):
> >>       self.stuff = bar + 42
>
> >> # this is another (mostly unrelated) class
> >> # with a class attribute 'stuff'
> >> class Bar(object):
> >>    stuff = 42
>
> >> # this is a dummy container class:
> >> class Dummy(object): pass
>
> >> # now let's play:
> >> import new
>
> >> d = Dummy()
> >> d.stuff = 84
> >> print func(d, 1)
>
> >> d.baaz = new.instancemethod(func, d, type(d))
> >> print d.baaz(2)
>
> >> f = Foo(33)
> >> print func(f, 3)
> >> Foo.baaz = func
> >> f.baaz(4)
>
> >> print func(Bar, 5)
> >> Bar.baaz = classmethod(func)
> >> Bar.baaz(6)
>
> >>>  and that makes it functionally the same as Me and
> >>> this in VB and Java.
> >> Depends on the context, cf above !-)
>
> > Please again, stop taking letters to the words, I don't meant them to
> > be exactly the same, rather the same would meant that they generally
> > can be considered equal,
>
> If you still think that way after having read the above code, then I
> can't help. We obviously don't share the same mental model here.

I don't get what you're trying to meant, in that piece of code self is
used in the regular way, in a regular context.

> > exceptions exists of course. And btw, I don't
> > understand what you meant by your example, they seemed to be a
> > completely OK program for me,
>
> Indeed it's ok (even if totally useless by itself). The point is that
> 'self' (or whatever you name it) is just and only the first argument of
> a function, period.

And it is... but I still don't get what you meant

> > even though it's a bit confusing to
> > follow[2].
>
> Nothing in it should be confusing to anyone having a decent knowledge of
> Python's object model IMHO.
>
> > [2] btw, the reason it's a bit confusing to follow is one of my
> > points: It is a Bad Thing(tm) to use the same name for different
> > variables
>
> Where do I "use the same name for different variables" here ?

It's not confusing in the way of object model, but in the way that you
used meaningless names in overloaded manner.

> > even in a language like Python that enforce explicit naming
> > of classes
>
> Python doesn't "enforce" explicit name of classes - IIRC, there are ways
> to instanciate anonymous class objects. But I definitively don't see how
> this relate to this discussion.

We're not talking about anonymous class objects here, and I'm sure you
actually understand what I meant by "naming the class" from previous
discussions.

> Yes, I know, "please guess what I mean" !-) but sorry, there's no sens
> discussing a technical point without using accurate and appropriate
> technical naming of technical concepts invlved.

Well, it's not my fault for being born as a non-native speaker of
English, sometimes what I meant might goes a bit off from what I
write. Anyway, human languages aren't designed to be fully
unambiguous, so it is natural for human to provide a margin of errors
when speaking to each other, well unless you're not a human...

> > Most other languages
> > 1) automatically assign the containing class' object
>  s/containing class' object/current instance/
> > in a keyword
> > (Java: this, VB: Me) behind the screen,
>  That's not very far from what a Python method object does -
>  automatically assign the current instance to something. The difference
>  is that Python uses functions to implement methods (instead of having
>  two distinct contructs), so the only reliable way to "inject" the
>  reference to the current instance is to pass it as an argument to the
>  function (instead of making it pop from pure air).
> >>> It isn't very far, but Python makes it obvious about the assignment
> >>> (not behind the screen).
> >> Exactly. And given both the simplicity of the solution and what it let
> >> you do, that's a *very* GoodThing(tm) IMHO.
>
> > I agree, it's a Good Thing but it doesn't make the point less pointy

Re: Is there a portable way to tell if data is available on a pipe?

2008-01-21 Thread Scott David Daniels
John Nagle wrote:
>I need some way to find out if a pipe has data available for
> a read without blocking if it does not.
...
>  I'd like to avoid having a thread to manage each pipe, but if I
> have to, so be it.

Well, without granting your wish, put a Queue.Queue "in front" of
each pipe.  The per-pipe thread reads a chunk, waiting if it has to,
and then writes to the queue.  To read from a pipe w/o waiting from
one of these assemblies, you can use the get_nowait method on the
associated queue.

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


Berlin (Germany) Python User Group is meeting on 23.1.

2008-01-21 Thread Stephan Diehl
The Berlin Python User Group is meeting on the 23.1. at newthinking store at
7pm. All details can be found at http://wiki.python.de/User_Group_Berlin.

The Berlin Python User Group is planning to meet every two month to talk
about Python. Most talking will be done in german, but I can assure you
that english could be spoken as well, if the need arises...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is it possible to set namespace to an object.

2008-01-21 Thread Wildemar Wildenburger
glomde wrote:
> Hi,
> 
> is it somehow possible to set the current namespace so that is in an
> object.
> [snip]
> set namespace testObj
> Name = "Test"
> 
> Name would set testObj.Name to "Test".
> 
> [snip]
> 
> Is the above possible?
> 
Don't know, sorry. But let me ask you this: Why do you want to do this? 
Maybe there is another way to solve the problem that you want to solve.

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


Re: When is min(a, b) != min(b, a)?

2008-01-21 Thread Pete Forman
Grant Edwards <[EMAIL PROTECTED]> writes:

 > For applications I work on, it should be NaN.  But I think the
 > result of comparing a Normal to a NaN is undefined, so the
 > above behavior is allowed by the IEEE spec.

Comparison of two floating point datums results in exactly one of
these being true:

1) less than
2) equal
3) greater than
4) unordered


IEEE 754r defines maxNum and minNum which are explicitly defined to
return one argument if the other is a NaN.  Any other operation (apart
from a few others that are specified) return a NaN if any argument is
NaN.

NaN generally represents the result of an invalid operation.  Using it
for missing value is not in the draft standard, though it is not
forbidden either.

If NaNs in your data are important then you must take care in explicit
and implicit comparisons to consider unordered results.
-- 
Pete Forman-./\.-  Disclaimer: This post is originated
WesternGeco  -./\.-   by myself and does not represent
[EMAIL PROTECTED]-./\.-   the opinion of Schlumberger or
http://petef.port5.com   -./\.-   WesternGeco.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Trouble writing to database: RSS-reader

2008-01-21 Thread Bruno Desthuilliers
Arne a écrit :
> Hi!
> 
> I try to make a rss-reader in python just for fun, and I'm almost
> finished.

Bad news : you're not.

> I don't have any syntax-errors, but when i run my program,
> nothing happends.
> 
> This program is supposed to download a .xml-file, save the contents in
> a buffer-file(buffer.txt) and parse the file looking for start-tags.
> When it has found a start tag, it asumes that the content (between the
> start-tag and the end-tag) is on the same line,

Very hazardous assumption. FWIW, you can more safely assule this will 
almost never be the case. FWIW, don't assume *anything* wrt/ newlines 
when it comes to XML - you can even have newlines between two attributes 
of a same tag...

> so then it removes the
> start-tag and the end-tag and saves the content and put it into a
> database.
> 
> The problem is that i cant find the data in the database! If i watch
> my program while im running it, i can see that it sucsessfuly
> downloads the .xml-file from the web and saves it in the buffer.
> 
> But I dont think that i save the data in the correct way, so it would
> be nice if someone had some time to help me.
> 
> Full code: http://pastebin.com/m56487698
> Saving to database: http://pastebin.com/m7ec69e1b
> Retrieving from database: http://pastebin.com/m714c3ef8

1/ you don't need to make each and every variable an attribute of the 
class - only use attributes for what constitute the object state (ie: 
need to be maintain between different, possibly unrelated method calls). 
In your update_sql method, for exemple, beside self.connection and 
_eventually_ self.cursor, you don't need any attribute - local variables 
are enough.

2/ you don't need these Stored variables at all - just reset 
title/link/description to None *when needed* (cf below), then test these 
variables against None.

3/ learn to use if/elif properly !-)

4/ *big* logic flaw (and probably the first cause of your problem): on 
*each* iteration, you reset your Stored flags to False - whether 
you stored something in the database or not. Since you don't expect to 
have all there data on a single line (another wrong assumption : you 
might get a whole rss stream as one single big line), I bet you never 
write anything into the database .

5/ other big flaw : either use an autoincrement for your primary key - 
and *dont* pass any value for it in your query -  or provide (a 
*unique*) id by yourself.

6/ FWIW, also learn to properly use the DB api - don't build your SQL 
query using string formatting, but pass the argument as a tuple, IOW:

# bad:
cursor.execute(
 '''INSERT INTO main VALUES(null, %s, %s, %s)'''
 % title, link, description
)

# good (assuming you're using an autoincrementing key for your id) :
cursor.execute(
 "INSERT INTO main VALUES(, , )",
 (title, link, description)
)

NB : replace  with the appropriate placeholder for your database - cf 
your db module documentation (usually either '?' or '%s')

This will make the db module properly escape and convert values.

7/ str.replace() doesn't modify the string in-place (Python strings are 
immutable), but returns a new string. so you want:
   line = line.replace('x', 'y')

8/ you don't need to explicitely call connection.commit on each and 
every statement, and you don't need to call it at all on SELECT 
statements !-)

9/ have you tried calling print_rss *twice* on the same instance ?-)

10/ are you sure it's useful to open the same 'buffer.txt' file for 
writing *twice* (once in __init__, the other in update_sql). BTW, use 
open(), not file().

11/ are you sure you need to use this buffer file at all ?

12/ are you really *sure* you want to *destroy* your table and recreate 
it each time you call your script ?

> And yes, I know that there is rss-parseres already built, but this is
> only for learning.

This should not prevent you from learning how to properly parse XML 
(hint: with an XML parser). XML is *not* a line-oriented format, so you 
just can't get nowhere trying to parse it this way.



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


Re: Default attribute values pattern

2008-01-21 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
>> Grab(argdict, key, default) is argdict.pop(key, default)
> 
> "pop() raises a KeyError when no default value is given and the key is
> not found."

Then use it with a default value !-)

>> def grab(kw, key, default=None):
>>try:
>>  return kw.pop(key)
>>except KeyError:
>>  return default
> 
> So Bruno's technique seems to me to be the correct one as it catches
> the KeyError.

Note that I cancelled the message (too bad, doesn't work everywhere). I 
totally agree with Arnaud on this, and should sometimes re-read the doc 
for stuff I use so often I think I know them.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Trouble writing to database: RSS-reader

2008-01-21 Thread Bruno Desthuilliers
Dennis Lee Bieber a écrit :
> On Mon, 21 Jan 2008 08:12:43 -0800 (PST), Arne <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
> 
>> The problem is that i cant find the data in the database! If i watch
>> my program while im running it, i can see that it sucsessfuly
>> downloads the .xml-file from the web and saves it in the buffer.
>>
>   Did you COMMIT the transaction with the database?

Did you READ the code ?-)

NB : Yes, he did. The problem*s* are elsewhere.


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


index of min element of sequence

2008-01-21 Thread Neal Becker
What's a good/fast way to find the index of the minimum element of a
sequence?  (I'm fairly sure sorting the sequence is not the fastest
approach)

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


Re: Trouble writing to database: RSS-reader

2008-01-21 Thread Gabriel Genellina
En Mon, 21 Jan 2008 14:12:43 -0200, Arne <[EMAIL PROTECTED]> escribi�:

> I try to make a rss-reader in python just for fun, and I'm almost
> finished. I don't have any syntax-errors, but when i run my program,
> nothing happends.
>
> This program is supposed to download a .xml-file, save the contents in
> a buffer-file(buffer.txt) and parse the file looking for start-tags.
> When it has found a start tag, it asumes that the content (between the
> start-tag and the end-tag) is on the same line, so then it removes the
> start-tag and the end-tag and saves the content and put it into a
> database.

That's a gratuitous assumption and may not hold on many sources; you  
should use a proper XML parser instead (using ElementTree, by example, is  
even easier than your sequence of find and replace)

> The problem is that i cant find the data in the database! If i watch
> my program while im running it, i can see that it sucsessfuly
> downloads the .xml-file from the web and saves it in the buffer.

Ok. So the problem should be either when you read the buffer again, when  
processing it, or when saving in the database.
It's very strange to create the table each time you want to save anything,  
but this gives you another clue: the table is created and remains empty,  
else the select statement in print_rss would have failed. So you know that  
those lines are executed. Now, the print statement is your friend:

 self.buffer = file('buffer.txt')
 for line in self.buffer.readline():
 print "line=",line # add this and see what you get

Once you get your code working, it's time to analyze it. I think someone  
told you "in Python, you have to use self. everywhere" and you read it  
literally. Let's see:

 def update_buffer(self):
 self.buffer = file('buffer.txt', 'w')
 self.temp_buffer = urllib2.urlopen(self.rssurl).read()
 self.buffer.write(self.temp_buffer)
 self.buffer.close()

All those "self." are unneeded and wrong. You *can*, and *should*, use  
local variables. Perhaps it's a bit hard to grasp at first, but local  
variables, instance attributes and global variables are different things  
used for different purposes. I'll try an example: you [an object] have a  
diary, where you record things that you have to remember [your instance  
attributes, or "data members" as they are called on other languages]. You  
also carry a tiny notepad in your pocket, where you make a few notes when  
you are doing something, but you always throw away the page once the job  
is finished [local variables]. Your brothers, sisters and parents [other  
objects] use the same schema, but there is a whiteboard on the kitchen  
where important things that all of you have to know are recorded [global  
variables] (anybody can read and write on the board).
Now, back to the code, why "self." everywhere? Let's see, self.buffer is a  
file: opened, written, and closed, all inside the same function. Once it's  
closed, there is no need to keep a reference to the file elsewhere. It's  
discardable, as your notepad pages: use a local variable instead. In fact,  
*all* your variables should be locals, the *only* things you should keep  
inside your object are rssurl and the database location, and perhaps  
temp_buffer (with another, more meaningful name, rssdata by example).

Other -more or less random- remarks:

 if self.titleStored == True and self.linkStored == True and  
descriptionStored == True:

Don't compare against True/False. Just use their boolean value:

 if titleStored and linkStored and descriptionStored:

Your code resets those flags at *every* line read, and since a line  
contains at most one tag, they will never be True at the same time. You  
should reset the flags only after you got the three items and wrote them  
onto the database.

The rss feed, after being read, is available into self.temp_buffer; why do  
you read it again from the buffer file? If you want to iterate over the  
individual lines, use:

 for line in self.temp_buffer.splitlines():

-- 
Gabriel Genellina

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

Re: index of min element of sequence

2008-01-21 Thread Peter Otten
Neal Becker wrote:

> What's a good/fast way to find the index of the minimum element of a
> sequence?  (I'm fairly sure sorting the sequence is not the fastest
> approach)

>>> items = "defbhkamnz"
>>> min(xrange(len(items)), key=items.__getitem__)
6
>>> items[6]
'a'

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


Re: is it possible to set namespace to an object.

2008-01-21 Thread glomde
On 21 Jan, 18:59, Wildemar Wildenburger
<[EMAIL PROTECTED]> wrote:
> glomde wrote:
> > Hi,
>
> > is it somehow possible to set the current namespace so that is in an
> > object.
> > [snip]
> > set namespace testObj
> > Name = "Test"
>
> > Name would set testObj.Name to "Test".
>
> > [snip]
>
> > Is the above possible?
>
> Don't know, sorry. But let me ask you this: Why do you want to do this?
> Maybe there is another way to solve the problem that you want to solve.

The reason is that I do not want to repeat myself. It is to set up XML
type like
trees and I would like to be able to do something like.

with ElemA():
  Name = "Top"
  Description "Blahaha..."
  with ElemB():
Name = "ChildA"
Description "Blahaha..."
 

This would be the instead of.
with ElemA() as node:
  node.Name = "Top"
  node.Description "Blahaha..."
  with ElemB() as node:
node.Name = "ChildA"
node.Description "Blahaha..."
 

So to save typing and have something that I think looks nicer.

BR

/T





>
> /W

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


Re: problem with 'global'

2008-01-21 Thread Gabriel Genellina
En Mon, 21 Jan 2008 11:44:54 -0200, Mel <[EMAIL PROTECTED]> escribi�:

> Duncan Booth wrote:
>>
>> The first sentence (which hasn't changed since 2.4) describing the  
>> global
>> statement seems clear enough to me: "The global statement is a  
>> declaration
>> which holds for the entire current code block."
>
> I don't think that would stop the OP from thinking the global
> statement had to be executed.  In the code example, it seems to have
> been stuck in a
>
>  if 1==2: global a
>
> and it still worked.

The future statement is another example, even worse:

if 0:
 from __future__ import with_statement

with open("xxx") as f:
 print f

All import statements are executable, only this special form is not. That  
"global" and "__future__" are directives and not executable statements, is  
confusing.

-- 
Gabriel Genellina

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

Re: How to solve "TypeError: list indices must be integers".

2008-01-21 Thread John Machin
On Jan 22, 3:15 am, "" <[EMAIL PROTECTED]> wrote:
> This is more details about my problem, which I running my py script
> for my project. Programming in pythoncard that we can develop a GUI
> based application easily.
>
> I was assigned dialog.colorDialog(self) return value to a result
> object, but I suspect that result.color is the attribute of the result
> object that can assign to a string variable.

The concepts " assigned  to a  object"
and " can be assigned to a  variable" just don't
exist in Python.

# Initially "name1" isn't bound to anything
name1 = 42
# "name1" now refers to an int object whose value is 42
name1 = 'abc'
# "name1" now refers to a str object whose value is 'abc'
name2 = name1
# "name2" now refers to the same str object

What is "dialog.colorDialog(self) return value"? What is "a result
 object"? Show us the code!

What is the connection between your last sentence above and the
"TypeError: list indices must be integers" problem? Show us the code!

>
> There is a error prompt from python console "TypeError: list indices
> must be integers".
> Have any suggestion to solve this problem?

Communication would be much easier if you show us the line of code
that causes the error message.

Here are two simple examples of what can trigger that error message:

>>> a_list = [1, 42, 666]
>>> not_an_integer = None

>>> a_list[not_an_integer] = 9876
Traceback (most recent call last):
  File "", line 1, in 
TypeError: list indices must be integers

>>> a_name = a_list[not_an_integer]
Traceback (most recent call last):
  File "", line 1, in 
TypeError: list indices must be integers

Look for the pattern a_list[not_an_integer] in the statement that
triggers the exception.


>
> When I print  result.color, it is print out something like (255,0,0).

Yes, that's most likely a tuple of (red, green, blue) values ... I'm
not astonished; are you?

> How to covert result.color into a string?

How? Use elementary Python functionality, after you've decided what
string representation you want. Examples:

>>> color = (255, 128, 0)
>>> "red=%d green=%d blue=%d" % color
'red=255 green=128 blue=0'
>>> '.someclass {background-color: #%02x%02x%02x; }' % color
'.someclass {background-color: #ff8000; }'
>>>

> How to convert a string to
> result.color type?

Reverse the process.

Again, what is the connection between "result.color" and the
"TypeError: list indices must be integers" problem?


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

Re: is it possible to set namespace to an object.

2008-01-21 Thread George Sakkis
On Jan 21, 1:56 pm, glomde <[EMAIL PROTECTED]> wrote:
> On 21 Jan, 18:59, Wildemar Wildenburger
>
>
>
> <[EMAIL PROTECTED]> wrote:
> > glomde wrote:
> > > Hi,
>
> > > is it somehow possible to set the current namespace so that is in an
> > > object.
> > > [snip]
> > > set namespace testObj
> > > Name = "Test"
>
> > > Name would set testObj.Name to "Test".
>
> > > [snip]
>
> > > Is the above possible?
>
> > Don't know, sorry. But let me ask you this: Why do you want to do this?
> > Maybe there is another way to solve the problem that you want to solve.
>
> The reason is that I do not want to repeat myself. It is to set up XML
> type like
> trees and I would like to be able to do something like.
>
> with ElemA():
>   Name = "Top"
>   Description "Blahaha..."
>   with ElemB():
> Name = "ChildA"
> Description "Blahaha..."
>  
>
> This would be the instead of.
> with ElemA() as node:
>   node.Name = "Top"
>   node.Description "Blahaha..."
>   with ElemB() as node:
> node.Name = "ChildA"
> node.Description "Blahaha..."
>  
>
> So to save typing and have something that I think looks nicer.

... and more confusing for anyone reading the code (including you
after a few weeks/months). If you want to save a few keystrokes, you
may use 'n' instead of 'node' or use an editor with easy auto
completion.

By the way, is there any particular reason for generating the XML
programmatically like this ? Why not have a separate template and use
one of the dozen template engines to populate it ?

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


Re: problem with 'global'

2008-01-21 Thread Marc 'BlackJack' Rintsch
On Mon, 21 Jan 2008 17:08:46 -0200, Gabriel Genellina wrote:

> The future statement is another example, even worse:
> 
> if 0:
>  from __future__ import with_statement
> 
> with open("xxx") as f:
>  print f

In Python >=2.5 it's a compile time error if that import is not the very
first statement in a source file.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Default attribute values pattern

2008-01-21 Thread George Sakkis
On Jan 19, 6:02 pm, "David Tweet" <[EMAIL PROTECTED]> wrote:
> Hello,
>
> Seems to me that setattrs sort of assumes that you want to have all your
> initialization arguments set as attributes of the same name.  I would think
> you'd sometimes want to be able to process the extra arguments inside of each
> __init__, assign them to attributes with different names, etc.
>
> My approach would be to treat each __init__ as a wrapping function, grabbing
> the items it needs out of the keyword dictionary and then calling the next
> __init__.  Curious to hear other approaches though:
>
> def Grab(argdict, key, default):
>   """Like argdict.get(key, default), but also deletes key from argdict."""
>   if key in argdict:
> retval = argdict["key"]
> del(argdict[key])
>   else:
> retval = default
>   return retval
>
> class Base(object):
>   def __init__(self, x=0, y=None):
> print "in Base init"
> self.x = x
> self.y = y
>
> class Derived1(Base):
>   def __init__(self, **kwargs):
> print "in Derived1 init"
> self.z = Grab(kwargs, "z", None)
> super(Derived1, self).__init__(**kwargs)
>
> class Derived2(Derived1):
>   def __init__(self, **kwargs):
> print "in Derived2 init"
> self.a = Grab(kwargs, "a", 0)
> self.b = Grab(kwargs, "b", False)
> super(Derived2, self).__init__(**kwargs)
> print self.__dict__
>
> newthing = Derived2(x=234, y="blah", a=5)


The problem with this (apart from being somewhat more verbose and less
explicit) is that you have to set existing attributes (like x and y)
*after* the call to super __init__ while new attributes (like z, a and
b) *before* the call. Mixing it up will either raise a runtime error
for passing an unknown argument to the parent, or (worse) set the
parent's default instead of the child's. So for the common attribute
setting case it involves more error-prone boilerplate code.

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


Re: Bug in __init__?

2008-01-21 Thread Gabriel Genellina
En Mon, 21 Jan 2008 05:59:38 -0200, <[EMAIL PROTECTED]> escribi�:

> Is there no way of adding a possible warning message (that obviously
> could be turned off) to warn users of possible problems linked to
> using mutable types as parameters?
>
> Seems to me this could save users a few minutes/hours of headaches and
> headscratching. (The biggest issue affecting new programmers these
> days!)

Most objects are mutable, such warning would happen so often that would  
become useless.
The only immutable objects are numbers, strings, tuples, None and a few  
esoteric types; all other instances, including instances of all user  
defined classes, are mutable unless explicitely their attributes are  
read-only.

-- 
Gabriel Genellina

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

Re: problem with 'global'

2008-01-21 Thread Duncan Booth
Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:

> On Mon, 21 Jan 2008 17:08:46 -0200, Gabriel Genellina wrote:
> 
>> The future statement is another example, even worse:
>> 
>> if 0:
>>  from __future__ import with_statement
>> 
>> with open("xxx") as f:
>>  print f
> 
> In Python >=2.5 it's a compile time error if that import is not the very
> first statement in a source file.
> 
That doesn't appear to be the case. With Python 2.5.1 the example 
Gabriel quoted will compile and run.


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


Re: index of min element of sequence

2008-01-21 Thread Paul Rubin
Neal Becker <[EMAIL PROTECTED]> writes:
> What's a good/fast way to find the index of the minimum element of a
> sequence?  (I'm fairly sure sorting the sequence is not the fastest
> approach)

Python 2.5 (untested):

   from operator import itemgetter
   minindex = min(enumerate(seq), key=itemgetter(1))[1]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: index of min element of sequence

2008-01-21 Thread Roger Miller
On Jan 21, 8:48 am, Peter Otten <[EMAIL PROTECTED]> wrote:

> Neal Becker wrote:
> > What's a good/fast way to find the index of the minimum element of a
> > sequence?
...

> >>> min(xrange(len(items)), key=items.__getitem__)
...

Or just
   items.index(min(items))
I found this to be significantly faster in a simple test (searching a
list of 1000 ints with the minimum in the middle), despite the fact
that it requires two passes.  I'm sure that one could find cased where
Peter's approach is faster, so you if you are concerned about speed
you should measure with your own data.



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


Re: is it possible to set namespace to an object.

2008-01-21 Thread glomde
On 21 Jan, 20:16, George Sakkis <[EMAIL PROTECTED]> wrote:
> On Jan 21, 1:56 pm, glomde <[EMAIL PROTECTED]> wrote:
>
>
>
> > On 21 Jan, 18:59, Wildemar Wildenburger
>
> > <[EMAIL PROTECTED]> wrote:
> > > glomde wrote:
> > > > Hi,
>
> > > > is it somehow possible to set the current namespace so that is in an
> > > > object.
> > > > [snip]
> > > > set namespace testObj
> > > > Name = "Test"
>
> > > > Name would set testObj.Name to "Test".
>
> > > > [snip]
>
> > > > Is the above possible?
>
> > > Don't know, sorry. But let me ask you this: Why do you want to do this?
> > > Maybe there is another way to solve the problem that you want to solve.
>
> > The reason is that I do not want to repeat myself. It is to set up XML
> > type like
> > trees and I would like to be able to do something like.
>
> > with ElemA():
> >   Name = "Top"
> >   Description "Blahaha..."
> >   with ElemB():
> > Name = "ChildA"
> > Description "Blahaha..."
> >  
>
> > This would be the instead of.
> > with ElemA() as node:
> >   node.Name = "Top"
> >   node.Description "Blahaha..."
> >   with ElemB() as node:
> > node.Name = "ChildA"
> > node.Description "Blahaha..."
> >  
>
> > So to save typing and have something that I think looks nicer.
>
> ... and more confusing for anyone reading the code (including you
> after a few weeks/months). If you want to save a few keystrokes, you
> may use 'n' instead of 'node' or use an editor with easy auto
> completion.
>
> By the way, is there any particular reason for generating the XML
> programmatically like this ? Why not have a separate template and use
> one of the dozen template engines to populate it ?
>
> George

I am not using it for XML generation. It was only an example. But
the reason for using it programmatically is that you mix power
of python with templating. Using for loops and so on.
XIST(www.livinglogic.de) is
doing something similar. But I would like the namespace thing.

The above was only an example. And yes it might be confusing if you
read the code. But I still want to do it, the question is it possible?





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


Building a pretrigger / posttrigger framework class

2008-01-21 Thread rh0dium
Hi all,

I am thinking about a class which can automatically determine the
order which it is run.  I would like to implement a super class which
has a run() method and a pretrigger() method.  The purpose of the
pretrigger method is to state what classes need to be run before this
class.run() method is executed.

So for example:

class superclass(object):
def run(self):
"""Method which will get overriden"""
def pretrigger(self):
"""Method which will get overriden and determine the order"""

class subclassA(superclass):
def run(self):
print "I am subclass A"
def pretrigger(self):
return [subclassB(),]

class subclassB(superclass):
def run(self):
print "I am subclass B"
def pretrigger(self): None
return [subclassC(), ]

class subclassC(superclass):
def run(self):
print "I am subclass C"
def pretrigger(self): None
return None

Now what I am looking for is some logic which can look at this and
draw the following conclusion.
- In order to run subclassA, I first need to run subclassB.  In order
to run subclassB I need to run subclassC.  So the order to run this
would be subclassC, subclassB, then subclassA.
I would also like some information on is this a good approach to using
a superclass or not?

Any and all comments are welcome.  Thanks!!

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


Re: index of min element of sequence

2008-01-21 Thread John Machin
On Jan 22, 6:38 am, Paul Rubin  wrote:
> Neal Becker <[EMAIL PROTECTED]> writes:
> > What's a good/fast way to find the index of the minimum element of a
> > sequence?  (I'm fairly sure sorting the sequence is not the fastest
> > approach)
>
> Python 2.5 (untested):
>
>from operator import itemgetter
>minindex = min(enumerate(seq), key=itemgetter(1))[1]

Bzzzt!

>>> seq = [1000, 9, 8, 7, 2000, 3000]
>>> from operator import itemgetter
>>> minindex = min(enumerate(seq), key=itemgetter(1))[1]
>>> minindex
7
>>> min(enumerate(seq), key=itemgetter(1))
(3, 7)

s/[1]/[0]/ or more generally:

minindex, minvalue = min(enumerate(seq), key=itemgetter(1))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a portable way to tell if data is available on a pipe?

2008-01-21 Thread John Nagle
Scott David Daniels wrote:
> John Nagle wrote:
>>I need some way to find out if a pipe has data available for
>> a read without blocking if it does not.
> ...
>>  I'd like to avoid having a thread to manage each pipe, but if I
>> have to, so be it.
> 
> Well, without granting your wish, put a Queue.Queue "in front" of
> each pipe.  The per-pipe thread ...

That's what I thought.  Oh, well.

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


Re: index of min element of sequence

2008-01-21 Thread Peter Otten
Roger Miller wrote:

> On Jan 21, 8:48 am, Peter Otten <[EMAIL PROTECTED]> wrote:
> 
>> Neal Becker wrote:
>> > What's a good/fast way to find the index of the minimum element of a
>> > sequence?
> ...
> 
>> >>> min(xrange(len(items)), key=items.__getitem__)
> ...
> 
> Or just
>items.index(min(items))
> I found this to be significantly faster in a simple test (searching a
> list of 1000 ints with the minimum in the middle), despite the fact
> that it requires two passes.  I'm sure that one could find cased where
> Peter's approach is faster, so you if you are concerned about speed
> you should measure with your own data.

I suppose those cases are rare (slow equality check), and even then I
might prefer your solution because it's so much clearer.

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


Re: problem with 'global'

2008-01-21 Thread Gabriel Genellina
En Mon, 21 Jan 2008 17:36:29 -0200, Duncan Booth  
<[EMAIL PROTECTED]> escribi�:

> Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
>
>> On Mon, 21 Jan 2008 17:08:46 -0200, Gabriel Genellina wrote:
>>
>>> The future statement is another example, even worse:
>>>
>>> if 0:
>>>  from __future__ import with_statement
>>>
>>> with open("xxx") as f:
>>>  print f
>>
>> In Python >=2.5 it's a compile time error if that import is not the very
>> first statement in a source file.
>>
> That doesn't appear to be the case. With Python 2.5.1 the example
> Gabriel quoted will compile and run.

Yes, but now I've noticed that the 0 has some magic. The code above works  
with 0, 0.0, 0j and ''. Using None, False, () or [] as the condition, will  
trigger the (expected) syntax error.

Mmm, it may be the peephole optimizer, eliminating the dead branch. This  
function has an empty body:

def f():
   if 0: print "0"
   if 0.0: print "0.0"
   if 0j: print "0j"
   if '': print "empty"

py> dis.dis(f)
   5   0 LOAD_CONST   0 (None)
   3 RETURN_VALUE

The other false values tested (False, None, () and []) aren't optimized  
out.

-- 
Gabriel Genellina

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

  1   2   >