Re: List of integers & L.I.S. (SPOILER)

2005-09-09 Thread n00m
Bravo, Bryan!
Looks very neat! (pity I can't give it a try in my Py 2.3.4
because of reversed() and sorted() functions)
And I've submitted it but got ... TLEs:
http://spoj.sphere.pl/status/SUPPER/
Funnily, the exec.time of the best C solution is only 0.06s!

PS
In my 1st submission I overlooked that your code handles only
1 testcase (there are 10 of them); hence its 0.13s exec. time.
PPS
This is the code's text I submitted:


#!/user/bin/env python
from sys import stdin

def one_way(seq):
 n = len(seq)
 dominators = [n + 1] * (n * 1)
 # dominators[j] is lowest final value of any increasing sequence
of
 # length j seen so far, as we left-right scan seq.
 score = [None] * n
 end = 0
 for (i, x) in enumerate(seq):
 # Binary search for x's place in dominators
 low, high = 0, end
 while high - low > 10:
 mid = (low + high) >> 1
 if dominators[mid] < x:
 low = mid + 1
 else:
 high = mid + 1
 while dominators[low] < x:
 low += 1
 dominators[low] = x
 score[i] = low
 end = max(end, low + 1)
 return score

def supernumbers(seq):
 forscore = one_way(seq)
 opposite = [len(seq) - x for x  in reversed(seq)]
 backscore = reversed(one_way(opposite))
 score = map(sum, zip(forscore, backscore))
 winner = max(score)
 return sorted([seq[i] for i in range(len(seq)) if score[i] ==
winner])

for tc in range(10):
_ = stdin.readline()
sequence = [int(ch) for ch in stdin.readline().split()]
supers = supernumbers(sequence)
print len(supers) 
for i in supers: 
 print i,

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


python script under windows

2005-09-09 Thread Jan Gregor
Hello

  I run python script on another computer and want to "survive" that
script after my logout. the script also uses drive mapping to network drive.

  Can you help me ?  Or better is there some info for unix person how
to survive with python on windows ;-)

thanks,
jan gregor
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Possible improvement to slice opperations.

2005-09-09 Thread Michael Hudson
Ron Adam <[EMAIL PROTECTED]> writes:

> Magnus Lycka wrote:
>> Ron Adam wrote:
[...]
>>> REVERSE ORDER STEPPING
>>> --
>>> When negative steps are used, a slice operation
>>> does the following.  (or the equivalent)
>>>
>>>1. reverse the list
>>>2. cut the reversed sequence using start and stop
>>>3. iterate forward using the absolute value of step.
>> I think you are looking at this from the wrong perspective.
>> Whatever sign c has:
>> For s[a:b:c], a is the index for the first item to include,
>> b is the item after the last to include (just like .end() in
>> C++ iterators for instance), and c describes the step size.
>
> Yes, and that is how it "should" work.  But
>
> With current slicing and a negative step...
>
> [   1   2   3   4   5   6   7   8   9  ]
>   -9  -8  -7  -6  -5  -4  -3  -2  -1  -0
>
> r[-3:]  ->  [7, 8, 9]# as expected
> r[-3::-1] ->  [7, 6, 5, 4, 3, 2, 1, 0]   # surprise
>
> The seven is include in both cases, so it's not a true inverse
> selection either.

Did you read what Magnus said: "a is the index for the first item to
include"?  How could r[-3::x] for any x not include the 7?

Cheers,
mwh

-- 
  Windows 2000: Smaller cow. Just as much crap.
   -- Jim's pedigree of operating systems, asr
-- 
http://mail.python.org/mailman/listinfo/python-list


sys.stdout

2005-09-09 Thread Sébastien Boisgérault
Hi,

The sys.stdout stream behaves strangely in my
Python2.4 shell:

>>> import sys
>>> sys.stdout.write("")
>>> sys.stdout.write("\n")

>>> sys.stdout.write("\n")

>>> sys.stdout.flush()
[...nothing...]

Have you ever seen sys.stdout behave like that ?
Any idea what is wrong with my Python2.4 install
or Linux (Mandrake 10.0) system ?

Cheers,

Sébastien

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


Re: List of integers & L.I.S. (SPOILER)

2005-09-09 Thread Bryan Olson
n00m wrote:
 > Bravo, Bryan!
 > It's incredibly fast!

Not compared to a good implementation for a compiled, low-level
language.

 > But your code got WA (wrong answer).
 > See my latest submission: http://spoj.sphere.pl/status/SUPPER/
 > Maybe you slipped a kind of typo in it? Silly boundary cases?

Hmmm ... wrong answer ... what could ... ah! Here's a problem: I
bomb on the empty sequence. Correction below.

I'm not a perfect programmer, but I like to think I'm a good
programmer. Good programmers own their bugs.

If there's another problem, I need more to go on. From what you
write, I cannot tell where it fails, nor even what submission is
yours and your latest.


--
--Bryan


#!/user/bin/env python

"""
 Python solution to:

 http://spoj.sphere.pl/problems/SUPPER/

 By Bryan Olson
"""

from sys import stdin


def one_way(seq):
 n = len(seq)
 dominators = [n + 1] * (n * 1)
 score = [None] * n
 end = 0
 for (i, x) in enumerate(seq):
 low, high = 0, end
 while high - low > 10:
 mid = (low + high) >> 1
 if dominators[mid] < x:
 low = mid + 1
 else:
 high = mid + 1
 while dominators[low] < x:
 low += 1
 dominators[low] = x
 score[i] = low
 end = max(end, low + 1)
 return score

def supernumbers(seq):
 forscore = one_way(seq)
 opposite = [len(seq) - x for x  in reversed(seq)]
 backscore = reversed(one_way(opposite))
 score = map(sum, zip(forscore, backscore))
 winner = max(score + [0])
 return sorted([seq[i] for i in range(len(seq)) if score[i] == winner])


_ = stdin.readline()
sequence = [int(ch) for ch in stdin.readline().split()]
supers = supernumbers(sequence)
print len(supers)
for i in supers:
 print i,

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


Re: sys.stdout

2005-09-09 Thread tiissa
Sébastien Boisgérault a écrit :
> The sys.stdout stream behaves strangely in my
> Python2.4 shell:
>
> >>> import sys
> >>> sys.stdout.write("")
> >>> sys.stdout.write("\n")
> 
> >>> sys.stdout.write("\n")
> 
> >>> sys.stdout.flush()
> [...nothing...]

There are two things competing on your stdout: what you explicitely ask
the program to write and the prompt and echo of the interpreter.

Try this:

import sys, time
sys.stdout.write('aaa'); sys.stdout.flush(); time.sleep(2)

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


Re: Sockets: code works locally but fails over LAN

