Re: Perl and Python, a practical side-by-side example.

2007-03-02 Thread Ben Finney
Bjoern Schliessmann <[EMAIL PROTECTED]> writes:

> Bruno Desthuilliers wrote:
> > Shawn Milo a écrit :
>
> >> if recs.has_key(piid) is False:
> > 
> > 'is' is the identity operator - practically, in CPython, it
> > compares memory addresses. You *dont* want to use it here.
>
> It's recommended to use "is None"; why not "is False"? Are there
> multiple False instances or is False generated somehow?

I'd recommend against using "is False" simply because it's more
confusing. This is better::

if not recs.has_key(piid):  # [1]

Moreover, any 'if' statement expects a boolean expression *anyway*, so
there's no point testing for identity against False. Otherwise, the
following would be just as reasonable::

if (recs.has_key(piid) is False) is True:

Or perhaps:

if (recs.has_key(piid) is False) is True) is False) is False) is True):


[1]: yes, this is even better written as 'if not piid in recs', but
that's beside the point for this discussion.

-- 
 \  "To be is to do"  -- Plato |
  `\"To do is to be"  -- Aristotle |
_o__) "Do be do be do"  -- Sinatra |
Ben Finney

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

Re: implementing SFTP using Python

2007-03-02 Thread Ben Finney
kadarla kiran kumar <[EMAIL PROTECTED]> writes:

> I have to implement SFTP conection from client to the server using
> Python script.  Iam very new new to python , and i dont't have much
> time to complete this. So I need some pointers from you.

You will probably want to investigate the "paramiko" package, a
pure-Python implementation of the SSH2 protocol.

http://www.lag.net/paramiko/>

On Debian ("etch" or newer), you can install the 'python-paramiko'
package. Alternatively, download it from the website.

-- 
 \   "I was in a bar the other night, hopping from barstool to |
  `\ barstool, trying to get lucky, but there wasn't any gum under |
_o__)any of them."  -- Emo Philips |
Ben Finney

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


Re: Perl and Python, a practical side-by-side example.

2007-03-02 Thread Bjoern Schliessmann
Bruno Desthuilliers wrote:
> Shawn Milo a écrit :

>> if recs.has_key(piid) is False:
> 
> 'is' is the identity operator - practically, in CPython, it
> compares memory addresses. You *dont* want to use it here.

It's recommended to use "is None"; why not "is False"? Are there
multiple False instances or is False generated somehow?

Regards,


Björn

-- 
BOFH excuse #135:

You put the disk in upside down.

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


Re: implementing SFTP using Python

2007-03-02 Thread Jean-Paul Calderone
On Fri, 2 Mar 2007 20:42:55 -0800 (PST), kadarla kiran kumar <[EMAIL 
PROTECTED]> wrote:
>Hi Everybody,
>
>  I have to implement SFTP conection from client to the server using Python 
> script.
>  Iam very new new to python , and i dont't have much time to complete this. 
> So I need some pointers from you.
>
>  If anybody has already done this kind of stuff, please let me know. Please 
> don't think Iam over ambitious, but i need some kind of Pseudo code ,if 
> possible source code.

http://www.google.com/search?hl=en&safe=off&q=%22python+sftp+server%22&btnG=Search
 might be a place to start.

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


Re: class attrdict

2007-03-02 Thread Alex Martelli
MonkeeSage <[EMAIL PROTECTED]> wrote:

> On Mar 2, 9:25 pm, [EMAIL PROTECTED] (Alex Martelli) wrote:
> > The problem is mostly that, given an instance a of attrdict, whether you
> > can call (e.g.) a.update(foo) depends on whether you ever set
> > a['update'], making the whole program extremely fragile -- a very high
> > price to pay for some modest amount of syntax sugar.
> 
> How about something like...
> 
> class attrdict(dict):
> def __init__(self, *args, **kwargs):
> dict.__init__(self, *args, **kwargs)
> for k, v in self.items():
> dict.__setattr__(self, str(k), v)
> def __setitem__(self, k, v):
> dict.__setitem__(self, k, v)
> dict.__setattr__(self, str(k), v)
> __setattr__ = __setitem__

Same problem: after x=attrdict(), x.update(foo) will work for a while,
then suddenly stop working after some innocuous loop such as:
for bah in yech: x[bah] = 23
when one of the items in yech just happens to be the word 'update'
(similar issues with words such as 'get', 'pop', 'clear', etc, etc).

Miscegenation between attributes and items *inevitably* sucks.


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


implementing SFTP using Python

2007-03-02 Thread kadarla kiran kumar
Hi Everybody,
   
  I have to implement SFTP conection from client to the server using Python 
script.
  Iam very new new to python , and i dont't have much time to complete this. So 
I need some pointers from you.
   
  If anybody has already done this kind of stuff, please let me know. Please 
don't think Iam over ambitious, but i need some kind of Pseudo code ,if 
possible source code.
   
  Thanks in Advance,
  K.Kiran Kumar

 
-
Never Miss an Email
Stay connected with Yahoo! Mail on your mobile. Get started!-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python Source Code Beautifier

2007-03-02 Thread greg
Alan Franzoni wrote:
> I would assume then, that if the '+=' operator
> is assumed to modify objects in-place, it would just fail on immutable
> objects, wouldn't I?

Then you wouldn't be able to do things like

x = 3
x += 1

which would result in howls of outrage from the
*other* half of the Python community.

The x += y syntax is designed to fill two different
but equally useful roles: one is to modify objects
in-place, the other is to be a short hand for
x = x + y.

This was all discussed at *very* great length many
years ago, and the addition of in-place operators
to the language was held up for a long time until
the present compromise was devised. You might not
like it, but it's here to stay.

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


Re: class attrdict

2007-03-02 Thread MonkeeSage
On Mar 2, 9:25 pm, [EMAIL PROTECTED] (Alex Martelli) wrote:
> The problem is mostly that, given an instance a of attrdict, whether you
> can call (e.g.) a.update(foo) depends on whether you ever set
> a['update'], making the whole program extremely fragile -- a very high
> price to pay for some modest amount of syntax sugar.

How about something like...

class attrdict(dict):
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
for k, v in self.items():
dict.__setattr__(self, str(k), v)
def __setitem__(self, k, v):
dict.__setitem__(self, k, v)
dict.__setattr__(self, str(k), v)
__setattr__ = __setitem__

Regards,
Jordan

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


Re: Perl and Python, a practical side-by-side example.

2007-03-02 Thread John Machin
On Mar 3, 12:36 pm, Bruno Desthuilliers >
[snip]
>  DATE = 5
>  TARGET = 6
[snip]
> Now for the bad news: I'm afraid your algorithm is broken : here are my
> test data and results:
>
> input = [
>  #ID  STATE ...  ...  ... TARG DATE
>  "aaa\tAAA\t...\t...\t...\tBBB\t20071212\n",
[snip]

Bruno, The worse news is that your test data is broken. According to
the OP (and your own code (DATE = 5 etc)), the target state comes
last. GIGO. At least you have demonstrated to the OP why naming the
field indexes is a good idea :-)
Cheers,
John

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


Re: Questions about app design - OOP with python classes

2007-03-02 Thread MRAB
On Mar 2, 4:47 am, Steven D'Aprano <[EMAIL PROTECTED]>
wrote:
> On Thu, 01 Mar 2007 20:24:33 -0800, Paul Rubin wrote:
> > Steven D'Aprano <[EMAIL PROTECTED]> writes:
> >> But if you used Apps Hungarian, and saw this line of code:
>
> >> if hmmCurrentHeight <= hinCriticalHeight:
>
> >> then you should instantly recognise that there's a problem. Comparing
> >> a height in millimetres to a height in inches is not a good thing to do,
> >> no matter that they're both floats.
>
> > That still sounds like an unreliable manual type system,
>
> It's unreliable in the sense that the coder has to follow the naming
> convention, and must have some bare minimum of sense. If your coders are
> morons, no naming convention will save you. (For that matter, nothing will
> save you.)
>
> > instead of an
> > automatic type system that includes dimension analysis.  You might
> > like this:
>
> >http://futureboy.homeip.net/frinkdocs/
>
> > There are many Python implementations of dimensioned units as well.  I
> > posted one here a few weeks ago.
>
> Sure, and I love the Unix utility "units", and my HP calculator.
> Dimensioned units are useful.
>
> But dimensioned units are still only part of the story. Joel describes the
> situation the early Word developers found: when you're writing a word
> processor, you are doing a LOT of conversions between screen coordinates
> and window pane coordinates. Both have the same type (a pair of ints),
> both have the same dimensional units (length/pixels) but they are
> semantically different. If you place the character "N" at coordinates 0,0,
> it makes a big difference if the coordinates are relative to the current
> window or relative to the screen.
>
> Apps Hungarian is a heuristic for dealing with semantic differences, not
> data types. It deals with more than just dimensional analysis.
>
Basically what you want are dimensions such as "screen coordinate" and
"window coordinate" as well as "pixel", and also other kinds of
dimensions which combine differently. For example:

The dimension "pixel" works one way and the dimensions "relative to
screen" and "relative to window" work a differnt way.

If:

p is a point relative to the screen: integer, ,
+

q is a point relative to the window: integer, ,
+

r is the window relative to the screen:  integer, ,
+, -

then:

p = q + r

 =  + 

 =  + ( - )

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


Re: class attrdict

2007-03-02 Thread Alex Martelli
Hallvard B Furuseth <[EMAIL PROTECTED]> wrote:

> Does this class need anything more?
> Is there any risk of a lookup loop?
> Seems to work...
> 
> class attrdict(dict):
> """Dict where d['foo'] also can be accessed as d.foo"""
> def __init__(self, *args, **kwargs):
> self.__dict__ = self
> dict.__init__(self, *args, **kwargs)
> def __repr__(self):
> return dict.__repr__(self).join(("attrdict(", ")"))

The problem is mostly that, given an instance a of attrdict, whether you
can call (e.g.) a.update(foo) depends on whether you ever set
a['update'], making the whole program extremely fragile -- a very high
price to pay for some modest amount of syntax sugar.


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


Re: Sort with extra variables

2007-03-02 Thread Alex Martelli
Thomas Dybdahl Ahle <[EMAIL PROTECTED]> wrote:

> I have a sort function in a python chess program.
> Currently it looks like this:
> 
> def sortMoves (board, table, ply, moves):
> f = lambda move: getMoveValue (board, table, ply, move)
> moves.sort(key=f, reverse=True)
> return moves
> 
> However I'd really like not to use the lambda, as it slows down the code.
> 
> I've thought about saving the extra variables in the global space, but it
> really feals ugly.
> 
> Do you have any ideas how I can sort these moves the fastest?

Maybe

  moves.sort(key=functool.partial(board, table, ply), reverse=True)

might be a bit faster?  Not sure, but maybe worth trying.

If not, a bit faster (nothing major) might be

  def f(move, board=board, table=table, ply=ply):
  return getMoveValue(board, table, ply, move)

the small advantage here would be to use the lexically scoped variable
lookup just once (at nested-def time) with the three names being then
looked up as locals in the len(moves) call to f...


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


Re: Newbie Test

2007-03-02 Thread James Stroud
Nicholas Parsons wrote:
> Greetings,
> 
> This is just a test to see if I can post to this mailing list.  Can  
> someone from the list please respond to this email so I know it worked?
> 
> Thanks in advance!
> --Nick

Congratulations, you passed the newbie test!

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


Re: Sort with extra variables

2007-03-02 Thread MonkeeSage
On Mar 2, 7:34 pm, Thomas Dybdahl Ahle <[EMAIL PROTECTED]> wrote:
> Well, you'd have to define the function inside the sortMoves function, as
> it is where the variables exists.

Oh, sorry, I wasn't thinking there!

Regards,
Jordan

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


Re: Perl and Python, a practical side-by-side example.

2007-03-02 Thread Paul Rubin
Here's my version (not tested much).  Main differences from yours:

1. It defines a Python class to hold row data, and defines the __cmp__ operation
on the class, so given two Row objects r1,r2, you can say simply
   if r1 > r2: ...
to see which is "better".  

2. Instead of reading all the rows into memory and then scanning the
list of records of each piid, it simply remembers the best it has seen
for each piid.

By putting the "better than" logic into the class definition, the main
loop becomes very simple.  It does parse out and store fields on the
Row objects consuming some extra memory, but you could eliminate that
at the cost of a little code and speed by re-parsing as needed in the
comparison function.



#! /usr/bin/env python

import sys

class Row:
def __init__(self, row):
self.row = row.rstrip('\n')
fields = self.row.split('\t')
self.piid = fields[0]
self.state = fields[1]
self.expiration_date = fields[5]
self.desired_state = fields[6]

def __cmp__(self, other):
# return +1 if self is better than other, -1 if other is better
# than self, or 0 if they are equally good
if self.state == self.desired_state:
if other.state != other.desired_state:
return 1
return cmp(self.expiration_date, other.expiration_date)
elif other.expiration_date > self.expiration_date:
# other record is better only if its exp date is newer
return 1
return 0

best = {}
input = sys.stdin

for row in input:
r = Row(row)
if r.piid not in best or r > best[r.piid]:
best[r.piid] = r

for piid,r in best.iteritems():
print r.row
-- 
http://mail.python.org/mailman/listinfo/python-list


"unknown encoding: string-escape" in frozen Python

2007-03-02 Thread Jeff Groves
I'm using FreezePython on a Python program that uses wxPython and subprocess.
The result almost works, but it always hits this bug:

  File "velauncher.py", line 847, in Launch
  File "python/velLaunchCode.py", line 61, in __init__
  File "python/velLaunchCode.py", line 143, in Unix
  File "python/subprocess.py", line 599, in __init__
  File "python/subprocess.py", line 1031, in _execute_child
  File "/usr/lib/python2.3/pickle.py", line 1394, in loads
return Unpickler(file).load()
  File "/usr/lib/python2.3/pickle.py", line 872, in load
dispatch[key](self)
  File "/usr/lib/python2.3/pickle.py", line 985, in load_string
self.append(rep.decode("string-escape"))
LookupError: unknown encoding: string-escape