2005-09-09 Thread Bryan Olson
n00m wrote:
[...]
 > Btw, the newest oops in the topic's subject is:
 > the code does not work in the case of:
 >
 > sqls_host, sqls_port = '192.168.0.8', 1433
 > proxy_host, proxy_port = '192.168.0.3', 1434
 > ## proxy_host, proxy_port = '127.0.0.1', 1434
 > ## proxy_host, proxy_port = '', 1434
 >
 > I.e. when both Python and vbs script run on one machine
 > (with ip = 192.168.0.3) and SQL Server runs on another
 > (with ip = 192.168.0.8)
 >
 > How namely it does not work:
 > in the idle window only one line is printed:
 >
 > VB_SCRIPT:.
 >
 > that's all. No errors from Python. After timeout expires
 > I get an error message from VBS (smth like preHandShake()
 > failed; I've never seen it before).
 >
 > I just wonder MUST (or not) it work at all (IN THEORY)?

No theoretically-must-or-even-should-work solution is generally
possible. Protocols can thwart proxies by using addresses that
they transfer within their payload-data. That's an essential
feature of some security protocols, such as SSL, and an
unfortunate consequence of some old or badly-designed protocols.

Were I a betting man (outside of Texas Hold'em, where I am), I'd
wager that your problem is more basic. The code you're running,
the settings you're setting, or -- well -- something there, is
not right.


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


Re: List of integers & L.I.S. (SPOILER)

2005-09-09 Thread n00m
Oops Bryan... I've removed my reply that you refer to...
See my previous - CORRECT - reply. The code just times
out... In some sense it doesn't matter right or wrong is
its output.
Btw, what is the complexity of your algorithm?
Currently I'm at work and it's not easy for me to concentrate
on our subject.

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


unicode, C++, python 2.2

2005-09-09 Thread Trond Eivind Glomsrød
I am currently writing a python interface to a C++ library.  Some of the 
functions in this library take unicode strings (UTF-8, mostly) as arguments.

However, when getting these data I run into problem on python 2.2 
(RHEL3) - while the data is all nice UCS4 in 2.3, in 2.2 it seems to be 
UTF-8 on top of UCS4.  UTF8 encoded in UCS4, meaning that 3 bytes of the 
UCS4 char is 0 and the first one contains a byte of the string encoding 
in UTF-8.

Is there a trick to get python 2.2 to do UCS4 more cleanly?

-- 
Trond Eivind Glomsrød
Senior Software Engineer
Scali - www.scali.com
Scaling the Linux Datacenter

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

Re: sys.stdout

2005-09-09 Thread Sébastien Boisgérault
Tiissa,

Thanks for your answer. The execution of  your example leads to a
'aaa' display during 2 secs, before it is erased by the prompt.

This behavior is standard ? The standard output is not supposed
to *concatenate* the 'aaa' and the '>>>' ?

SB

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


Re: dual processor

2005-09-09 Thread Robin Becker
Robin Becker wrote:
> Paul Rubin wrote:
> 

>>
>>This module might be of interest:  http://poshmodule.sf.net
>>
> 
> It seems it might be a bit out of date. I've emailed the author via sf, but 
> no 
> reply. Does anyone know if poshmodule works with latest stuff?
haven't been able to contact posh's author, but this blog entry

http://blog.amber.org/2004/12/10/posh-power/

seems to suggest that posh might not be terribly useful in its current state

"Updated: I spoke with one of the authors, Steffen Viken Valvåg, and his 
comment 
was that Posh only went through proof of concept, and never further, so it has 
a 
lot of issues. That certainly clarifies the problems I’ve had with it. For now, 
I’m going to put it on the back burner, and come back, and perhaps update it 
myself."

-- 
Robin Becker

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


Re: List of integers & L.I.S. (SPOILER)

2005-09-09 Thread n00m
> nor even what submission is yours and your latest.
Oops.. my UserName there is ZZZ.
Submissions in the html table are ordered by date DESC.

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


Inconsistent reaction to extend

2005-09-09 Thread Jerzy Karczmarczuk
Gurus, before I am tempted to signal this as a bug, perhaps
you might convince me that it should be so. If I type

l=range(4)
l.extend([1,2])

l  gives [0,1,2,3,1,2], what else...

On the other hand, try

p=range(4).extend([1,2])

Then, p HAS NO VALUE (NoneType).

With append the behaviour is similar. I didn't try other methods, but
I suspect that it won't improve.


WHY?
It seems that there was already some discussion about consistency and
somebody produced the example:   h = {}.update(l)  which didn't work,
but I wasn't subscribed to this nsgr, I couldn't follow this affair.

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


Re: sys.stdout

2005-09-09 Thread Robert Kern
Sébastien Boisgérault wrote:
> Tiissa,
> 
> Thanks for your answer. The execution of  your example leads to a
> 'aaa' display during 2 secs, before it is erased by the prompt.
> 
> This behavior is standard ? The standard output is not supposed
> to *concatenate* the 'aaa' and the '>>>' ?

FWIW:

Python 2.4.1 (#2, Mar 31 2005, 00:05:10)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.stdout.write('')
>>> sys.stdout.write('\n')

>>>

-- 
Robert Kern
[EMAIL PROTECTED]

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

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

Re: Inconsistent reaction to extend

2005-09-09 Thread Timo

Jerzy Karczmarczuk kirjoitti:

> On the other hand, try
>
> p=range(4).extend([1,2])
>
> Then, p HAS NO VALUE (NoneType).
>
> With append the behaviour is similar. I didn't try other methods, but
> I suspect that it won't improve.
>
>
> WHY?

range(4) returns a list and Python's list.extend() returns None. Extend
is a in-place operation.

-- timo

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


Re: Inconsistent reaction to extend

2005-09-09 Thread Fredrik Lundh
Jerzy Karczmarczuk wrote:

> Gurus, before I am tempted to signal this as a bug, perhaps
> you might convince me that it should be so.

it's not a bug, and nobody should have to convince you about any-
thing; despite what you may think from reading certain slicing threads,
this mailing list is not an argument clinic.

> If I type
>
> l=range(4)
> l.extend([1,2])
>
> l  gives [0,1,2,3,1,2], what else...
>
> On the other hand, try
>
> p=range(4).extend([1,2])
>
> Then, p HAS NO VALUE (NoneType).

(footnote: None is a value in Python.  it can be used to represent "no value",
but it can also be used for other things)

> With append the behaviour is similar. I didn't try other methods, but
> I suspect that it won't improve.
>
> WHY?

because you're saving the return value of "extend", not "range", and "extend"
returns None.

if you split it up like this

l = range(4)
p = l.extend([1, 2])

it should be obvious that "l" and "p" doesn't necessarily contain the same 
thing.

 



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


Re: Inconsistent reaction to extend

2005-09-09 Thread Robert Kern
Jerzy Karczmarczuk wrote:
> Gurus, before I am tempted to signal this as a bug, perhaps
> you might convince me that it should be so. If I type
> 
> l=range(4)
> l.extend([1,2])
> 
> l  gives [0,1,2,3,1,2], what else...
> 
> On the other hand, try
> 
> p=range(4).extend([1,2])
> 
> Then, p HAS NO VALUE (NoneType).
> 
> With append the behaviour is similar. I didn't try other methods, but
> I suspect that it won't improve.
> 
> WHY?

.append(), .extend(), .sort() (as well as .update() for dictionaries)
all are methods whose *only* effect is to modify the object in-place.
They return None as a reminder that they do modify the object instead of
copying the object and then modifying the copy. From the FAQ[1] with
respect to .sort():

"""This way, you won't be fooled into accidentally overwriting a list
when you need a sorted copy but also need to keep the unsorted version
around."""

[1]
http://www.python.org/doc/faq/general.html#why-doesn-t-list-sort-return-the-sorted-list

-- 
Robert Kern
[EMAIL PROTECTED]

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

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


Re: sys.stdout

2005-09-09 Thread Fredrik Lundh
Sébastien Boisgérault wrote:

> Thanks for your answer. The execution of  your example leads to a
> 'aaa' display during 2 secs, before it is erased by the prompt.
>
> This behavior is standard ? The standard output is not supposed
> to *concatenate* the 'aaa' and the '>>>' ?

what "python shell" are you using, and what platform are you running
it on?  here's what I get on a standard Unix console:

>>> import sys
>>> sys.stdout.write("")
>>> sys.stdout.write("\n")

>>> sys.stdout.write("\n")

>>>

 



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

Re: Inconsistent reaction to extend

2005-09-09 Thread Steven D'Aprano
On Fri, 09 Sep 2005 11:47:41 +0200, Jerzy Karczmarczuk wrote:

> Gurus, before I am tempted to signal this as a bug, perhaps
> you might convince me that it should be so. If I type
> 
> l=range(4)
> l.extend([1,2])
> 
> l  gives [0,1,2,3,1,2], what else...

That is correct. range() returns a list. You then call the extend method
on that list. Extend has deliberate side-effects: it operates on the list
that calls it, it does not create a new list.

> On the other hand, try
> 
> p=range(4).extend([1,2])
> 
> Then, p HAS NO VALUE (NoneType).

p has the value None, which is also correct. The extend() method returns
None, it does not create a new list. There is nothing inconsistent about
it. Unintuitive, perhaps. Unexpected, maybe. But not inconsistent.

[snip]

> WHY?

Because creating a new list is potentially very time-consuming and
expensive of memory. Imagine you have a list of 100,000 large objects, and
you want to add one more object to it. The way Python works is that append
and extend simply add that new object to the end of the existing list. The
way you imagined it would work would require Python to duplicate the
entire list, all 100,000 large objects, plus the extra one.



-- 
Steven.

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


python callbacks and windows

2005-09-09 Thread davidstummer
I was wondering if anyone could point me to an example. Currently i
have a c++ program which calls and c++ dll (i created both). The dll
uses SendMessage to pass messages back to the calling .exe, and the
.exe process the messages in it's  Windows Procedure function
WindProc().

What i want is to receive these messages ( the contents of each message
will be plain text), in python using a callback (i think this is what i
need).

I don't know whether (or if it's possible) to implement the windows
procedure and stuff in python, eliminating the need for the .exe
altogether.

or should i do it the other way, to add a callback function in python,
and for the windows procedure in the .exe to call this python callback?

in any case, some simple code examples would be great.

cheers.

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


Re: sys.stdout

2005-09-09 Thread Sébastien Boisgérault

Robert Kern wrote:
> Sébastien Boisgérault wrote:
> > Tiissa,
> >
> > Thanks for your answer. The execution of  your example leads to a
> > 'aaa' display during 2 secs, before it is erased by the prompt.
> >
> > This behavior is standard ? The standard output is not supposed
> > to *concatenate* the 'aaa' and the '>>>' ?
>
> FWIW:
>
> Python 2.4.1 (#2, Mar 31 2005, 00:05:10)
> [GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import sys
> >>> sys.stdout.write('')
> >>> sys.stdout.write('\n')
> 
> >>>
>
> --
> Robert Kern
> [EMAIL PROTECTED]

Robert,

I used to have exactly this behavior on my previous platform ...
In the good old days ;)

Do you know if this behavior is mandatory ? Can I *officially*
 state that my Python interpreter is broken ?

I have already tried to recompile and reinstall Python2.4
without any noticeable difference and the Python2.3 rpm
that I have tested exhibits the same behavior ... Doh !


SB

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


Re: sys.stdout

2005-09-09 Thread Fredrik Lundh
> what "python shell" are you using, and what platform are you running
> it on?  here's what I get on a standard Unix console:
>
 import sys
 sys.stdout.write("")
> >>> sys.stdout.write("\n")
> 
 sys.stdout.write("\n")
> 
> >>>

btw, what does

>>> sys.stdout.encoding

print ?

 



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


Re: sys.stdout

2005-09-09 Thread Sébastien Boisgérault

Fredrik Lundh wrote:
> Sébastien Boisgérault wrote:
>
> > Thanks for your answer. The execution of  your example leads to a
> > 'aaa' display during 2 secs, before it is erased by the prompt.
> >
> > This behavior is standard ? The standard output is not supposed
> > to *concatenate* the 'aaa' and the '>>>' ?
>
> what "python shell" are you using, and what platform are you running
> it on?

The python interpreter is invoked from a bash/konsole session,
inside a KDE env.:

bash$ python
Python 2.4.1 (#4, Sep  8 2005, 19:11:54)
[GCC 3.3.2 (Mandrake Linux 10.0 3.3.2-6mdk)] on linux2
Type "help", "copyright", "credits" or "license" for more
information.
>>>

> here's what I get on a standard Unix console:
>
> >>> import sys
> >>> sys.stdout.write("")
> >>> sys.stdout.write("\n")
> 
> >>> sys.stdout.write("\n")
> 
> >>>
> 
> 

Yep. And I hate you for this ;)

Cheers,

SB

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


Re: sys.stdout

2005-09-09 Thread Sébastien Boisgérault

Fredrik Lundh a écrit :

> > what "python shell" are you using, and what platform are you running
> > it on?  here's what I get on a standard Unix console:
> >
>  import sys
>  sys.stdout.write("")
> > >>> sys.stdout.write("\n")
> > 
>  sys.stdout.write("\n")
> > 
> > >>>
>
> btw, what does
>
> >>> sys.stdout.encoding
>
> print ?
> 
> 


   >>> sys.stdout.encoding
   'ISO-8859-15'


SB

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


Re: encryption with python

2005-09-09 Thread Steven D'Aprano
On Wed, 07 Sep 2005 15:52:19 -0700, James Stroud wrote:

> Also, I should note that the sha function will, to the limits of anyone's 
> ability to analyze it, decouple the information from the hash. So, to be 
> careful, you should keep the algorithm to generate the IDs secret.

Security by obscurity is very little security at all. If there is any
motive at all to reverse-engineer the algorithm, people will reverse
engineer the algorithm. Keeping a weak algorithm secret does not make it
strong.



-- 
Steven.

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


Re: List of integers & L.I.S. (SPOILER)

2005-09-09 Thread Bryan Olson
n00m wrote:
 > Oops Bryan... I've removed my reply that you refer to...
 > See my previous - CORRECT - reply. The code just times
 > out... In some sense it doesn't matter right or wrong is
 > its output.

If my code times out, then they are using an archaic platform.
With respect to my code, you noted:

 Bravo, Bryan! It's incredibly fast!

I myself did not claim 'incredibly fast'; but the code should
beat the 9-second mark on any currently-viable platform, even if
the machine were bought on special at Wal-Mart.

For this kind of low-level challenge, Python cannot compete with
the speed of C/C++, nor Ada, Pascal, ML, PL/1, nor even good
Java implementations. Nevertheless, even in the rare cases in
which efficiency of such computations is an issue, the Python
solution is usually worthy contender, and often the superior
solution.

Human time is more valuable than machine time. Python emphasizes
human-friendly code.


Alas, I would be (and, since I did cite it, was) wrong on that.
My code failed for the empty sequence. Wheter or not that was
one of the test cases, and whether or not it was a consideration
as the problem was defined, it was a bug. As I wrote:

 Good programmers own their bugs.


 > Btw, what is the complexity of your algorithm?

For a list of n items, time Theta(n ln(n)), space Theta(n).


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


Re: visit_decref: Assertion `gc->gc.gc_refs != 0' failed.

2005-09-09 Thread Michael Hudson
"alexLIGO" <[EMAIL PROTECTED]> writes:

> Hi,
>
> I got this error when trying to execute the following python command
> with in a C module:  Py_BuildValue

You get that error immediately on calling that function?

> Do anyone have any idea what this error is about?

You've probably got your refcounting wrong somewhere.

Cheers,
mwh

-- 
  You can lead an idiot to knowledge but you cannot make him
  think.  You can, however, rectally insert the information,
  printed on stone tablets, using a sharpened poker.-- Nicolai
   -- http://home.xnet.com/~raven/Sysadmin/ASR.Quotes.html
-- 
http://mail.python.org/mailman/listinfo/python-list


signal.SIGHUP handling

2005-09-09 Thread Maksim Kasimov

hi, please help to find out where is the problem:

i'm trying to hadle signal.SIGHUP (in unix prompt: kill -HUP )

first of all, i'm trying to do:
signal.signal(signal.SIGHUP, signal.SIG_IGN)

- it works fine (signal ignored)


but if use my handler, than it raises "Interrupted system call":

# all i need to do it is reopen log-file.
# It was opened at the time of pragramm start
def myHandler(signum, frame):
 sys.stdout = sys.stderr = open("mylog.log", "a+")

signal.signal(signal.SIGHUP, myHandler)



-- 
Best regards,
Maksim Kasimov
mailto: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python script under windows

2005-09-09 Thread Harlin Seritt
Hi Jan,

Unfortunately you will have to register it as a service. I am almost
certain there is no other way to do it. However, setting up an
executable as a true Windows Service is extremely tedious. You can try
this utility that I use. You can get it here:
http://www.seritt.org/pub/srvinst13b.exe. I'm probably not supposed to
distribute it, but the site and owners that used to host it have gone
belly up best that I can tell. As with anything, use it at your own
risk. I found it as freeware a few months back.

If you want a decent cheap solution, FireDaemon is pretty good. I think
it's like 30USD but it does a great job and adds a few extra features.

HTH,

Harlin Seritt
Internet Villa: www.seritt.org

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


Re: encryption with python

2005-09-09 Thread Steven D'Aprano
On Wed, 07 Sep 2005 14:31:03 -0700, jlocc wrote:

> Basically I will like to combine a social security number (9 digits)
> and a birth date (8 digits, could be padded to be 9) and obtain a new
> 'student number'. It would be better if the original numbers can't be
> traced back, they will be kept in a database anyways. Hope this is a
> bit more specific, thanks!!!


There are "one-way" encryption functions where the result can't easily be
traced back to the input, but why do you need the input anyway? Here is my
quick-and-dirty student ID algorithm:

last_number_used = 123  # or some other appropriate value

def make_studentID():
global last_number_used
last_number_used = last_number_used + 1
return last_number_used

For a real application, I'd check the database to see if the number has
already been used before returning the number. Also, if you need more
than four digits in your IDs, I'd add a checksum to the end so you can
detect many typos and avoid much embarrassment.

Since the ID is entirely random (a factor of what order the students are
entered into the database) no attacker can regenerate their SSN from their
student ID. At worst, an attacker might be able to work out roughly what
day they were added to the database. Big deal. And if that is a problem,
you might do something like this:

last_number_used = 12345
usable_IDs = []

def make_studentID():
global last_number_used
global usable_IDs
if not usable_IDs:
# generate another batch of IDs in random order
usable_IDs = range(last_number_used, last_number_used + 1000)
usable_IDs.sort(random.random())
last_number_used += 1000
return usable_IDs.pop()

In a real application you would need to store the global variables in a
database, otherwise each time you reload the Python script you start
generating the same IDs over and over again.


-- 
Steven.

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


Re: List of integers & L.I.S. (SPOILER)

2005-09-09 Thread n00m
Oh!
Seems you misunderstand me!
See how the last block in your code should look:

for tc in range(10):
_ = stdin.readline()
sequence = [int(ch) for ch in stdin.readline().split()]
supers = supernumbers(sequence)
print len(supers)
for i in supers:
 print i,


When I submitted it (for the 1st time) without
> for tc in range(10):
the e-judge counted the output of your code as
Wrong Answer; just because the e-judge got an answer
for only the very 1st testcase (I think in it was not
too large input data).

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


subprocess solved all my problems

2005-09-09 Thread Jacek Popławski
In the last week I was working to create script which will read command 
from socket, call it, return result, stdout, stderr and kill it after 
timeout.
After playing with threads, processes, spawns and popens I found 
subprocess module.

To call command I use following construction:

finish=time.time()+self.timeout 
 
self.p=subprocess.Popen(self.command,shell=True,
stdout=subprocess.PIPE,stderr=subprocess.PIPE)
while (self.p.poll()==None) and (time.time()http://mail.python.org/mailman/listinfo/python-list


Re: Inconsistent reaction to extend

2005-09-09 Thread Antoon Pardon
Op 2005-09-09, Steven D'Aprano schreef <[EMAIL PROTECTED]>:
> On Fri, 09 Sep 2005 11:47:41 +0200, Jerzy Karczmarczuk wrote:
>
>> Gurus, before I am tempted to signal this as a bug, perhaps
>> you might convince me that it should be so. If I type
>> 
>> l=range(4)
>> l.extend([1,2])
>> 
>> l  gives [0,1,2,3,1,2], what else...
>
> That is correct. range() returns a list. You then call the extend method
> on that list. Extend has deliberate side-effects: it operates on the list
> that calls it, it does not create a new list.
>
>> On the other hand, try
>> 
>> p=range(4).extend([1,2])
>> 
>> Then, p HAS NO VALUE (NoneType).
>
> p has the value None, which is also correct. The extend() method returns
> None, it does not create a new list. There is nothing inconsistent about
> it. Unintuitive, perhaps. Unexpected, maybe. But not inconsistent.
>
> [snip]
>
>> WHY?
>
> Because creating a new list is potentially very time-consuming and
> expensive of memory. Imagine you have a list of 100,000 large objects, and
> you want to add one more object to it. The way Python works is that append
> and extend simply add that new object to the end of the existing list. The
> way you imagined it would work would require Python to duplicate the
> entire list, all 100,000 large objects, plus the extra one.

This has nothing to do with the need to create a new list.

The extend method could just have returned self. Just as sort and reverse could 
have done so. This would have made it possible to do things like the following:

  lst.sort().reverse()

instead of having to write:

  lst.sort()
  lst.reverse()

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


Re: Inconsistent reaction to extend

2005-09-09 Thread Christophe
Antoon Pardon a écrit :
>>Because creating a new list is potentially very time-consuming and
>>expensive of memory. Imagine you have a list of 100,000 large objects, and
>>you want to add one more object to it. The way Python works is that append
>>and extend simply add that new object to the end of the existing list. The
>>way you imagined it would work would require Python to duplicate the
>>entire list, all 100,000 large objects, plus the extra one.
> 
> 
> This has nothing to do with the need to create a new list.
> 
> The extend method could just have returned self. Just as sort and reverse 
> could 
> have done so. This would have made it possible to do things like the 
> following:
> 
>   lst.sort().reverse()
> 
> instead of having to write:
> 
>   lst.sort()
>   lst.reverse()

This was done on purpose to avoid a second class of problems. The one 
where you forget that reverse modifies the list in place. That second 
class of problems was deemed more dangerous because it works without 
immediate errors.
-- 
http://mail.python.org/mailman/listinfo/python-list


using metaclass __call__ to replace class instance

2005-09-09 Thread Ksenia Marasanova
Hi all,

I am creating some library, and want use "declarative" style in the
subclasses as much as possible, while the actual use will be more
method-like.

Just to give an impression, the library would be something like this:

class Baseclass(object):
# lot's of code goes here...

class Basemethod(object):
foo = None
def get_foo(cls):
return cls.foo
get_foo = classmethod(get_foo)

The subclasses:

class Class(Baseclass):

class method1(Basemethod):
foo = "foo1"

class method2(Basemethod):
foo = "foo2"


And the actual use would be:

print Class.method1()
"foo1"

print Class.method2()
"foo2"

So I thought that the way to accomplish it would be using metaclass
__call__ method:

class BasemethodMeta(type):
def __new__(cls, class_name, bases, new_attrs):
cls = type.__new__(cls, class_name, bases, new_attrs)
new_attrs['__metaclass__'].cls = cls
return cls

def __call__(self):
return self.cls.get_foo()

class Basemethod(object):
__metaclass__ = BasemethodMeta
def get_foo(cls):
return cls.foo
get_foo = classmethod(get_foo)


But it doesn't work as I expected:

print Class.method1()
"foo2"
print Class.method2()
"foo2"

I understand now that because BasemethodMeta is *type* (not sure if
this is the right word)  for all Basemethod classes, it always
returnes the latest declared class... Creating dictionary and putting
all classes in it doesn't make much sense either, because
BasemethodMeta still doesn't know what is the current class that is
being called... (right?)
Now I am stuck. Can anybody show me the light?

Appreciate any help,
-- 
Ksenia
-- 
http://mail.python.org/mailman/listinfo/python-list


how to get the return value of a thread?

2005-09-09 Thread Leo Jay
Dear all,

i would like to get the return value of all threads

e.g.
def foo(num):
if num>10:
return 1
elif num>50:
return 2
else
return 0


after i invoked 
t = thread.start_new_thread(foo,(12,))
how to get the return value of `foo'?

Thanks

-- 
Best Regards,
Leo Jay
-- 
http://mail.python.org/mailman/listinfo/python-list


Python linear algebra module -- requesting comments on interface

2005-09-09 Thread C. Barnes

Hi, I'm in the process of writing a Python linear
algebra module.

The current targeted interface is:

  http://oregonstate.edu/~barnesc/temp/linalg/

The interface was originally based on Raymond
Hettinger's
Matfunc [1].  However, it has evolved so that now it
is
nearly identical to JAMA [2], the Java matrix library.

I am soliticing comments on this interface.

Please post up any criticism that you have.  Even
small
things -- if something isn't right, it's better to fix
it now than later.

I have not made source code available yet, since the
current code is missing the decompositions and doesn't
match the new interface.  I'm in the process of
rewritting the code to match the new interface.  You
can e-mail me and ask for the old code if you're
curious
or skeptical.

[1]. http://users.rcn.com/python/download/python.htm
[2]. http://math.nist.gov/javanumerics/jama/

-
Brief comparison with Numeric
-

Numeric and linalg serve different purposes.

Numeric is intended to be a general purpose array
extension.  It takes a "kitchen sink" approach,
and includes every function which could potentially
be useful for array manipulations.

Linalg is intended to handle real/complex vectors
and matrices, for scientific and 3D applications.
It has a more restricted scope.  Because it is
intended for 3D applications, it is optimized
for dimension 2, 3, 4 operations.

For the typical matrix operations, the linalg
interface is much intuitive than Numeric's.  Real
and imaginary components are always cast to
doubles, so no headaches are created if a matrix
is instantiated from a list of integers.  Unlike
Numeric, the * operator performs matrix
multiplication, A**-1 computes the matrix inverse,
A == B returns True or False, and the 2-norm and
cross product functions exist.

As previously stated, linalg is optimized for
matrix arithmetic with small matrices (size 2, 3, 4).

A (somewhat out of date) set of microbenchmarks [3]
[4]
show that linalg is roughly an order of magnitude
faster than Numeric for dimension 3 vectors and
matrices.

[3].
Microbenchmarks without psyco:
http://oregonstate.edu/~barnesc/temp/
numeric_vs_linalg_prelim-2005-09-07.pdf

[4].
Microbenchmarks with psyco:
http://oregonstate.edu/~barnesc/temp/
numeric_vs_linalg_prelim_psyco-2005-09-07.pdf



__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inconsistent reaction to extend

2005-09-09 Thread Antoon Pardon
Op 2005-09-09, Christophe schreef <[EMAIL PROTECTED]>:
> Antoon Pardon a écrit :
>>>Because creating a new list is potentially very time-consuming and
>>>expensive of memory. Imagine you have a list of 100,000 large objects, and
>>>you want to add one more object to it. The way Python works is that append
>>>and extend simply add that new object to the end of the existing list. The
>>>way you imagined it would work would require Python to duplicate the
>>>entire list, all 100,000 large objects, plus the extra one.
>> 
>> 
>> This has nothing to do with the need to create a new list.
>> 
>> The extend method could just have returned self. Just as sort and reverse 
>> could 
>> have done so. This would have made it possible to do things like the 
>> following:
>> 
>>   lst.sort().reverse()
>> 
>> instead of having to write:
>> 
>>   lst.sort()
>>   lst.reverse()
>
> This was done on purpose to avoid a second class of problems.

I know, but I didn't think it was relevant enough for what I was addressing.

> The one 
> where you forget that reverse modifies the list in place. That second 
> class of problems was deemed more dangerous because it works without 
> immediate errors.

I know this is the explanation that is frequently given, but I find
that rather weak. IMO one could argue that the following code
has the same kind of problem as you mention.

lst2 = lst1
lst1.reverse()

If you forget that lst2 is not a copy of lst1 but just an other
name for the same object you are in trouble too and this too
works without immediate errors. So why should lst.sort().reverse()
be so much more dangerous?

Well it doesn't matter much. Python will probably not change in
this respect in the future, so unless you can give me an
argument I haven't heard before I'll just drop this.

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


Re: Video display, frame rate 640x480 @ 30fps achievable?

2005-09-09 Thread Guenter
Peter Hansen schrieb:
>
> Maybe it would be a good idea to tell us something about the nature of
> the image you'll be displaying (though the fact that it needs a
> cross-hair or something is useful information, for a start).  For
> example, is it a photographic image?  A map?  A drawing?  Is it
> generated dynamically, or is it static?  Do you pan over it, or zoom it,
> or what?
>
> -Peter

It is a video image coming from a camera over a frame grabber board.
The video from the frame grabber is passed to another board that
performs some processing and when it comes back from that board it
needs to be displayed. The joystick allows to specify some regions of
interest in the image, but any zooming is done by the chip on that
second board. So the application needs only to take the image it gets
from that second board, displays it, handle the joystick input and does
some book keeping of where it is with the joystick position and zoom
factor.

It also needs to initiate the frame grabber and the second processing
board, but that should be simple by having some python extensions to
the respective software api provided with the boards. As the data
transfers between the boards are DMA based it should not put any
constrain on the application.

Guenter

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


Re: using metaclass __call__ to replace class instance

2005-09-09 Thread Ksenia Marasanova
2005/9/9, Ksenia Marasanova <[EMAIL PROTECTED]>:
> class BasemethodMeta(type):
> def __new__(cls, class_name, bases, new_attrs):
> cls = type.__new__(cls, class_name, bases, new_attrs)
> new_attrs['__metaclass__'].cls = cls
> return cls
> 
> def __call__(self):
> return self.cls.get_foo()
> 
> class Basemethod(object):
> __metaclass__ = BasemethodMeta
> def get_foo(cls):
> return cls.foo
> get_foo = classmethod(get_foo)
> 
> 
> But it doesn't work as I expected:
> 
> print Class.method1()
> "foo2"
> print Class.method2()
> "foo2"

As usual, it helps to write things down :)

I found an alternative way, probably a lot easier to maintain: return
*instance* of Basemethod class in __new__ method of the
BasemethodMeta, and then use __call__ method of Basemethod class for
all the things.

Python is such fun...  

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


Re: subprocess solved all my problems

2005-09-09 Thread Peter Hansen
Jacek Popławski wrote:
> In the last week I was working to create script which will read command 
> from socket, call it, return result, stdout, stderr and kill it after 
> timeout.
> After playing with threads, processes, spawns and popens I found 
> subprocess module.
[snip rest of answer]

While in general it's greatly appreciated when people post followups 
showing the answer to their problems, by not posting this in response to 
the original thread (and by changing the subject line) you are vastly 
reducing the value of your post.  It's much less likely someone 
searching the archives will ever discover that you did find a solution 
than if you were to go back and repost it to the original thread.

(If you can't find it in your news server, you could probably use Google 
Groups.  I *think* this was the thread you were referring to, but you 
should confirm for yourself:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/94281f5a797489b1/ebca44930a016f74?lnk=st&q=group:comp.lang.python.*+jacek+popen+thread&rnum=2#ebca44930a016f74
)

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


Re: using metaclass __call__ to replace class instance

2005-09-09 Thread Peter Otten
Ksenia Marasanova wrote:

> class BasemethodMeta(type):
> def __new__(cls, class_name, bases, new_attrs):
> cls = type.__new__(cls, class_name, bases, new_attrs)
> new_attrs['__metaclass__'].cls = cls
> return cls
> 
> def __call__(self):
> return self.cls.get_foo()

Though I'm not sure what you are trying to do, I fear it will get more
complicated than necessary. But you do get the desired output if
you change your metaclass to

class BasemethodMeta(type):
def __call__(cls):
# the instance of the metaclass already is a class
# so you can drop the double indirection
return cls.get_foo()

Peter


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


Re: Video display, frame rate 640x480 @ 30fps achievable?

2005-09-09 Thread Guenter
Michael Sparks schrieb:

> Yes.
>
> Co-incidentally we've been looking at video playback this week as well.
> We've been using Pygame with an Overlay surface, and it works fairly well.

I guess Pygame was more suitable overall for your application? I would
just be interested whether you have considered using PyMedia? I knew
about Pygame, but haven't done anything with it yet. So far when I
needed a GUI based application I have used wxPython, but I am not stuck
to that.

> Initially we're testing with simple IYUV raw video data, and it's a good
> idea to use a modern video card supported by your OS, but other than that
> we've not had problems. If you're interested in code, let us know :-)
>
Thanks for the offer. If it is getting serious and I need some jump
start I might come back to you about the code.

[...]


Guenter

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


Timezone and ISO8601 struggles with datetime and xml.utils.iso8601.parse

2005-09-09 Thread Samuel
Hello,

I am trying to convert a local time into UTC ISO8601, then parse it
back into local time. I tried the following:

--
#!/usr/bin/python
import time
import datetime
import xml.utils.iso8601

year   = 2005
month  = 7
day= 22
hour   = 10   # This is localtime
minute = 30

mydatetime = datetime.datetime(year, month, day, hour, minute)
strtime= mydatetime.isoformat()

print "Time: " + strtime  # Localtime too
mytimestamp = xml.utils.iso8601.parse(strtime)
--

How can I convert this into UTC? Commonsense would have me guess that
the date is converted into UTC on construction of the datetime object,
hovever, this doesn't seem to be the case. I also found the
astimezone(tz) method, but where can I obtain the concrete tz object?

The second problem has to do with the ISO8601 parser, which raises the
following error:

--
Traceback (most recent call last):
  File "./timetest.py", line 16, in ?
mytimestamp = xml.utils.iso8601.parse(strtime)
  File "/usr/lib/python2.4/site-packages/_xmlplus/utils/iso8601.py",
line 22, in parse
raise ValueError, "unknown or illegal ISO-8601 date format: " + `s`
ValueError: unknown or illegal ISO-8601 date format:
'2005-07-22T10:30:00'
--