I tried adding --include-modules=encodings to the arguments, but I'm still
getting the string-escape error. How can I include the encoding in the freeze?

I'm using Python2.3 and the downloadable version of subprocess.py for Python2.3
on Redhat.

-Jeff Groves


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


Re: Sort with extra variables

2007-03-02 Thread Thomas Dybdahl Ahle
Den Fri, 02 Mar 2007 16:46:05 -0800 skrev Paul Rubin:

> Thomas Dybdahl Ahle <[EMAIL PROTECTED]> writes:
>> Do you mean that I add my moves something like this?
>> 
>> from heapq import heappush, heappop
>> heap = []
>> for move in genAll():
>> heappush(heap, (-getMoveValue (board, table, ply, move), move))
>> 
>> And then use heappop(heap) in the alphabeta loop?
> 
> Yes, something like that.  If you want to get, say, the five smallest
> values in a list, heapq lets you do that without having to sort the
> whole list.

Yeah, I use this now. The only think I don't really like, is the need of 
creating a ton of tupples, but it doesn't show me too much it seams.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sort with extra variables

2007-03-02 Thread Thomas Dybdahl Ahle
Den Fri, 02 Mar 2007 16:27:47 -0800 skrev MonkeeSage:

> On Mar 2, 5:51 pm, Thomas Dybdahl Ahle <[EMAIL PROTECTED]> wrote:
>> I guess the thing is that I'd have to create a new callable no matter
>> how, as it is the only way to bring the extra variables into the
>> getValue function when called by sort.
> 
> Yes, but you don't have to create it every time you call sortMoves...
> 
> def sortKey(move):
> return getMoveValue(board, table, ply, move)
> 
> def sortMoves(board, table, ply, moves):
> moves.sort(key=sortKey, reverse=True) return moves

Well, you'd have to define the function inside the sortMoves function, as 
it is where the variables exists.

def sortMoves(board, table, ply, moves):
def sortKey(move):
return getMoveValue(board, table, ply, move)
moves.sort(key=sortKey, reverse=True) return moves

Wouldn't that make it create the callable at each call?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: cyclic iterators ?