Why does it fail to parse the value returned by the datetime object,
and how can I create a parseable time from the datetime object?

Thanks,
-Samuel

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


Re: Video display, frame rate 640x480 @ 30fps achievable?

2005-09-09 Thread Peter Hansen
Guenter wrote:
> It is a video image coming from a camera over a frame grabber board.
> The video from the frame grabber is passed to another board that
> performs some processing and when it comes back from that board it
> needs to be displayed. The joystick allows to specify some regions of
> interest in the image, but any zooming is done by the chip on that
> second board. So the application needs only to take the image it gets
> from that second board, displays it, handle the joystick input and does
> some book keeping of where it is with the joystick position and zoom
> factor.

Cool!  It sounds to me as though Pygame (perhaps embedded in a wxPython 
app) would be most appropriate.  I know it has direct support for 
joysticks, which I doubt the standard GUI frameworks generally have. 
(Hmm... no, I'm wrong.  At least wxPython does have Joystick support. 
Check it out in the demo.)

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


Re: How to dynamicly define function and call the function?

2005-09-09 Thread bruno modulix
FAN wrote:
> I want to define some function in python script dynamicly and call
> them later, but I get some problem. I have tried the following:
> 
> ##
> # code
> ##
> class test:
> def __init__(self):
> exec("def dfunc(msg):\n\tprint msg\nprint 'exec def function'")
> dfunc('Msg in init ...')   #  it work
>   
> def show(self, msg):
>  dfunc(msg) # doesn't work !
> I think this maybe cause by the scope of function definition, for the
> first call of 'dfunc' in __init__ work.

The exec statement syntax is:
"exec" expression  ["in" expression ["," expression]]

http://www.python.org/doc/2.4.1/ref/exec.html

Without the optional part, the default is to execute the statement in
the current scope. As Python allows defining nested functions, the
dfunc() function is local to the the __init__() function and doesn't
exists in the class scope or the global scope.

class Test2(object):
def __init__(self):
exec "def dfunc(msg):\n\tprint msg\nprint 'exec def function'" \
 in globals()
dfunc('Msg in init ...')   #  it work

def show(self, msg):
dfunc(msg)

d2 = Test2()
d2.show('hello')

But I would not advise you to use exec this way...

> So I tried to define the
> function as a member function of class 'test', but this time even the
> first call doesn't work:
>
> ##
> # code
> ##
> class test:
> def __init__(self):
> exec("def dfunc(self,msg):\n\tprint msg\nprint 'exec def
function'")
> self.dfunc('Msg in init ...')

Here again, for the function to become a method of the class, it has to
be defined in the scope of the class - not in the scope of the
__init__() function:

class Test(object):
exec "def dfunc(self,msg):\n\tprint msg\nprint 'exec def function'"

def __init__(self):
self.dfunc('Msg in init ...')


def show(self, msg):
self.dfunc(msg)

d = Test()
d.show('hello')

> Is there any way I can solve this problem?

The first question that comes to mind is "aren't you trying to solve the
wrong problem ?". If you tell us more about your real use case, we may
point you to others - possibly better - ways of solving it. I don't mean
that it's wrong to use the exec statement, but my experience is that
I've never had a use case for it in 5+ years of Python programming.
Everytime I thought I needed exec, it turned out that there was a much
better solution, usually involving callables, closures, properties,
descriptors, metaclasses, or any combination of...

Also, the fact that you seems to be at lost with Python's inner
mechanisms makes me think you probably don't know other - possibly
better - ways to solve your problem.

If what you need is to "parameterize" a function, closures and nested
functions may be a better solution. A silly exemple:

def makeadder(step):
  def adder(num):
return step + num
  return adder

add1 = makeadder(1)
add3 = makeadder(3)

add1(1)
=> 2
add1(2)
=> 3
add2(1)
=> 3
add2(2)
=> 4

Functions being first-class citizen in Python, it's easy to parameterize
a function with another:

import sys
def buildfun(funtest, funiftrue, funiffalse):
  def built(arg):
if funtest(arg):
print "%s is true for %s" % (funtest, arg)
funiftrue("%s\n" % str(arg))
else:
print "%s is false for %s" % (funtest, arg)
funiffalse("%s\n" % str(arg))
  return built

b = buildfun(lambda arg: arg == 42, sys.stdout.write, sys.stderr.write)
b(42)
b("toto")

Another possibility is to work with callable objects. A function in
Python is just an object (an instance of the function class), and any
object having a __call__() method is callable:

class Greeter(object):
   def __init__(self,
name,
greeting="hello %(who)s, my name is %(name)s"):

 """ greeting is supposed to be a format string
 with %(name)s and %(who)s in it
 """
 self.name = name
 self.greeting = greeting

   def __call__(self, who):
 return self.greeting % {'name': self.name, 'who': who}

Yet another possibility is to go with metaclasses, but I won't give an
exemple here !-)


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


Re: python script under windows

2005-09-09 Thread Benji York
Jan Gregor wrote:
>   I run python script on another computer and want to "survive" that
> script after my logout.

Start at http://www.python.org/windows/win32/#NTServices.
--
Benji York

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


Re: how to get the return value of a thread?

2005-09-09 Thread Fredrik Lundh
Leo Jay wrote:

> i would like to get the return value of all threads
>
> e.g.
> def foo(num):
>if num>10:
>return 1
>elif num>50:
>return 2
>else
>return 0
>
>
> after i invoked
> t = thread.start_new_thread(foo,(12,))
> how to get the return value of `foo'?

threads are subprograms, not functions.  to allow a thread to generate values,
create a shared Queue object and let your threads add stuff to that queue.  an
example:

import threading
import Queue
import time, random

class Worker(threading.Thread):

def __init__(self, index, queue):
self.__index = index
self.__queue = queue
threading.Thread.__init__(self)

def run(self):
# pretend we're doing something that takes 10-100 ms
time.sleep(random.randint(10, 100) / 1000.0)
# pretend we came up with some kind of value
self.__queue.put((self.__index, random.randint(0, 1000)))

queue = Queue.Queue()

for i in range(10):
Worker(i, queue).start() # start a worker

for i in range(10):
print "worker %d returned %d" % queue.get()

 



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


Re: Python linear algebra module -- requesting comments on interface

2005-09-09 Thread Volker Grabsch
C. Barnes wrote:
> Hi, I'm in the process of writing a Python linear
> algebra module.
> 
> The current targeted interface is:
>   http://oregonstate.edu/~barnesc/temp/linalg/

Is this going to become free software. If yes, what license
will you use?


So my suggestions:

In cases like these ones:

random_matrix(m, n=-1)
zero_matrix(m, n=-1)

.. I think it's better to set the default value to "None"
instead of a number:

random_matrix(m, n=None)
zero_matrix(m, n=None)

IMHO, this is more intuitive and more "pythonic".

I also suggest to make the "random function" choosable:

random_matrix(m, n=None, randfunc=random.random)
random_vector(n, randfunc=random.random)

This way it's more easy for those who want another range
of numbers, or want another kind of distribution of the
random numbers.


At the top of your documentation, there is a link "overview",
which is broken:

See _overview_ for a quick start.


Greets,

Volker

-- 
Volker Grabsch
---<<(())>>---
\frac{\left|\vartheta_0\times\{\ell,\kappa\in\Re\}\right|}{\sqrt
[G]{-\Gamma(\alpha)\cdot\mathcal{B}^{\left[\oint\!c_\hbar\right]}}}
-- 
http://mail.python.org/mailman/listinfo/python-list


is interactive mode same as calculator mode?

2005-09-09 Thread Alex
Loking at Rossum's tutorial I've seen that he sometimes uses the
expression "interactive mode" and sometimes "calculator mode". Or these
concepts same?

I've made the following assertion.

"When Python prompts for the next command with the primary prompt ">>>
", the interpreter is said to be in an interactive mode, or in a
calculator mode. In interactive mode, the Python interpreter acts as a
simple calculator: you can type an expression at it and it will write
back the value of that expression."

Is this correct or incorrect?

Alex

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


Re: is interactive mode same as calculator mode?

2005-09-09 Thread Peter Hansen
Alex wrote:
> Loking at Rossum's tutorial I've seen that he sometimes uses the
> expression "interactive mode" and sometimes "calculator mode". Or these
> concepts same?

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


ANN: pythonutils 0.2.1

2005-09-09 Thread Fuzzyman
Hello Python Folk,

pythonutils 0.2.1 is now available.

This is a *major* update since 0.1.0

http://www.voidspace.org.uk/python/modules.shtml#pythonutils
http://www.voidspace.org.uk/cgi-bin/voidspace/downman.py?file=pythonutils-0.2.1.win32.zip
http://www.voidspace.org.uk/cgi-bin/voidspace/downman.py?file=pythonutils-0.2.1.zip

What is pythonutils ?
=

The Voidspace Pythonutils package is a simple way of installing the
Voidspace collection of modules. Several of the Voidspace Projects
depend on these modules. They are also useful in their own right of
course. They are primarily general utility modules that simplify common
programming tasks in Python.


The modules included are all fully documented. They are :

ConfigObj - simple config file handling
validate - validation and type conversion system
listquote - string to list conversion
StandOut - simple logging and output control object
pathutils - for working with paths and files
cgiutils - cgi helpers
urlpath - functions for handling URLs
odict - Ordered Dictionary Class

Note: These modules have changed quite significantly since 0.1.0. Only
install if you're sure this won't break your applications :-)


What Has Changed Since 0.1.0 ?
==

The *major* change is that *all* these modules now have their own
online documentation (and almost all of them have been refactored).
There are links to them all via :

http://www.voidspace.org.uk/python/pythonutils.html#documentation

2005/09/04 - Version 0.2.1
--

Version 0.2.1

Updated to ConfigObj 4.0.0 beta 4

This contains bugfixes to ConfigObj.

2005/08/31 - Version 0.2.0
--

Refactored and redocumented.

**Major** update to ConfigObj and validate.

Removed caseless, and added odict and urlpath.

* ConfigObj   4.0.0 beta 3
* listquote   1.4.0
* validate0.2.0
* StandOut2.1.0
* pathutils   0.2.1
* cgiutils0.3.2
* odict   0.1.0
* urlpath 0.1.0

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


Re: using metaclass __call__ to replace class instance

2005-09-09 Thread Ksenia Marasanova
2005/9/9, Peter Otten <[EMAIL PROTECTED]>:
> Ksenia Marasanova wrote:
> 
> > class BasemethodMeta(type):
> > def__new__(cls,class_name,bases,new_attrs):
> > cls=type.__new__(cls,class_name,bases,new_attrs)
> > new_attrs['__metaclass__'].cls=cls
> > returncls
> >
> > def__call__(self):
> > returnself.cls.get_foo()
> 
> Though I'm not sure what you are trying to do, I fear it will get more
> complicated than necessary. But you do get the desired output if
> you change your metaclass to
> 
> class BasemethodMeta(type):
> def __call__(cls):
> # the instance of the metaclass already is a class
> # so you can drop the double indirection
> return cls.get_foo()
> 
> Peter
> 


Man.. that's easy. Thanks a lot, Peter.

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


Re: redefining a function through assignment

2005-09-09 Thread Terry Hancock
On Thursday 08 September 2005 06:56 pm, Daniel Britt wrote:
> This will print out 'new method'. If any other instance of mod1.test is 
> created calling func1, func1 will always reference the newFunc function. 
> This is less than desirable to say the least.

Well, actually it's very desireable, but I'm sorry it surprised you. ;-)

ISTM, you're just discovering that functions are "first-class objects"
in Python.  That's going to be the expectation of anyone familiar with
programming in the language.

> Is there any way of preventing 
> this from ever happening? I searched around for quite a while and I haven't 
> been able to find anyone who has a solution. 

Please don't try to delete this functionality -- you will cause equally
unpleasant surprises for anyone trying to use your package.

> The reason I am asking this is 
> b/c I want to build an application in python that has plugins. I want to 
> make sure that a programmer could not accidently or intentionally clobber 
> over another plugins code, which they could easily do. Any help would be 
> appreciated. Thanks

The solution is to keep each plugin in its own namespace.

More protection than that shouldn't be attempted. Even if a plugin
does manage to clobber another plugin's code, it won't be unintentional.
You don't know what that programmer is attempting to do. You can always
regard the plugin as "broken" or "dangerous" or "noncompliant" if it
does this sort of thing and document the point.

But how can you be sure there isn't a good reason for it if the plugin
author feels it was necessary?

It's very unlikely that they will do anything of the sort if you just
keep each plugin module in it's own namespace (which basically means
not using any "from plugin_mod import *" but rather "import plugin_mod").

This approach has worked for me in the past.

HTH,
Terry

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

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


Re: redefining a function through assignment

2005-09-09 Thread Peter Hansen
> Daniel Britt wrote:
> 
>> I am new to Python so if there is an obvious answer to my question 
>> please forgive me. Lets say I have the following code in mod1.py
>>
>> class test:
>>def func1(self):
>>   print 'hello'
>>
>>
>> Now lets say I have another file called main.py:
>>
>> import mod1
>>
>> inst = mod1.test()
>> inst.func1()
>>
>>
>> This will print out hello. Now if I added the following to main:
>> def newFunc(var):
>>print 'new method'
>>
>> mod1.test.func1 = newFunc

If what you're really saying is that you would like to be able to change 
the method that is called *for the instance named 'inst'*, but without 
the problem you mentioned, then there is a way, and you don't need the 
complexity of meta-classes and such.

 >>> class test:
...   def func1(self):
... print 'hello'
...
 >>> inst = test()
 >>> inst.func1()
hello
 >>>
 >>> def newFunc(self):
...   print 'new method'
...
 >>> import new
 >>> inst.func1 = new.instancemethod(newFunc, test)
 >>> inst.func1()
new method
 >>> inst2 = test()
 >>> inst2.func1()
hello


(This might not have anything to do with your real use case, but since 
"plugin" covers a lot of territory, this might solve whatever problem 
you thought you would have.  If not, well, at least it's probably new to 
you and might be useful in the future. :-)  )

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


Re: Inconsistent reaction to extend

2005-09-09 Thread Steve Holden
Fredrik Lundh wrote:
> Jerzy Karczmarczuk wrote:
> 
> 
>>Gurus, before I am tempted to signal this as a bug, perhaps
>>you might convince me that it should be so.
> 
> 
> it's not a bug, and nobody should have to convince you about any-
> thing; despite what you may think from reading certain slicing threads,
> this mailing list is not an argument clinic.
> 
Yes it is :)

then-there's-the-£10-argument-next-door-ly y'rs  - steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

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


Re: python script under windows

2005-09-09 Thread Larry Bates
Making a Python program into a service isn't all that "tedious".
Get a copy of Mark Hammonds "Python Programming on Win32" which
contains excellent examples on how to do this.  I've written
several and after the first one, it is quite easy to do.

-Larry Bates

Harlin Seritt wrote:
> Hi Jan,
> 
> Unfortunately you will have to register it as a service. I am almost
> certain there is no other way to do it. However, setting up an
> executable as a true Windows Service is extremely tedious. You can try
> this utility that I use. You can get it here:
> http://www.seritt.org/pub/srvinst13b.exe. I'm probably not supposed to
> distribute it, but the site and owners that used to host it have gone
> belly up best that I can tell. As with anything, use it at your own
> risk. I found it as freeware a few months back.
> 
> If you want a decent cheap solution, FireDaemon is pretty good. I think
> it's like 30USD but it does a great job and adds a few extra features.
> 
> HTH,
> 
> Harlin Seritt
> Internet Villa: www.seritt.org
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


NDMP Library?

2005-09-09 Thread Jesse Noller
Does anyone know of a python module/library for communicating with the
NDMP (ndmp.org) protocol? I'm doing some research and anything would
be a great help, thanks!

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


New docs for Leo

2005-09-09 Thread Edward K. Ream
Leo has new documentation: simpler, clearer, shorter. See:
http://webpages.charter.net/edreamleo/leo_TOC.html

Everything a newbie needs to know about Leo is at:
http://webpages.charter.net/edreamleo/intro.html

Please post any questions, comments or corrections here:
http://sourceforge.net/forum/forum.php?forum_id=10226

Edward

Edward K. Ream   email:  [EMAIL PROTECTED]
Leo: http://webpages.charter.net/edreamleo/front.html



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


Re: What's the difference between VAR and _VAR_?

2005-09-09 Thread S. D. Rose
I can't get the value of the variable (out of the class function) if it has
two leading underscores.

-Dave

>>> class encrypt:
 def encrypt(self, userValue):
  self.initialNumber = userValue
  self.__secretSeed = 7
  return self.initialNumber * self.__secretSeed

>>> enc = encrypt()
>>> enc.encrypt(5)
35
>>> print enc.initialNumber
5
>>> print enc.__secretSeed

Traceback (most recent call last):
  File "", line 1, in -toplevel-
print enc.__secretSeed
AttributeError: encrypt instance has no attribute '__secretSeed'



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


Re: python script under windows

2005-09-09 Thread Roger Upole
You can use the Task Scheduler to run a script persistently if you
don't need the capabilities of the service framework.

 Roger

"Jan Gregor" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
> Hello
>
>  I run python script on another computer and want to "survive" that
> script after my logout. the script also uses drive mapping to network drive.
>
>  Can you help me ?  Or better is there some info for unix person how
> to survive with python on windows ;-)
>
> thanks,
> jan gregor 



== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ 
Newsgroups
= East and West-Coast Server Farms - Total Privacy via Encryption =
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question from beginner

2005-09-09 Thread dario
Dennis, my english is not too good...

About first question this is the implementation of SER class (this is
freeware from the source www.telit.it):

#Telit Extensions
#
#Copyright © 2004, DAI Telecom S.p.A.
#All rights reserved.
#
#Redistribution and use in source and binary forms, with or without
#modification, are permitted provided that the following conditions
#are met:
#
#Redistributions of source code must retain the above copyright notice,

#this list of conditions and the following disclaimer.
#
#Redistributions in binary form must reproduce the above copyright
#notice, this list of conditions and the following disclaimer in
#the documentation and/or other materials provided with the
distribution.
#
#
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS
#IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
#TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
#PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR
#CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
#EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
#PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
#LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
#NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
#SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
import time
import serial

freeser = serial.Serial('COM4', 9600, timeout=0, rtscts=1)

def send(string):
  global freeser
  freeser.write(string)
  result = 1
  return result

def receive(timeout):
  global freeser
  sectimeout = int((timeout+5)/10)
  time.sleep(sectimeout)
  string = freeser.read(512)
  return string

def read():
  global freeser
  string = freeser.read(512)
  return string

def sendbyte(byte):
  global freeser
  string = chr(byte)
  freeser.write(string)
  result = 1
  return result

def receivebyte(timeout):
  global freeser
  sectimeout = int((timeout+5)/10)
  time.sleep(sectimeout)
  string = freeser.read(1)
  if string == '':
result = -1
  else:
result = ord(string)
  return result

def readbyte():
  global freeser
  string = freeser.read(1)
  if string == '':
result = -1
  else:
result = ord(string)
  return result

def SetSpeed(speed):
  global freeser
  if speed == '9600':
freeser.setBaudrate(9600)
result = 1
  elif speed == '19200':
freeser.setBaudrate(19200)
result = 1
  elif speed == '115200':
freeser.setBaudrate(115200)
result = 1
  else:
result = -1
  return result

This is the serial class

class Serial(serialutil.FileLike):
def __init__(self,
 port,  #number of device, numbering
starts at
#zero. if everything fails, the
user
#can specify a device string,
note
#that this isn't portable
anymore
 baudrate=9600, #baudrate
 bytesize=EIGHTBITS,#number of databits
 parity=PARITY_NONE,#enable parity checking
 stopbits=STOPBITS_ONE, #number of stopbits
 timeout=None,  #set a timeout value, None to
wait forever
 xonxoff=0, #enable software flow control
 rtscts=0,  #enable RTS/CTS flow control
 ):
"""initialize comm port"""

self.timeout = timeout

if type(port) == type(''):   #strings are taken directly
self.portstr = port
else:
self.portstr = device(port)

try:
self.hComPort = win32file.CreateFile(self.portstr,
   win32con.GENERIC_READ | win32con.GENERIC_WRITE,
   0, # exclusive access
   None, # no security
   win32con.OPEN_EXISTING,
   win32con.FILE_ATTRIBUTE_NORMAL |
win32con.FILE_FLAG_OVERLAPPED,
   None)
except Exception, msg:
self.hComPort = None#'cause __del__ is called anyway
raise serialutil.SerialException, "could not open port: %s"
% msg
# Setup a 4k buffer
win32file.SetupComm(self.hComPort, 4096, 4096)

#Save original timeout values:
self.orgTimeouts = win32file.GetCommTimeouts(self.hComPort)

#Set Windows timeout values
#timeouts is a tuple with the following items:
#(ReadIntervalTimeout,ReadTotalTimeoutMultiplier,
# ReadTotalTimeoutConstant,WriteTotalTimeoutMultiplier,
# WriteTotalTimeoutConstant)
if timeout is None:
timeouts = (0, 0, 0, 0, 0)
elif timeout == 0:
timeouts = (win32con.MAXDWORD, 0, 0, 0, 0)
else:
#timeouts = (0, 0, 0, 0, 0) #timeouts are done with
WaitForSingleObject
timeouts = (0, 0,

Python linear algebra module -- requesting comments on interface

2005-09-09 Thread barnesc

Thanks for your commentary.

The module will be public domain.

I fixed the broken link (epydoc was inserting backslashes in URLs),
changed the default arguments to None as you suggested, and added
a randfunc=None and randargs=() default argument for random_matrix()
and random_vector() (the matrix is populated with randfunc(*randargs)
entries if randfunc is not None).

 - Connelly Barnes
   E-mail address: 'Y29ubmVsbHliYXJuZXNAeWFob28uY29t\n'.
   decode('base64')

>C. Barnes wrote:
>> Hi, I'm in the process of writing a Python linear
>> algebra module.
>>
>> The current targeted interface is:
>>   http://oregonstate.edu/~barnesc/temp/linalg/
>
>Is this going to become free software. If yes, what license
>will you use?
>
>
>So my suggestions:
>
>In cases like these ones:
>
>   random_matrix(m, n=-1)
>   zero_matrix(m, n=-1)
>
>.. I think it's better to set the default value to "None"
>instead of a number:
>
>   random_matrix(m, n=None)
>   zero_matrix(m, n=None)
>
>IMHO, this is more intuitive and more "pythonic".
>
>I also suggest to make the "random function" choosable:
>
>   random_matrix(m, n=None, randfunc=random.random)
>   random_vector(n, randfunc=random.random)
>
>This way it's more easy for those who want another range
>of numbers, or want another kind of distribution of the
>random numbers.
>
>
>At the top of your documentation, there is a link "overview",
>which is broken:
>
>   See _overview_ for a quick start.
>
>
>Greets,
>
>   Volker
>
>--
>Volker Grabsch
-- 
http://mail.python.org/mailman/listinfo/python-list


How to upgrade to 2.4.1 on Mac OS X tiger

2005-09-09 Thread stri ker
Has anyone here upgraded from 2.3 to 2.4 on Tiger?
If so how'd ya do it?

TIA,
Kevin
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unicode, C++, python 2.2

2005-09-09 Thread jepler
Python comes in two flavors.  In one, sys.maxunicode is 65535 and Py_UNICODE is
a 16-bit type, and in the other, sys.maxunicode is 1114111 and Py_UNICODE is a
32-bit type.  This is selected at compile time, and RedHat has chosen in some
versions to compile for sys.maxunicode == 1114111.

By using the Py_UNICODE typedef, you generally don't have to worry about this
distinction.  Here is some code that works on RedHat 9's Python 2.2
(sys.maxunicode == 1114111) and a manually built Python 2.3 (sys.maxunicode ==
65535).

#include 

PyObject *f(PyObject *self, PyObject *o) {
if(PyString_Check(o)) {
char *c = PyString_AS_STRING(o);
int sz = PyString_GET_SIZE(o);
int i;
printf("   Byte string: ");
for(i=0; i

pgpDEx2W2IVa0.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Interactive use of Help with class/instance data

2005-09-09 Thread Colin J. Williams
help(instance.property) gives the same information as help(instance) but
help(cls.property) gives information specific to the property.

Is this a bug?

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


re module help

2005-09-09 Thread rattan
I am trying to make prescript-2.2 (old python based psotscript to plain
text converter).
It gives the following dprecation message

/local/users/ishwar/prescript-2.2/misc.py:23: DeprecationWarning: the
regex module is deprecated; please use the re module
  import os, regex, sys, string

if I start replacing regex by re I get stuck at replacement of
   regex.symcomp() and regex.pattern()

methods. The are not in re module.

Is there a solution?
-ishwar

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


Re: Inconsistent reaction to extend

2005-09-09 Thread Terry Hancock
On Friday 09 September 2005 08:29 am, Steve Holden wrote:
> Yes it is :)

That's not an argument! That's just a contradiction.

I'm not payin' for this!


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

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


Re: Python linear algebra module -- requesting comments on interface

2005-09-09 Thread Martin Miller
Since one of the module's targeted applications is for 3D applications,
I think there should be some specific support for applying the
Matrix-vector product operation to a sequence of vectors instead of
only one at a time -- and it should be possible to optimize the
module's code for this common case.

I'd also like to see some special specific errors defined and raised
from the Matrix det(), inverse(), and transpose() methods when the
operation is attempted on an ill-formed matrices (e.g. for non-square,
non-invertible, singular cases). This would allow client code to handle
errors better.

Very nice work overall, IMHO.

Best,
-Martin

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


Why do Pythoneers reinvent the wheel?

2005-09-09 Thread Stefano Masini
On 8 Sep 2005 08:24:50 -0700, Fuzzyman <[EMAIL PROTECTED]> wrote:
> What is pythonutils ?
> =
> ConfigObj - simple config file handling
> validate - validation and type conversion system
> listquote - string to list conversion
> StandOut - simple logging and output control object
> pathutils - for working with paths and files
> cgiutils - cgi helpers
> urlpath - functions for handling URLs
> odict - Ordered Dictionary Class

Fuzzyman, your post reminded me of something I can't stop thinking
about. Please don't take this as a critique on your work. I place
myself on the same side of yours.
I just wanted to share this thought with everybody had an opinion about it.

I wonder how many people (including myself) have implemented their own
versions of such modules, at least once in their pythonic life. I
indeed have my own odict (even same name! :). My own pathutils
(different name, but same stuff). My own validate... and so forth.

This is just too bad.
There are a few ares where everybody seems to be implementing their
own stuff over and over: logging, file handling, ordered dictionaries,
data serialization, and maybe a few more.
I don't know what's the ultimate problem, but I think there are 3 main reasons:
1) poor communication inside the community (mhm... arguable)
2) lack of a rich standard library (I heard this more than once)
3) python is such an easy language that the "I'll do it myself" evil
side lying hidden inside each one of us comes up a little too often,
and prevents from spending more time on research of what's available.

It seems to me that this tendency is hurting python, and I wonder if
there is something that could be done about it. I once followed a
discussion about placing one of the available third party modules for
file handling inside the standard library. I can't remember its name
right now, but the discussion quickly became hot with considerations
about the module not being "right" enough to fit the standard library.
The points were right, but in some sense it's a pity because by being
in the stdlib it could have had a lot more visibility and maybe people
would have stopped writing their own, and would have begun using it.
Then maybe, if it was not perfect, people would have begun improving
it, and by now we would have a solid feature available to everybody.

mhm... could it be a good idea to have two versions of the stdlib? One
stable, and one testing, where stuff could be thrown in without being
too picky, in order to let the community decide and improve?

Again, Fuzzyman, your post was just the excuse to get me started. I
understand and respect your work, also because you put the remarkable
effort to make it publicly available.

That's my two cents,
stefano
-- 
http://mail.python.org/mailman/listinfo/python-list


icmp sniffer with pcapy module

2005-09-09 Thread billiejoex
Hi all. The source below is a simple icmp sniffer made with pcapy.
To decode packets I'm using the EthDecoder() function that returns a 
rapresentation of the packet including ICMP type, ICMP code, IP source and 
IP destination.
All I need, now, is to get the ip src and ip dst only but I don't know how 
to do it.
I tried to use the IPDecoder instead of EthDecoder to decode packets but 
misteriously it doesn't works.
Does anybody have a good idea about how to get this values only?

Best regards

#!/usr/bin/python
### sniffer
import pcapy
from impacket.ImpactDecoder import *

def recv_pkts(hdr, data):
x = EthDecoder().decode(data)
print x

def get_int():
devs = pcapy.findalldevs()
i=0
for eth in devs:
print " %d - %s" %(i,devs[i])
i+=1
sel=input(" Select interface: ")
dev=devs[sel]
return dev

dev = get_int()
p = pcapy.open_live(dev, 1500, 0, 100)
p.setfilter('icmp')
print "Listening on eth: net=%s, mask=%s\n" % (p.getnet(), p.getmask())
p.loop(-1, recv_pkts) 


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


Create new instance of Python class in C

2005-09-09 Thread Sybren Stuvel
Hi people,

I'm creating a program that can solve and create Sudoku puzzles. My
creation function needs to make a lot of copies of a puzzle. Until
now, I used copy.deepcopy(), but that's too slow. I want to implement
such a copying function in C and use that instead. My idea about this
is:

- Get the data from a puzzle (a list containing lists containing
  strings) and make a copy of it. That's coded already.

- Create a new SodokuPuzzle instance and assign the data to it.

That last step can be done by passing the data to the constructor, so
that's easy too once I know how to do that in C. My question is: how
do I create a new instance in C of a class written in Python? I've
searched Google, but found nothing of help.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: visit_decref: Assertion `gc->gc.gc_refs != 0' failed.