2007-03-02 Thread Paul Rubin
"Tool69" <[EMAIL PROTECTED]> writes:
> I've tried something like this to have a cyclic iterator without
> sucess:
> 
> def iterate_mylist(my_list):
> k = len((my_list)
> i=0
> while i <= k :
> yield my_list[i]
> i += 1
> i = 0
> yield my_list[0]
> 
> I missed something, but I don't know what exactly.

As Bruno says, you can use itertools.cycle, but the problem above is
that you're not looping repeatedly through the list; you yield all the
elements, then yield the first element again, then stop.  So for
['a','b','c']  you'd yield the sequence a,b,c,a.  

I'd rewrite the above something like:

  def iterate_mylist(my_list):
 while True:
   for m in my_list:
  yield m

This just loops through the list over and over again.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: cyclic iterators ?

2007-03-02 Thread Bruno Desthuilliers
Tool69 a écrit :
> Hi,
> 
> Let say I've got a simple list like my_list = [ 'a', ',b', 'c' ].
> We can have an iterator from it by k =  iter( my_list), then we can
> access each of her (his ?) element by k.next(), etc.
> 
> Now, I just wanted k to have the following cyclic behaviour (without
> rising the ) :
> 
> 
>>>k.next() 
> 'a'
>>>k.next()
> 'b'
>>>k.next()
> 'c'
>>>k.next() -> not raising StopIteration error
> 'a'
>>>k.next()
> 'b'
> etc.
> 

> I've tried something like this to have a cyclic iterator without
> sucess:
> 
(snip code)


> I missed something, but I don't know what exactly.

from itertools import cycle

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


Re: How *extract* data from XHTML Transitional web pages? got xml.dom.minidom troubles..

2007-03-02 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> I'm trying to extract some data from an XHTML Transitional web page.
> 
> What is best way to do this?
> 
> xml.dom.minidom.

As a side note, cElementTree is probably a better choice. Or even a 
simple SAX parser.

>parseString("text of web page") gives errors about it
> not being well formed XML.

If it's not well-formed XML, most - if not all - XML parsers will shoke 
on it.

> Do I just need to add something like  or what?

How could we say without looking at the XML ?

But anyway, even if the XHTML is crappy, BeautifulSoup may do the job...

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


Re: Newbie Test

2007-03-02 Thread Tool69
On 3 mar, 01:44, Nicholas Parsons <[EMAIL PROTECTED]> wrote:
> Greetings,
>
> This is just a test to see if I can post to this mailing list.  Can
> someone from the list please respond to this email so I know it worked?
>
> Thanks in advance!
> --Nick

Hi Nicholas,

Does it work for you ?

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


cyclic iterators ?

2007-03-02 Thread Tool69
Hi,

Let say I've got a simple list like my_list = [ 'a', ',b', 'c' ].
We can have an iterator from it by k =  iter( my_list), then we can
access each of her (his ?) element by k.next(), etc.

Now, I just wanted k to have the following cyclic behaviour (without
rising the ) :

>> k.next()
'a'
>> k.next()
'b'
>> k.next()
'c'
>> k.next() -> not raising StopIteration error
'a'
>> k.next()
'b'
etc.

I've tried something like this to have a cyclic iterator without
sucess:

def iterate_mylist(my_list):
k = len((my_list)
i=0
while i <= k :
yield my_list[i]
i += 1
i = 0
yield my_list[0]

I missed something, but I don't know what exactly.
Thanks.

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


Re: Perl and Python, a practical side-by-side example.

2007-03-02 Thread Bruno Desthuilliers
John Machin a écrit :
> On Mar 3, 9:44 am, "Shawn Milo" <[EMAIL PROTECTED]> wrote:
> 
(snip)
> 
> [big snip]
> Here is my rewrite in what I regard as idiomatic reasonably-modern
> Python (OMMV of course). 

(snip)

John, I *swear* I didn't read your code before posting my own version !
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Perl and Python, a practical side-by-side example.

2007-03-02 Thread Bruno Desthuilliers
Shawn Milo a écrit :
> I'm new to Python and fairly experienced in Perl, although that
> experience is limited to the things I use daily.
> 
> I wrote the same script in both Perl and Python, and the output is
> identical. The run speed is similar (very fast) and the line count is
> similar.
> 
> Now that they're both working, I was looking at the code and wondering
> what Perl-specific and Python-specific improvements to the code would
> look like, as judged by others more knowledgeable in the individual
> languages.
> 
> I am not looking for the smallest number of lines, or anything else
> that would make the code more difficult to read in six months. Just
> any instances where I'm doing something inefficiently or in a "bad"
> way.
> 
(snip)
> 
> #! /usr/bin/env python
> 
> import sys
> 
> input = sys.stdin
> 
> recs = {}
> 
> for row in input:
> row = row.rstrip('\n')
> piid = row.split('\t')[0]
> if recs.has_key(piid) is False:

'is' is the identity operator - practically, in CPython, it compares 
memory addresses. You *dont* want to use it here.

Another way to test if a key is already in a dict is to use the 'in' 
operator, ie:
   if not piid in recs:

> recs[piid] = []
> recs[piid].append(row)

As a last point, dicts have a setdefault(key, default) method that 
returns the value associated with key if it already exists, else add the 
key=>default pair and returns default, but it's a little bit slower.


for row in input:
 row = row.rstrip('\n')
 piid = row.split('\t')[0]
 recs.setdefault(piid, []).append(row)

or

for row in input:
 row = row.rstrip('\n')
 piid = row.split('\t')[0]
 if piid not in recs:
 recs[piid] = []
 recs[piid].append(row)



> for piid in recs.keys():

You don't need to call key() here - it's already the default iteration 
for dicts.

But since you want the values too, you should use dict.items() or 
dict.iteritems():

for piid, rows in recs.iteritems()

> best = ""
> for current in recs[piid]:
> if best == "":
> best = current;

Get rid of this ";" !-)

Better to use None - it's the "no value" object, and it let you use an 
identity test:

best = None
for current in rows:
   if best is None:
   best = row

And while we're at it, you can save yourself a test here:

best = row[0]
for current in row[1:]:
   # start tests

> #If the current record is the correct state
> if current.split("\t")[1] == current.split("\t")[6]:
> #If the existing record is the correct state
> if best.split("\t")[1] == best.split("\t")[6]:
> #If the new record has a newer exp. date
> if current.split("\t")[5] > best.split("\t")[5]:

You're repeatingly calling split() on the same objects. This is a 
serious waste of time and CPU.

> best = current
> else:
> best = current
> else:
> #If the existing  record does not have the correct state
> #and the new record has a newer exp. date
> if best.split("\t")[1] != best.split("\t")[6] and
> current.split("\t")[5] > best.split("\t")[5]:
> best = current
>
> print best

Here's a somewhat corrected version:
# ---
import sys

def findbests(input=sys.stdin, output=sys.stdout):
 DATE = 5
 TARGET = 6
 STATE = 1
 recs = {}

 for row in input:
 row = row.rstrip('\n').split("\t")
 piid = row[0]
 if piid not in recs:
 recs[piid] = []
 recs[piid].append(row)

 for piid, rows in recs.iteritems():
 best = rows[0]
 for current in rows[1:]:
 if current[STATE] == current[TARGET]:
 if best[STATE] == best[TARGET]:
 if current[DATE] > best[DATE]:
 best = current
 else:
 best = current
 elif best[STATE] != best[TARGET] \
  and current[DATE] > best[DATE]:
 best = current

 print >> output, "\t".join(best)

if __name__ == '__main__':
 findbdest()

# ---

It's somewhat shorter, a bit more readable IMHO, and somewhat faster too 
(=~ 30/40% faster on my machine). Also, it's usable as both a program 
and an importable module, and with any line input and file-like output.

Now for the bad news: I'm afraid your algorithm is broken : here are my 
test data and results:

input = [
 #ID  STATE ...  ...  ... TARG DATE
 "aaa\tAAA\t...\t...\t...\tBBB\t20071212\n",
 "aaa\tAAA\t...\t...\t...\tAAA\t20070120\n",
 "aaa\tAAA\t...\t...\t...\tAAA\t20070101\n",
 "aaa\tAAA\t...\t...\t...\tBBB\t20071010\n",
 "aaa\tAAA\t...\t...\t...\tBBB\t2007\n",
 "ccc\tAAA\t...\t...\t...\tBBB\t20071201\n",
 "ccc\tAAA\t...\t...\t...\tAAA\t20070101\

Re: Sort with extra variables

2007-03-02 Thread Paul Rubin
Thomas Dybdahl Ahle <[EMAIL PROTECTED]> writes:
> Do you mean that I add my moves something like this?
> 
> from heapq import heappush, heappop
> heap = []
> for move in genAll():
> heappush(heap, (-getMoveValue (board, table, ply, move), move))
> 
> And then use heappop(heap) in the alphabeta loop?

Yes, something like that.  If you want to get, say, the five smallest
values in a list, heapq lets you do that without having to sort the
whole list.
-- 
http://mail.python.org/mailman/listinfo/python-list


Newbie Test

2007-03-02 Thread Nicholas Parsons
Greetings,

This is just a test to see if I can post to this mailing list.  Can  
someone from the list please respond to this email so I know it worked?

Thanks in advance!
--Nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Perl and Python, a practical side-by-side example.

2007-03-02 Thread John Machin
On Mar 3, 9:44 am, "Shawn Milo" <[EMAIL PROTECTED]> wrote:
> I'm new to Python and fairly experienced in Perl, although that
> experience is limited to the things I use daily.
>
> I wrote the same script in both Perl and Python, and the output is
> identical. The run speed is similar (very fast) and the line count is
> similar.
>
> Now that they're both working, I was looking at the code and wondering
> what Perl-specific and Python-specific improvements to the code would
> look like, as judged by others more knowledgeable in the individual
> languages.
>
> I am not looking for the smallest number of lines, or anything else
> that would make the code more difficult to read in six months. Just
> any instances where I'm doing something inefficiently or in a "bad"
> way.
>
> I'm attaching both the Perl and Python versions, and I'm open to
> comments on either. The script reads a file from standard input and
> finds the best record for each unique ID (piid). The best is defined
> as follows: The newest expiration date (field 5) for the record with
> the state (field 1) which matches the desired state (field 6). If
> there is no record matching the desired state, then just take the
> newest expiration date.
>

[big snip]
Here is my rewrite in what I regard as idiomatic reasonably-modern
Python (OMMV of course). A few of the comments are applicable
irrespective of the language used.

HTH,
John
8<--
#! /usr/bin/env python

### Layout: Use 4-space indent. Don't use tabs. Don't exceed 79 chars
per line.

import sys

def process_file(opened_file=sys.stdin):
### Local variable access is faster than global

### input = sys.stdin ### shadowing built_in function "input"

### Use names to access elements in rows
PIID = 0
ACTUAL_STATE = 1
DESIRED_STATE = 6
EXPIRY_DATE = 5

recs = {}

for row in opened_file:
row = row.rstrip('\n').split('\t')
### Do the split('\t') *once* per row
piid = row[PIID]
### if recs.has_key(piid) is False:
### has_key() is ancient
### "if boolean_expression is False" is megabletchworthy;
### use "if not boolean_expression"
if piid not in recs:
recs[piid] = []
recs[piid].append(row)

### for piid in recs.keys():
for piid in recs:
best = None ### use out-of-band sentinel
for current in recs[piid]:
if best is None:
best = current ### had cockroach crap (";") at EOL
else:
#If the current record is the correct state
### Clear code (like the next line) doesn't need
comments
### like the above line
if current[ACTUAL_STATE] == current[DESIRED_STATE]:
if best[ACTUAL_STATE] == best[DESIRED_STATE]:
if current[EXPIRY_DATE] > best[EXPIRY_DATE]:
best = current
else:
best = current
else:
if (best[ACTUAL_STATE] != best[ACTUAL_STATE]
and current[EXPIRY_DATE] > best[EXPIRY_DATE]):
best = current
print "\t".join(best)

if __name__ == "__main__":
### Standard idiom to avoid executing script content
### when/if file is imported
process_file()
8<


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


Re: Sort with extra variables

2007-03-02 Thread MonkeeSage
On Mar 2, 5:51 pm, Thomas Dybdahl Ahle <[EMAIL PROTECTED]> wrote:
> I guess the thing is that I'd have to create a new callable no matter
> how, as it is the only way to bring the extra variables into the getValue
> function when called by sort.

Yes, but you don't have to create it every time you call sortMoves...

def sortKey(move):
return getMoveValue(board, table, ply, move)

def sortMoves(board, table, ply, moves):
moves.sort(key=sortKey, reverse=True)
return moves

Regards,
Jordan

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


Re: How *extract* data from XHTML Transitional web pages? got xml.dom.minidom troubles..

2007-03-02 Thread James Graham
[EMAIL PROTECTED] wrote:
> I'm trying to extract some data from an XHTML Transitional web page.
> 
> What is best way to do this?

May I suggest html5lib [1]? It's based on the parsing section of the 
WHATWG "HTML5" spec [2] which is in turn based on the behavior of major 
web browsers so it should parse more or less* any invalid markup you 
throw at it. Despite the name "html5lib" it works with any (X)HTML 
document. By default, you have the option of producing a minidom tree, 
an ElementTree, or a "simpletree" - a lightweight DOM-like 
html5lib-specific tree.

If you are happy to pull from SVN I recommend that version; it has a few 
bug fixes over the 0.2 release as well as improved features including 
better error reporting and detection of encoding from  elements 
(the next release is imminent).

[1] http://code.google.com/p/html5lib/
[2] http://whatwg.org/specs/web-apps/current-work/#parsing

* There might be a problem if e.g. the document uses a character 
encoding that python does not support, otherwise it should parse anything.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: class declaration shortcut

2007-03-02 Thread MonkeeSage
On Mar 2, 5:48 pm, "Luis M. González" <[EMAIL PROTECTED]> wrote:
> Thanks for your detailed reply!
> So after all, the www.rubyclr.com code is not a fair comparison.
> Because the c# code shows a class definition, and the ruby code shows
> a struct definition, which is not equivalent to a class.
> Is that right?

Well c sharp has a struct type, but it's basically just a class, so in
that sense the comparison is accurate. But I don't think the ruby code
is supposed to be a one to one comparison (you could write a similar
Struct class in c sharp too). I assume that what the author there was
trying to say was that ruby is a higher-level language / has more
syntactic sugar than c sharp many times. The same can be said of
python as well, though python is a bit more reserved about adding
sugar (ruby is more aligned with perl in TMTOWTDI, python is more like
"There should be one -- and preferably only one -- obvious way to do
it").

Regards,
Jordan

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


Re: Perl and Python, a practical side-by-side example.

2007-03-02 Thread bearophileHUGS
Few suggestions, some important, some less important. All my
suggestions are untested.


Use 4 spaces to indent.


If you want to speed up this code you can move it inside a function.
After that, if you want to make it even faster you can use Psyco too.


Ho are the dates represented? How do you test what is the older one?


You seem to compute current.split("\t") and best.split("\t") many
times, so you can compute it once only.
You can keep best and best_splitted.


You can split the last line:
if best.split("\t")[1] != best.split("\t")[6] and \
   current.split("\t")[5] > best.split("\t")[5]:


input() is a builtin function, so you may want to use a different
name, or just:
for row in sys.stdin:


Instead of:
row = row.rstrip('\n')
You often may use just:
row = row.strip()


Instead of:
piid = row.split('\t')[0]
You can probably use (test it):
piid = row.split('\t', 1)[0]


Instead of:
if recs.has_key(piid) is False:
Better:
if piid not in recs:


Instead of (on Python 2.5):
recs = {}
for row in input:
row = ...
piid = ...
if recs.has_key(piid) is False:
recs[piid] = []
recs[piid].append(row)
You can probably use:
from collection import defaultdict
recs = defaultdict(list)
for row in input:
row = ...
piid = ...
recs[piid].append(row)


Instead of:
for piid in recs.keys():
You can use this, lazily:
for piid in recs:


Instead of:
for piid in recs.keys():
best = ""
for current in recs[piid]:
You can probably use:
for piid, piii_recs in recs.iteritems():
best = ""
for current in piii_recs:
But your version may be a little faster anyway.


Instead of:
best = ""
for current in recs[piid]:
if best == "":
best = current;
You may want to use the singleton None:
best = None
for current in recs[piid]:
if best is None:
best = current


Note that to read such files you may use the csv module (present in
the standard library).

You can try to modify the code and show us the second working version.

Bye,
bearophile

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


Re: How *extract* data from XHTML Transitional web pages? got xml.dom.minidom troubles..

2007-03-02 Thread Thomas Dybdahl Ahle
Den Fri, 02 Mar 2007 15:32:58 -0800 skrev [EMAIL PROTECTED]:

> I'm trying to extract some data from an XHTML Transitional web page.
> xml.dom.minidom.parseString("text of web page") gives errors about it
> not being well formed XML.
> Do I just need to add something like  or what?

As many HTML Transitional pages are very bad formed, you can't really 
create a dom of them.

I've written multiple grabbers, which grab tv data from html pages, and 
parses it into xml.

Basicly there are three ways to get the info:

  # Use find(): If you are only searching for a few data pieces, you 
might be able to find some html code always appearing before the data you 
need.

  # Use regular expressions: This can very quickly get all data from a 
table or so into a nice list. Only problem is regular expressions having 
a little steep learing curve.

  # Use a SAX parser: This will iterate through all html items, not 
carring if they validate or not. You will define a method to be called 
each time it finds a tag, a piece of text etc.

> What is best way to do this?

In the beginning I mostly did the SAX way, but it really generates a lot 
of code, which is not necessaryly more readable than the regular 
expressions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: classes and functions

2007-03-02 Thread Thomas Dybdahl Ahle
Den Fri, 02 Mar 2007 19:26:08 -0300 skrev Silver Rock:

> Friends,
> 
> I don´t see why using classes.. functions does everything already. I
> read the Rossum tutotial and two other already.
> 
> Maybe this is because I am only writing small scripts, or some more
> serious misunderstandings of the language.
> 
> Please give me a light.

I guess you are fimiliar with the string methods. You can do stuff like 
"hi hi".split(" ") or "  hi".strip().
This is because a string is a class.
The same functionality could be done by functions:
split("hi hi", " ") and strip("  hi")
but it feals more inituitive to put the dot after the variable.
It also makes it easier to know where to look for functions related to 
the object.

And yes, I'm sure you will see the light, when doing larger programs :) 
Don't worry.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Sort with extra variables

2007-03-02 Thread Thomas Dybdahl Ahle
Den Fri, 02 Mar 2007 15:20:33 -0800 skrev MonkeeSage:

> On Mar 2, 5:11 pm, Thomas Dybdahl Ahle <[EMAIL PROTECTED]> wrote:
>> Wouldn't that be just as slow?
> 
> Well, I'm not sure about speed, but with the lambda you're creating a
> new callable for f every time you call sortMoves. Intuitively, that
> seems like it would be more of a hit than just doing a lookup for a
> predefined function. Mabye not though...you could time it and see.

I guess the thing is that I'd have to create a new callable no matter 
how, as it is the only way to bring the extra variables into the getValue 
function when called by sort.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How *extract* data from XHTML Transitional web pages? got xml.dom.minidom troubles..

2007-03-02 Thread Paul Boddie
[EMAIL PROTECTED] wrote:
> I'm trying to extract some data from an XHTML Transitional web page.
>
> What is best way to do this?

An XML parser should be sufficient. However...

> xml.dom.minidom.parseString("text of web page") gives errors about it
> not being well formed XML.
>
> Do I just need to add something like  or what?

If the page isn't well-formed then it isn't proper XHTML since the
XHTML specification [1] says...

4.1. Documents must be well-formed

Yes, it's a heading, albeit in an "informative" section describing how
XHTML differs from HTML 4. See "3.2. User Agent Conformance" for a
"normative" mention of well-formedness.

You could try libxml2dom (or other libxml2-based solutions) for some
fairly effective HTML parsing:

libxml2dom.parseString("text of document here", html=1)

See http://www.python.org/pypi/libxml2dom for more details.

Paul

[1] http://www.w3.org/TR/xhtml1/

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


Re: class declaration shortcut

2007-03-02 Thread Luis M. González
On Mar 2, 8:29 pm, "MonkeeSage" <[EMAIL PROTECTED]> wrote:
> On Feb 28, 1:26 pm, "Luis M. González" <[EMAIL PROTECTED]> wrote:
>
> > I've come across a code snippet inwww.rubyclr.comwhere they show how
> > easy it is to declare a class compared to equivalent code in c#.
> > I wonder if there is any way to emulate this in Python.
>
> I posted like 10 minutes ago, but it looks like it didn't go through.
> The ruby code is not an easy way to declare a class, it is a ruby
> class for creating c-like struct objects.
>
> This is the basic idea behind the ruby Struct class (but this is quick
> and dirty, the real implementation is different and done in c, but you
> should get the basic idea):
>
> class Struct2
> def initialize(*args)
> @@attrs = []
> args.each { |arg|
> eval("class << self; attr_accessor :#{arg} end")
> @@attrs.push(arg)
> }
> end
> def new(*args)
> args.each_index { |i|
> eval("self.#{@@attrs[i]}=args[i]")
> return self
> }
> end
> end
>
> Person = Struct2.new(:name)
> bob = Person.new('bob')
> puts bob.name
>
> A python equiv. would be something like:
>
> class Struct():
> def __init__(self, *args):
> self.attrs = []
> for arg in args:
> setattr(self, arg, None)
> self.attrs.append(arg)
> def __call__(self, *args):
> for i in range(len(args)):
> setattr(self, self.attrs[i], args[i])
> return self
>
> Person = Struct('name')
> bob = Person('bob')
> print bob.name
>
> Regards,
> Jordan


Thanks for your detailed reply!
So after all, the www.rubyclr.com code is not a fair comparison.
Because the c# code shows a class definition, and the ruby code shows
a struct definition, which is not equivalent to a class.
Is that right?

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


thread safe SMTP module

2007-03-02 Thread Gordon Messmer
I believe that I've seen this discussed previously, so maybe there's 
some interest in it.  I wrote a threaded mail filtering framework a 
while ago, and one of the modules does address verification via SMTP.  
Since smtplib.SMTP uses blocking IO, it can block the whole 
interpreter.  Sometimes the whole thing would stop working indefinitely.


I'm now aware that Twisted offers a non-blocking SMTP class, but I 
didn't really want to make that a dependency of the address 
verification.  I ended up subclassing the smtplib.SMTP class and 
rewriting the functions that do I/O.  Perhaps someone who doesn't want 
to install Twisted will find this class useful, someday.  It doesn't 
support TLS, but it is otherwise a thread-safe SMTP class.



class ThreadSMTP(smtplib.SMTP):
"""SMTP class safe for use in threaded applications.

This class reimplements the SMTP class with non-blocking IO,
so that threaded applications don't lock up.

This class won't make starttls support thread-safe.
"""
def connect(self, host='localhost', port=0):
"""Connect to a host on a given port.

If the hostname ends with a colon (`:') followed by a number, and
there is no port specified, that suffix will be stripped off and the
number interpreted as the port number to use.

Note: This method is automatically invoked by __init__, if a host is
specified during instantiation.

"""
if not port and (host.find(':') == host.rfind(':')):
i = host.rfind(':')
if i >= 0:
host, port = host[:i], host[i+1:]
try: port = int(port)
except ValueError:
raise socket.error, "nonnumeric port"
if not port: port = smtplib.SMTP_PORT
if self.debuglevel > 0: print>>sys.stderr, 'connect:', (host, port)
msg = "getaddrinfo returns an empty list"
self.sock = None
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
self.sock = socket.socket(af, socktype, proto)
self.sock.setblocking(0)
if self.debuglevel > 0: print>>sys.stderr, 'connect:', (host, port)
# Try to connect to the non-blocking socket.  We expect connect()
# to throw an error, indicating that the connection is in progress.
# Use select to wait for the connection to complete, and then check
# for errors with getsockopt.
try:
self.sock.connect(sa)
except socket.error:
readySocks = select.select([self.sock], [], [], _smtpTimeout)
if self.sock in readySocks[0]:
soError = self.sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
if soError:
raise socket.error, 'connection failed, error: %d' % soError
else:
# The connection timed out.
raise socket.error, 'connection timed out'
except socket.error, msg:
if self.debuglevel > 0: print>>sys.stderr, 'connect fail:', (host, port)
if self.sock:
self.sock.close()
self.sock = None
continue
break
if not self.sock:
raise socket.error, msg
(code, msg) = self.getreply()
if self.debuglevel > 0: print>>sys.stderr, "connect:", msg
return (code, msg)


def send(self, str):
"""Send `str' to the server."""
if self.debuglevel > 0: print>>sys.stderr, 'send:', repr(str)
if self.sock:
try:
# Loop: Wait for select() to indicate that the socket is ready
# for data, and call send().  If send returns a value smaller
# than the total length of str, save the remaining data, and
# continue to attempt to send it.  If select() times out, raise
# an exception and let the handler close the connection.
while str:
readySocks = select.select([], [self.sock], [], _smtpTimeout)
if not readySocks[1]:
raise socket.error, 'Write timed out.'
sent = self.sock.send(str)
if sent < len(str):
str = str[sent:]
else:
# All the data was written, break the loop.
break
except socket.error:
self.close()
raise smtplib.SMTPServerDisconnected('Server not connected')
else:
raise smtplib.SMTPServerDisconnected('please run connect() first')


def getreply(self):
"""Get a reply from the server.

Returns a tuple consisting 

How *extract* data from XHTML Transitional web pages? got xml.dom.minidom troubles..

2007-03-02 Thread [EMAIL PROTECTED]
I'm trying to extract some data from an XHTML Transitional web page.

What is best way to do this?

xml.dom.minidom.parseString("text of web page") gives errors about it
not being well formed XML.

Do I just need to add something like  or what?

Chris

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


Re: class declaration shortcut

2007-03-02 Thread MonkeeSage
On Feb 28, 1:26 pm, "Luis M. González" <[EMAIL PROTECTED]> wrote:
> I've come across a code snippet in www.rubyclr.com where they show how
> easy it is to declare a class compared to equivalent code in c#.
> I wonder if there is any way to emulate this in Python.

I posted like 10 minutes ago, but it looks like it didn't go through.
The ruby code is not an easy way to declare a class, it is a ruby
class for creating c-like struct objects.

This is the basic idea behind the ruby Struct class (but this is quick
and dirty, the real implementation is different and done in c, but you
should get the basic idea):

class Struct2
def initialize(*args)
@@attrs = []
args.each { |arg|
eval("class << self; attr_accessor :#{arg} end")
@@attrs.push(arg)
}
end
def new(*args)
args.each_index { |i|
eval("self.#{@@attrs[i]}=args[i]")
return self
}
end
end

Person = Struct2.new(:name)
bob = Person.new('bob')
puts bob.name


A python equiv. would be something like:

class Struct():
def __init__(self, *args):
self.attrs = []
for arg in args:
setattr(self, arg, None)
self.attrs.append(arg)
def __call__(self, *args):
for i in range(len(args)):
setattr(self, self.attrs[i], args[i])
return self

Person = Struct('name')
bob = Person('bob')
print bob.name

Regards,
Jordan

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


Re: Sort with extra variables

2007-03-02 Thread MonkeeSage
On Mar 2, 5:11 pm, Thomas Dybdahl Ahle <[EMAIL PROTECTED]> wrote:
> Wouldn't that be just as slow?

Well, I'm not sure about speed, but with the lambda you're creating a
new callable for f every time you call sortMoves. Intuitively, that
seems like it would be more of a hit than just doing a lookup for a
predefined function. Mabye not though...you could time it and see.

Regards,
Jordan

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


Re: class declaration shortcut

2007-03-02 Thread Arnaud Delobelle
On Mar 2, 8:28 pm, Bjoern Schliessmann  wrote:
> This is somehow contrary to my understanding of the Python names
> concept.
>
> What if I use a loop to define several classes based on data --
> they'll all have the same __name__ unless I change it manually.

Well that's not a typical way of defining classes.  It is then your
job to name those classes.

> Having this __name__ attribute set seems to me like "magic behind
> the lines" which Python strives to evade, doesn't it? Personally,
> I'd prefer inserting a mechanism for this manually if and when I
> really need the functionality, but see below.

So you want a Class object without a __name__, and then you would
subclass it to NamedClass with a __name__.
OTOH every class that you define in python using the 'class' keyword
has an obvious name (the identifier that follows the 'class' keyword),
so it seems natural to me to endow each defined class with a __name__.

> > What I described above is quite useful I think.  The alternative
> > (anonymous classes) is that given an object myobj you have no
> > means to find out what its class is (by that I mean to be able to
> > locate the class definition in your source code), apart from
> > stabbing in the dark (i.e. trying type(myobj)==someclass until
> > successful).
>
> In the typical case where you have one name per class definition,
> yes.

As you say this is the typical case, and a __name__ attribute is very
useful in this case.  For the minority of cases when you have a class
factory for example, then I guess it is your responsibility to name
the class appropriately.

IMHO if you create classes in a way that makes it  impossible to name
them naturally, then it is likely that you are misusing the class
object.

> Perhaps I'm lacking a typical application of __name__; that must be
> why I'm so stubborn here ;)

Here are 3 (please correct me if I'm wrong)

>>> class Foo: pass
>>> Foo# typical application 1

>>> foo=Foo()
>>> foo# typical application 2
<__main__.Foo instance at 0x1372788>
>>> pickle.dumps(foo)# typical application 3
 '(i__main__\nFoo\np0\n(dp1\nb.'

--
Arnaud

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


Re: Sort with extra variables

2007-03-02 Thread Thomas Dybdahl Ahle
Den Fri, 02 Mar 2007 20:33:45 +0100 skrev Diez B. Roggisch:

> Thomas Dybdahl Ahle schrieb:
>> I have a sort function in a python chess program. Currently it looks
>> like this:
>> 
>> def sortMoves (board, table, ply, moves):
>> f = lambda move: getMoveValue (board, table, ply, move)
>> moves.sort(key=f, reverse=True)
>> return moves
>> 
>> However I'd really like not to use the lambda, as it slows down the
>> code.
>> 
>> I've thought about saving the extra variables in the global space, but
>> it really feals ugly.
>> 
>> Do you have any ideas how I can sort these moves the fastest?
> 
> First of all, in your case it is somewhat strange to use
> f = lambda ...
> because then you could as well use
> def f(move):
>

Wouldn't that be just as slow?

> But that is just a general remark. Regarding the question: I don't see
> how that could possibly become faster without much more insight into
> what you are doing in getMoveValue. As it seems, it is dependend of a
> lot of factors that change often, so caching it isn't a real option. And
> I hope you are aware that the key-method is invoked only _once_ per
> list-item!

Yeah, key is a nice thing. My only problem is that I need these other 
objects to generate the value, and I don't want to create a new function 
each time..

In my profiling the functions with the lambda line says 860 cumtime and 
getMoveValue says 580.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sort with extra variables

2007-03-02 Thread Thomas Dybdahl Ahle
Den Fri, 02 Mar 2007 11:44:27 -0800 skrev Paul Rubin:

> Thomas Dybdahl Ahle <[EMAIL PROTECTED]> writes:
>> Do you have any ideas how I can sort these moves the fastest?
> 
> One idea: if you're using alpha-beta pruning, maybe you can use
> something like heapq instead of sorting, since a lot of the time you
> only have to look at the first few moves (ordered best-first).

Do you mean that I add my moves something like this?

from heapq import heappush, heappop
heap = []
for move in genAll():
heappush(heap, (-getMoveValue (board, table, ply, move), move))

And then use heappop(heap) in the alphabeta loop?
I don't know much of heap queues, but it actually looks very smart.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: classes and functions

2007-03-02 Thread Nicholas Parsons
Hi Claire,

That is the beauty of using Python.  You have a choice of using  
classes and traditional OOP techniques or sticking to top level  
functions.  For short, small scripts it would probably be overkill to  
use classes.  Yet the programmer still has classes in his tool chest  
if he/she is writing code that is going to be reused in larger  
projects.  In contrast, languages like Java force you into doing  
everything with classes.

Another good resource to read is "Learning Python" by Mark Lutz and  
David Ascher if you want to learn more about python.

Hope this helps...

--Nick



On Mar 2, 2007, at 5:26 PM, Silver Rock wrote:

> Friends,
>
> I don´t see why using classes.. functions does everything already. I
> read the Rossum tutotial and two other already.
>
> Maybe this is because I am only writing small scripts, or some more
> serious misunderstandings of the language.
>
> Please give me a light.
>
> thanks guys,
> Claire
> -- 
> http://mail.python.org/mailman/listinfo/python-list

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


Re: classes and functions

2007-03-02 Thread Bruno Desthuilliers
Silver Rock a écrit :
> Friends,
> 
> I don´t see why using classes.. functions does everything already. I
> read the Rossum tutotial and two other already.
> 
> Maybe this is because I am only writing small scripts, or some more
> serious misunderstandings of the language.

or both ?-)

If you only write small scripts, then you may not have a use for 
classes. OTOH, everything in Python (including functions) is an object - 
that is, an instance of a class. So as soon as you're coding in Python, 
you are at least using classes one way or another. The nice thing is 
that you can safely ignore this if doesn't make sens to you !-)

One of the benefit of classes is that they allow you to have many 
instances of the same object, each with it's own values - while if you 
only use functions + global variables (to share state between 
functions), you only have one set of values (one 'instance') at a time. 
This is probably no big deal in your case, but it becomes quite useful 
as soon as your scripts start to turn into a full blown application.

My 2 cents...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sort with extra variables

2007-03-02 Thread Thomas Dybdahl Ahle
Den Fri, 02 Mar 2007 21:13:02 +0100 skrev Bjoern Schliessmann:

> Thomas Dybdahl Ahle wrote:
> 
>> However I'd really like not to use the lambda, as it slows down the
>> code.
> 
> Did you check how much the slowdown is?

Yes, the lambda adds 50%
-- 
http://mail.python.org/mailman/listinfo/python-list


Perl and Python, a practical side-by-side example.

2007-03-02 Thread Shawn Milo
I'm new to Python and fairly experienced in Perl, although that
experience is limited to the things I use daily.

I wrote the same script in both Perl and Python, and the output is
identical. The run speed is similar (very fast) and the line count is
similar.

Now that they're both working, I was looking at the code and wondering
what Perl-specific and Python-specific improvements to the code would
look like, as judged by others more knowledgeable in the individual
languages.

I am not looking for the smallest number of lines, or anything else
that would make the code more difficult to read in six months. Just
any instances where I'm doing something inefficiently or in a "bad"
way.

I'm attaching both the Perl and Python versions, and I'm open to
comments on either. The script reads a file from standard input and
finds the best record for each unique ID (piid). The best is defined
as follows: The newest expiration date (field 5) for the record with
the state (field 1) which matches the desired state (field 6). If
there is no record matching the desired state, then just take the
newest expiration date.

Thanks for taking the time to look at these.

Shawn

##
Perl code:
##
#! /usr/bin/env perl

use warnings;
use strict;

my $piid;
my $row;
my %input;
my $best;
my $curr;

foreach $row (<>){

chomp($row);
$piid = (split(/\t/, $row))[0];

push ( @{$input{$piid}}, $row );
}

for $piid (keys(%input)){

$best = "";

for $curr (@{$input{$piid}}){
if ($best eq ""){
$best = $curr;
}else{
#If the current record is the correct state

if ((split(/\t/, $curr))[1] eq (split(/\t/, $curr))[6]){
#If existing record is the correct state
if ((split(/\t/, $best))[1] eq (split(/\t/, 
$curr))[6]){
if ((split(/\t/, $curr))[5] gt 
(split(/\t/, $best))[5]){
$best = $curr;
}
}else{
$best = $curr;
}
}else{
#if the existing record does not have the 
correct state
#and the new one has a newer expiration date
if (((split(/\t/, $best))[1] ne (split(/\t/, 
$curr))[6]) and
((split(/\t/, $curr))[5] gt (split(/\t/, $best))[5])){
$best = $curr;
}
}
}


}
print "$best\n";
}

##
End Perl code
##






##
Python code
##

#! /usr/bin/env python

import sys

input = sys.stdin

recs = {}

for row in input:
row = row.rstrip('\n')
piid = row.split('\t')[0]
if recs.has_key(piid) is False:
recs[piid] = []
recs[piid].append(row)

for piid in recs.keys():
best = ""
for current in recs[piid]:
if best == "":
best = current;
else:
#If the current record is the correct state
if current.split("\t")[1] == current.split("\t")[6]:
#If the existing record is the correct state
if best.split("\t")[1] == best.split("\t")[6]:
#If the new record has a newer exp. date
if current.split("\t")[5] > 
best.split("\t")[5]:
best = current
else:
best = current
else:
#If the existing  record does not have the 
correct state
#and the new record has a newer exp. date
if best.split("\t")[1] != best.split("\t")[6] 
and
current.split("\t")[5] > best.split("\t")[5]:
best = current

print best


##
End Python code
##
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New to Tkinter GUI building

2007-03-02 Thread Adam
Thanks for the reply, will work with this tomorrow.

Adam

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


classes and functions

2007-03-02 Thread Silver Rock
Friends,

I don´t see why using classes.. functions does everything already. I
read the Rossum tutotial and two other already.

Maybe this is because I am only writing small scripts, or some more
serious misunderstandings of the language.

Please give me a light.

thanks guys,
Claire
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: class attrdict

2007-03-02 Thread James Stroud
Hallvard B Furuseth wrote:
> Does this class need anything more?
> Is there any risk of a lookup loop?
> Seems to work...
> 
> class attrdict(dict):
> """Dict where d['foo'] also can be accessed as d.foo"""
> def __init__(self, *args, **kwargs):
> self.__dict__ = self
> dict.__init__(self, *args, **kwargs)
> def __repr__(self):
> return dict.__repr__(self).join(("attrdict(", ")"))
> 

Strangely enough, this seems okay since an instance of a dict subclass 
object has an empty __dict__ attribute anyway and so you won't be 
unwittingly destroying some behavior.

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


Re: Matplotlib axes label

2007-03-02 Thread John Henry
On Mar 2, 7:22 am, [EMAIL PROTECTED] wrote:
> On Mar 2, 7:02 am, "John Henry" <[EMAIL PROTECTED]> wrote:
>
> > On Mar 1, 10:07 pm, "John Henry" <[EMAIL PROTECTED]> wrote:
>
> > > On Mar 1, 9:53 pm, [EMAIL PROTECTED] wrote:
>
> (snipped)
>
>
>
> > > > You can try adjusting the labels and ticks
> > > > using matplotlib.ticker.
>
> > > > To the example you cited, one can add
>
> > > > from matplotlib.ticker import MultipleLocator, FormatStrFormatter
>
> > > > # ...
>
> > > > minorLocator = MultipleLocator(0.1)
> > > > minorFormattor = FormatStrFormatter('%0.1f')
> > > > ax.yaxis.set_minor_locator(minorLocator)
> > > > ax.yaxis.set_minor_formatter(minorFormattor)
>
> > > > show()
>
> > > Thank you for the response.  Yes, adding those lines did work.
>
> > > But what exactly is going on here?  Why would adding these two lines
> > > works?
>
> > > Thanks,
>
> > Okay, I played with the ticker formater and locator routines.
> > Unfortunately, it doesn't help.  The locator sets the major value and
> > the formatter determines how the axes label is formatted.  It doesn't
> > gurantee that the first label starts at the origin.  Half of my plots
> > works, and half of them doesn't.
>
> As default, matplotlib places labels and tick marks
> at major ticks.  Minor ticks are invisible as
> a default.
>
> The lines that I added turned on *minor*
> ticks and their labels; I set them to appear
> at integer multiples of 0.1 and I
> formatted them as floating point numbers.
>
> There's nothing to prevent you from
> having minor ticks appear at intervals
> that exceed those of major ticks.  E.g.,
>
> minorLocator = MultipleLocator(1.1)
>
> # etc.
>
> --
> Hope this helps,
> Steven


Thanks,

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


Re: Converting a c array to python list

2007-03-02 Thread Russell E. Owen
In article <[EMAIL PROTECTED]>,
 zefciu <[EMAIL PROTECTED]> wrote:

> Hi!
> 
> I want to embed a function in my python application, that creates a
> two-dimensional array of integers and passes it as a list (preferably a
> list of lists, but that is not necessary, as the python function knows
> the dimensions of this array).  As I read the reference, I see, that I
> must first initialize a list object and then item-by-item put the values
> to the list.  Is there any faster way to do it?  And is it worth to
> implement?  The same problem is resolved in the current version by
> calling a smaller c function (that counts just one element of the array)
> many times.  Will it add much performance to the process?

My first thought is to use the numpy library since it is good at quickly 
creating large arrays (of any dimension) and you can easily get the data 
out as a list if you really need that (but are you sure you need that? 
You may be able to just use the numpy array directly).

It might help to have a clearer idea of why you want to do this. 

-- Russell

P.S. numarray or Numeric would also do the job. They are older, 
deprecated numeric libraries. numpy is recommended for new code.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I Color a QTableView row in PyQt4

2007-03-02 Thread Mel
Now that I can change the row colors of QTableView when loading data I
now need to be able to set the color of the row at anytime.  I've been
trying by using an item delegate but I'm not sure if I'm using it
correctly.  Would I try and set an item delegate for the row and
change the background color that way?  An example or a link to easy to
understand documentation on changing a row color for an object based
on QTableView using QSqlQueryModel as a model would be greatly
appreciated.  I'm still a bit confused in Qt4.

Mel

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


Re: Strange method signature via COM

2007-03-02 Thread Richard Jebb
After digging around in the group archives I've figured it out. It's not
been helped by my inability to identify the API's COM server/type library in
the list produced by the MakePy utility, so I've largely been flying blind.

Some posts on this same subject back in 1999 revealed the answer, namely
that when win32com encounters a method signature like the one we had, it
expects you to call it like this:

obj.Value("myfield", "newvalue")

If there already exists an interface to Value() with this signature, then it
prepends the original method name with "Set", so that in Python you would
call

obj.SetValue("myfield", "newvalue")

We still have some other issues with the API, but I'm hoping once the
application vendor has revealed what name it will appear under in MakePy we
will be able to sort those out as well.


"Bruno Desthuilliers" <[EMAIL PROTECTED]> wrote in
message news:[EMAIL PROTECTED]
> Richard Jebb a écrit :
> > We are trying to use the API of a Win32 app which presents the API as a
COM
> > interface. The sample VB code for getting and setting the values of
custom
> > data fields on an object shows a method named Value():
> >
> > getterobj.Value("myfield")
> > setterobj.Value("myfield") = newvalue
> >
> > Using Python 2.5 and PythonWin we can get data from data fields using
the
> > identical syntax
>
> I have no experience with Python/COM, but IIRC, in VB (at least in VB6),
> the parens are also used for array subscript.
>
> >
> print comp.Value("Phone1")
> > 99080980
> >
> > However the set value fails (unsurprisingly)
> >
> >
> comp.value("Phone1") = "6876876876"
> >
> > SyntaxError: can't assign to function call
> >
> > Does anyone have any idea how to use Python to address this type of
method
> > signature?
>
> Have you tried inspecting your COM object in an interactive Python
> shell, using dir(), help() and the inspect module ?
>
> And FWIW, disd you try the following syntaxes:
> comp.value['Phone1'] = "xxx"
> comp['Phone1'] = "xxx"
>
> My 2 cents


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

Re: is it bug or feature in xml.dom.minidom?

2007-03-02 Thread Paul Boddie
Maksim Kasimov wrote:
> Hi, i'm faced with such a problem when i use xml.dom.minidom:
>
> to append all child nodes from "doc" in "_requ" to "doc" in "_resp", i do the 
> following:
>
> _requ = 
> minidom.parseString("OneTwo")
> _resp = minidom.parseString("")

Note that these are different documents - this is important later on.

> iSourseTag = _requ.getElementsByTagName('doc')[0]
> iTargetTag = _resp.getElementsByTagName('doc')[0]
>
>
> # it prints me that there are two child nodes
> for iChild in iSourseTag.childNodes:
>  print iChild.toxml()

Seems alright.

> # when i walk elements, only first iteration was made
> # and iSourseTag.childNodes now have only one element instead of two
> for iChild in iSourseTag.childNodes:
>  iTargetTag.appendChild(iChild)

But since you're taking a node from one document to add it to another,
you should instead use importNode to make that node importable into
the target document:

for iChild in iSourseTag.childNodes:
# 1 or True should cause a deep copy
iNewChild = _resp.importNode(iChild, 1)
iTargetTag.appendChild(iNewChild)

> # it prints me that there is only one child node
> for iChild in iSourseTag.childNodes:
>  print iChild.toxml()

That's probably because you've "stolen" the node from its document in
order to add it to the target document - something which is possibly
an artifact of the minidom implementation.

> i'm not sure, whether i append child nodes in properly way, but IMHO it looks 
> like a bug.

That minidom does not refuse to let you "move" nodes in this way could
be debated as being a bug or not, but the correct way of copying nodes
is to use importNode.

> My question is how to avoid the "iSourseTag" changes while iterate its nodes?
>
> And, of course, how to append all child nodes to "iTargetTag"?

These questions are hopefully answered above.

Paul

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


Re: class declaration shortcut

2007-03-02 Thread Bjoern Schliessmann
Arnaud Delobelle wrote:

> Don't see it as the first name a class is bound to, but rather as
> the name a class is defined as.
> If class_object.__name__ == 'Foo' it means that somewhere in your
> code there is a class definition:
> 
> class Foo:
> # stuff
> 
> Same for function: if function_object.__name__ == 'bar' it means
> that somewhere you have
> 
> def bar(...):
> # stuff
> 
> (Of course this is not the case if you use another way to define
> functions or classes, e.g. type() )

This is somehow contrary to my understanding of the Python names
concept.

What if I use a loop to define several classes based on data --
they'll all have the same __name__ unless I change it manually.

Having this __name__ attribute set seems to me like "magic behind
the lines" which Python strives to evade, doesn't it? Personally,
I'd prefer inserting a mechanism for this manually if and when I
really need the functionality, but see below.

> What I described above is quite useful I think.  The alternative
> (anonymous classes) is that given an object myobj you have no
> means to find out what its class is (by that I mean to be able to
> locate the class definition in your source code), apart from
> stabbing in the dark (i.e. trying type(myobj)==someclass until
> successful).

In the typical case where you have one name per class definition,
yes.

Perhaps I'm lacking a typical application of __name__; that must be
why I'm so stubborn here ;)

Regards,


Björn

-- 
BOFH excuse #419:

Repeated reboots of the system failed to solve problem

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


Re: Sorting strings containing special characters (german 'Umlaute')

2007-03-02 Thread Bjoern Schliessmann
Robin Becker wrote:

> Björn, in one of our projects we are sorting in javascript in
> several languages English, German, Scandinavian languages,
> Japanese; from somewhere (I cannot actually remember) we got this
> sort spelling function for scandic languages
> 
> a
> .replace(/\u00C4/g,'A~') //A umlaut
> .replace(/\u00e4/g,'a~') //a umlaut
> .replace(/\u00D6/g,'O~') //O umlaut
> .replace(/\u00f6/g,'o~') //o umlaut
> .replace(/\u00DC/g,'U~') //U umlaut
> .replace(/\u00fc/g,'u~') //u umlaut
> .replace(/\u00C5/g,'A~~') //A ring
> .replace(/\u00e5/g,'a~~'); //a ring
> 
> does this actually make sense?

If I'm not mistaken, this would sort all umlauts after the "pure"
vowels. This is, according to , used in Austria. 

If you can't understand german, the rules given there in
section "Einsortierungsregeln" (roughly: ordering rules) translate
as follows:

"X und Y sind gleich": "X equals Y"
"X kommt nach Y": "X comes after Y"

Regards&HTH,


Björn

-- 
BOFH excuse #146:

Communications satellite used by the military for star wars.

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


Re: Sort with extra variables

2007-03-02 Thread Bjoern Schliessmann
Thomas Dybdahl Ahle wrote:

> However I'd really like not to use the lambda, as it slows down
> the code.

Did you check how much the slowdown is?
 
Regards,


Björn

-- 
BOFH excuse #65:

system needs to be rebooted

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


Re: Sort with extra variables

2007-03-02 Thread Paul Rubin
Thomas Dybdahl Ahle <[EMAIL PROTECTED]> writes:
> Do you have any ideas how I can sort these moves the fastest?

One idea: if you're using alpha-beta pruning, maybe you can use
something like heapq instead of sorting, since a lot of the time you
only have to look at the first few moves (ordered best-first).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Strange method signature via COM

2007-03-02 Thread Bruno Desthuilliers
Richard Jebb a écrit :
> We are trying to use the API of a Win32 app which presents the API as a COM
> interface. The sample VB code for getting and setting the values of custom
> data fields on an object shows a method named Value():
> 
> getterobj.Value("myfield")
> setterobj.Value("myfield") = newvalue
> 
> Using Python 2.5 and PythonWin we can get data from data fields using the
> identical syntax

I have no experience with Python/COM, but IIRC, in VB (at least in VB6), 
the parens are also used for array subscript.

> 
print comp.Value("Phone1")
> 99080980
> 
> However the set value fails (unsurprisingly)
> 
> 
comp.value("Phone1") = "6876876876"
> 
> SyntaxError: can't assign to function call
> 
> Does anyone have any idea how to use Python to address this type of method
> signature? 

Have you tried inspecting your COM object in an interactive Python 
shell, using dir(), help() and the inspect module ?

And FWIW, disd you try the following syntaxes:
comp.value['Phone1'] = "xxx"
comp['Phone1'] = "xxx"

My 2 cents
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sort with extra variables

2007-03-02 Thread Diez B. Roggisch
Thomas Dybdahl Ahle schrieb:
> I have a sort function in a python chess program.
> Currently it looks like this:
> 
> def sortMoves (board, table, ply, moves):
> f = lambda move: getMoveValue (board, table, ply, move)
> moves.sort(key=f, reverse=True)
> return moves
> 
> However I'd really like not to use the lambda, as it slows down the code.
> 
> I've thought about saving the extra variables in the global space, but it 
> really feals ugly.
> 
> Do you have any ideas how I can sort these moves the fastest?

First of all, in your case it is somewhat strange to use

f = lambda ...

because then you could as well use

def f(move):
   

But that is just a general remark. Regarding the question: I don't see 
how that could possibly become faster without much more insight into 
what you are doing in getMoveValue. As it seems, it is dependend of a 
lot of factors that change often, so caching it isn't a real option. And 
I hope you are aware that the key-method is invoked only _once_ per 
list-item!

Thus it is pretty efficient.

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


Sort with extra variables

2007-03-02 Thread Thomas Dybdahl Ahle
I have a sort function in a python chess program.
Currently it looks like this:

def sortMoves (board, table, ply, moves):
f = lambda move: getMoveValue (board, table, ply, move)
moves.sort(key=f, reverse=True)
return moves

However I'd really like not to use the lambda, as it slows down the code.

I've thought about saving the extra variables in the global space, but it 
really feals ugly.

Do you have any ideas how I can sort these moves the fastest?
-- 
http://mail.python.org/mailman/listinfo/python-list


mercurial is not known from apache2

2007-03-02 Thread soloturn
as i'm not sure if apache2 or python is responsible for this, excuse
if i try to ask here too.

our problem is that mercurial does not work from apache, but from
python command-line it does. what could be a reason for this
behaviour?

---
from the command line it works:
---
[EMAIL PROTECTED] ~
$ which python
/usr/local/bin/python
[EMAIL PROTECTED] ~
$ echo $LD_LIBRARY_PATH
/usr/local/lib:/usr/lib:/usr/local/lib:/opt/sfw/lib
[EMAIL PROTECTED] ~
$ python
Python 2.5 (r25:51908, Feb 22 2007, 11:38:23)
[GCC 3.4.2] on sunos5
Type "help", "copyright", "credits" or "license" for more information.
>>> from mercurial.hgweb.hgwebdir_mod import hgwebdir
>>> ^D
[EMAIL PROTECTED] ~

---
from apache-2.2.4 it does not work:
---

environment, output via:
def print_env():
print "Content-Type: text/html\n\n";
for name, value in os.environ.items():
print "%s\t= %s " % (name, value)
print sys.path

SERVER_SOFTWARE = Apache/2.2.4 (Unix) DAV/2 mod_python/3.2.10 Python/
2.5 SVN/1.4.3 mod_ssl/2.2.4 OpenSSL/0.9.8d
SCRIPT_NAME = /hg
SERVER_SIGNATURE =
REQUEST_METHOD = GET
SERVER_PROTOCOL = HTTP/1.1
QUERY_STRING =
PATH = /usr/local/sbin:/usr/local/bin:/usr/local/bin:/usr/ccs/bin:/usr/
sbin:/usr/bin:/usr/dt/bin:/usr/local/bin:/cs/local/bin:/opt/sfw/bin:/
usr/ccs/bin:/opt/VRTS/bin
HTTP_USER_AGENT = Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;
SV1; i-NavFourF; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.1)
TZ = MET
SERVER_NAME = myserver
REMOTE_ADDR = 169.63.210.220
SERVER_PORT = 80
SERVER_ADDR = 169.62.140.224
DOCUMENT_ROOT = /usr/local/data/htdocs
SCRIPT_FILENAME = /usr/local/data/hg09/hgwebdir.cgi
SERVER_ADMIN = [EMAIL PROTECTED]
HTTP_HOST = myserver
HTTP_CONNECTION = Keep-Alive
REQUEST_URI = /hg
HTTP_ACCEPT = */*
GATEWAY_INTERFACE = CGI/1.1
REMOTE_PORT = 3751
HTTP_ACCEPT_LANGUAGE = en,de-ch;q=0.7,fr;q=0.3
HTTP_ACCEPT_ENCODING = gzip, deflate
UNIQUE_ID = [EMAIL PROTECTED]@EAAB9ZBgoF
['/usr/local/data/hg09', '/usr/local/lib/python2.5/site-packages/
setuptools-0.6c3-py2.5.egg', '/usr/local/lib/python2.5/site-packages/
Genshi-0.4dev_r494-py2.5.egg', '/usr/local/lib/python2.5/site-packages/
TracAccountManager-0.1.3dev_r1844-py2.5.egg', '/usr/local/lib/
python2.5/site-packages/TracCombineWiki-1.2-py2.5.egg', '/usr/local/
lib/python2.5/site-packages/TracForge-1.0-py2.5.egg', '/usr/local/lib/
python2.5/site-packages/TracWebAdmin-0.1.2dev_r4429-py2.5.egg', '/usr/
local/lib/python2.5/site-packages/TracHTTPAuth-1.1-py2.5.egg', '/usr/
local/lib/python2.5/site-packages/IniAdmin-0.1-py2.5.egg', '/usr/local/
lib/python2.5/site-packages/LdapPlugin-0.5.1dev_r1611-py2.5.egg', '/
usr/local/lib/python2.5/site-packages/tracreposearch-0.2-py2.5.egg', '/
usr/local/lib/python2.5/site-packages/TracXMLRPC-0.1-py2.5.egg', '/usr/
local/lib/python2.5/site-packages/TracTicketDelete-1.1.4-py2.5.egg', '/
usr/local/lib/python2.5/site-packages/TracNav-3.92-py2.5.egg', '/usr/
local/lib/python25.zip', '/usr/local/lib/python2.5', '/usr/local/lib/
python2.5/plat-sunos5', '/usr/local/lib/python2.5/lib-tk', '/usr/local/
lib/python2.5/lib-dynload', '/usr/local/lib/python2.5/site-packages']
exception output:
Python 2.5: /usr/local/bin/python
 /usr/local/data/hg09/hgwebdir.cgi in ()
   29 from mercurial.hgweb.hgwebdir_mod import hgwebdir
   30 from mercurial.hgweb.request import wsgiapplication
   31 import mercurial.hgweb.wsgicgi as wsgicgi

mercurial undefined, hgwebdir undefined
 /usr/local/lib/python2.5/site-packages/mercurial/hgweb/__init__.py in
()
7 # of the GNU General Public License, incorporated herein by
reference.
9 import hgweb_mod, hgwebdir_mod
   11 def hgweb(*args, **kwargs):

hgweb_mod undefined, hgwebdir_mod undefined
 /usr/local/lib/python2.5/site-packages/mercurial/hgweb/hgweb_mod.py
in ()
7 # of the GNU General Public License, incorporated herein by
reference.
9 import os, mimetypes, re, zlib, mimetools, cStringIO, sys
   10 import tempfile, urllib, bz2
   11 from mercurial.node import *
os = None, mimetypes = None, re = None, zlib undefined, mimetools
undefined, cStringIO undefined, sys undefined
: ld.so.1: python: fatal: relocation
error: file /usr/local/lib/python2.5/lib-dynload/zlib.so: symbol
inflateCopy: referenced symbol not found

---
file system
---

# ls -l /usr/local/lib/python2.5/site-packages/mercurial/hgweb/
hgweb_mod.py*
-rw-r-   1 www-data other  40810 Mär  2 14:13 /usr/local/lib/
python2.5/site-packages/mercurial/hgweb/hgweb_mod.py
-rw-r-   1 www-data other  45015 Mär  2 14:34 /usr/local/lib/
python2.5/site-packages/mercurial/hgweb/hgweb_mod.pyc

---
try to manipulate LD_LIBRARY_PATH
---
if we try to set the ld_library_path in 

Re: Python 2.5, problems reading large ( > 4Gbyes) files on win2k

2007-03-02 Thread Paul Duffy
I am not using the universal newline.  File reading loop is essentially...

ifile = open("fileName", "r")
for line in ifile
  ...

Thanks

Peter Otten wrote:
> [EMAIL PROTECTED] wrote:
>
>   
>> I've a Python 2.5 app running on 32 bit Win 2k SP4 (NTFS volume).
>> Reading a file of 13 GBytes, one line at a time.  It appears that,
>> once the read line passes the 4 GByte boundary, I am getting
>> occasional random line concatenations.  Input file is confirmed good
>> via UltraEdit.  Groovy version of the same app runs fine.
>>
>> Any ideas?
>> 
>
> Do you open the file in  universal newline mode -- open(filename, "U") --,
> and if not, does the problem persist if you do?
>
> Peter
>   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: HL7 servers in Python?

2007-03-02 Thread Tim Churches
Richard Low, MD wrote:
> Richard,
> 
> I was most impressed by your answer below (in '03)
> 
> Do you know whether there is a third party application/library that can
> interface our software to the HL7 sockets systems so we do not have to
> develop them?
> 
> If you do, which one would you recommend?
>
> Richard M. Low MD
> CEO
> 
> Infor-Med Corporation
> 6271 Variel Avenue, Suite A
> Woodland Hills, California 91367-2512, USA
> Phone:  818-592-2900
> Direct fax: (818)743-7759
> Email: [EMAIL PROTECTED]
> URL:  http://www.infor-med.com

I posed the original question back in 2003 which prompted Richard
Sharp's reply, and as far as I am aware, there is still no general
purpose HL7 2.x "server" written in Python. If that is still your
requirement, then you'll have to write one, but it is highly feasible.
We ended up writing our own, back in 2003, which met our specific need
of listening for incoming HL7 2.x messages of just a few specific types
using MLLP (HL7 minimum lower-level protocol), parsing and validating
them, writing the data as a transaction to a special purpose PostgreSQL
database and sending back an ACK. It is part of a public health
surveillance system described here:
http://www.biomedcentral.com/1471-2458/5/141

The code for our listener is available at
http://sourceforge.net/project/showfiles.php?group_id=123700&package_id=139062

Please note and observe the the open source license under which that
code is made available (it is a Mozilla license, so should not cause you
too many difficulties should you chose to make use of it, but do read
the license). At the very least examination of our code may give you
some ideas, although it is written for POSIX platforms and I note that
your company's products seem to be MS-Windows-based. The Python-based
solution has been relentlessly reliable in production use over the last
3 and a half years.

If you are looking for more general HL7 servers which use Python in some
respect but aren't necessarily written entirely in Python, then have a
look at Mirth - see http://www.mirthproject.org/ - which is an open
source HL7 messaging server which can use Python (or Jython) to script
rules and actions for incoming and outgoing messages, and Interfaceware,
whose  closed-source products also embed Python for scripting purposes -
see for example http://www.interfaceware.com/manual/ch-7-7-4.html

There may be others.

Hope this helps,

Tim C

> HL7 servers in Python?
> 
> Richard Sharp
> rbsharp
> at gmx.de
> Mon Jun 16 17:29:22 CEST 2003
> 
>* Previous message:
> "Structure
> and Interpretation of Computer Programs" in Python?
>* Next message:
> HL7
> servers in Python?
>* Messages sorted by:
> [
> date ]
> [
> thread ]
> [
> subject ]
> [
> author ]
> 
> --
> 
> On Fri, 13 Jun 2003 07:10:26 +1000, Tim Churches wrote:
> 
>> Does anyone know of a Python HL7 socket server/daemon - that is, a
>> daemon which accepts socket connections on a TCP port from an HL7
>> source, receives an HL7 message via the connection, hands off the
>> message for processing, and then sends back an ACK or NACK H7 message -
>> usually synchronously, via a blocking connection (thus the server needs
>> to be multi-threaded)?
>>
>> HL7 stands for Health Level 7 (where 7 represents the 7th layer of the
>> OSI network stack) and is a widely-used standard for communication of
>> medical information. I'm not looking for HL7 message assembly or parsing
>> libraries, just the socket server bit. Perhaps the SocketServer module
>> in the Python library makes this so trivial that no-one has felt the
>> need to write a specific HL7 server in Python? Anyway, I've looked on
>> Google but can't spot anything obvious.
> 
> It is extremely doubtful, given the specialised nature of the question,
> whether most people understand what you want. Given that HL7 is really
> only sending and receiving some information in a curious format, and that
> you either receive data and then send the other side an ACK or a NAK, or
> wait until they do that in reply to your message, it is really not all
> that complicated.
> 
> The short answer to you question ist Twisted -
> http://www.twistedmatrix.com
> 
> What may confuse you is that it does not use blocking sockets and
> therefore does not need to be multithreaded, although I think it can be,
> but it does work.
> 
> My brea

Re: tkinter what do you use?

2007-03-02 Thread vegaseat
On Mar 2, 8:32 am, "Eric Brunel" <[EMAIL PROTECTED]> wrote:
> On Fri, 02 Mar 2007 16:17:32 +0100, Gigs_ <[EMAIL PROTECTED]> wrote:
> > list = Listbox()
> > list.insert('end', x)
> > list.insert(END, x)
>
> > what do you use 'end' or END?
> >>> from Tkinter import END
> >>> END == 'end'
>
> True
>
> So this isn't really important... My personal usage varies: for your use  
> case, I tend to use the symbolic constant (END); for sticky options in  
> grids, I tend to use the strings ('nswe' is shorter than N+S+W+E, not to  
> mention tk.N+tk.S+tk.W+tk.E).
> --
> python -c "print ''.join([chr(154 - ord(c)) for c in  
> 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"

When you use other modules like PIL with Tkinter, it is best to give
Tkinter a namespace.  This way you keep track where things are coming
from.  I prefer 'import Tkinter as tk' then it is much simpler to use
'end' or 'nswe'.  Otherwise you have to use tk.END or God forbit tk.N
+tk.S+tk.W+tk.E -- see what I mean?

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


Re: Python 2.5, problems reading large ( > 4Gbyes) files on win2k

2007-03-02 Thread Peter Otten
[EMAIL PROTECTED] wrote:

> I've a Python 2.5 app running on 32 bit Win 2k SP4 (NTFS volume).
> Reading a file of 13 GBytes, one line at a time.  It appears that,
> once the read line passes the 4 GByte boundary, I am getting
> occasional random line concatenations.  Input file is confirmed good
> via UltraEdit.  Groovy version of the same app runs fine.
> 
> Any ideas?

Do you open the file in  universal newline mode -- open(filename, "U") --,
and if not, does the problem persist if you do?

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


Re: Will Python Run On Microsoft Vista?

2007-03-02 Thread vegaseat
On Feb 5, 9:24 am, Jonathan Curran <[EMAIL PROTECTED]> wrote:
> On Monday 05 February 2007 11:08, slogging_away wrote:
>
> > I know, I know - flame away but its not clear to me if Python will run
> > on a system running MicrosoftVista.  Is anyone successfully running
> > Python onVista?  If so, is it what version of Python are you
> > running?  I'm ordering a new system and if Python won't work onVista
> > then it will definately influence the OS selection.
>
> > Thanks in advance!
>
> I don't see why Python wouldn't work. The 2.5 version clearly has a version
> forVistaalbeit its the x64 Edition. If you downloaded the regular version
> (x86) then I assume it would work just fine. D/L an evaluation copy ofVista
> and try it yourself.
>
> - Jonathan

Python works fine with Vista using the normal Python-2.5.msi
installer.  The one fly in the ointment is that Tkinter will not work
at this point (can't find _tkinter).  Good news is that wxPython
works!

Vega

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


Python 2.5, problems reading large ( > 4Gbyes) files on win2k

2007-03-02 Thread paduffy
Folks,

I've a Python 2.5 app running on 32 bit Win 2k SP4 (NTFS volume).
Reading a file of 13 GBytes, one line at a time.  It appears that,
once the read line passes the 4 GByte boundary, I am getting
occasional random line concatenations.  Input file is confirmed good
via UltraEdit.  Groovy version of the same app runs fine.

Any ideas?

Cheers

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


Re: pyHook or SetWindowsHookEx

2007-03-02 Thread abcd
:(

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


Re: Sorting strings containing special characters (german 'Umlaute')

2007-03-02 Thread Robin Becker
Bjoern Schliessmann wrote:
> Hallvard B Furuseth wrote:
>> [EMAIL PROTECTED] writes:
...
> 
> In German, there are some different forms:
> 
> - the classic sorting for e.g. word lists: umlauts and plain vowels
> are of same value (like you mentioned): ä = a
> 
> - name list sorting for e.g. phone books: umlauts have the same
> value as their substitutes (like Dierk described): ä = ae
> 
> There are others, too, but those are the most widely used.

Björn, in one of our projects we are sorting in javascript in several languages 
English, German, Scandinavian languages, Japanese; from somewhere (I cannot 
actually remember) we got this sort spelling function for scandic languages

a
.replace(/\u00C4/g,'A~') //A umlaut
.replace(/\u00e4/g,'a~') //a umlaut
.replace(/\u00D6/g,'O~') //O umlaut
.replace(/\u00f6/g,'o~') //o umlaut
.replace(/\u00DC/g,'U~') //U umlaut
.replace(/\u00fc/g,'u~') //u umlaut
.replace(/\u00C5/g,'A~~') //A ring
.replace(/\u00e5/g,'a~~'); //a ring

does this actually make sense?
-- 
Robin Becker

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


Re: Python GUI + OpenGL

2007-03-02 Thread MonkeeSage
On Mar 2, 9:17 am, Achim Domma <[EMAIL PROTECTED]> wrote:
> I need a OpenGL context without restrictions and some settings dialogs.
> Is wx + PyOpenGL the way to go? Or could somebody recommend a better set
> of tools/libs?

You could use pygtk + pygtkglext.

http://pygtk.org/
http://gtkglext.sourceforge.net/

Regards,
Jordan

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


Re: Python GUI + OpenGL

2007-03-02 Thread Mike C. Fletcher
Achim Domma wrote:
> Hi,
>
> I'm developing a GUI app in Python/C++ to visualize numerical results. 
> Currently I'm using Python 2.4 with wx and PyOpenGLContext, but there 
> are no windows binaries for Python 2.5 for quite some time now.
>
> I need a OpenGL context without restrictions and some settings dialogs. 
> Is wx + PyOpenGL the way to go? Or could somebody recommend a better set 
> of tools/libs?
>
> regards,
> Achim
>   
PyOpenGL 3.x (currently in alpha state, but reasonably usable) works on 
Python 2.5, there are no binaries because the system no longer requires 
binary versions.  Install the setuptools package, then run easy_install 
PyOpenGL and the egg file should be downloaded and installed to your 
machine.  The current version doesn't package GLE along with the code, 
however, so you'll have to find a DLL for that if you need it.

HTH,
Mike

-- 

  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://www.vrplumber.com
  http://blog.vrplumber.com

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


HL7 servers in Python?

2007-03-02 Thread Richard Low, MD

Richard,

I was most impressed by your answer below (in '03)

Do you know whether there is a third party application/library that 
can interface our software to the HL7 sockets systems so we do not 
have to develop them?


If you do, which one would you recommend?

Thank you,

[]

Richard M. Low MD
CEO

Infor-Med Corporation
6271 Variel Avenue, Suite A
Woodland Hills, California 91367-2512, USA
Phone:  818-592-2900
Direct fax: (818)743-7759
Email: [EMAIL PROTECTED]
URL:  http://www.infor-med.com










HL7 servers in Python?

Richard Sharp 
rbsharp 
at gmx.de

Mon Jun 16 17:29:22 CEST 2003

   * Previous message: 
"Structure 
and Interpretation of Computer Programs" in Python?
   * Next message: 
HL7 
servers in Python?
   * Messages sorted by: 
[ 
date ] 
[ 
thread ] 
[ 
subject ] 
[ 
author ]


--

On Fri, 13 Jun 2003 07:10:26 +1000, Tim Churches wrote:

> Does anyone know of a Python HL7 socket server/daemon - that is, a
> daemon which accepts socket connections on a TCP port from an HL7
> source, receives an HL7 message via the connection, hands off the
> message for processing, and then sends back an ACK or NACK H7 message -
> usually synchronously, via a blocking connection (thus the server needs
> to be multi-threaded)?
>
> HL7 stands for Health Level 7 (where 7 represents the 7th layer of the
> OSI network stack) and is a widely-used standard for communication of
> medical information. I'm not looking for HL7 message assembly or parsing
> libraries, just the socket server bit. Perhaps the SocketServer module
> in the Python library makes this so trivial that no-one has felt the
> need to write a specific HL7 server in Python? Anyway, I've looked on
> Google but can't spot anything obvious.

It is extremely doubtful, given the specialised nature of the question,
whether most people understand what you want. Given that HL7 is really
only sending and receiving some information in a curious format, and that
you either receive data and then send the other side an ACK or a NAK, or
wait until they do that in reply to your message, it is really not all
that complicated.

The short answer to you question ist Twisted -
http://www.twistedmatrix.com

What may confuse you is that it does not use blocking sockets and
therefore does not need to be multithreaded, although I think it can be,
but it does work.

My bread and butter Python work is software that interfaces between a
Pathology System running any number of versions of Unix and some
overarching Hospital System that provides me with patient data and to
which I deliver reports and accounting data, mostly, but not always, in
HL7.

I have one Pathology Unit that does work for two hospitals and
communicates with two hospital systems. With Twisted I basically subclass
protocol.Factory and implement the necessary submethods.

It is a little daunting at first and there was at the time (about 2 years
ago) when no usable documentation worth speaking of was available. I am
also stuck at the moment with Twisted 0.18.0, because it runs with Python
1.5.2, and I had trouble getting Python >= 2.0 running on the all the
Unixes I had to get it running on. In the meantime, I think I've got that
under control.

If you're interested in looking at the programms I will have to ask the
company I developed the software for, but the complete program is only ca.
800 Lines and covers 4 Low Level Protocols.

I hope I have been of some help. Once people realise that what you want is
some sort of select-loop-server, then they will probably gush forth with
helpful suggestions.

Greetings,

Richard Sharp



--
   * Previous message: 
"Structure 
and Interpretation of Computer Programs" in Python?
   * Next message: 
HL7 
servers in Python?
   * Messages sorted by: 
[ 
date ] 
[ 
thread ] 
[ 
subject ] 
[ 
author ]


--
More information 
about the Python-l

Re: Dialog with a process via subprocess.Popen blocks forever

2007-03-02 Thread Donn Cave
In article <[EMAIL PROTECTED]>,
 "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:

> En Thu, 01 Mar 2007 14:42:00 -0300, <[EMAIL PROTECTED]> escribió:
> 
> > BUT If I use PIPE for both (so I can .write() on the stdin and .read()
> > from the subprocess' stdout stream (better: file descriptor)) reading
> > from the subprocess stdout blocks forever. If I write something onto
> > the subprocess' stdin that causes it to somehow proceed, I can read
> > from its stdout.
> 
> On http://docs.python.org/lib/popen2-flow-control.html there are some  
> notes on possible flow control problems you may encounter.

It's a nice summary of one problem, a deadlock due to full pipe
buffer when reading from two pipes.  The proposed simple solution
depends too much on the cooperation of the child process to be
very interesting, though.  The good news is that there is a real
solution and it isn't terribly complex, you just have to use select()
and UNIX file descriptor I/O.  The bad news is that while this is
a real problem, it isn't the one commonly encountered by first
time users of popen.

The more common problem, where you're trying to have a dialogue
over pipes with a program that wasn't written specifically to
support that, is not solvable per se - I mean, you have to use
another device (pty) or redesign the application.

> If you have no control over the child process, it may be safer to use a  
> different thread for reading its output.

Right - `I used threads to solve my problem, and now I have two
problems.'  It can work for some variations on this problem, but
not the majority of them.

   Donn Cave, [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list

is it bug or feature in xml.dom.minidom?

2007-03-02 Thread Maksim Kasimov

Hi, i'm faced with such a problem when i use xml.dom.minidom:

to append all child nodes from "doc" in "_requ" to "doc" in "_resp", i do the 
following:

_requ = 
minidom.parseString("OneTwo")
_resp = minidom.parseString("")


iSourseTag = _requ.getElementsByTagName('doc')[0]
iTargetTag = _resp.getElementsByTagName('doc')[0]


# it prints me that there are two child nodes
for iChild in iSourseTag.childNodes:
print iChild.toxml()


# when i walk elements, only first iteration was made
# and iSourseTag.childNodes now have only one element instead of two
for iChild in iSourseTag.childNodes:
iTargetTag.appendChild(iChild)


# it prints me that there is only one child node
for iChild in iSourseTag.childNodes:
print iChild.toxml()

i'm not sure, whether i append child nodes in properly way, but IMHO it looks 
like a bug.

My question is how to avoid the "iSourseTag" changes while iterate its nodes?

And, of course, how to append all child nodes to "iTargetTag"?

Thank for any help.

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


Re: Dialog with a process via subprocess.Popen blocks forever

2007-03-02 Thread Bernhard Herzog
[EMAIL PROTECTED] writes:

> So, once I start the C Program from the shell, I immediately get its
> output in my terminal. If I start it from a subprocess in python and
> use python's sys.stdin/sys.stdout as the subprocess' stdout/stdin I
> also get it immediately.

If stdout is connected to a terminal, it's usually line buffered, so the
buffer is flushed whenever a newline is written.

> BUT If I use PIPE for both (so I can .write() on the stdin and .read()
> from the subprocess' stdout stream (better: file descriptor)) reading
> from the subprocess stdout blocks forever. If I write something onto
> the subprocess' stdin that causes it to somehow proceed, I can read
> from its stdout.

When stdout is not connected to a terminal, it's usually fully buffered,
so that nothing is actually written to the file until the buffer
overflows or until it's explictly flushed.

If you can modify the C program, you could force its stdout stream to be
line buffered.  Alternatively, you could call fflush on stdout whenever
you're about to read from stdin.  If you can't modify the C program you
may have to resort to e.g. pseudo ttys to trick it into believing that
its stdout is a terminal.

   Bernhard

-- 
Intevation GmbH http://intevation.de/
Skencil   http://skencil.org/
Thuban  http://thuban.intevation.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python GUI + OpenGL

2007-03-02 Thread Diez B. Roggisch
Achim Domma wrote:

> Hi,
> 
> I'm developing a GUI app in Python/C++ to visualize numerical results.
> Currently I'm using Python 2.4 with wx and PyOpenGLContext, but there
> are no windows binaries for Python 2.5 for quite some time now.
> 
> I need a OpenGL context without restrictions and some settings dialogs.
> Is wx + PyOpenGL the way to go? Or could somebody recommend a better set
> of tools/libs?

PyQt, but then there is the licensing question of course.

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


Re: ANN: PyDSTool now compatible with numpy 1.0.1, scipy 0.5.2 and 64-bit CPUs.

2007-03-02 Thread Rob Clewley
Mike,

Yes, that is a pretty fair description of our support for symbolics
using Python's own inheritance. Our ModelSpec classes provide only an
elementary form of inheritance, polymorphism and type checking. We
hope to expand our existing support for hybrid/DAE systems at the
level of our ModelSpec model-building tools. All ideas and code
contributions are welcome!

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


Re: class declaration shortcut

2007-03-02 Thread Arnaud Delobelle
On Mar 2, 3:01 pm, Bjoern Schliessmann  wrote:
> Steven D'Aprano wrote:
> > Overkill? Storage of a single attribute holding a (usually short)
> > string is overkill?
>
> No, but storing the first name a class is bound to in it is a bit
> of, IMHO.

Don't see it as the first name a class is bound to, but rather as the
name a class is defined as.
If class_object.__name__ == 'Foo' it means that somewhere in your code
there is a class definition:

class Foo:
# stuff

Same for function: if function_object.__name__ == 'bar' it means that
somewhere you have

def bar(...):
# stuff

(Of course this is not the case if you use another way to define
functions or classes, e.g. type() )

> > When you do that, you wouldn't expect the __name__ of
> > some.module.function to change to f, and it doesn't.
>
> But what is it for then? =) Showing the first name the class was
> bound to?

What I described above is quite useful I think.  The alternative
(anonymous classes) is that given an object myobj you have no means to
find out what its class is (by that I mean to be able to locate the
class definition in your source code), apart from stabbing in the dark
(i.e. trying type(myobj)==someclass until successful).

--
Arnaud

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


Re: Dialog with a process via subprocess.Popen blocks forever

2007-03-02 Thread bayer . justin
> If you are both waiting for input, you have a Mexican standoff...

That is not the problem. The problem is, that the buffers are not
flushed correctly. It's a dialogue, so nothing complicated. But python
does not get what the subprocess sends onto the subprocess' standard
out - not every time, anyway.

I'm quite confused, but hopefully will understand what's going on and
come back here.




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


Re: Sorting strings containing special characters (german 'Umlaute')

2007-03-02 Thread [EMAIL PROTECTED]
On 2 Mrz., 15:25, Peter Otten <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > For sorting the letter "Ä" is supposed to be treated like "Ae",
There are several way of defining the sorting order. The variant "ä
equals ae" follows DINDIN 5007 (according to wikipedia); defining (a
equals ä) complies with DIN 5007-1. Therefore both options are
possible.

> The default locale is not used by default; you have to set it explicitly
>
> >>> import locale
> >>> locale.strcoll("Ärger", "Beere")
> 1
> >>> locale.setlocale(locale.LC_ALL, "")
> 'de_DE.UTF-8'
> >>> locale.strcoll("Ärger", "Beere")
>
> -1

On my machine
>>> locale.setlocale(locale.LC_ALL, "")
gives
'German_Germany.1252'

But this does not affect the sorting order as it does on your
computer.
>>> locale.strcoll("Ärger", "Beere")
yields 1 in both cases.

Thank you for your hint using unicode from the beginning on, see the
difference:
>>> s1 = unicode("Ärger", "latin-1")
>>> s2 = unicode("Beere", "latin-1")
>>> locale.strcoll(s1, s2)
1
>>> locale.setlocale(locale.LC_ALL, "")
-1

compared to

>>> s1 = "Ärger"
>>> s2 = "Beere"
>>> locale.strcoll(s1, s2)
1
>>> locale.setlocale(locale.LC_ALL, "")
'German_Germany.1252'
>>> locale.strcoll(s1, s2)
1

Thanks for your help.

  Dierk




>
> ['Ara', '\xc3\x84rger', 'Ast']
>
> Peter
>
> (*) German for "trouble"


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


AJAX Calander like Google Calender

2007-03-02 Thread lalit
Hi all,

I would like to make the the calender cery similar to google
event calander in python. can any one help me where
i will get library that uses AJAX is this feasible

reg,
Lalit

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


Re: Sorting strings containing special characters (german 'Umlaute')

2007-03-02 Thread Bjoern Schliessmann
Hallvard B Furuseth wrote:
> [EMAIL PROTECTED] writes:

>> For sorting the letter "Ä" is supposed to be treated like "Ae",
>> therefore sorting this list should yield
>> l = ["Aber, "Ärger", "Beere"]
> 
> Are you sure?  Maybe I'm thinking of another language, I thought Ä
> shold be sorted together with A, but after A if the words are
> otherwise equal.

In German, there are some different forms:

- the classic sorting for e.g. word lists: umlauts and plain vowels
are of same value (like you mentioned): ä = a

- name list sorting for e.g. phone books: umlauts have the same
value as their substitutes (like Dierk described): ä = ae

There are others, too, but those are the most widely used.

Regards,


Björn

-- 
BOFH excuse #277:

Your Flux Capacitor has gone bad.

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


Re: tkinter what do you use?

2007-03-02 Thread Eric Brunel
On Fri, 02 Mar 2007 16:17:32 +0100, Gigs_ <[EMAIL PROTECTED]> wrote:

> list = Listbox()
> list.insert('end', x)
> list.insert(END, x)
>
>
> what do you use 'end' or END?

>>> from Tkinter import END
>>> END == 'end'
True

So this isn't really important... My personal usage varies: for your use  
case, I tend to use the symbolic constant (END); for sticky options in  
grids, I tend to use the strings ('nswe' is shorter than N+S+W+E, not to  
mention tk.N+tk.S+tk.W+tk.E).
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter menus

2007-03-02 Thread Eric Brunel
On Fri, 02 Mar 2007 13:41:12 +0100, Gigs_ <[EMAIL PROTECTED]> wrote:
> is it alright to use Menu instead Toplevel or Tk
> like this?
>
> from Tkinter import *
> from tkMessageBox import *
>
> class MenuDemo(Menu):
>  def __init__(self, master=None):
>  Menu.__init__(self, master)
>  self.createWidgets()
>  self.master.title('Toolbars and Mennus')
>  self.master.iconname('tkpython')
>
>  def createWidgets(self):
>  self.makeMenuBar()
>  self.makeToolBar()
>  L = Label(self.master, text='Menu and Toolbar demo')
>  L.config(relief=SUNKEN, width=40, height=10, bg='white')
>  L.pack(expand=YES, fill=BOTH)

Feels weird to me. Creating widgets in a window from what is supposed to  
its its menu is quite unexpected. I would definitely create a sub-class of  
Toplevel or Tk and create the menu in it.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Python installation problem

2007-03-02 Thread Ray Buck
I've been trying to install Mailman, which requires a newer version 
of the Python language compiler (p-code generator?) than the one I 
currently have on my linux webserver/gateway box.


It's running a ClarkConnect 2.01 package based on Red Hat 7.2 linux.

I downloaded the zipped tarball (Python-2.4.4.tgz), ran gunzip, then 
un-tarred it in /usr/local.  Then (logged in as root) from 
/usr/local/Python-2.4.4 I ran the configure script which appeared to 
run properly.  At least there were no error messages that I 
saw.  Then I attempted to run "make install" and ended up with an 
error "make *** Error 1".  It was right at the "libinstall" section 
of the make, so I did some googling and came up with the following command:

[EMAIL PROTECTED] Python-2.4.4]# make libinstall inclinstall

After thrashing for about 5 minutes, I got basically the same message:
Compiling /usr/local/lib/python2.4/zipfile.py ...
make: *** [libinstall] Error 1

I dunno if this is relevant, but I have Python 2.2.2 in the 
/usr/Python-2.2.2 directory.  Do I have to blow this away in order to 
install the newer distro?  Or do I need to install the new one in/usr 
instead of /usr/local?


Although I'm a retired programmer (mainframes), I'm still learning 
this linux stuff.  I guess that makes me a noob...I hope you'll take 
that into consideration.


Thanks,

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

A more navigable Python Library Reference page

2007-03-02 Thread m . n . summerfield
Although a fan of Python, I find the Python Library Reference page
(lib.html) very inconvenient because of its book contents-like layout.
Also, some things that seem to me to belong together, such as string
methods and string services are dispersed. Another annoyance is that
it is
so verbose: this is good for Python newbies, but frustrating once you
know
what you want to find.

So I now use a tiny Python script to read lib.html and produce a new
HTML
file, with a few manual tweaks to get something that addresses the
issues
I've mentioned.

Google doesn't seem to let you add attachments so I've put a sample of
the output here:
http://www.qtrac.eu/libindex.html
at the bottom of the page there is a link to the ~100 line libindex.py
script that generated it.

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


Re: float64 print digits

2007-03-02 Thread Grant Edwards
On 2007-03-02, Ulrich Dorda <[EMAIL PROTECTED]> wrote:
> I need a pytho nscript to read numbers(with loads of digits) from a 
> file, do some basic math on it and write the result out to another file.
>
> My problem: I don't get python to use more digits:
>
> In order to try this I type:
>
> The normal precision one:
> >>> from numpy import *
> >>> x=1.23456789123456789123456789
> >>> print "%35.25e" %x
> 1.23456789123456790e+000
>
>
> Now I try to use float64 to get more digits

You're already using 64 bit floats (which have about 15
significant digits).

> >>> z=zeros(3,float64)
> >>> z[0]
> 0.0
> >>> type(z[0])
>
> >>> z[0]=1.23456789123456789123456789
> >>> type(z[0])
>
> >>> print "%35.25e" %z[0]
> 1.23456789123456790e+000
>
> This cuts the digits just like the 32bit case.

What 32-bit case?  A 32-bit float only has 7-8 significant
digits.

> Can anyone please help me get more digits?

Use the decimal module?

-- 
Grant Edwards   grante Yow!  What a
  at   COINCIDENCE! I'm an
   visi.comauthorized "SNOOTS OF THE
   STARS" dealer!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorting strings containing special characters (german 'Umlaute')

2007-03-02 Thread Hallvard B Furuseth
[EMAIL PROTECTED] writes:
> For sorting the letter "Ä" is supposed to be treated like "Ae",
> therefore sorting this list should yield
> l = ["Aber, "Ärger", "Beere"]

Are you sure?  Maybe I'm thinking of another language, I thought Ä shold
be sorted together with A, but after A if the words are otherwise equal.
E.g. Antwort, Ärger, Beere.  A proper strcoll handles that by
translating "Ärger" to e.g. ["Arger", ],
then it can sort first by the un-accentified name and then by the rest.

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


Re: Matplotlib axes label

2007-03-02 Thread attn . steven . kuo
On Mar 2, 7:02 am, "John Henry" <[EMAIL PROTECTED]> wrote:
> On Mar 1, 10:07 pm, "John Henry" <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Mar 1, 9:53 pm, [EMAIL PROTECTED] wrote:
>

(snipped)

> > > You can try adjusting the labels and ticks
> > > using matplotlib.ticker.
>
> > > To the example you cited, one can add
>
> > > from matplotlib.ticker import MultipleLocator, FormatStrFormatter
>
> > > # ...
>
> > > minorLocator = MultipleLocator(0.1)
> > > minorFormattor = FormatStrFormatter('%0.1f')
> > > ax.yaxis.set_minor_locator(minorLocator)
> > > ax.yaxis.set_minor_formatter(minorFormattor)
>
> > > show()
>
>
> > Thank you for the response.  Yes, adding those lines did work.
>
> > But what exactly is going on here?  Why would adding these two lines
> > works?
>
> > Thanks,
>
> Okay, I played with the ticker formater and locator routines.
> Unfortunately, it doesn't help.  The locator sets the major value and
> the formatter determines how the axes label is formatted.  It doesn't
> gurantee that the first label starts at the origin.  Half of my plots
> works, and half of them doesn't.





As default, matplotlib places labels and tick marks
at major ticks.  Minor ticks are invisible as
a default.

The lines that I added turned on *minor*
ticks and their labels; I set them to appear
at integer multiples of 0.1 and I
formatted them as floating point numbers.

There's nothing to prevent you from
having minor ticks appear at intervals
that exceed those of major ticks.  E.g.,

minorLocator = MultipleLocator(1.1)

# etc.

--
Hope this helps,
Steven

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


tkinter what do you use?

2007-03-02 Thread Gigs_
list = Listbox()
list.insert('end', x)
list.insert(END, x)


what do you use 'end' or END?
-- 
http://mail.python.org/mailman/listinfo/python-list


Python GUI + OpenGL

2007-03-02 Thread Achim Domma
Hi,

I'm developing a GUI app in Python/C++ to visualize numerical results. 
Currently I'm using Python 2.4 with wx and PyOpenGLContext, but there 
are no windows binaries for Python 2.5 for quite some time now.

I need a OpenGL context without restrictions and some settings dialogs. 
Is wx + PyOpenGL the way to go? Or could somebody recommend a better set 
of tools/libs?

regards,
Achim
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Matplotlib axes label

2007-03-02 Thread John Henry
On Mar 1, 10:07 pm, "John Henry" <[EMAIL PROTECTED]> wrote:
> On Mar 1, 9:53 pm, [EMAIL PROTECTED] wrote:
>
>
>
> > On Mar 1, 3:10 pm, "John Henry" <[EMAIL PROTECTED]> wrote:
>
> > > I've been asking this question at the matplotlib user list and never
> > > gotten an answer.  I am hoping that there are matplotlib users here
> > > that can help.
>
> > > My problem with matplotlib's way of handling axes label is illustrated
> > > by this example:
>
> > >http://www.scipy.org/Cookbook/Matplotlib/MulticoloredLine
>
> > > Notice that the y-axis goes from (-1.1, 1.1) but the first label is at
> > > -1.0.
>
> > (snipped)
>
> > > Is there a way to force the label to start at -1.1 instead of -1.0?
>
> > > Thanks,
>
> > You can try adjusting the labels and ticks
> > using matplotlib.ticker.
>
> > To the example you cited, one can add
>
> > from matplotlib.ticker import MultipleLocator, FormatStrFormatter
>
> > # ...
>
> > minorLocator = MultipleLocator(0.1)
> > minorFormattor = FormatStrFormatter('%0.1f')
> > ax.yaxis.set_minor_locator(minorLocator)
> > ax.yaxis.set_minor_formatter(minorFormattor)
>
> > show()
>
> > --
> > Hope this helps,
> > Steven
>
> Thank you for the response.  Yes, adding those lines did work.
>
> But what exactly is going on here?  Why would adding these two lines
> works?
>
> Thanks,


Okay, I played with the ticker formater and locator routines.
Unfortunately, it doesn't help.  The locator sets the major value and
the formatter determines how the axes label is formatted.  It doesn't
gurantee that the first label starts at the origin.  Half of my plots
works, and half of them doesn't.

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


Re: class declaration shortcut

2007-03-02 Thread Bjoern Schliessmann
Steven D'Aprano wrote:

> Overkill? Storage of a single attribute holding a (usually short)
> string is overkill?

No, but storing the first name a class is bound to in it is a bit
of, IMHO.
 
> When you do that, you wouldn't expect the __name__ of
> some.module.function to change to f, and it doesn't.

But what is it for then? =) Showing the first name the class was
bound to?
 
Regards,


Björn

-- 
BOFH excuse #217:

The MGs ran out of gas.

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


Re: How to update DNS record

2007-03-02 Thread Martin P. Hellwig
Andi Clemens wrote:

> 
> It's working!!!
> Yeah!
> I don't know why I didn't get this the first time I tried dnspython, but now
> its working! And it's so easy, 3 lines of code:
> 
> def make_dns_entry(pix):
>  update = dns.update.Update(_DOMAIN)
>  update.replace(pix.name, 3600, 'a', pix.outbound)
>  response = dns.query.tcp(update, _NAMESERVER)
> 
> Thank you for all your help!
> 
> Andi

Glad to be of service!

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


Re: Converting a c array to python list

2007-03-02 Thread zefciu
I have just read about buffer and array objects and I think one of them
could be fit for my need.  However there are two questions.

If i make a buffer from a part of dynamically allocated memory, what
would free it?  Should it be allocated with malloc or some
python-specific function?

How on earth can I create array object in C?

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


Re: Sorting strings containing special characters (german 'Umlaute')

2007-03-02 Thread Peter Otten
[EMAIL PROTECTED] wrote:

> I know that this topic has been discussed in the past, but I could not
> find a working solution for my problem: sorting (lists of) strings
> containing special characters like "ä", "ü",... (german umlaute).
> Consider the following list:
> l = ["Aber", "Beere", "Ärger"]
> 
> For sorting the letter "Ä" is supposed to be treated like "Ae",

I don't think so:

>>> sorted(["Ast", "Ärger", "Ara"], locale.strcoll)
['Ara', '\xc3\x84rger', 'Ast']

>>> sorted(["Ast", "Aerger", "Ara"])
['Aerger', 'Ara', 'Ast']

> therefore sorting this list should yield
> l = ["Aber, "Ärger", "Beere"]
> 
> I know about the module locale and its method strcoll(string1,
> string2), but currently this does not work correctly for me. Consider
>  >>> locale.strcoll("Ärger", "Beere")
>  1
> 
> Therefore "Ärger" ist sorted after "Beere", which is not correct IMO.
> Can someone help?
> 
> Btw: I'm using WinXP (german) and
 locale.getdefaultlocale()
> prints
>('de_DE', 'cp1252')

The default locale is not used by default; you have to set it explicitly

>>> import locale
>>> locale.strcoll("Ärger", "Beere")
1
>>> locale.setlocale(locale.LC_ALL, "")
'de_DE.UTF-8'
>>> locale.strcoll("Ärger", "Beere")
-1

By the way, you will avoid a lot of "Ärger"* if you use unicode right from
the start.

Finally, for efficient sorting, a key function is preferable over a cmp
function:

>>> sorted(["Ast", "Ärger", "Ara"], key=locale.strxfrm)
['Ara', '\xc3\x84rger', 'Ast']

Peter

(*) German for "trouble"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorting strings containing special characters (german 'Umlaute')

2007-03-02 Thread Robin Becker
[EMAIL PROTECTED] wrote:
> Hi !
> 
> I know that this topic has been discussed in the past, but I could not
> find a working solution for my problem: sorting (lists of) strings
> containing special characters like "ä", "ü",... (german umlaute).
> Consider the following list:
> l = ["Aber", "Beere", "Ärger"]
> 
> For sorting the letter "Ä" is supposed to be treated like "Ae",
> therefore sorting this list should yield
> l = ["Aber, "Ärger", "Beere"]
> 
> I know about the module locale and its method strcoll(string1,
> string2), but currently this does not work correctly for me. Consider
>  >>> locale.strcoll("Ärger", "Beere")
>  1
> 
> Therefore "Ärger" ist sorted after "Beere", which is not correct IMO.
> Can someone help?
> 
> Btw: I'm using WinXP (german) and
 locale.getdefaultlocale()
> prints
>('de_DE', 'cp1252')
> 
> TIA.
> 
>   Dierk
> 
we tried this in a javascript version and it seems to work sorry for long line 
and possible bad translation to Python


#coding: cp1252
def _deSpell(a):
u = a.decode('cp1252')
return 
u.replace(u'\u00C4','Ae').replace(u'\u00e4','ae').replace(u'\u00D6','OE').replace(u'\u00f6','oe').replace(u'\u00DC','Ue').replace(u'\u00fc','ue').replace(u'\u00C5','Ao').replace(u'\u00e5','ao')
def deSort(a,b):
return cmp(_deSpell(a),_deSpell(b))

l = ["Aber", "Ärger", "Beere"]
l.sort(deSort)
print l



-- 
Robin Becker

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


  1   2   >