2005-09-09 Thread Tim Peters
[alexLIGO]
> I got this error when trying to execute the following python command
> with in a C module:  Py_BuildValue
>
> Do anyone have any idea what this error is about?

Just the comment on the failing assert:

assert(gc->gc.gc_refs != 0); /* else refcount was too small */

There are more pointers to the object than the object's reference
count says there are.  That's fatally bad.  Probably due to a missing
Py_INCREF, possibly due to an "extra" Py_DECREF.

> And does anyone have any idea how to debug a python script?

You need to debug C code here, not Python code.  It's unlikely that
the problem is in C code that ships with Python; it's far more likely
to be in your C code, or in C code from a third-party extension
module.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP-able? Expressional conditions

2005-09-09 Thread Terry Hancock
On Thursday 08 September 2005 04:30 am, Paul Rubin wrote:
> Terry Hancock <[EMAIL PROTECTED]> writes:
> > > Not the same at all.  It evaluates both the true and false results,
> > > which may have side effects.
> > 
> > If you are depending on that kind of nit-picking behavior,
> > you have a serious design flaw, a bug waiting to bite you,
> > and code which shouldn't have been embedded in an expression
> > in the first place.
> 
> Are you kidding?  Example (imagine a C-like ?: operator in Python):
> 
>x = (i < len(a)) ? a[i] : None# make sure i is in range
>
> Where's the design flaw? 

It's a syntax error. See?

>>> x = (i < len(a)) ? a[i] : None# make sure i is in range
  File "", line 1
x = (i < len(a)) ? a[i] : None# make sure i is in range
 ^
SyntaxError: invalid syntax

That's a pretty serious design flaw.

You see, I'm not discussing an imaginary Python interpreter here.

> Where's the bug waiting to bite?  That's a
> completely normal use of a conditional expression.  If the conditional
> expression works correctly, this does the right thing, as intended.
> If both results get evaluated, it throws a subscript out of range
> error, not good.

No. It throws a syntax error, as I demonstrated.

> Every time this topic comes up, the suggestions that get put forth are
> far more confusing than just adding conditional expressions and being
> done with it.

If it's so easy, then do it, and quit whining. You could easily
have published an alternative "better" ternary function instead
of just complaining that mine "isn't right", by which you mean
only that it doesn't work exactly as it would in C, or in your
imaginary Python interpreter.

Myself, I just can't see how writing:

if (i < len(a)): x = a[i]
else:x = None

is gonna kill you.  It's also not by any means a solution so obvious
that I would not want to see the special case on it's own line.

After all, in most cases where I would use a limiter like this, I'd
want the special case to be handled by something other than None. Or
I'd want to raise an exception, even.  Which, come to think of it,
I wouldn't even have to code, would I?  The thing is, if you return
None like this, you won't be able to treat it the same as the normal
output, so you're still going to have to check the result. Which just
means you've moved the complexity upwards  (almost always a bad move 
which replicates effort -- another design flaw).

If you want to go and argue with Guido over this, go ahead. I'm all
for a ternary operator.

But IIRC, that parrot is dead. It's an ex-parrot.

Hence, I'm not big on discussing what sort of fake wings we can
glue onto it. It isn't that hard to live without a ternary operator.

You're just trying to program a C idiom in Python and cussing the
fact that it doesn't translate.  Sorry, loads of stuff doesn't, but
it doesn't necessarily make that a design flaw.

But if you really must avoid evaluating the results in your hand-crafted
ternary function, that is of course, also possible.  Go ahead and
write it and share it here, please.

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

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


Launching Python programs from Linux shell script

2005-09-09 Thread Ernesto
Does anyone know how to start Python program(s) from a Linux shell
script?  Is it just 

$python myscript.py

??

Thanks,

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


Re: python script under windows

2005-09-09 Thread Grig Gheorghiu
Jan,

Here's what I did to run a Python script (let's call it myscript.py) as
a service:

1. Install Win2K Resource Kit.

2. Run instsrv to install srvany.exe as a service with the name
myscript:

C:\Program Files\Resource Kit\instsrv myscript "C:\Program
Files\Resource Kit\srvany.exe"

3. Go to Computer Management->Services and make sure myscript is listed
as a service. Also make sure the Startup Type is Automatic.

4. Create a myscript.bat file with the following contents in e.g.
C:\pyscripts:

C:\Python23\python C:\pyscripts\myscript.py

5. Create new registry entries for the new service.
- run regedt32 and go to the
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\myscript entry
- add new key (Edit->Add Key) called Parameters
- add new entry for Parameters key (Edit->Add Value) to set the
Application name => Name should be Application, Type should be
REG_SZ, Value should be path to myscript.bat, i.e.
C:\pyscripts\myscript.bat
- add new entry for Parameters key (Edit->Add Value) to set the working
directory => Name should be AppDir, Type should be
REG_SZ, Value should be path to pyscripts directory, i.e. C:\pyscripts

6. Test starting and stopping the myscript service in Computer
Management->Services.

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


Where do .pyc files come from?

2005-09-09 Thread Ernesto
I noticed in a python distribution there were 5 python files (.py) and
5 other files with the same name, but with the extension .pyc .  Is
this some kind of compiled version of the .py files.  Thanks,

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


Re: DrPython debugger

2005-09-09 Thread Colin J. Williams
Pandiani wrote:
> Thanks for repy.
> However, I found SimpleDebugger 0.5 from sourceforge.net as plugin for
> drPython but I'm getting error message because DrPython cannot load
> module drPythonChooser and it seems that the module is removed from
> latest version of drPython. Or maybe I wasn't able to figure out how to
> install it...:)
> 
You might consider Mark Hammond's PythonWin.  Debugger and editor in one 
package.

Boa-constructor also has a good debugger/editor.

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


Re: sys.stdout

2005-09-09 Thread Jorgen Grahn
On 9 Sep 2005 03:40:58 -0700, Sébastien Boisgérault <[EMAIL PROTECTED]> wrote:
>
> Fredrik Lundh wrote:
>> Sébastien Boisgérault wrote:
>>
>> > Thanks for your answer. The execution of  your example leads to a
>> > 'aaa' display during 2 secs, before it is erased by the prompt.
>> >
>> > This behavior is standard ? The standard output is not supposed
>> > to *concatenate* the 'aaa' and the '>>>' ?
>>
>> what "python shell" are you using, and what platform are you running
>> it on?
>
> The python interpreter is invoked from a bash/konsole session,
> inside a KDE env.:

So, it's either of these things:
- konsole and its bugs/features
- your $TERM settings
- your readline and its bugs/features
- your ~/.inputrc settings (see the readline man page)

It's hard to say what's right and wrong really, and whose fault it is.
I'm pretty sure it's not Python.  What happens if you try bash?

  tuva:~> bash
  [EMAIL PROTECTED]:~$ echo -n 'foo'
  [EMAIL PROTECTED]:~$

/Jorgen

-- 
  // Jorgen GrahnR'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Py2exe-users] py2exe 0.6.2 released

2005-09-09 Thread Thomas Heller
Ray Schumacher <[EMAIL PROTECTED]> writes:

> First, Thanks again for the update.
>
> At 08:55 AM 9/7/2005, Thomas Heller wrote:
>
>>  This part of the code is distributed under the MPL 1.1, so this
>>  license is now pulled in by py2exe.
>
> As I read it, it seems that I need to include an Exibit A
> http://www.mozilla.org/MPL/MPL-1.1.html#exhibit-a
> filled out so that it includes the py2exe home, as well as Python, probably.
> It could be put in the Zip or Rar to be viewed on extraction.
> Does this sound correct?

Probably.  But IANAL.

Thomas

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


Re: Where do .pyc files come from?

2005-09-09 Thread tooper
Yes, these are bytecode files.
If you run "python -o", you should also get .pyo files for optimized
bytecode. As long as you do not modify the source code, python directly
reuse the bytecode (that's also a way to distribute script without
source code to avoid your users fiddling in thecode and make it not
work properly - even if any advanced user will know how to revert back
to source code)

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


Re: Launching Python programs from Linux shell script

2005-09-09 Thread tooper
Yes, provided your python interpreter is installed, and in your path
("$ whereis python" should give you something like /usr/bin/python or
/usr/local/bin/python)

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


Re: Launching Python programs from Linux shell script

2005-09-09 Thread tooper
Yes, provided your python interpreter is installed, and in your path
("$ whereis python" should give you something like /usr/bin/python or
/usr/local/bin/python)

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


Re: Video display, frame rate 640x480 @ 30fps achievable?

2005-09-09 Thread Michael Sparks
Guenter wrote:
> Michael Sparks schrieb:
>> Yes.
>>
>> Co-incidentally we've been looking at video playback this week as
>> well. We've been using Pygame with an Overlay surface, and it works
>> fairly well.
>
> I guess Pygame was more suitable overall for your application? 

It's not really that, it's just that it was the easiest most obvious
(and we've found portable) approach to getting the video onscreen.
You create an overlay object and simply throw decoded YUV data at
in and don't worry too much.

We can generally mix and match UI's happily at the moment with our
work, so we can have tkinter and pygame side by side for example.

> I would just be interested whether you have considered using
> PyMedia? 

We did look at it, but found sufficient numbers of problems to decide
that it might be worth coming back to at a later point in time. Also
we kept hitting issues on 64-bit machines which didn't really help. API
changes also invalidated some of the examples causing confusion (I
wasn't the person directly working on it). 

That said I've heard enough people say enough good things about it to
suggest that don't take our experience as the best example - I suspect
it's far from the best example. (I wish we had more time to try and
help fix it!)

(We've decided to wrap dirac instead for now)

>> Initially we're testing with simple IYUV raw video data, and it's a
>> good idea to use a modern video card supported by your OS, but other
>> than that we've not had problems. If you're interested in code, let
>> us know :-)
>>
> Thanks for the offer. If it is getting serious and I need some jump
> start I might come back to you about the code.

No problem.


Michael
-- 
[EMAIL PROTECTED], http://kamaelia.sourceforge.net/
British Broadcasting Corporation, Research and Development
Kingswood Warren, Surrey KT20 6NP

This message (and any attachments) may contain personal views
which are not the views of the BBC unless specifically stated.

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


Re: bug in numarray?

2005-09-09 Thread Colin J. Williams
Xiangyi wrote:
> Hi, there,
> 
> I got the following segmentation fault.
> 
>> from numarray import *
>> a = zeros((5,100), Float64)
>> b = kroneckerproduct(a, identity(12))
>> segmentation fault
> 
> 
> If I use a = zeros((5,100)), everything is fine. Kind of weird!
> Can someone help me figure it out? BTW, the python version is 2.4.1 and 
> numarray 1.3.2
> 
> Many thanks!
> Xiangyi
> 
>>
>> -- 
>> http://mail.python.org/mailman/listinfo/python-list
>>
> 
> 
Looks OK to me, Winodows XP, Python 2.4.1, numarray 1.3.3

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


Re: Where do .pyc files come from?

2005-09-09 Thread Fredrik Lundh
Ernesto wrote:

>I noticed in a python distribution there were 5 python files (.py) and
> 5 other files with the same name, but with the extension .pyc .  Is
> this some kind of compiled version of the .py files.  Thanks,

http://www.python.org/doc/2.4.1/tut/node8.html#SECTION00812

 



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


Re: Using Python with COM to communicate with proprietary Windows software

2005-09-09 Thread Joakim Persson
On Fri, 09 Sep 2005 08:36:00 +0200, Thomas Heller <[EMAIL PROTECTED]>
wrote:

>Joakim Persson <[EMAIL PROTECTED]> writes:
>
>> I have a rather bloated C++ client prototype which "works", so I
>> should have all the code needed to invoke the interface, but this
>> client is of course rather bloated in itself and not suitable for my
>> experimental programming approach. Am I right in believing that the
>> COM interface I am trying to use is of what is called a "custom" type,
>> that I cannot access using Python + win32com?
>
>Sounds like a perfect job for comtypes, which is a COM library
>implemented in pure Python, based on ctypes.  comtypes should make it
>easy to access custom (non-dispatch derived) com interfaces, or the
>vtable based part of dual interfaces - it would be good however, if you
>have a type library for the interfaces.
>
>http://sourceforge.net/projects/comtypes/
>
>No docs yet, but there are tests included which should get you started.
>
>(I have released and announced this 3 weeks ago, but haven't got a
>single feedback.  So it seems the need to access custom interfaces is
>very low.)
>
>Thommas

Looks good, I think I downloaded ctypes but didn't put in the effort
to wrap the custom COM interface.

I have the type library and full documentation of the interface, so
IMO it _should_ be possible to make a 100% Python application for
testing this particular interface, which would definitely speed up
prototyping, which is the entire goal of my work. I will give it a
spin tomorrow, and I'll get back on the NG once I have tested it. Many
thanks! 

It seems most Python uses for COM rely on "simple" automation of COM
interfaces of the IDispatch type, but I need something more (full
client<->server communication and threading, for instance). Hopefully
your module will at least let me get one step further... 

My remaining two options, seeing as I would really like to at least
put the data processing and presentation part in Python, are linking
Python with C++ for the COM part and building (Data + Presentation) in
Python, or making a complete standalone C++ part for the COM part and
then _another_ client<->server solution using e.g. named
pipes/sockets. 

-- 
Joakim Persson
M.Sc student, CS/E @ LTH
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: distutils question

2005-09-09 Thread Jorgen Grahn
On Wed, 07 Sep 2005 10:56:40 -0700, Joachim Dahl <[EMAIL PROTECTED]> wrote:
> I am trying to make a customized install script for an extension module 
> using the distutils.ccompiler class.
>
> I want to embed an existing makefile for the C libraries into the Python 
> setup script, but I am not sure what's the right way to do it...
>
> E.g., say I want to compile a project as:
>
> gcc -Ddef1 -c foo.c -o foo_def1.o
> gcc -Ddef2 -c foo.c -o foo_def2.o
> gcc foo_def1.o foo_def2.o -o myext_module.o
>
> How would I do that using distutils? It doesn't seem to be possible with
> the normal core.setup method, and distutils.ccompiler seems to be the
> best option, but I couldn't get it working...

When I once had to do such an abomination, I started my setup.py with code
which created renamed copies of the master source file (if they didn't
already exist and were newer than the source) and then let normal C
compilation take place,

/Jorgen

[1] For bizarre reasons, I had to import three identical *.pyd modules into
one Python program under different names, so the *pyd files and their
init methods had to have distinct names. Don't ask why.

-- 
  // Jorgen GrahnR'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Launching Python programs from Linux shell script

2005-09-09 Thread Ruben Charles
Yes...
-
Or... 
Add this line in de source:
#!/usr/bin/env python 
then
chmod +x myscript.py
./myscript.py


On 9 Sep 2005 08:31:27 -0700, Ernesto <[EMAIL PROTECTED]> wrote:
> Does anyone know how to start Python program(s) from a Linux shell
> script?  Is it just
> 
> $python myscript.py
> 
> ??
> 
> Thanks,
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why do Pythoneers reinvent the wheel?

2005-09-09 Thread Michael Amrhein
Stefano Masini schrieb:
> On 8 Sep 2005 08:24:50 -0700, Fuzzyman <[EMAIL PROTECTED]> wrote:
> 
>>What is pythonutils ?
>>=
>>ConfigObj - simple config file handling
>>validate - validation and type conversion system
>>listquote - string to list conversion
>>StandOut - simple logging and output control object
>>pathutils - for working with paths and files
>>cgiutils - cgi helpers
>>urlpath - functions for handling URLs
>>odict - Ordered Dictionary Class
> 
> 
> Fuzzyman, your post reminded me of something I can't stop thinking
> about. Please don't take this as a critique on your work. I place
> myself on the same side of yours.
> I just wanted to share this thought with everybody had an opinion about it.
> 
> I wonder how many people (including myself) have implemented their own
> versions of such modules, at least once in their pythonic life. I
> indeed have my own odict (even same name! :). My own pathutils
> (different name, but same stuff). My own validate... and so forth.
> 
> This is just too bad.
> There are a few ares where everybody seems to be implementing their
> own stuff over and over: logging, file handling, ordered dictionaries,
> data serialization, and maybe a few more.
> I don't know what's the ultimate problem, but I think there are 3 main 
> reasons:
> 1) poor communication inside the community (mhm... arguable)
> 2) lack of a rich standard library (I heard this more than once)
> 3) python is such an easy language that the "I'll do it myself" evil
> side lying hidden inside each one of us comes up a little too often,
> and prevents from spending more time on research of what's available.
> 
> It seems to me that this tendency is hurting python, and I wonder if
> there is something that could be done about it. I once followed a
> discussion about placing one of the available third party modules for
> file handling inside the standard library. I can't remember its name
> right now, but the discussion quickly became hot with considerations
> about the module not being "right" enough to fit the standard library.
> The points were right, but in some sense it's a pity because by being
> in the stdlib it could have had a lot more visibility and maybe people
> would have stopped writing their own, and would have begun using it.
> Then maybe, if it was not perfect, people would have begun improving
> it, and by now we would have a solid feature available to everybody.
> 
> mhm... could it be a good idea to have two versions of the stdlib? One
> stable, and one testing, where stuff could be thrown in without being
> too picky, in order to let the community decide and improve?
> 
> Again, Fuzzyman, your post was just the excuse to get me started. I
> understand and respect your work, also because you put the remarkable
> effort to make it publicly available.
> 
> That's my two cents,
> stefano

Did you take a look at pyPI (http://www.python.org/pypi) ?
At least you'd find another odict ...
;-) Michael
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Create new instance of Python class in C

2005-09-09 Thread djw
Sybren Stuvel wrote:
> Hi people,
> 
> I'm creating a program that can solve and create Sudoku puzzles. My
> creation function needs to make a lot of copies of a puzzle. Until
> now, I used copy.deepcopy(), but that's too slow. I want to implement
> such a copying function in C and use that instead. My idea about this
> is:
> 
> - Get the data from a puzzle (a list containing lists containing
>   strings) and make a copy of it. That's coded already.
> 
> - Create a new SodokuPuzzle instance and assign the data to it.
> 
> That last step can be done by passing the data to the constructor, so
> that's easy too once I know how to do that in C. My question is: how
> do I create a new instance in C of a class written in Python? I've
> searched Google, but found nothing of help.
> 
> Sybren
Personally, I would try Psyco first, and consider Pyrex next. Are you 
sure your algorithm can't be optimized first, before you start trying to 
write this in C?

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


Re: Why do Pythoneers reinvent the wheel?

2005-09-09 Thread djw
Stefano Masini wrote:

> I don't know what's the ultimate problem, but I think there are 3 main 
> reasons:
> 1) poor communication inside the community (mhm... arguable)
> 2) lack of a rich standard library (I heard this more than once)
> 3) python is such an easy language that the "I'll do it myself" evil
> side lying hidden inside each one of us comes up a little too often,
> and prevents from spending more time on research of what's available.
> 

I think, for me, this most important reason is that the stdlib version 
of a module doesn't always completely fill the requirements of the 
project being worked on. That's certainly why I wrote my own, much 
simpler, logging module. In this case, its obvious that the original 
author of the stdlib logging module had different ideas about how 
straightforward and simple a logging module should be. To me, this just 
demonstrates how difficult it is to write good library code - it has to 
try and be everything to everybody without becoming overly general, 
abstract, or bloated.

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


looping over arrays in numarray/numeric

2005-09-09 Thread proof
a = range(100)
b = [a] * 3

b[1] = [k + i for k, i in zip(b[1], b[2])]

This is rather slow in python and I thought that kind of things should
be written using numeric or numarray. I tried to read trough manuals
but it didn't help me. So how is this done using numeric or numarray?

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


disabling TCP connections, just for one script

2005-09-09 Thread Adam Monsen
It would be helpful to be able to temporarily disable AF_INET socket
connections (I don't care about IPv6 for now).

What I'd like to do is create an environment for a Python script that
appears like the network interface is down, so any remote socket stuff
should fail (like an HTTP GET request to Google's home page, for
example).

Anyone know an easy way to do that? Maybe by manipulating the socket
module or something? I'd still like to be able to access the internet
from other programs (like my Web browser, IM app, etc.) while I'm
working on this script, so unplugging the network cable or just
temporarily shutting down networking for the whole system aren't really
acceptable solutions.

Maybe chroot would be useful, but this seems a little complicated for
what I'm trying to do. Setting up some kind of Xen or UML (user mode
Linux) environment, and just disabling networking within that virtual
machine would possibly work, too.

--
Adam Monsen
http://adammonsen.com/

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


Re: Why do Pythoneers reinvent the wheel?

2005-09-09 Thread Dave Brueck
Stefano Masini wrote:
> I wonder how many people (including myself) have implemented their own
> versions of such modules, at least once in their pythonic life. I
> indeed have my own odict (even same name! :). My own pathutils
> (different name, but same stuff). My own validate... and so forth.
> 
> This is just too bad.
> There are a few ares where everybody seems to be implementing their
> own stuff over and over: logging, file handling, ordered dictionaries,
> data serialization, and maybe a few more.
> I don't know what's the ultimate problem, but I think there are 3 main 
> reasons:
> 1) poor communication inside the community (mhm... arguable)
> 2) lack of a rich standard library (I heard this more than once)
> 3) python is such an easy language that the "I'll do it myself" evil
> side lying hidden inside each one of us comes up a little too often,
> and prevents from spending more time on research of what's available.

IMO the reason is something similar to #3 (above and beyond #1 and #2 by a long 
shot). The cost of developing _exactly_ what you need often is (or at least 
*appears* to be) the same as or lower than bending to use what somebody else 
has 
already built.

(my wheel reinvention has typically covered config files, logging, and simple 
HTTP request/response/header processing)

> It seems to me that this tendency is hurting python

I think it helps on the side of innovation - the cost of exploring new ideas is 
cheaper than in many other languages, so in theory the community should be able 
to stumble upon truly great ways of doing things faster than would otherwise be 
possible. The problem lies in knowing when we've found that really good way of 
doing something, and then nudging more and more people to use it and refine it 
without turning it into a bloated one-size-fits-all solution.

I think we have half of what we need - people like Fuzzyman coming up with 
handy 
modules and then making them available for others to use. But right now it's 
hard for a developer to wade through all the available choices out there and 
know which one to pick.

Maybe instead of being included in the standard library, some modules could at 
least attain some "recommended" status by the community. You can't exactly tell 
people to stop working on their pet project because it's not special or 
different enough from some other solution, so maybe the solution is to go the 
other direction and single out some of the really best ones, and hope that the 
really good projects can begin to gain more momentum.

For example, there are several choices available to you if you need to create a 
standalone Windows executable; if it were up to me I'd label py2exe "blessed by 
the BDFL!", ask the other tool builders to justify the existence of their 
alternatives, and then ask them to consider joining forces and working on 
py2exe 
instead. But of course I'm _not_ in charge, I don't even know if the BDFL likes 
py2exe, and it can be really tough knowing which 1 or 2 solutions should 
receive 
recommended status.

FWIW, RubyOnRails vs all the Python web frameworks is exactly what you're 
talking about. What makes ROR great has little to do with technology as far as 
I 
can tell, it's all about lots of people pooling their efforts - some of them 
probably not seeing things develop precisely as they'd prefer, but remaining 
willing to contribute anyway.

Many projects (Python-related or not) often seem to lack precisely what has 
helped Python itself evolve so well - a single person with decision power who 
is 
also trusted enough to make good decisions, such that when disagreements arise 
they don't typically end in the project being forked (the number of times 
people 
disagreed but continued to contribute to Python is far higher than the number 
of 
times they left to form Prothon, Ruby, and so on).

In the end, domain-specific BDFLs and their projects just might have to buble 
to 
the top on their own, so maybe the best thing to do is find the project you 
think is the best and then begin contributing and promoting it.

> and I wonder if
> there is something that could be done about it. I once followed a
> discussion about placing one of the available third party modules for
> file handling inside the standard library. I can't remember its name
> right now, but the discussion quickly became hot with considerations
> about the module not being "right" enough to fit the standard library.

I think an extremely rich standard library is both a blessing and a curse. It's 
so handy to have what you need already there, but as you point out it becomes 
quite a debate to know what should be added. For one, a module to be added 
needs 
to be sufficiently broad in scope and power to be widely useful, but this often 
breeds complexity (e.g. the logging package added in Py2.3 sure looks powerful, 
but other than playing around with it for a few minutes I've never used it in a 
real app because it's a little overwhelming and it see

Re: distutils question

2005-09-09 Thread Fredrik Lundh
Joachim Dahl wrote:

> E.g., say I want to compile a project as:
>
> gcc -Ddef1 -c foo.c -o foo_def1.o
> gcc -Ddef2 -c foo.c -o foo_def2.o
> gcc foo_def1.o foo_def2.o -o myext_module.o
>
> How would I do that using distutils? It doesn't seem to be possible with
> the normal core.setup method, and distutils.ccompiler seems to be the
> best option, but I couldn't get it working...

easy: add a new C file (e.g. myext_module.c) that includes "foo.c"
twice (using define/undef/ifdef), and compile the new file instead.

almost as easy: change foo.c so it includes itself.

 



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


Re: re module help

2005-09-09 Thread Daniel Dittmar
[EMAIL PROTECTED] wrote:
> if I start replacing regex by re I get stuck at replacement of
>regex.symcomp() and regex.pattern()

Groups identified by names are part of the standard regular expression 
syntax:
regex.symcomp ('\([a-z][a-z0-9]*\)')
becomes
re.compile ('(?Pid[a-z][a-z0-9]*)')

I get AttributeError for both regex.pattern and regex.compile 
('abc').pattern.

re compiled regular expression have a pattern attribute, this was named 
givenpat and realpat in the regex module.

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


Re: Create new instance of Python class in C

2005-09-09 Thread Sybren Stuvel
djw enlightened us with:
> Personally, I would try Psyco first, and consider Pyrex next.

Ok, I'll take a look at those.

> Are you sure your algorithm can't be optimized first, before you
> start trying to write this in C?

I'm sure there will be optimizations, but profiling showed that the
copying of the puzzles took the most time. Since the copy.deepcopy()
function is implemented it Python, I'd thought it would get quite a
speed boost when done in C instead.

As a side-question: how would I go about compiling my C module in
Windows, if I want to ship a Windows version?

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Yielding a chain of values

2005-09-09 Thread [EMAIL PROTECTED]
>>unless you are going many levels deep
(and that's usually a design smell of some kind)

No, its not a bug. its a feature! See the discussion in the recursive
generator thread below:

http://groups.google.com/group/comp.lang.python/browse_frm/thread/4c749ec4fc5447fb/36f2b915eba66eac?q=recursive+generator&rnum=1#36f2b915eba66eac

In my opinion, traversing recursive data structure is where generator
shine best. Alternative implementation using iterator is lot more
difficult and lot less elegant. Unfortunate the right now recursive
generator would carry a price tag of O(n^2) to the level of depth.

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


Re: Why do Pythoneers reinvent the wheel?

2005-09-09 Thread Stefano Masini
On 9/9/05, Michael Amrhein <[EMAIL PROTECTED]> wrote:
> Did you take a look at pyPI (http://www.python.org/pypi) ?
> At least you'd find another odict ...

Oh, yeah. And another filesystem abstraction layer... and another xml
serialization methodology... :)
PyPI is actually pretty cool. If I had to vote for something going
into a "testing" stdlib, I'd vote for PyPI.

You see, that's my point, we have too many! :)

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


  1   2   >