Re: How to better pickle an extension type

2007-04-16 Thread Ziga Seilnacht
dgdev wrote:
> I would like to pickle an extension type (written in pyrex).  I have
> it working thus far by defining three methods:
>
> class C:
> # for pickling
> __getstate__(self):
> ... # make 'state_obj'
> return state_obj
>
> __reduce__(self):
> return C,(args,to,__init__),me.__getstate__()
>
> # for unpickling
> __setstate__(self,state_obj):
> self.x=state_obj.x
> ...
>
> This gets the class pickling and unpickling.
>
> However, I'd like to not specify arguments for __init__ (as I do now
> in __reduce__), and so not have __init__ invoked during unpickling.
>
> I would like to have the pickling machinery somehow create an
> uninitialized object, and then call its __setstate__, where I can re-
> create it from 'state_obj'.
>
> Is there a kosher way to do so, that is without me having to have a
> special mode in the constructor for when the object is being created
> by the unpickler?

Why are you overwriting the __reduce__() method?  The default
object.__reduce__() method, inherited by all new style classes,
already does what you want.  If you really must overwrite it, and
you don't want __init__() to get called, then you should return a
reconstructor named __newobj__() as the first item of reduce
tuple.  Something like this:

>>> def __newobj__(cls, *args):
... return cls.__new__(cls, *args)
...
>>> class C(object):
... def __init__(self):
... print "I shouldn't be called at reconstruction"
... def __reduce__(self):
... try:
... getnewargs = self.__getnewargs__
... except AttributeError:
... newargs = (self.__class__,)
... else:
... newargs = (self.__class__,) + getnewargs()
... try:
... getstate = self.__getstate__
... except AttributeError:
... # this ignores __slots__ complications
... state = self.__dict__
... else:
... state = getstate()
... # this ignores list and dict subclasses
... return __newobj__, newargs, state
...
>>> c = C()
I shouldn't be called at reconstruction
>>> import pickle
>>> for proto in range(3):
... assert isinstance(pickle.loads(pickle.dumps(c, proto)), C)
...
>>>

Ziga

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


Re: Queue enhancement suggestion

2007-04-16 Thread Antoon Pardon
On 2007-04-17, Hendrik van Rooyen <[EMAIL PROTECTED]> wrote:
> "Antoon Pardon" <[EMAIL PROTECTED]> wrote:
>
>
>> The problem is this doesn't work well if you have multiple producers.
>> One producer can be finished while the other is still putting values
>> on the queue.
>>
>> The solution I have been thinking on is the following.
>>
>> Add an open and close operation. Only threads that have the queue
>> open can access it. The open call should specify whether you
>> want to read or write to the queue or both. When all writers
>> have closed the queue and the queue is empty a q.get will
>> raise an exception. This may be done by putting a sentinel
>> on the queue when the last writer closed the queue.
>>
>
> This is beginning to look like a named pipe to me.
>
> The nice thing about queues is that there is currently so little
> BS about them - you just import the module, create one by binding
> a name to it, and you are in business, and anyone can read and/or
> write to it.

And if you are not carefull you have a deadlock. I tried queues
in a threaded gui application. Al the advise you get about such
applications tell you to have one thread doing all the gui-stuff.
So you basically have n producers and one consumer. Unfortunatly
the gui thread sometimes has things of its own it want to show.
So when the gui thread wants to put things on the queue you
risk a deadlock.


> If I were faced with the sort of thing addressed by this thread, I would
> probably use some sort of time out to decide when the end has happened.
> After all - if the task is long running, it never stops (hopefully), and if 
> its
> a batch type job, it runs out of input and stops putting stuff on the queue.

This is unworkable for worker threads in a gui environment.


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


Re: Queue enhancement suggestion

2007-04-16 Thread Antoon Pardon
On 2007-04-17, Paul Rubin  wrote:
> Antoon Pardon <[EMAIL PROTECTED]> writes:
>> The problem is this doesn't work well if you have multiple producers.
>> One producer can be finished while the other is still putting values
>> on the queue.
>
> Right, you'd wait for all the producers to finish, then finish the queue:
>for p in producer_threads: p.join()
>q.finish()
>
>> The solution I have been thinking on is the following.
>> 
>> Add an open and close operation. Only threads that have the queue
>> open can access it. The open call should specify whether you
>> want to read or write to the queue or both. When all writers
>> have closed the queue and the queue is empty a q.get will
>> raise an exception. This may be done by putting a sentinel
>> on the queue when the last writer closed the queue.
>
> That's an idea, but why would readers need to open the queue?

That has to do with how I implemented it. My implementation
puts n sentinels on the queue when there are n readers at the
moment the last writer closes the queue.

I also treat writers differently from read-writers. Read-writers
never block, while writers can be blocked if the queue is "full".

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


Re: strange behaviour sys.argv

2007-04-16 Thread Charles Sanders
schnupfy wrote:
> 
> ok, thanks for the answers. I try to hand over the 3rd part (the long
> trap) as one cmd argument. I will ask in a shell ng. Thanks again.
> 
> Cheers

Should be as simple as removing the backslashes

/root/mk/services.py $HOST $SEVERITY "$TRAP"

should pass TRAP as a single arg

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


python-list@python.org

2007-04-16 Thread Peter Otten
[EMAIL PROTECTED] wrote:

> Once in while I too have something to ask. This is a little problem
> that comes from a Scheme Book (I have left this thread because this
> post contains too much Python code for a Scheme newsgroup):

> For fun I have tried to make it lazy, if may be useful if seq is a
> very long iterable. So I've used tee:
> 
> from itertools import ifilter, tee
> 
> def multiremberandco4(el, iseq, fun):
> iseq1, iseq2 = tee(iseq)
> iterable1 = ifilter(lambda x: x == el, iseq1)
> iterable2 = ifilter(lambda x: x != el, iseq2)
> return fun(iterable1, iterable2)
> 
> def leniter(seq):
> count = 0
> for el in seq:
> count += 1
> return count
> 
> idata = iter(data)
> print multiremberandco4('a', idata, lambda l1,l2: (leniter(l1),
> leniter(l2)))
> 
> 
> But from the docs: >in general, if one iterator is going to use most
> or all of the data before the other iterator, it is faster to use
> list() instead of tee().<
> 
> So I have tried to create two iterables for the fun function scanning
> seq once only, but I haven't succed so far (to do it I have tried to
> use two coroutines with the enhanced generators, sending el to one or
> to the other according to the value of x == el, this time I don't show
> my failed versions), do you have suggestions?

I think the showstopper here is fun() which could either combine or
operate indepently on both iterables, e. g.:

def fun(a, b): return [a*b for a, b in zip(a, b)]
def fun(a, b): return sum(a), sum(b)

If you changed multirembrandtco() to accept two functions that are
guaranteed to be independent and to consume all items from their iterable
argument, you could run them in two threads and provide the iterable items
via a Queue that would block fun1() until pending items for fun2() are
processed. 

You'd rather cut your ear off? No, that would be multivangoghco()...

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


how to copy the contents of pygtk into a file

2007-04-16 Thread PARIMALA KALAVALA

hi,

   I want to know how to copy the contents of a pygtk application into a
file and include that in other applications.

   Pls reply to this .

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

python-list@python.org

2007-04-16 Thread attn . steven . kuo
On Apr 16, 5:14 pm, [EMAIL PROTECTED] wrote:
> Once in while I too have something to ask. This is a little problem
> that comes from a Scheme Book (I have left this thread because this
> post contains too much Python code for a Scheme 
> newsgroup):http://groups.google.com/group/comp.lang.scheme/browse_thread/thread/...
>


(snipped)

>
> For fun I have tried to make it lazy, if may be useful if seq is a
> very long iterable. So I've used tee:
>
> from itertools import ifilter, tee
>
> def multiremberandco4(el, iseq, fun):
> iseq1, iseq2 = tee(iseq)
> iterable1 = ifilter(lambda x: x == el, iseq1)
> iterable2 = ifilter(lambda x: x != el, iseq2)
> return fun(iterable1, iterable2)
>
> def leniter(seq):
> count = 0
> for el in seq:
> count += 1
> return count
>
> idata = iter(data)
> print multiremberandco4('a', idata, lambda l1,l2: (leniter(l1),
> leniter(l2)))
>
> But from the docs: >in general, if one iterator is going to use most
> or all of the data before the other iterator, it is faster to use
> list() instead of tee().<
>
> So I have tried to create two iterables for the fun function scanning
> seq once only, but I haven't succed so far (to do it I have tried to
> use two coroutines with the enhanced generators, sending el to one or
> to the other according to the value of x == el, this time I don't show
> my failed versions), do you have suggestions?


Scan once, two iterables:

class It(object):
def __init__(self, iseq, fun, fun2):
self.iseq = iseq
self.wanted = fun
self.queue = []
self.divert = fun2
def append(self, item):
self.queue.append(item)
def __iter__(self):
while True:
if self.queue:
yield self.queue.pop(0)
else:
try:
item = self.iseq.next()
if self.wanted(item):
yield item
else:
self.divert(item)
except StopIteration:
raise

class TwoFromOne(object):
def __init__(self, iseq, el):
self.i1 = It(iseq, lambda x: x == el, lambda y:
self.i2.append(y))
self.i2 = It(iseq, lambda x: x != e1, lambda y:
self.i1.append(y))
def getiters(self):
return self.i1, self.i2

def leniter(seq):
count = 0
for el in seq:
count += 1
return count

data =  [1, 'a', 3, 'a', 4, 5, 6, 'a']
lazy_eye = TwoFromOne(iter(data), 'a')
it1, it2 = lazy_eye.getiters()
print (lambda i1, i2: (leniter(i1), leniter(i2)))(it1, it2)

--
Hope this helps,
Steven



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


Re: Python Feature Request: Allow changing base of member indices to 1

2007-04-16 Thread Tim Roberts
"Beliavsky" <[EMAIL PROTECTED]> wrote:
>
>Fortran has allowed a user-specified base since at least the 1977
>standard -- see for example 
>http://www.umiacs.umd.edu/~jhu/DOCS/SP/docs/essl/essl159.html
>.

You can strike "at least"; this extension was introduced in FORTRAN 77.
FORTRAN 66 didn't do this.
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: script for seconds in given month?

2007-04-16 Thread Hendrik van Rooyen
"Paul McGuire" <[EMAIL PROTECTED]> wrote:

> On Apr 16, 11:22 am, "edfialk" <[EMAIL PROTECTED]> wrote:
> > Hi, does anyone happen to know of a script that would return the
> > number of seconds in a month if I give it a month and a year?
> >
> > My python is a little weak, but if anyone could offer some suggestions
> > I think I could handle it myself, or if anyone happens to know of a
> > script already written that performs this I would be extremely
> > grateful.
> >
> > Thanks!
> > -Ed
> 
> Do you need to handle leap seconds too? (not a joke)
> 
> -- Paul

>From some assembler, here are some values.
Stick them in a two dicts for normal and leap year.
the first one is a cumulative table, I included it in 
case you can use it...

; SECONDS TABLES (LITTLE ENDIAN)


MSECTAB_NORM:

 DB 080H,033H,0E1H,001H ;MONTH ZERO HAS FULL YEAR SECONDS
 DB 000H,000H,000H,000H ;JANUARY
 DB 080H,0DEH,028H,000H ;FEBRUARY
 DB 080H,0C8H,04DH,000H ;MARCH
 DB 000H,0A7H,076H,000H ;APRIL
 DB 000H,034H,09EH,000H ;MAY
 DB 080H,012H,0C7H,000H ;JUNE
 DB 080H,09FH,0EEH,000H ;JULY
 DB 000H,07EH,017H,001H ;AUGUST
 DB 080H,05CH,040H,001H ;SEPTEMBER
 DB 080H,0E9H,067H,001H ;OCTOBER
 DB 000H,0C8H,090H,001H ;NOVEMBER
 DB 000H,055H,0B8H,001H ;DECEMBER


MSECTAB_LEAP:

 DB 000H,085H,0E2H,001H ;MONTH ZERO HAS FULL LEAP YEAR SECONDS
 DB 000H,000H,000H,000H ;JANUARY
 DB 080H,0DEH,028H,000H ;FEBRUARY
 DB 000H,01AH,04FH,000H ;MARCH
 DB 080H,0F8H,077H,000H ;APRIL
 DB 080H,085H,09FH,000H ;MAY
 DB 000H,064H,0C8H,000H ;JUNE
 DB 000H,0F1H,0EFH,000H ;JULY
 DB 080H,0CFH,018H,001H ;AUGUST
 DB 000H,0AEH,041H,001H ;SEPTEMBER
 DB 000H,03BH,069H,001H ;OCTOBER
 DB 080H,019H,092H,001H ;NOVEMBER
 DB 080H,0A6H,0B9H,001H ;DECEMBER


; NUMBER OF SECONDS IN MONTH (LITTLE ENDIAN)


MSTAB_NORM:

 DB 000H,000H,000H,000H ;MONTH ZERO HAS NO SECONDS
 DB 080H,0DEH,028H,000H ;JANUARY
 DB 000H,0EAH,024H,000H ;FEBRUARY
 DB 080H,0DEH,028H,000H ;MARCH
 DB 000H,08DH,027H,000H ;APRIL
 DB 080H,0DEH,028H,000H ;MAY
 DB 000H,08DH,027H,000H ;JUNE
 DB 080H,0DEH,028H,000H ;JULY
 DB 080H,0DEH,028H,000H ;AUGUST
 DB 000H,08DH,027H,000H ;SEPTEMBER
 DB 080H,0DEH,028H,000H ;OCTOBER
 DB 000H,08DH,027H,000H ;NOVEMBER
 DB 080H,0DEH,028H,000H ;DECEMBER

MSTAB_LEAP:

 DB 000H,000H,000H,000H ;MONTH ZERO HAS NO SECONDS
 DB 080H,0DEH,028H,000H ;JANUARY
 DB 080H,03BH,026H,000H ;FEBRUARY
 DB 080H,0DEH,028H,000H ;MARCH
 DB 000H,08DH,027H,000H ;APRIL
 DB 080H,0DEH,028H,000H ;MAY
 DB 000H,08DH,027H,000H ;JUNE
 DB 080H,0DEH,028H,000H ;JULY
 DB 080H,0DEH,028H,000H ;AUGUST
 DB 000H,08DH,027H,000H ;SEPTEMBER
 DB 080H,0DEH,028H,000H ;OCTOBER
 DB 000H,08DH,027H,000H ;NOVEMBER
 DB 080H,0DEH,028H,000H ;DECEMBER


; *

hth - Hendrik

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


Re: Queue enhancement suggestion

2007-04-16 Thread Hendrik van Rooyen
"Antoon Pardon" <[EMAIL PROTECTED]> wrote:


> The problem is this doesn't work well if you have multiple producers.
> One producer can be finished while the other is still putting values
> on the queue.
>
> The solution I have been thinking on is the following.
>
> Add an open and close operation. Only threads that have the queue
> open can access it. The open call should specify whether you
> want to read or write to the queue or both. When all writers
> have closed the queue and the queue is empty a q.get will
> raise an exception. This may be done by putting a sentinel
> on the queue when the last writer closed the queue.
>

This is beginning to look like a named pipe to me.

The nice thing about queues is that there is currently so little
BS about them - you just import the module, create one by binding
a name to it, and you are in business, and anyone can read and/or
write to it.

If I were faced with the sort of thing addressed by this thread, I would
probably use some sort of time out to decide when the end has happened.
After all - if the task is long running, it never stops (hopefully), and if its
a batch type job, it runs out of input and stops putting stuff on the queue.

It means you have to use non blocking gets and try - except, though.
But then - to use any of the methods put forward in this thread,
you have to use try - except anyway...

Why does this remind me of COBOL:

read input_file at end go to close_down  ?

: - )

- Hendrik




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


Re: Queue enhancement suggestion

2007-04-16 Thread Paul Rubin
Antoon Pardon <[EMAIL PROTECTED]> writes:
> The problem is this doesn't work well if you have multiple producers.
> One producer can be finished while the other is still putting values
> on the queue.

Right, you'd wait for all the producers to finish, then finish the queue:
   for p in producer_threads: p.join()
   q.finish()

> The solution I have been thinking on is the following.
> 
> Add an open and close operation. Only threads that have the queue
> open can access it. The open call should specify whether you
> want to read or write to the queue or both. When all writers
> have closed the queue and the queue is empty a q.get will
> raise an exception. This may be done by putting a sentinel
> on the queue when the last writer closed the queue.

That's an idea, but why would readers need to open the queue?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to better pickle an extension type

2007-04-16 Thread Alex Martelli
dgdev <[EMAIL PROTECTED]> wrote:

> I would like to pickle an extension type (written in pyrex).  I have
> it working thus far by defining three methods:
> 
> class C:
>   # for pickling
>   __getstate__(self):
>   ... # make 'state_obj'
>   return state_obj
> 
>   __reduce__(self):
>   return C,(args,to,__init__),me.__getstate__()
> 
>   # for unpickling
>   __setstate__(self,state_obj):
>   self.x=state_obj.x
>   ...
> 
> 
> This gets the class pickling and unpickling.
> 
> However, I'd like to not specify arguments for __init__ (as I do now
> in __reduce__), and so not have __init__ invoked during unpickling.
> 
> I would like to have the pickling machinery somehow create an
> uninitialized object, and then call its __setstate__, where I can re-
> create it from 'state_obj'.
> 
> Is there a kosher way to do so, that is without me having to have a
> special mode in the constructor for when the object is being created
> by the unpickler?

I don't understand why you have a problem -- __init__ is NOT called by
default upon loading an object w/__setstate__.  Witness:

>>> class C(object):
...   def __init__(self, *a): print 'init', a
...   def __getstate__(self): print 'gs'; return {}
...   def __setstate__(self, *a): print 'ss', a
... 
>>> c = C()  
init ()
>>> s = cPickle.dumps(c, 2)
gs
>>> s
'\x80\x02c__main__\nC\nq\x01)\x81q\x02}b.'
>>> z = cPickle.loads(s)
ss ({},)


Perhaps you're not using protocol 2?  You should be...


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


Re: Python Feature Request: Add the "using" keyword which works like "with" in Visual Basic

2007-04-16 Thread Alex Martelli
Paul Boddie <[EMAIL PROTECTED]> wrote:

> > Now I hear that the word "with" is being discussed for a different
> > purpose in Py 3 as a result of a PEP and I don't want to conflict with
> > that.
> 
> The "with" keyword appears in 2.5 onwards.

...but needs a "from __future__ import with_statement" in 2.5 itself.


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


python-list@python.org

2007-04-16 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> So I have tried to create two iterables for the fun function scanning
> seq once only, but I haven't succed so far (to do it I have tried to
> use two coroutines with the enhanced generators, sending el to one or
> to the other according to the value of x == el, this time I don't show
> my failed versions), do you have suggestions?

I think there is not any way short of using something like list or
tee, if you want both output iterators to be available simultaneously.
Say there are 17 occurrences of el in the input iterator.  The only
way to know this is to scan through the whole iterator.  But now all
of its elements have to be available again at the output.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: script for seconds in given month?

2007-04-16 Thread Alex Martelli
edfialk <[EMAIL PROTECTED]> wrote:

> Hi, does anyone happen to know of a script that would return the
> number of seconds in a month if I give it a month and a year?
> 
> My python is a little weak, but if anyone could offer some suggestions
> I think I could handle it myself, or if anyone happens to know of a
> script already written that performs this I would be extremely
> grateful.

import calendar

def seconds_in_month(month, year):
nomatter, daysinmonth = calendar.monthrange(year, month)
return daysinmonth * 24 * 60 * 60


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


Re: strange behaviour with keyword arguments and inheritance

2007-04-16 Thread Alex Martelli
Steve Holden <[EMAIL PROTECTED]> wrote:
   ...
> > livibetter has a better solution. the reason is that you need to
> > create a new list object everytime, am I right?
> > 
> Yes, specifically on every *call*.

...and livibetter's solution also creates a new list on every call to
Child (that [] passed on to Parent.__init__ does exactly that).


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


python-list@python.org

2007-04-16 Thread Paddy
On Apr 17, 1:14 am, [EMAIL PROTECTED] wrote:
> Once in while I too have something to ask. This is a little problem
> that comes from a Scheme Book (I have left this thread because this
> post contains too much Python code for a Scheme 
> newsgroup):http://groups.google.com/group/comp.lang.scheme/browse_thread/thread/...
>
> The function multiremberandco is hard (for me still) if done in that
> little Scheme subset, but it's very easy with Python. It collects two
> lists from a given one, at the end it applies the generic given fun
> function to the two collected lists and returns its result:
>
> def multiremberandco1(el, seq, fun):
> l1, l2 = [], []
> for x in seq:
> if x == el:
> l2.append(el)
> else:
> l1.append(el)
> return fun(l1, l2)
>
Hi bearophile,

Couldn't you also use count rather than the explicit loop to
get something like:

def multiremberandco1(el, seq, fun):
l1, l2 = [], []
c = seq.count(e1)
l1 = [el] * c
l2 = [el] * (len(seq) - c)
return fun(l1, l2)

I don't have the book so can't comment on its suitability,
but there you go.

- Paddy.

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


How to Passs NULL as a IDispatch Pointer to method?

2007-04-16 Thread ZhaoYingpu
Hello,all
  I am using win32com to use com. and invoke a method as follows:
void AddShapeInfo(LPCTSTR name, LONG type, IDispatch* pDisp);
but i pass 0 or None to third parameter and get error info:

>>> x.AddShapeInfo("who", 10, 0)

Traceback (most recent call last):
  File "", line 1, in 
x.AddShapeInfo("who", 10, 0)
  File "", line 2, in AddShapeInfo
com_error: (-2147352571, 'Type mismatch.', None, 3)

or

>>> x.AddShapeInfo("who",0,None)

Traceback (most recent call last):
  File "", line 1, in 
x.AddShapeInfo("who",0,None)
  File "", line 2, in AddShapeInfo
com_error: (-2147352571, 'Type mismatch.', None, 3)

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

Re: is laziness a programer's virtue?

2007-04-16 Thread Markus E Leypold

"Xah Lee" <[EMAIL PROTECTED]> writes:

> • Please remind yourself what is on-topic and off-topic. Unless you

You, Sir, ARE off-topic. I suggest you make the experiment to post
your drivel on your web site and let your fans come to you. Should be
an eye opener, this experiment.

Regards -- Markus

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

python-list@python.org

2007-04-16 Thread James Stroud
[EMAIL PROTECTED] wrote:
> Once in while I too have something to ask. This is a little problem
> that comes from a Scheme Book (I have left this thread because this
> post contains too much Python code for a Scheme newsgroup):
> http://groups.google.com/group/comp.lang.scheme/browse_thread/thread/a059f78eb4457d08/
> 
> The function multiremberandco is hard (for me still) if done in that
> little Scheme subset, but it's very easy with Python. It collects two
> lists from a given one, at the end it applies the generic given fun
> function to the two collected lists and returns its result:
> 
> def multiremberandco1(el, seq, fun):
> l1, l2 = [], []
> for x in seq:
> if x == el:
> l2.append(el)
> else:
> l1.append(el)
> return fun(l1, l2)
> 
> data = [1, 'a', 3, 'a', 4, 5, 6, 'a']
> print multiremberandco1('a', data, lambda l1,l2: (len(l1), len(l2)))
> 
> More compact:
> 
> def multiremberandco2(el, seq, fun):
> l1, l2 = [], []
> for x in seq:
> [l1, l2][x == el].append(el)
> return fun(l1, l2)
> 
> 
> A bit cleaner (but I don't like it much):
> 
> def multiremberandco3(el, seq, fun):
> l1, l2 = [], []
> for x in seq:
> (l2 if x == el else l1).append(el)
> return fun(l1, l2)
> 
> 
> For fun I have tried to make it lazy, if may be useful if seq is a
> very long iterable. So I've used tee:
> 
> from itertools import ifilter, tee
> 
> def multiremberandco4(el, iseq, fun):
> iseq1, iseq2 = tee(iseq)
> iterable1 = ifilter(lambda x: x == el, iseq1)
> iterable2 = ifilter(lambda x: x != el, iseq2)
> return fun(iterable1, iterable2)
> 
> def leniter(seq):
> count = 0
> for el in seq:
> count += 1
> return count
> 
> idata = iter(data)
> print multiremberandco4('a', idata, lambda l1,l2: (leniter(l1),
> leniter(l2)))
> 
> 
> But from the docs: >in general, if one iterator is going to use most
> or all of the data before the other iterator, it is faster to use
> list() instead of tee().<
> 
> So I have tried to create two iterables for the fun function scanning
> seq once only, but I haven't succed so far (to do it I have tried to
> use two coroutines with the enhanced generators, sending el to one or
> to the other according to the value of x == el, this time I don't show
> my failed versions), do you have suggestions?
> 
> (Note: in some situations it may be useful to create a "splitting"
> function that given an iterable and a fitering predicate, returns two
> lazy generators, of the items that satisfy the predicate and of the
> items that don't satisfy it, so this exercise isn't totally useless).
> 
> Bye,
> bearophile
> 


I think it might be provable that two iterators are required for this 
exercise. In this example, for example, leniter() will be called on one 
list and then the other. How will it get an accurate count of one list 
without iterating through the other?

I.e.:

 data = [1, 'a', 3, 'a', 4, 5, 6, 'a']
   ^
   To count this 'a', it must have gone through the
   numbers, so the leniter() can not act independently
   on the lists using a single iterator.

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


regarding tree iterators

2007-04-16 Thread PARIMALA KALAVALA

hi ,

I wanted to know how to move data from one row to another row  or how to
copy contents of one row to another row if we click any button  in a table
in pygtk.

Do we need to use get value and set value methods in tree iterators.


pls reply to this as early as possible.

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

Re: strange behaviour sys.argv

2007-04-16 Thread schnupfy
On Apr 17, 3:00 pm, Charles Sanders <[EMAIL PROTECTED]>
wrote:
> Michael Hoffman wrote:
> > schnupfy wrote:
>
> >> I am not used to python and I am wondering about this thing:
>
> > This is not a Python question. It is a question about how to use bash.
>
> [snip]
>
> Michael is correct, it is a bash thing, nothing to do with python.
> bash (and other *nix like shells) generally break arguments on
> white space. Quoting (both single and double) overrides this with
> (slightly) different rules for different shells.
>
>  > /root/mk/services.py 192.168.1.101 critical "192.168.1.101
>  > 192.168.1.101 SNMPv2-MIB::sysUpTime.0 14:13:02:57.06 SNMPv2-
>  > MIB::snmpTrapOID.0 SNMPv2-SMI::enterprises.789.0.13 SNMPv2-
>  > SMI::enterprises.789.0.2"cfCannotTakeover == 1 priority == critical"
>  > SNMP-COMMUNITY-MIB::snmpTrapAddress.0 192.168.1.101 SNMP-COMMUNITY-
>  > MIB::snmpTrapCommunity.0 "public""
>
> Assuming this has been folded and actually is one long
> line (which the output confirms), you have passed the python
> script seven arguments
>
> '192.168.1.101'  (blank seperated)
> 'critical'   (also blank seperated)
> a string extending from just after the first double quote to
> just before the second, ie starting with '192.168.1.101' and
> ending with '789.0.2', with the immediately following (no
> white space) unquoted text 'fCannotTakeover' appended
> '==' (blank seperated)
> 'priority"
> '=='
> a string starting with critical, with the quoted string from
> 'SNMP-COMMUNITY' to 'Community.0 ' (including the blank), the
> unquoted string 'public', and the null quoted string "" all
> appended.
>
>  > TRAP='192.168.1.101 192.168.1.101 SNMPv2-MIB::sysUpTime.0
>  > 14:13:02:57.06 SNMPv2-MIB::snmpTrapOID.0 SNMPv2-SMI::enterprises.
>  > 789.0.13 SNMPv2-SMI::enterprises.789.0.2"cfCannotTakeover == 1
>  > priority == critical" SNMP-COMMUNITY-MIB::snmpTrapAddress.0
>  > 192.168.1.101 SNMP-COMMUNITY-MIB::snmpTrapCommunity.0 "public"'
>  > HOST=$(echo "$TRAP" | awk '{print $1}')
>  > SEVERITY='critical'
>  > /root/mk/services.py $HOST $SEVERITY \"$TRAP\"
>
> Here, the variables are expanded, and then split into
> arguments on white space unless quoted. The backslashes protect
> the double quotes so they are treated as normal characters, so
> the $TRAP variable is also split into arguments on white space.
> Quotes resulting from the substitution of $TRAP are also protected
> (ie are treated as ordinary characters).
>
> The result is
>
> '192.168.1.101"   (From $HOST)
> 'critical'(From $SEVERITY)
> '"192.168.1.101'  (Leading '"' from \", rest from
>$TRAP, blank seperated)
> '192.168.1.101'   (from $TRAP, blank seperated)
> 'SNMPv2-MIB::sysUpTime.0'
> and so on for the rest of the $TARP string, splitting it at
> white space. The last part of $TRAP, '"public"', has a double
> quote appended from the \".
>
> Python is giving exactly what the shell has given it in both cases.
>
> Charles

ok, thanks for the answers. I try to hand over the 3rd part (the long
trap) as one cmd argument. I will ask in a shell ng. Thanks again.

Cheers

Marcus

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


Re: list insertion question

2007-04-16 Thread Paul Rubin
[EMAIL PROTECTED] writes:

> hi
> i have a list (after reading from a file), say
> data = [ 'a','b','c','d','a','b','e','d']
> 
> I wanted to insert a word after every 'a', and before every 'd'. so i
> use enumerate this list:
> for num,item in enumerate(data):
> if "a" in item:
>   data.insert(num+1,"aword")
> if "d" in item:
> data.insert(num-1,"dword") #this fails
> but the above only inserts after 'a' but not before 'd'.  What am i
> doing wrong? is there better way?thanks

As others have said, you're mutating the list while iterating through
it, which can give whacked results.  Also, even if you operate on a
copy of the list, that algorithm uses quadratic time because of all
the insertions into the list.  These days I like to write in the style

def g():
   for w in data:
 if 'd' in w: yield 'dword'
 yield w
 if 'a' in w: yield 'aword'
data = list(g(data))

instead of using list.append as someone else suggested.  The iterator
approach is probably a bit slower but can be seen as a bit cleaner,
depending on your stylistic preferences.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list insertion question

2007-04-16 Thread attn . steven . kuo
On Apr 16, 6:05 pm, [EMAIL PROTECTED] wrote:
> hi
> i have a list (after reading from a file), say
> data = [ 'a','b','c','d','a','b','e','d']
>
> I wanted to insert a word after every 'a', and before every 'd'. so i
> use enumerate this list:
> for num,item in enumerate(data):
> if "a" in item:
> data.insert(num+1,"aword")
> if "d" in item:
> data.insert(num-1,"dword") #this fails
> but the above only inserts after 'a' but not before 'd'.  What am i
> doing wrong? is there better way?thanks


Traverse the list from highest index
to lowest index:

data = [ 'a', 'b', 'c', 'd', 'a', 'b', 'e', 'd' ]

print data
for idx, value in reversed(list(enumerate(data))):
if value == 'a':
data.insert(idx+1, 'aword')
elif value == 'd':
data.insert(idx, 'dword')

print data

# OR

last_idx = len(data) - 1

for idx in range(last_idx+1):
ridx = last_idx - idx
if data[ridx] == 'a':
data.insert(ridx+1, 'aword')
elif data[ridx] == 'd':
data.insert(ridx, 'dword')

print data

--
Hope this helps,
Steven

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


question of easyExcel (<>)

2007-04-16 Thread Tommy Zong
Hi,

 

class easyExcel:

  def __init__(self, filename=None):

self.xlApp = Dispatch('Excel.Application')

if filename:

  self.filename = filename

  self.xlBook = self.xlApp.Workbooks.Open(filename)

else:

  self.xlBook = self.xlApp.Workbooks.Add()

  self.filename = ''

 

  def save(self, newfilename=None):

if newfilename:

  self.filename = newfilename

  self.xlBook.SaveAs(newfilename)

else:

  self.xlBook.Save()

 

  def close(self):

self.xlBook.Close(SaveChanges=0)

del self.xlApp

 

  def getSheets(self):

return self.xlBook.Worksheets

 

  def getCell(self, sheet, row, col):

sht = self.xlBook.Worksheets(sheet)

return sht.Cells(row, col).Value

 

  def setCell(self, sheet, row, col, value, noerr=True):

sht = self.xlBook.Worksheets(sheet)

sht.Cells(row, col).Value = value

 

  def cpSheet(self, before):

shts = self.xlBook.Worksheets

shts(1).Copy(None,shts(1))

 

  def show(self, visible=True):

  self.xlApp.Visible = visible

 

easyExcel comes from <>, it provides a easy way
to process excel files. 

 

However, I found a problem today - it works fine in single thread version
but can not work properly in multi-thread version - If I move excel file
operations to sub-thread, it will complain 'CoInitialize has not been
called'. I noticed the exception is thrown in
"Lib\site-packages\win32com\client\dynamic.py", I tried to add
"pythoncom.CoInitialize()" in line 78 and "pythoncom.CoUninitialize()" in
line 330, it will be ok. I have following questions and hope someone can
give me some comments. Thanks a lot.

 

1.   After doing such modifications, the excel file will be opened as
"read only" mode, how to avoid this?

2.   Is it necessary to add these two lines? Is there any mistake I
made?

 

Below is information of my python:

ActivePython 2.4.3 Build 12 (ActiveState Software Inc.) based on

Python 2.4.3 (#69, Apr 11 2006, 15:32:42) [MSC v.1310 32 bit (Intel)] on
win32

 

- Tommy

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

Re: strange behaviour sys.argv

2007-04-16 Thread Charles Sanders
Michael Hoffman wrote:
> schnupfy wrote:
> 
>> I am not used to python and I am wondering about this thing:
> 
> This is not a Python question. It is a question about how to use bash.
> 
[snip]

Michael is correct, it is a bash thing, nothing to do with python.
bash (and other *nix like shells) generally break arguments on
white space. Quoting (both single and double) overrides this with
(slightly) different rules for different shells.

 > /root/mk/services.py 192.168.1.101 critical "192.168.1.101
 > 192.168.1.101 SNMPv2-MIB::sysUpTime.0 14:13:02:57.06 SNMPv2-
 > MIB::snmpTrapOID.0 SNMPv2-SMI::enterprises.789.0.13 SNMPv2-
 > SMI::enterprises.789.0.2"cfCannotTakeover == 1 priority == critical"
 > SNMP-COMMUNITY-MIB::snmpTrapAddress.0 192.168.1.101 SNMP-COMMUNITY-
 > MIB::snmpTrapCommunity.0 "public""

Assuming this has been folded and actually is one long
line (which the output confirms), you have passed the python
script seven arguments

'192.168.1.101'  (blank seperated)
'critical'   (also blank seperated)
a string extending from just after the first double quote to
just before the second, ie starting with '192.168.1.101' and
ending with '789.0.2', with the immediately following (no
white space) unquoted text 'fCannotTakeover' appended
'==' (blank seperated)
'priority"
'=='
a string starting with critical, with the quoted string from
'SNMP-COMMUNITY' to 'Community.0 ' (including the blank), the
unquoted string 'public', and the null quoted string "" all
appended.

 > TRAP='192.168.1.101 192.168.1.101 SNMPv2-MIB::sysUpTime.0
 > 14:13:02:57.06 SNMPv2-MIB::snmpTrapOID.0 SNMPv2-SMI::enterprises.
 > 789.0.13 SNMPv2-SMI::enterprises.789.0.2"cfCannotTakeover == 1
 > priority == critical" SNMP-COMMUNITY-MIB::snmpTrapAddress.0
 > 192.168.1.101 SNMP-COMMUNITY-MIB::snmpTrapCommunity.0 "public"'
 > HOST=$(echo "$TRAP" | awk '{print $1}')
 > SEVERITY='critical'
 > /root/mk/services.py $HOST $SEVERITY \"$TRAP\"

Here, the variables are expanded, and then split into
arguments on white space unless quoted. The backslashes protect
the double quotes so they are treated as normal characters, so
the $TRAP variable is also split into arguments on white space.
Quotes resulting from the substitution of $TRAP are also protected
(ie are treated as ordinary characters).

The result is

'192.168.1.101"   (From $HOST)
'critical'(From $SEVERITY)
'"192.168.1.101'  (Leading '"' from \", rest from
   $TRAP, blank seperated)
'192.168.1.101'   (from $TRAP, blank seperated)
'SNMPv2-MIB::sysUpTime.0'
and so on for the rest of the $TARP string, splitting it at
white space. The last part of $TRAP, '"public"', has a double
quote appended from the \".

Python is giving exactly what the shell has given it in both cases.

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


Re: Python and SSL

2007-04-16 Thread Paul Rubin
"Martin v. Löwis" <[EMAIL PROTECTED]> writes:
> It means that these modules can do encrypted communication for their
> respective protocol. They cannot validate that they are really talking
> to the server they think they talk to (so they are prone to a
> man-in-the-middle attack), however, as communication is encrypted, they
> are protected against wire-tapping.

Unless the wiretapper is running a man-in-the-middle attack...

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


Re: Queue enhancement suggestion

2007-04-16 Thread Paul Rubin
Jean-Paul Calderone <[EMAIL PROTECTED]> writes:
> Instead of putting multiple sentinels, just pre-construct the iterator
> object.
> work = iter(q.get, sentinel)
> Re-use the same iterator in each thread, and you'll get the behavior
> you're after.

Whaaat???  Can I do that?  It looks like it depends on the
insides of iter being thread-safe, which I wouldn't have been
willing to assume.  Am I missing something?  Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strange behaviour with keyword arguments and inheritance

2007-04-16 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> On Apr 17, 9:36 am, livibetter <[EMAIL PROTECTED]> wrote:
>> On Apr 17, 8:56 am, "matthewperpick" <[EMAIL PROTECTED]> wrote:
>>
>>> Check out this toy example that demonstrates some "strange" behaviour
>>> with keyword arguments and inheritance.
>>> =
>>> class Parent:
>>> def __init__(self, ary = []):
>>> self.ary = ary
>> This should work:
>>
>> class Parent:
>> def __init__(self, ary = []):
>> self.ary = list(ary)
>>
>> And 
>> FYIhttp://groups.google.com/group/comp.lang.python/browse_thread/thread/...
> 
> livibetter has a better solution. the reason is that you need to
> create a new list object everytime, am I right?
> 
Yes, specifically on every *call*.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Recent Ramblings   http://holdenweb.blogspot.com

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


Re: yield, curry, mix-in, new.function, global, closure, .... what will work?

2007-04-16 Thread ecir . hana
On Apr 17, 3:51 am, [EMAIL PROTECTED] wrote:
> I'm reading the docs now and I stumbled upon something:
> section "15.3 threading -- Higher-level threading interface" mensions
> a class "local", in which "... Thread-local data are data whose values
> are thread specific. ..."
>
> Does it mean, I can create global variables whose changing is thread-
> safe?
> More specific:
>
> import threading
>
> def change_i(arg):
> global k
> k.i = arg
>
> def change_j(arg):
> global k
> k.j = arg
>
> def changer():
> change_i('changed_i')
> change_j('changed_j')
>
> def run(i='', j=''):
> global k
> k = threading.local()
> k.i = i
> k.j = j
> changer()
> i = k.i
> j = k.j
> return i, j
>
> print run() == ('changed_i', 'changed_j')
>
> Is this ok?

I was too quick, "k = threading.local()" has to by outside of run(),
right?

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


Re: strange behaviour with keyword arguments and inheritance

2007-04-16 Thread [EMAIL PROTECTED]
On Apr 17, 9:36 am, livibetter <[EMAIL PROTECTED]> wrote:
> On Apr 17, 8:56 am, "matthewperpick" <[EMAIL PROTECTED]> wrote:
>
> > Check out this toy example that demonstrates some "strange" behaviour
> > with keyword arguments and inheritance.
>
> > =
>
> > class Parent:
> > def __init__(self, ary = []):
> > self.ary = ary
>
> This should work:
>
> class Parent:
> def __init__(self, ary = []):
> self.ary = list(ary)
>
> And 
> FYIhttp://groups.google.com/group/comp.lang.python/browse_thread/thread/...

livibetter has a better solution. the reason is that you need to
create a new list object everytime, am I right?

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


Re: list insertion question

2007-04-16 Thread [EMAIL PROTECTED]
On Apr 17, 9:47 am, Michael Hoffman <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > hi
> > i have a list (after reading from a file), say
> > data = [ 'a','b','c','d','a','b','e','d']
>
> > I wanted to insert a word after every 'a', and before every 'd'. so i
> > use enumerate this list:
> > for num,item in enumerate(data):
> > if "a" in item:
> >data.insert(num+1,"aword")
> > if "d" in item:
> > data.insert(num-1,"dword") #this fails
> > but the above only inserts after 'a' but not before 'd'.  What am i
> > doing wrong? is there better way?thanks
>
> If you modify a list while you are iterating over it, you may get
> unexpected results (an infinite loop in this case for me). Also ("a" in
> item) will match "aword" since "a" is a component of it. I imagine you
> mean (item == "a").
>
> Try this:
>
> output = []
> for item in data:
>  if item == "d":
>  output.append("dword")
>  output.append(item)
>  if item == "a":
>  output.append("aword")
>
>  >>> output
> ['a', 'aword', 'b', 'c', 'dword', 'd', 'a', 'aword', 'b', 'e', 'dword', 'd']
> --
> Michael Hoffman

Infinite loop for me too! ^_^, should think of it b4 pressing F5.

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


Re: yield, curry, mix-in, new.function, global, closure, .... what will work?

2007-04-16 Thread ecir . hana
I'm reading the docs now and I stumbled upon something:
section "15.3 threading -- Higher-level threading interface" mensions
a class "local", in which "... Thread-local data are data whose values
are thread specific. ..."

Does it mean, I can create global variables whose changing is thread-
safe?
More specific:

import threading

def change_i(arg):
global k
k.i = arg

def change_j(arg):
global k
k.j = arg

def changer():
change_i('changed_i')
change_j('changed_j')

def run(i='', j=''):
global k
k = threading.local()
k.i = i
k.j = j
changer()
i = k.i
j = k.j
return i, j

print run() == ('changed_i', 'changed_j')

Is this ok?

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


Re: list insertion question

2007-04-16 Thread Michael Hoffman
[EMAIL PROTECTED] wrote:
> hi
> i have a list (after reading from a file), say
> data = [ 'a','b','c','d','a','b','e','d']
> 
> I wanted to insert a word after every 'a', and before every 'd'. so i
> use enumerate this list:
> for num,item in enumerate(data):
> if "a" in item:
>   data.insert(num+1,"aword")
> if "d" in item:
> data.insert(num-1,"dword") #this fails
> but the above only inserts after 'a' but not before 'd'.  What am i
> doing wrong? is there better way?thanks

If you modify a list while you are iterating over it, you may get 
unexpected results (an infinite loop in this case for me). Also ("a" in 
item) will match "aword" since "a" is a component of it. I imagine you 
mean (item == "a").

Try this:

output = []
for item in data:
 if item == "d":
 output.append("dword")
 output.append(item)
 if item == "a":
 output.append("aword")

 >>> output
['a', 'aword', 'b', 'c', 'dword', 'd', 'a', 'aword', 'b', 'e', 'dword', 'd']
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: combination function in python

2007-04-16 Thread [EMAIL PROTECTED]
On Apr 16, 6:40 pm, Anton Vredegoor <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > Isn't that what docstrings are for? Can't you leave
> > the function name noverk() and add something to the
> > effect of "this function calculates combinations"?
> > Then it would show up in searches, wouldn't it?
>
> Yes, a doc string would help finding it in searches, however since this
> thread now contains a collection of function names it will suffice.
>
> There is also the other consideration of being able to easily read code
> that others write. Functions that try to do the same thing having the
> same name would help.

Why not simply the same doc string? You can't expect everyone to
use the same function name.

> If we had some module in the standard distro that
> would contain comb and fac and maybe a few other functions people could
> start using the same name to point to the same thing etc.

You COULD add those to the standard distro. You COULD read the
newsgroups and get various Pythonic solutions. But you don't
HAVE to if you're looking just for a solution.

>
>  def noverk(n,k):
>  ? ? ?return reduce(lambda a,b: a*(n-b)/(b+1),xrange(k),1)
> >> This is a rather concise function which has the added advantage that it
> >> returns 0 when k>n.
>
> > import gmpy
> > print gmpy.comb(4,8)
>
> > ## 0
>
> There is more to it than that. If I see the way the function computes
> the values it gives me hints about how I could write a function that
> lists all combinations.

But you said returning 0 was an advantage, as if that's not
typical. I was merely pointing out that it is NOT an advantage
over gmpy. Giving you hints about further application is
a different advantage than what you listed.

>
> For example the fact that one can divide the product 'on the fly' -I
> mean without computing the totals above and below the division bar-
> tells me something about how to tackle the problem of generating the
> corresponding combinatorial structure. I *love* combinatorial
> structures. Little functions like this have more than once helped me to
> understand them better.

Fine, and gmpy doesn't give you the actual combinations, so I wrote
my own. But if there's a faster, better 3rd party library that
can do the same things mine does (permutations with replacement,
combinations with replacement, permutations without replacement and
combinations without replacement) then I'll drop mine like a live
grenade.

I wrote this because I needed to use it in a bigger application,
the details were not important, just the output. It's the bigger
applications details I'm concerned about.

>
> Math is not so much my way of describing things, I like executable
> pseudo code better. Sometimes I had to read math formulas and have
> become somewhat used to that notation -it has its uses too- but if
> things are written down in code I can rely on the *computer* to execute
> the code instead of my brain which unfortunately is not as reliable.
>
> These advantages are lost when one just imports some optimized code library.

And once I looked up the Extended Euclidean Algorithm, made a Python
implementaion of it and after I got it all working, I found it was
all unnecessary because there was a gmpy function already present
(which I had previously ignored because it didn't understand what
it meant) that did exactly what I want. Yes, I'm glad I went through
the trouble of learning the algorithm, but I simply threw away my
version.

You talk about losing the advantage of learning how to do this,
but is there any difference between your code and gmpy as far as
the OP is concerned? Is he going to actually learn anything from
your program or is he just going to use it? Is it going to matter
to the OP whether he uses a 3rd party module or some code (that he
doesn't understand) that he found on Usenet?

>
> > Perhaps you should use the name
>
> > comb_works_just_like_the_gmpy_version_only_slower()
>
> Or maybe 'comb_in_executable_pseudocode', but maybe some other
> implementations posted in this thread would be better suited for that.
>
> Anyway, I have the impression you just don't get the point of people
> posting various functions so that one can determine which algorithms
> work best or so that one can include each others ideas and create better
> functions that combine the best elements of all posted code. Cutting and
> pasting Python functions works a lot better in Usenet than importing C
> libraries.

"Works better" for learning the algorithms, doesn't "work better"
performance wise.

>
> If no one posts code -even if it's not completely working code- how are
> we to learn from each other?

By focusing on things that aren't available in 3rd party modules.

> The fact that someone else somewhere
> already saw the light and wrote the perfect function in optimized C or
> Fortran code should not stop us from 'reinventing the wheel' -as you
> call it- because one can get more proficient in wheel making in the
> process and every now and th

Re: strange behaviour sys.argv

2007-04-16 Thread Michael Hoffman
schnupfy wrote:

> I am not used to python and I am wondering about this thing:

This is not a Python question. It is a question about how to use bash.

I would try to help anyway, but I am unsure what results you actually 
want. Your example is too complicated as well. You should strip down 
your example to only the arguments that change. In doing this you may 
solve the problem on your own.
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strange behaviour with keyword arguments and inheritance

2007-04-16 Thread livibetter
On Apr 17, 8:56 am, "matthewperpick" <[EMAIL PROTECTED]> wrote:
> Check out this toy example that demonstrates some "strange" behaviour
> with keyword arguments and inheritance.
>
> =
>
> class Parent:
> def __init__(self, ary = []):
> self.ary = ary
>

This should work:

class Parent:
def __init__(self, ary = []):
self.ary = list(ary)

And FYI
http://groups.google.com/group/comp.lang.python/browse_thread/thread/e203f9cd64125a78/8d89b250ceca1458#8d89b250ceca1458

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


strange behaviour sys.argv

2007-04-16 Thread schnupfy
Hi,

I am not used to python and I am wondering about this thing:

If I execute this from the shell:

/root/mk/services.py 192.168.1.101 critical "192.168.1.101
192.168.1.101 SNMPv2-MIB::sysUpTime.0 14:13:02:57.06 SNMPv2-
MIB::snmpTrapOID.0 SNMPv2-SMI::enterprises.789.0.13 SNMPv2-
SMI::enterprises.789.0.2"cfCannotTakeover == 1 priority == critical"
SNMP-COMMUNITY-MIB::snmpTrapAddress.0 192.168.1.101 SNMP-COMMUNITY-
MIB::snmpTrapCommunity.0 "public""

I have the following cmd arguments:

['/root/mk/services.py', '192.168.1.101', 'critical', '192.168.1.101
192.168.1.101 SNMPv2-MIB::sysUpTime.0 14:13:02:57.06 SNMPv2-
MIB::snmpTrapOID.0 SNMPv2-SMI::enterprises.789.0.13 SNMPv2-
SMI::enterprises.789.0.2cfCannotTakeover', '==', '1', 'priority',
'==', 'critical SNMP-COMMUNITY-MIB::snmpTrapAddress.0 192.168.1.101
SNMP-COMMUNITY-MIB::snmpTrapCommunity.0 public']

If I execute the same thing from a bash script:

#!/bin/bash
TRAP='192.168.1.101 192.168.1.101 SNMPv2-MIB::sysUpTime.0
14:13:02:57.06 SNMPv2-MIB::snmpTrapOID.0 SNMPv2-SMI::enterprises.
789.0.13 SNMPv2-SMI::enterprises.789.0.2"cfCannotTakeover == 1
priority == critical" SNMP-COMMUNITY-MIB::snmpTrapAddress.0
192.168.1.101 SNMP-COMMUNITY-MIB::snmpTrapCommunity.0 "public"'
HOST=$(echo "$TRAP" | awk '{print $1}')
SEVERITY='critical'
/root/mk/services.py $HOST $SEVERITY \"$TRAP\"

I get the following result:

['/root/mk/services.py', '192.168.1.101', 'critical',
'"192.168.1.101', '192.168.1.101', 'SNMPv2-MIB::sysUpTime.0',
'14:13:02:57.06', 'SNMPv2-MIB::snmpTrapOID.0', 'SNMPv2-
SMI::enterprises.789.0.13', 'SNMPv2-SMI::enterprises.
789.0.2"cfCannotTakeover', '==', '1', 'priority', '==', 'critical"',
'SNMP-COMMUNITY-MIB::snmpTrapAddress.0', '192.168.1.101', 'SNMP-
COMMUNITY-MIB::snmpTrapCommunity.0', '"public""']

Can someone help me with that?

This is the output of echo /root/mk/services.py $HOST $SEVERITY \"$TRAP
\"

/root/mk/services.py 192.168.1.101 critical "192.168.1.101
192.168.1.101 SNMPv2-MIB::sysUpTime.0 14:13:02:57.06 SNMPv2-
MIB::snmpTrapOID.0 SNMPv2-SMI::enterprises.789.0.13 SNMPv2-
SMI::enterprises.789.0.2"cfCannotTakeover == 1 priority == critical"
SNMP-COMMUNITY-MIB::snmpTrapAddress.0 192.168.1.101 SNMP-COMMUNITY-
MIB::snmpTrapCommunity.0 "public""

Thank you.

Cheers

Marcus

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


Re: strange behaviour with keyword arguments and inheritance

2007-04-16 Thread [EMAIL PROTECTED]
On Apr 17, 8:56 am, "matthewperpick" <[EMAIL PROTECTED]> wrote:
> Check out this toy example that demonstrates some "strange" behaviour
> with keyword arguments and inheritance.
>
> =
>
> class Parent:
> def __init__(self, ary = []):
> self.ary = ary
>
> def append(self):
> self.ary.append(1)
>
> class Child(Parent):
> def __init__(self):
> Parent.__init__(self)
> self.append()
>
> def main():
> a = Child()
> print a.ary
> b = Child()
> print b.ary
>
> main()
>
> =
>
> You would think the output of this program would be [1], [1]. But
> strangely enough the output is [1,], [1,1]. I suppose that the
> Parent.__class__ object is only created once and thus the keyword
> argument always refers to the same thing, but I don't know. I have a
> very rudimentary understading of python's guts, but I would still call
> the behaviour unexpected. Or perhaps I should rtfm?
>
> Any thoughts would be much appreciated. Thanks.

A slight modification of init-ing the parent can give you the expected
output.

class Child(Parent):
def __init__(self):
Parent.__init__(self, [])
self.append()


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


list insertion question

2007-04-16 Thread eight02645999
hi
i have a list (after reading from a file), say
data = [ 'a','b','c','d','a','b','e','d']

I wanted to insert a word after every 'a', and before every 'd'. so i
use enumerate this list:
for num,item in enumerate(data):
if "a" in item:
data.insert(num+1,"aword")
if "d" in item:
data.insert(num-1,"dword") #this fails
but the above only inserts after 'a' but not before 'd'.  What am i
doing wrong? is there better way?thanks

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


Re: unittest assertRaises Problem

2007-04-16 Thread john
On Apr 16, 6:35 pm, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
> On 16 Apr 2007 15:13:42 -0700, john <[EMAIL PROTECTED]> wrote:
>
>
>
> >All:
>
> >Hi. I am an experienced developer (15 yrs), but new to Python and have
> >a question re unittest and assertRaises. No matter what I raise,
> >assertRaises is never successful. Here is the test code:
>
> >class Foo:
> >def testException(self):
> >   raise ValueError
>
> >class FooTestCase(unittest.TestCase):
>
> >   testTryThis(self):
> >  f = Foo()
> >  self.assertRaises(ValueError, f.testException())
>
> The 2nd argument to assertRaises should be a callable.  assertRaises
> will call it (so that it can do exception handling), so you shouldn't:
>
> self.assertRaises(ValueError, f.testException)
>
> Jean-Paul

Steven, Jean-Paul:

Thank you both for your answers - worked like a charm!

Best,
John

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


strange behaviour with keyword arguments and inheritance

2007-04-16 Thread matthewperpick
Check out this toy example that demonstrates some "strange" behaviour
with keyword arguments and inheritance.

=

class Parent:
def __init__(self, ary = []):
self.ary = ary

def append(self):
self.ary.append(1)

class Child(Parent):
def __init__(self):
Parent.__init__(self)
self.append()

def main():
a = Child()
print a.ary
b = Child()
print b.ary

main()

=

You would think the output of this program would be [1], [1]. But
strangely enough the output is [1,], [1,1]. I suppose that the
Parent.__class__ object is only created once and thus the keyword
argument always refers to the same thing, but I don't know. I have a
very rudimentary understading of python's guts, but I would still call
the behaviour unexpected. Or perhaps I should rtfm?

Any thoughts would be much appreciated. Thanks.

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


python-list@python.org

2007-04-16 Thread bearophileHUGS
Once in while I too have something to ask. This is a little problem
that comes from a Scheme Book (I have left this thread because this
post contains too much Python code for a Scheme newsgroup):
http://groups.google.com/group/comp.lang.scheme/browse_thread/thread/a059f78eb4457d08/

The function multiremberandco is hard (for me still) if done in that
little Scheme subset, but it's very easy with Python. It collects two
lists from a given one, at the end it applies the generic given fun
function to the two collected lists and returns its result:

def multiremberandco1(el, seq, fun):
l1, l2 = [], []
for x in seq:
if x == el:
l2.append(el)
else:
l1.append(el)
return fun(l1, l2)

data = [1, 'a', 3, 'a', 4, 5, 6, 'a']
print multiremberandco1('a', data, lambda l1,l2: (len(l1), len(l2)))

More compact:

def multiremberandco2(el, seq, fun):
l1, l2 = [], []
for x in seq:
[l1, l2][x == el].append(el)
return fun(l1, l2)


A bit cleaner (but I don't like it much):

def multiremberandco3(el, seq, fun):
l1, l2 = [], []
for x in seq:
(l2 if x == el else l1).append(el)
return fun(l1, l2)


For fun I have tried to make it lazy, if may be useful if seq is a
very long iterable. So I've used tee:

from itertools import ifilter, tee

def multiremberandco4(el, iseq, fun):
iseq1, iseq2 = tee(iseq)
iterable1 = ifilter(lambda x: x == el, iseq1)
iterable2 = ifilter(lambda x: x != el, iseq2)
return fun(iterable1, iterable2)

def leniter(seq):
count = 0
for el in seq:
count += 1
return count

idata = iter(data)
print multiremberandco4('a', idata, lambda l1,l2: (leniter(l1),
leniter(l2)))


But from the docs: >in general, if one iterator is going to use most
or all of the data before the other iterator, it is faster to use
list() instead of tee().<

So I have tried to create two iterables for the fun function scanning
seq once only, but I haven't succed so far (to do it I have tried to
use two coroutines with the enhanced generators, sending el to one or
to the other according to the value of x == el, this time I don't show
my failed versions), do you have suggestions?

(Note: in some situations it may be useful to create a "splitting"
function that given an iterable and a fitering predicate, returns two
lazy generators, of the items that satisfy the predicate and of the
items that don't satisfy it, so this exercise isn't totally useless).

Bye,
bearophile

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


Re: combination function in python

2007-04-16 Thread Anton Vredegoor
[EMAIL PROTECTED] wrote:

> Isn't that what docstrings are for? Can't you leave
> the function name noverk() and add something to the
> effect of "this function calculates combinations"?
> Then it would show up in searches, wouldn't it?

Yes, a doc string would help finding it in searches, however since this 
thread now contains a collection of function names it will suffice.

There is also the other consideration of being able to easily read code 
that others write. Functions that try to do the same thing having the 
same name would help. If we had some module in the standard distro that 
would contain comb and fac and maybe a few other functions people could 
start using the same name to point to the same thing etc.

 def noverk(n,k):
 ? ? ?return reduce(lambda a,b: a*(n-b)/(b+1),xrange(k),1)
>> This is a rather concise function which has the added advantage that it
>> returns 0 when k>n.
> 
> import gmpy
> print gmpy.comb(4,8)
> 
> ## 0

There is more to it than that. If I see the way the function computes 
the values it gives me hints about how I could write a function that 
lists all combinations.

For example the fact that one can divide the product 'on the fly' -I 
mean without computing the totals above and below the division bar- 
tells me something about how to tackle the problem of generating the 
corresponding combinatorial structure. I *love* combinatorial 
structures. Little functions like this have more than once helped me to 
understand them better.

Math is not so much my way of describing things, I like executable 
pseudo code better. Sometimes I had to read math formulas and have 
become somewhat used to that notation -it has its uses too- but if 
things are written down in code I can rely on the *computer* to execute 
the code instead of my brain which unfortunately is not as reliable.

These advantages are lost when one just imports some optimized code library.

> Perhaps you should use the name
> 
> comb_works_just_like_the_gmpy_version_only_slower()

Or maybe 'comb_in_executable_pseudocode', but maybe some other 
implementations posted in this thread would be better suited for that.

Anyway, I have the impression you just don't get the point of people 
posting various functions so that one can determine which algorithms 
work best or so that one can include each others ideas and create better 
functions that combine the best elements of all posted code. Cutting and 
pasting Python functions works a lot better in Usenet than importing C 
libraries.

If no one posts code -even if it's not completely working code- how are 
we to learn from each other? The fact that someone else somewhere 
already saw the light and wrote the perfect function in optimized C or 
Fortran code should not stop us from 'reinventing the wheel' -as you 
call it- because one can get more proficient in wheel making in the 
process and every now and then it even leads to better wheels.

Don't even get me started about this archaic scheme of writing code only 
for 'work' instead of for gaining insight that you seem to promote.

> But when there *is* no documentation, that becomes a problem,
> doesn't it?

This thread is also documentation and I hope it will encourage people to 
post more code and share thoughts.

> Unless you don't know how to write the functions you need
> in which case you're better off relying on external
> modules. Have you ever wondered why Python even *has*
> a standard library? Why doesn't everyone just write
> the functionality they need?

The main virtue of Pythons standard library should be that it shows one 
how to do things and that it introduces a common naming scheme. That was 
what got me interested in python in the first place: Now I got to see 
how things work! No more dark secrets and proprietary code!

Sometimes it's better to sacrifice clarity for speed and write optimized 
lower level code but that doesn't mean there aren't large trade offs 
involved.

In the future if computers will become faster it would be wise to drop 
the optimized code libraries again and reintroduce the Python versions 
of the same because by then the Python versions would be fast enough and 
it would also result in a smaller code base (but a more functional and 
flexible and readable one).

What are you doing on this planet anyway if it's not trying to 
understand things?

>> Since I'm also interested in the
>> functions themselves -in this case- I'd rather have a
>> few lines of code in my source than importing an
>> optimized code library.
> 
> Well, some people prefer optimized libraries because
> they have real work to do, not just acedemic excercizes.

Real work is just an excuse for having a larger slice of the cake than 
other people. Other people can be just as or even more essential in the 
whole process of developing code than those who get paid.

A reason against using third party libraries in general is not wanting 
to include too many external dependencies that would force the user t

UpdateLayeredWindow in pywin32

2007-04-16 Thread livibetter
Hi!

I am trying to making an On-Screen Display, which is implemented by
wx.Frame.
Basically I created a wx.Frame with style like

super(OSDBase, self).__init__(parent, id, title,
  style = 
wx.STAY_ON_TOP |
  
wx.FRAME_NO_TASKBAR |
  
wx.TRANSPARENT_WINDOW |
  wx.NO_BORDER)
self.SetTransparent(128)

But if I try to draw an image with alpha channel(like PNG format), I
always get
a background behind this image. But I don't want the background.

Then I read this article, http://www.codeproject.com/csharp/OSDwindow.asp
The demo program is written in C#. I understand that I need to use
UpdateLayeredWindow to update visual content of a layered window.

But I always got an error:

Traceback (most recent call last):
  File "osd_post.py", line 60, in 
osd.Update()
  File "osd_post.py", line 56, in Update
2)
pywintypes.error: (87, 'UpdateLayeredWindow', 'The parameter is
incorrect.')

I am not sure did I use UpdateLayeredWindow correctly.

Any help would be appreciated.


My Python is 2.5, pywin32 is 210, wxPython is 2.8.1

UpdateLayeredWindow Function Help from MSDN:
http://msdn2.microsoft.com/en-us/library/ms633556.aspx

UpdateLayeredWindow Function Help from pywin32:

http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/pywin32/win32gui__UpdateLayeredWindow_meth.html

My source code:

"""pyitctrl - OSD"""
# Created Date : 2007/03/14
# Author: livibetter

import wx, winxpgui, win32con

class OSDBase(wx.Frame):
def __init__(self, parent, id, title):
super(OSDBase, self).__init__(parent, id, title,
  style = wx.STAY_ON_TOP |
  wx.FRAME_NO_TASKBAR |
  wx.TRANSPARENT_WINDOW |
  wx.NO_BORDER)
self.SetTransparent(128)

print hex(winxpgui.GetWindowLong(self.GetHandle(),
win32con.GWL_EXSTYLE))
print winxpgui.GetLayeredWindowAttributes(self.GetHandle())

self.img = wx.Image("icon.png")
self.bmp = self.img.ConvertToBitmap()
w, h = self.bmp.GetWidth(), self.bmp.GetHeight()
self.SetClientSize( (w, h) )

def Update(self):
print "Update"

screenDC = winxpgui.GetDC(winxpgui.GetDesktopWindow())
print screenDC
cScreenDC = winxpgui.CreateCompatibleDC(0)
print cScreenDC

(w, h) = self.GetSizeTuple()
bmp = wx.EmptyBitmap(w, h)
tmpDC = wx.MemoryDC()
tmpDC.SelectObject(bmp)
tmpDC.SetBackground(wx.Brush("BLACK"))
tmpDC.Clear()
tmpDC.DrawBitmap(self.bmp,0,0, True)
tmpDC.Destroy()
del tmpDC

winxpgui.SelectObject(cScreenDC, bmp.GetHandle())

winxpgui.UpdateLayeredWindow(self.GetHandle(),
 screenDC,
 self.GetPositionTuple(),
 self.GetSizeTuple(),
 cScreenDC,
 (0,0),
 0,
 (0,0,128,1),
 win32con.ULW_ALPHA)

app = wx.App(False)
osd = OSDBase(None, wx.ID_ANY, 'OSD Frame')
osd.Update()
osd.Show()

app.MainLoop()

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


Re: Queue enhancement suggestion

2007-04-16 Thread Jean-Paul Calderone
On 15 Apr 2007 23:12:34 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid> 
wrote:
>I'd like to suggest adding a new operation
>
>   Queue.finish()
>
>This puts a special sentinel object on the queue.  The sentinel
>travels through the queue like any other object, however, when
>q.get() encounters the sentinel, it raises StopIteration instead
>of returning the sentinel.  It does not remove the sentinel from
>the queue, so further calls to q.get also raise StopIteration.
>That permits writing the typical "worker thread" as
>
>   for item in iter(q.get): ...
>
>without having to mess with the task-counting stuff that recently got
>added to the Queue module.  The writing end of the queue simply
>calls .finish() when it's done adding items.
>
>Someone in an earlier thread suggested
>
> # writing side
> sentinel = object()
> q.put(sentinel)
>
> ...
> # reading side
> for item in iter(q.get, sentinel): ...
>
>however that actually pops the sentinel, so if there are a lot of
>readers then the writing side has to push a separate sentinel for
>each reader.  I found my code cluttered with
>
>for i in xrange(number_of_worker_threads):
>   q.put(sentinel)
>
>which certainly seems like a code smell to me.

Instead of putting multiple sentinels, just pre-construct the iterator
object.

work = iter(q.get, sentinel)

Re-use the same iterator in each thread, and you'll get the behavior
you're after.

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


Re: Really badly structured Python Books.

2007-04-16 Thread Klaas
On Apr 14, 11:37 am, "Andre P.S Duarte" <[EMAIL PROTECTED]>
wrote:
> I started reading the beginning Python book. It is intended for people
> who are starting out in the Python world. But it is really
> complicated, because he tries to explain, then after a bad explanation
> he puts out a bad example. I really recommend NOT reading the book.
> For it will make you want not to continue in Python. This is just me
> letting the air out of my lungs. No need to reply this is just a
> recommendation. Txs for the opportunity .

I went ahead and didn't read the book, and I can feel the improvement
already!

-Mikw

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


Re: Queue enhancement suggestion

2007-04-16 Thread Klaas
On Apr 15, 11:12 pm, Paul Rubin  wrote:
> I'd like to suggest adding a new operation
>
>Queue.finish()
>
> This puts a special sentinel object on the queue.  The sentinel
> travels through the queue like any other object, however, when
> q.get() encounters the sentinel, it raises StopIteration instead
> of returning the sentinel.  It does not remove the sentinel from
> the queue, so further calls to q.get also raise StopIteration.
> That permits writing the typical "worker thread" as

This is a pretty good idea.  However, it needs a custom __iter__
method to work... the syntax below is wrong on many levels.

>for item in iter(q.get): ...

Once you implement __iter__, you are left with 'for item in q'.  The
main danger here is that all the threading synchro stuff is hidden in
the guts of the __iter__ implementation, which isn't terribly clear.
There is no way to handle Empty exceptions and use timeouts, for
instance.

> however that actually pops the sentinel, so if there are a lot of
> readers then the writing side has to push a separate sentinel for
> each reader.  I found my code cluttered with
>
> for i in xrange(number_of_worker_threads):
>q.put(sentinel)
>
> which certainly seems like a code smell to me.

Yeah, it kind of does.  Why not write a Queue + Worker manager that
keeps track of the number of workers, that has a .finish() method that
does this smelly task for you?

-Mike

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


Re: script for seconds in given month?

2007-04-16 Thread Paul McGuire
On Apr 16, 12:49 pm, "edfialk" <[EMAIL PROTECTED]> wrote:
> Jim: I need years too, basically from 1960-2000.  Don't want to
> hardcode all those days :)
>
> Matt: Thanks, I will try this out.
>
> Paul: I don't believe we need leap seconds.  Leap days definitely.
>
> I'll let you know how Matt's code works.  Any other suggestions feel
> free to let me know.
>
> Thanks all!
> -Ed

I googled for "NIST leap second" and found this table online of leap
seconds, if you do in fact need them: 
http://tf.nist.gov/pubs/bulletin/leapsecond.htm

-- Paul

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


Re: unittest assertRaises Problem

2007-04-16 Thread Jean-Paul Calderone
On 16 Apr 2007 15:13:42 -0700, john <[EMAIL PROTECTED]> wrote:
>All:
>
>Hi. I am an experienced developer (15 yrs), but new to Python and have
>a question re unittest and assertRaises. No matter what I raise,
>assertRaises is never successful. Here is the test code:
>
>
>class Foo:
>def testException(self):
>   raise ValueError
>
>class FooTestCase(unittest.TestCase):
>
>   testTryThis(self):
>  f = Foo()
>  self.assertRaises(ValueError, f.testException())
>

The 2nd argument to assertRaises should be a callable.  assertRaises
will call it (so that it can do exception handling), so you shouldn't:

self.assertRaises(ValueError, f.testException)

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


Re: unittest assertRaises Problem

2007-04-16 Thread attn . steven . kuo
On Apr 16, 3:13 pm, "john" <[EMAIL PROTECTED]> wrote:
> All:
>
> Hi. I am an experienced developer (15 yrs), but new to Python and have
> a question re unittest and assertRaises. No matter what I raise,
> assertRaises is never successful. Here is the test code:
>
> class Foo:
> def testException(self):
>raise ValueError
>
> class FooTestCase(unittest.TestCase):
>
>testTryThis(self):
>   f = Foo()
>   self.assertRaises(ValueError, f.testException())
>


The second argument should be a callable object, not the
result from invoking that callable object.  Thus, change

self.assertRaises(ValueError, f.testException())

to

self.assertRaises(ValueError, f.testException)

--
Hope this helps,
Steven

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


unittest assertRaises Problem

2007-04-16 Thread john
All:

Hi. I am an experienced developer (15 yrs), but new to Python and have
a question re unittest and assertRaises. No matter what I raise,
assertRaises is never successful. Here is the test code:


class Foo:
def testException(self):
   raise ValueError

class FooTestCase(unittest.TestCase):

   testTryThis(self):
  f = Foo()
  self.assertRaises(ValueError, f.testException())

This fails --- unittest reports the following:
FAILED (errors=1)

This seems like the most basic thing in the world. I am running Python
2.5 on Windows XP using Eclipse and PyDev

Any help appreciated.

Thanks,
John

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


Re: Pyqt calling a custom dialog and returning the vars

2007-04-16 Thread David Boddie
On Monday 16 April 2007 22:06, Marcpp wrote:

> I call a dialog from a principal program but cannot return the value
> of the
> variables (text box's). Here is a example...

[...]

> class ag (Agenda):
> ...
> ...
> def _slotAddClicked(self):
> d=dialogo1()
> d.exec_()
> d.connect(d.buttonOk,SIGNAL("clicked()"),self._procesadialog1)
> 
> def _procesadialog1():
> d=dialogo1()
> drempresa = d.dempresa.text()
> print drempresa  #

Without seeing more of what you've done, it's difficult to tell, but
you are just creating a new dialog in _procesadialog1() and reading
the default text in its "dempresa" attribute which I presume is a
QLineEdit widget.

Assuming everything else is working correctly, I think you should
remove the second method and rewrite the first one in the following
way:

class ag (Agenda):
...
...
def _slotAddClicked(self):
d=dialogo1()
if d.exec_() == QDialog.Accepted:
drempresa = d.dempresa.text()
print drempresa  #

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


Re: OverflowError: mktime argument out of range ???

2007-04-16 Thread John Machin
On Apr 17, 1:02 am, "Paul Boddie" <[EMAIL PROTECTED]> wrote:
> John Machin wrote:
>
> > Maybe it does. It sure would be nice to get a definite answer. Pity
> > nobody documented the time module.
>
> "The epoch is the point where the time starts. On January 1st of that
> year, at 0 hours, the ``time since the epoch'' is zero. For Unix, the
> epoch is 1970. To find out what the epoch is, look at gmtime(0)."
>
> "The functions in this module do not handle dates and times before the
> epoch or far in the future."
>
> http://docs.python.org/lib/module-time.html
>

Hypothesis 1: I must have missed that somehow!
Hypothesis 2: That page wasn't there yesterday!
Hypothesis 3: You may need to consider rebooting your irony detector.

FWIW you didn't quote what it says about the function that the OP was
calling (mktime):

"""If the input value cannot be represented as a valid time, either
OverflowError or ValueError will be raised (which depends on whether
the invalid value is caught by Python or the underlying C libraries).
The earliest date for which it can generate a time is platform-
dependent."""

Cheers,
John


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


Re: Pyqt calling a custom dialog and returning the vars

2007-04-16 Thread Diez B. Roggisch
Marcpp schrieb:
> I call a dialog from a principal program but cannot return the value
> of the
> variables (text box's). Here is a example...
> 
> 
> 
> from ui import Agenda
> from dialog1 import dialogo1
> from PyQt4 import *
> import dbm
> import sys
> 
> class principal (QApplication):
> 
> def __init__(self, args):
> """ In the constructor we're doing everything to get our
> application
> started, which is basically constructing a basic
> QApplication by
> its __init__ method, then adding our widgets and finally
> starting
> the exec_loop."""
> QApplication.__init__(self,args)
> 
> # We pass None since it's the top-level widget, we could in
> fact leave
> # that one out, but this way it's easier to add more dialogs
> or widgets.
> self.maindialog = ag(None)
> 
> self.setMainWidget(self.maindialog)
> self.maindialog.show()
> self.exec_loop()
> 
> class ag (Agenda):
> ...
> ...
> def _slotAddClicked(self):
> d=dialogo1()
> d.exec_()
> d.connect(d.buttonOk,SIGNAL("clicked()"),self._procesadialog1)

Shouldn't you connect the signal _before_ the dialog is shown?


> def _procesadialog1():
> d=dialogo1()
> drempresa = d.dempresa.text()
> print drempresa  #
> < Nothing
> appears
> ...
> ...
> if __name__ == "__main__":
> app = principal(sys.argv)
> 

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


[OT] Re: is laziness a programer's virtue?

2007-04-16 Thread D Herring
Xah Lee wrote:
> In a couple of posts in the past year i have crossed-posted (e.g.
> recently “What are OOP's Jargons and Complexities”, “is laziness a
> programer's virtue?”, “On Java's Interface (the meaning of interface
> in computer programing)” ), there are a some controversy, and lots of
> off-topic and careless follow ups.

Please don't dismiss so many posts as being "off-topic and careless".

> I think a few things today's tech geekers should remind themselves:
> 
> • If you deem something off-topic to “your” newsgroup, and want to
> tech-geek by changing the “follow-up group”, start with yourself.
> Please do not cross-post yourself, and tweak the follow-up, and
> proudly proclaim that you changed the follow-up as a benign gesture.
...

A few more points:
- I know many geeks but not so many geekers...
http://www.urbandictionary.com/define.php?term=geeker

- Please topquote snippets from the threads about which you are commenting.

- Please set your newsreader to prepend "Re: " or somesuch when replying 
to a toplevel post.

- Please don't preach about "meta-talk and policing" in a post which is 
mostly meta-talk and preaching.

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

Re: Python editor/IDE on Linux?

2007-04-16 Thread Bruno Desthuilliers
Ali a écrit :
> On 14 Apr, 05:48, "Jack" <[EMAIL PROTECTED]> wrote:
> 
>>That's a good one. I got to find out what's special with Emacs :)
> 
> 
> The users.
> 
+10 OT-QOTW !-)

(ouch, it hurts...)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C++ extension problem

2007-04-16 Thread Martin v. Löwis
> Now this is what confuses me: Why does it say that I have the wrong
> type when it's the same type as it suggests?

When referring to the type, you must *always* form the address of the
type structure, including, but not limited to, the line

> if (!PyArg_ParseTuple(args, "O!", SillyStringType, &o))

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


Re: Python and SSL

2007-04-16 Thread Martin v. Löwis
> - I noticed that socket module provides an SSL class (socket.ssl) but
> even if documentation reports that it does not do any certificate
> verification a lot of stdlib modules (imaplib, poplib, smtplib,
> httplib and urllib2) provides SSL extension classes wherein socket.ssl
> is used. What does it mean?

It means that these modules can do encrypted communication for their
respective protocol. They cannot validate that they are really talking
to the server they think they talk to (so they are prone to a
man-in-the-middle attack), however, as communication is encrypted, they
are protected against wire-tapping. Also, some servers require
encrypted connections (e.g. when passwords are transmitted), so they
can use SSL for that.

> - On top of that why such extension classes [examples: 1, 2, 3]
> accepts key-files and cert-files as optional argouments if no
> certificate verification occurs?
> [1] poplib.POP3_SSL( host[, port[, keyfile[, certfile]]])
> [2] imaplib.IMAP4_SSL( [host[, port[, keyfile[, certfile)
> [3] smtplib.starttls( [keyfile[, certfile]])

These are client certificates. Some servers require that clients
authenticate through client certificates. This effectively avoids
man-in-the-middle attacks, as the server will validate the client's
certificate.

> - By searching through the web I found some daemons supporting SSL
> such as this one:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442473
> By looking at the code I notice that pyopenssl package is used and
> that a certificate file is required. Why do I need to use pyopenssl
> and how do I generate the cert file?

You can generate certificate files using the openssl command line
tool; see the openssl documentation for details.

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


Re: Compare regular expressions

2007-04-16 Thread Adam Atlas
On Apr 16, 1:50 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> It's not. For the simplest of expressions one might come up with a
> relation between them, but even that would be hard. General case? No chance.

I wouldn't say there's 'no chance'. It would require external parsing,
for sure, but if anything, it may only be impossible for unusual
cases.

(Maybe I'll try this the next time I feel like writing parsers for fun
(which is surprisingly frequently).)

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


is laziness a programer's virtue?

2007-04-16 Thread Xah Lee
2007-03-29

Dear tech geekers,

In a couple of posts in the past year i have crossed-posted (e.g.
recently “What are OOP's Jargons and Complexities”, “is laziness a
programer's virtue?”, “On Java's Interface (the meaning of interface
in computer programing)” ), there are a some controversy, and lots of
off-topic and careless follow ups.

I think a few things today's tech geekers should remind themselves:

• If you deem something off-topic to “your” newsgroup, and want to
tech-geek by changing the “follow-up group”, start with yourself.
Please do not cross-post yourself, and tweak the follow-up, and
proudly proclaim that you changed the follow-up as a benign gesture.

• Please remind yourself what is on-topic and off-topic. Unless you
are the auhority of a online forum, otherwise, Meta-talk, and
policing, are off-topic in general, and only tends to worsen the
forum's quality. This issue is cleared up in online communications as
early as early 1990s.

• The facility of cross-posting is a good thing as a progress of
communication technology, and the action of cross-posting is a good
thing with respect to communication. What the common tech-geekers's
sensitivity to cross-posting are due to this collective's lack of
understanding of social aspects of communication. Cross-posting isn't
a problem. The problem is the power-struggling male nature and
defensiveness in propergating the tongues of a tech geeker's own.

  Tech-geeker's behavior towards cross-posting over the years did
nothing to enhance the content quality of newsgroups, but engendered
among computing language factions incommunicado, and aided in the
proliferation of unnecessary re-invention (e.g. the likes of Perl,
PHP, Python, Ruby that are essentially the same) and stagnation (e.g.
the lisp camp with their above-it attitude).

If you are a programer of X and is learning Y or wondering about Y,
please do cross-post it.  If your article is relevant to X, Y, and Z,
please cross post it.  If you are really anti-cross-posting, please
use a online forum that is more specialized with controlled
communication, such as mailing lists, developer's blogs, and website-
based forums.

I hope that the computing newsgroups will revive to its ancient nature
of verdant cross communication of quality content, as opposed to
today's rampant messages focused on politics, mutual sneering, closed-
mindedness, and careless postings.

References:

“Tech Geekers versus Spammers”
http://xahlee.org/UnixResource_dir/writ/tech_geekers_vs_spammers.html

Netiquette Guidelines, 1995, by S Hambridge. (RFC 1855)
http://tools.ietf.org/html/rfc1855

  Xah
  [EMAIL PROTECTED]
∑ http://xahlee.org/

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

Re: Python + ogr module?

2007-04-16 Thread kyosohma
On Apr 16, 11:36 am, Szkandera.Karel <[EMAIL PROTECTED]>
wrote:
> Hi,
> I need to do web service, which will be convert vector formats, like 
> shapefile, dgn, mapinfo..(and other formats, which are supported in gdal - 
> ogr2ogr). I want to do it with using ogr2ogr in the ogr python module, but i 
> am newbie in python, so here is my questions. Is here anybody, who wrote any 
> similar scripts and can give it me? If not, can at least anyone point me to 
> few examples of using ogr2ogr in the ogr
> python module?
>
> Thank you for every answer, K.Szkandera

Not much info is out there. Sheesh! Here's an example I found:
http://postgis.refractions.net/support/wiki/index.php?OGR%20Examples

And here's some more:

http://zcologia.com/news/16/graticule-hacking-with-ogr/
http://www.perrygeo.net/wordpress/?p=4

Sorry I couldn't find more. I know nothing about this module.

Good luck!

Mike

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


Re: looking for library to read ppt files

2007-04-16 Thread kyosohma
On Apr 16, 1:42 pm, Larry Bates <[EMAIL PROTECTED]> wrote:
> Aljosa Mohorovic wrote:
> > i'm looking for a way to read ppt (powerpoint) files using python and
> > to convert slides into jpeg files.
> > any links or tips how to do this?
>
> Not really a Python question but Google turned up:
>
> http://www.sharewareconnection.com/ppt-to-jpeg-jpg-tiff-bmps-converte...http://www.print-driver.com/howto/converting/convert_microsoft_powerp...
>
> -Larry

I suppose you could also use the win32 module and the COM object to
grab the info from the slide and then use the PIL module to create a
jpeg. Sounds like a lot of head banging to me, but it might be an
interesting project.

For info on accessing PowerPoint with Python, see links below:

http://www.thescripts.com/forum/thread592690.html
http://www.thescripts.com/forum/thread19132.html
http://www.p-nand-q.com/python/ms_office.html

Also see Hammond's "Python Programming on Win32" book or Chun's Core
Python Programming". Both have some examples of accessing MS Apps.

PIL can be found at: http://www.pythonware.com/products/pil/

Mike

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


Re: Printing Using Python

2007-04-16 Thread kyosohma
On Apr 16, 2:13 pm, "Raja" <[EMAIL PROTECTED]> wrote:
> Hi,
>   Attached is the code . I want my program to save the current printer
> job properties and , when I reconnect the printer at a latter date , i
> need to print the saved job . Can you please help with my code ? How
> to print a document at a later stage and any errors in my code ?
>
> import win32ui
> import win32con
>
> myprinter_name = ""
> # get the name from your Printers folder
>
> printer_properties=[]
>
> def save():
>  pHandle = win32print.OpenPrinter(myprinter_name)
>  properties = win32print.GetPrinter(pHandle, 2)
>  pDevModeObj = properties["pDevMode"]
>  printer_properties.append(pDevModeObj.FormName)
>  printer_properties.append(pDevModeObj.PaperSize)
>  printer_properties.append(pDevModeObj.Orientation)
>  printer_properties.append(pDevModeObj.Color)
>  printer_properties.append(pDevModeObj.Copies)
>  printer_properties.append(pDevModeObj.DefaultSource)
>  win32print.ClosePrinter(pHandle)
>
> def apply():
> hprinter = win32print.OpenPrinter(myprinter_name)
>
> devmode = win32print.GetPrinter(hprinter, 2)["pDevMode"]
> devmode.FormName=printer_properties[0]
> devmode.PaperSize=printer_properties[1]
> devmode.Orientation=printer_properties[2]
> devmode.Color=printer_properties[3]
> devmode.Copies=printer_properties[4]
> devmode.DefaultSource=printer_properties[5]
>
> hdc = win32gui.CreateDC("WinPrint",myprinter_name,devmode)
> dc = win32ui.CreateDCFromHandle(hdc)
>
> dc.StartDoc('My Python Document')
> dc.StartPage()
> dc.EndPage()
> dc.EndDoc()
> del dc
>
> You help is greatly appreciated.
>
> Thank You,
> Raja.

This sounds like a job for the pickle: 
http://docs.python.org/lib/module-pickle.html

I would try "pickling" the printer_properties list and when you later
need the pickled printer properties, unpickle them.

Mike

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


Re: moving multiple directories

2007-04-16 Thread ici
On Apr 16, 9:36 pm, Larry Bates <[EMAIL PROTECTED]> wrote:
> DataSmash wrote:
> > Hi,
> > I need to organize thousands of directories full of files.
> > I want to move these directories into other subdirectories.
> > For example, all the directories that start with 01, move to
> > a directory named "one", all directories that start with 02, move
> > to a directory name "two", and so on
>
> > I can't seem to find any easy way to do this.
> > Looks like shutil.move only lets you move if the subdirectory DOES
> > NOT exist, so after the first directory moves, the script blows up on
> > the second move.
> > I guess you could use shutil.copy or shutil.copytree but then you have
> > to
> > delete as well.  Much longer process when you have hundreds of
> > gigabytes of data.
>
> > Thanks for your help!
> > R.D.
>
> Use win32.moveFile method instead.  This links directly to the Windows
> MoveFile method that just moves the directory entries around.
>
> From Win32 Documentation:
>
> win32api.MoveFile
> MoveFile(srcName, destName)
>
> Renames a file, or a directory (including its children).
>
> Parameters
>
> srcName : string
>
> The name of the source file.
>
> destName : string
>
> The name of the destination file.
>
> Comments
> This method can not move files across volumes.
>
> -Larry

Instead win32api, use "native" shutil module

import shutil
shutil.move(src,dest)

Recursively move a file or directory to another location.

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


Re: Python editor/IDE on Linux?

2007-04-16 Thread Joshua J. Kugler
On Friday 13 April 2007 10:20, Jack wrote:

> I wonder what everybody uses for Python editor/IDE on Linux?
> I use PyScripter on Windows, which is very good.

I'm using  WingWare's WingIDE.  Visual debugger, python-scriptable,
projects, code-completion that is second-to-none (I LOVE it.).  And a very
responsive support team.  Yes, it's commercial, but it's cheaper than
Komodo, and works a lot better for Python.

Plus, it's written in Python, so the developers eat their own dog food. 
During the development cycle for 3.0 (it's at Alpha 1 right now*), all they
used to development was the active code base.

*I'm using 3.0a1 right now for my development work, and have not had a
single crash or glitch.  It's good stuff.

j

-- 
Joshua Kugler
Lead System Admin -- Senior Programmer
http://www.eeinternet.com
PGP Key: http://pgp.mit.edu/  ID 0xDB26D7CE

-- 
Posted via a free Usenet account from http://www.teranews.com

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

Pyqt calling a custom dialog and returning the vars

2007-04-16 Thread Marcpp
I call a dialog from a principal program but cannot return the value
of the
variables (text box's). Here is a example...



from ui import Agenda
from dialog1 import dialogo1
from PyQt4 import *
import dbm
import sys

class principal (QApplication):

def __init__(self, args):
""" In the constructor we're doing everything to get our
application
started, which is basically constructing a basic
QApplication by
its __init__ method, then adding our widgets and finally
starting
the exec_loop."""
QApplication.__init__(self,args)

# We pass None since it's the top-level widget, we could in
fact leave
# that one out, but this way it's easier to add more dialogs
or widgets.
self.maindialog = ag(None)

self.setMainWidget(self.maindialog)
self.maindialog.show()
self.exec_loop()

class ag (Agenda):
...
...
def _slotAddClicked(self):
d=dialogo1()
d.exec_()
d.connect(d.buttonOk,SIGNAL("clicked()"),self._procesadialog1)

def _procesadialog1():
d=dialogo1()
drempresa = d.dempresa.text()
print drempresa  #
< Nothing
appears
...
...
if __name__ == "__main__":
app = principal(sys.argv)

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


Re: Compare regular expressions

2007-04-16 Thread Paddy
On Apr 16, 10:50 am, Thomas Dybdahl Ahle <[EMAIL PROTECTED]> wrote:
> Hi, I'm writing a program with a large data stream to which modules can
> connect using regular expressions.
>
> Now I'd like to not have to test all expressions every time I get a line,
> as most of the time, one of them having a match means none of the others
> can have so.
>
> But ofcource there are also cases where a regular expression can
> "contain" another expression, like in:
> "^strange line (\w+) and (\w+)$" and "^strange line (\w+) (?:.*?)$" in
> which case I'd like to first test the seccond and only if it mathces test
> the seccond.
>
> Do anybody know if such a test is possible?
> if exp0.contains(exp1): ...

you could OR all the individual RE's test them all at once then find
out which matched.

big_re = "|".join( r"(?P<__match_%i__>%s)" % (i, r)
   for i,r in enumerate(regexps) )

now if one of the regexps matches then the corresponding named
group should have a non-empty string value.

- Paddy.

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


Re: script for seconds in given month?

2007-04-16 Thread Shane Geiger


import datetime

def first_day_of_next_month( year, month ):
   """returns the first day of the next month
   >>> first_day_of_next_month(2007,5)
   datetime.datetime(2007, 6, 1, 0, 0)
   >>> first_day_of_next_month(2007,12)
   datetime.datetime(2008, 1, 1, 0, 0)
   """
   oneday = datetime.timedelta(days=1)
   day = datetime.datetime(year, month, 1)
   if day.day == 1:
   day += oneday
   while day.day != 1:
   day += oneday
   return day


from time import mktime
def secondsInMonth(year, month):
   s1 = mktime((year,month,1,0,0,0,0,0,-1))
   day = first_day_of_next_month(year, month)
   year = day.year
   month = day.month
   s2 = mktime((year,month+1,1,0,0,0,0,0,-1))
   return s2-s1


year = 2007
month = 2
print secondsInMonth(year, month)





[EMAIL PROTECTED] wrote:

Matt> from time import mktime
Matt> def secondsInMonth(year, month):
Matt> s1 = mktime((year,month,1,0,0,0,0,0,-1))
Matt> s2 = mktime((year,month+1,1,0,0,0,0,0,-1))
Matt> return s2-s1

Probably won't work if month==12. ;-)

Skip
  


--
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

begin:vcard
fn:Shane Geiger
n:Geiger;Shane
org:National Council on Economic Education (NCEE)
adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States
email;internet:[EMAIL PROTECTED]
title:IT Director
tel;work:402-438-8958
x-mozilla-html:FALSE
url:http://www.ncee.net
version:2.1
end:vcard

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

Re: C++ extension problem

2007-04-16 Thread Michael Hoffman
[EMAIL PROTECTED] wrote:

> I'm having a bit of trouble when writing a python extension. I can't
> seem to figure out what I did wrong.
> I tried to make a minimal example, but it's still quite a bit of
> code.
> It would be very appreciated if anyone could tell me what I've done
> wrong.

I can't answer your question since I have no experience writing 
extension types. I know this is at least partially a learning exercise 
for you, but might I suggest that your time might be better spent 
learning Boost.Python instead? It is "a C++ library which enables 
seamless interoperability between C++ and the Python programming language."

http://www.boost.org/libs/python/doc/
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: moving multiple directories

2007-04-16 Thread DataSmash
Thanks Larry, I'll give that a try...
R.D.



>
> Use win32.moveFile method instead.  This links directly to the Windows
> MoveFile method that just moves the directory entries around.
>
> From Win32 Documentation:
>
> win32api.MoveFile
> MoveFile(srcName, destName)
>
> Renames a file, or a directory (including its children).
>
> Parameters
>
> srcName : string
>
> The name of the source file.
>
> destName : string
>
> The name of the destination file.
>
> Comments
> This method can not move files across volumes.
>
> -Larry


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


Printing Using Python

2007-04-16 Thread Raja
Hi,
  Attached is the code . I want my program to save the current printer
job properties and , when I reconnect the printer at a latter date , i
need to print the saved job . Can you please help with my code ? How
to print a document at a later stage and any errors in my code ?

import win32ui
import win32con

myprinter_name = ""
# get the name from your Printers folder

printer_properties=[]

def save():
 pHandle = win32print.OpenPrinter(myprinter_name)
 properties = win32print.GetPrinter(pHandle, 2)
 pDevModeObj = properties["pDevMode"]
 printer_properties.append(pDevModeObj.FormName)
 printer_properties.append(pDevModeObj.PaperSize)
 printer_properties.append(pDevModeObj.Orientation)
 printer_properties.append(pDevModeObj.Color)
 printer_properties.append(pDevModeObj.Copies)
 printer_properties.append(pDevModeObj.DefaultSource)
 win32print.ClosePrinter(pHandle)

def apply():
hprinter = win32print.OpenPrinter(myprinter_name)

devmode = win32print.GetPrinter(hprinter, 2)["pDevMode"]
devmode.FormName=printer_properties[0]
devmode.PaperSize=printer_properties[1]
devmode.Orientation=printer_properties[2]
devmode.Color=printer_properties[3]
devmode.Copies=printer_properties[4]
devmode.DefaultSource=printer_properties[5]

hdc = win32gui.CreateDC("WinPrint",myprinter_name,devmode)
dc = win32ui.CreateDCFromHandle(hdc)

dc.StartDoc('My Python Document')
dc.StartPage()
dc.EndPage()
dc.EndDoc()
del dc


You help is greatly appreciated.

Thank You,
Raja.

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


Re: getting from command line options to file

2007-04-16 Thread Michael Hoffman
CSUIDL PROGRAMMEr wrote:
> hi folks
> I am new to python. I have a module does call a os.command(cmd) where
> cmd is a rpm command.
> Instead of using os.command and getting the results on command line ,
> i would like to dump the output in a file. Is os.command(cmd >
> filename)  the most efficient command??

I think the best thing to do would be something like this (Python 2.5):

from __future__ import with_statement
import subprocess

with file("test.out", "w") as outfile:
 subprocess.check_call(["ls", "/etc"], stdout=outfile)
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to check the 'content/type' using urlopen

2007-04-16 Thread John J. Lee
Michael Bentley <[EMAIL PROTECTED]> writes:

> On Apr 15, 2007, at 6:25 PM, John wrote:
> 
> >
> > i have the following code to open a URL address, but can you please
> > tell me how can I check the content type of the url response?
> >
> > Thank you.
> >
> >   try:
> > req = Request(url, txdata, txheaders)
> > handle = urlopen(req)
> > except IOError, e:
> > print e
> > print 'Failed to open %s' % url
> > return 0;
> >
> > else:
> > data = handle.read()
> 
> Not absolutely sure about this, but try handle.headers.get('Content-
> Type') before the read.

handle.get_header("Content-type")


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


Re: looking for library to read ppt files

2007-04-16 Thread Larry Bates
Aljosa Mohorovic wrote:
> i'm looking for a way to read ppt (powerpoint) files using python and
> to convert slides into jpeg files.
> any links or tips how to do this?
> 

Not really a Python question but Google turned up:

http://www.sharewareconnection.com/ppt-to-jpeg-jpg-tiff-bmps-converter.htm
http://www.print-driver.com/howto/converting/convert_microsoft_powerpoint_presentation_to_jpeg.htm


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


Re: moving multiple directories

2007-04-16 Thread Larry Bates
DataSmash wrote:
> Hi,
> I need to organize thousands of directories full of files.
> I want to move these directories into other subdirectories.
> For example, all the directories that start with 01, move to
> a directory named "one", all directories that start with 02, move
> to a directory name "two", and so on
> 
> I can't seem to find any easy way to do this.
> Looks like shutil.move only lets you move if the subdirectory DOES
> NOT exist, so after the first directory moves, the script blows up on
> the second move.
> I guess you could use shutil.copy or shutil.copytree but then you have
> to
> delete as well.  Much longer process when you have hundreds of
> gigabytes of data.
> 
> Thanks for your help!
> R.D.
> 
Use win32.moveFile method instead.  This links directly to the Windows
MoveFile method that just moves the directory entries around.

>From Win32 Documentation:

win32api.MoveFile
MoveFile(srcName, destName)

Renames a file, or a directory (including its children).

Parameters

srcName : string

The name of the source file.

destName : string

The name of the destination file.

Comments
This method can not move files across volumes.

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


getting from command line options to file

2007-04-16 Thread CSUIDL PROGRAMMEr
hi folks
I am new to python. I have a module does call a os.command(cmd) where
cmd is a rpm command.
Instead of using os.command and getting the results on command line ,
i would like to dump the output in a file. Is os.command(cmd >
filename)  the most efficient command??


thanks

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


Re: subprocess confusion

2007-04-16 Thread Michael Hoffman
Tim Arnold wrote:

> If 'machine' value is different than the current machine name, I want to 
> remsh the command to that machine, but obviously I misunderstood the 
> preexec_fn arg.

I don't think the return value of preexec_fn is used for anything. You 
can use to do things like set process group IDs in the child. For your 
use, everything needs to be args.

If you are using Python 2.5, and log is a file, you want:

from __future__ import with_statement

with log:
 if machine != socket.gethostname():
 command = "/bin/remsh %s %s" % (machine, command)

 subprocess.check_call(command, shell=True, env=env,
   stderr=subprocess.STDOUT, stdout=log)

The semantics are slightly different, since log will always close this 
way, while in the other example, you have left it open if there is an 
exception.
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


looking for library to read ppt files

2007-04-16 Thread Aljosa Mohorovic
i'm looking for a way to read ppt (powerpoint) files using python and
to convert slides into jpeg files.
any links or tips how to do this?

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


Re: script for seconds in given month?

2007-04-16 Thread attn . steven . kuo
On Apr 16, 10:18 am, [EMAIL PROTECTED] wrote:
> Matt> from time import mktime
> Matt> def secondsInMonth(year, month):
> Matt> s1 = mktime((year,month,1,0,0,0,0,0,-1))
> Matt> s2 = mktime((year,month+1,1,0,0,0,0,0,-1))
> Matt> return s2-s1
>
> Probably won't work if month==12. ;-)
>
> Skip



Actually, mktime as described in the C Standard does not
restrict members such as tm_mon of struct tm to the
range 0-11 (1-12 for the corresponding entry in the
time tuple in Python).  So the underlying struct in
CPython may be normalized and return a perfectly valid
time even if month is > 12.

--
Regards,
Steven


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


Re: Compare regular expressions

2007-04-16 Thread Karthik Gurusamy
On Apr 16, 2:50 am, Thomas Dybdahl Ahle <[EMAIL PROTECTED]> wrote:
> Hi, I'm writing a program with a large data stream to which modules can
> connect using regular expressions.
>
> Now I'd like to not have to test all expressions every time I get a line,
> as most of the time, one of them having a match means none of the others
> can have so.
>
> But ofcource there are also cases where a regular expression can
> "contain" another expression, like in:
> "^strange line (\w+) and (\w+)$" and "^strange line (\w+) (?:.*?)$" in
> which case I'd like to first test the seccond and only if it mathces test
> the seccond.
>
> Do anybody know if such a test is possible?
> if exp0.contains(exp1): ...


What you want is finding if R2 is a superset of R1 for two given
regular languages R1 and R2. I know of some methods for finding
intersection of two regular languages; and I think the time/space
complexity is big.

So the simple answer is it is not feasible to provide such support for
two generic r.e.s without a large time/space usage. You may consult
any of the math/theory groups for more insights.

If you know already R2 >= R1 (that is you precompute and remember),
then it's a trivial to skip checking for R1 if R2 turned up negative.
You can even arrange all the Rs in a binary tree like fashion and skip
checking a whole subtree if the sub-tree's root node gave negative for
r.e. match.

Karthik

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


Re: Compare regular expressions

2007-04-16 Thread Diez B. Roggisch
Thomas Dybdahl Ahle schrieb:
> Hi, I'm writing a program with a large data stream to which modules can 
> connect using regular expressions.
> 
> Now I'd like to not have to test all expressions every time I get a line, 
> as most of the time, one of them having a match means none of the others 
> can have so.
> 
> But ofcource there are also cases where a regular expression can 
> "contain" another expression, like in:
> "^strange line (\w+) and (\w+)$" and "^strange line (\w+) (?:.*?)$" in 
> which case I'd like to first test the seccond and only if it mathces test 
> the seccond.
> 
> Do anybody know if such a test is possible?
> if exp0.contains(exp1): ...

It's not. For the simplest of expressions one might come up with a 
relation between them, but even that would be hard. General case? No chance.

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


Re: script for seconds in given month?

2007-04-16 Thread edfialk
Jim: I need years too, basically from 1960-2000.  Don't want to
hardcode all those days :)

Matt: Thanks, I will try this out.

Paul: I don't believe we need leap seconds.  Leap days definitely.

I'll let you know how Matt's code works.  Any other suggestions feel
free to let me know.

Thanks all!
-Ed

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


subprocess confusion

2007-04-16 Thread Tim Arnold
Hi,
Just discovered that my subprocess call with the preexec_fn wasn't doing 
what I thought.
If 'machine' value is different than the current machine name, I want to 
remsh the command to that machine, but obviously I misunderstood the 
preexec_fn arg.

Should I just put the remsh in the actual command instead of preexec_fn?
thanks,
--Tim Arnold
---
if machine == socket.gethostname():
shname = None
else:
shname = lambda :'/bin/remsh %s ' % (machine)
p = subprocess.Popen(preexec_fn = shname,
shell  = True,
args   = command,
stderr = subprocess.STDOUT,
stdout = log,
env= env,
)
try:
p.wait()
if log:
log.close()
except:
pass

--- 


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


Re: script for seconds in given month?

2007-04-16 Thread Paul McGuire
On Apr 16, 11:22 am, "edfialk" <[EMAIL PROTECTED]> wrote:
> Hi, does anyone happen to know of a script that would return the
> number of seconds in a month if I give it a month and a year?
>
> My python is a little weak, but if anyone could offer some suggestions
> I think I could handle it myself, or if anyone happens to know of a
> script already written that performs this I would be extremely
> grateful.
>
> Thanks!
> -Ed

Do you need to handle leap seconds too? (not a joke)

-- Paul

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


Re: swig win32 scons

2007-04-16 Thread myheartinamerica
It turns out I didn't need the DEF file for exports.



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


Re: script for seconds in given month?

2007-04-16 Thread skip

Matt> from time import mktime
Matt> def secondsInMonth(year, month):
Matt> s1 = mktime((year,month,1,0,0,0,0,0,-1))
Matt> s2 = mktime((year,month+1,1,0,0,0,0,0,-1))
Matt> return s2-s1

Probably won't work if month==12. ;-)

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


swig win32 scons

2007-04-16 Thread myheartinamerica
Hello,

I spent the morning figuring out how to use SWIG on Microsoft Windows.
I compiled the example from the SWIG tutorial on http://www.swig.org.
The biggest stumbling block was not knowing that I needed to rename
the DLL created to have a PYD extension. I also ended up writing
a .def file for exporting functions from the DLL.

Here is my SConstruct file for using SCons to build the library. It is
not perfect, but it should be evident as to what I was doing. I hope
that others will be able to find this in the future and save
themselves some time.:


##
SWIG_EXE = r'C:\Python25\swig\swig.exe'


env = Environment(SWIG=SWIG_EXE,
  SWIGFLAGS=['-python'],
  CPPPATH=[r'C:\Python25\include'],
  LIBPATH=[r'C:\Python25\libs'])
swigObject = env.SharedObject(['example.i'])
copyToPYD = Copy('_example.pyd', '_example.dll')
env.AddPostAction('_example.dll', copyToPYD)
env.SharedLibrary('_example.dll', ['example.c', swigObject])

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


Re: yield, curry, mix-in, new.function, global, closure, .... what will work?

2007-04-16 Thread ecir . hana
On Apr 16, 5:36 pm, "Jason" <[EMAIL PROTECTED]> wrote:
> On Apr 16, 7:28 am, [EMAIL PROTECTED] wrote:
>
>
>
> > On Apr 16, 3:05 am, Paul Rubin  wrote:
>
> > > [EMAIL PROTECTED] writes:
>
> > > > Please, can you elaborate further, I'm not sure if I understood.
> > > > Should I lock global variables i, j during the execution of run()? In
> > > > that case I have to apologize, I showed rather simplified version of
> > > > the actual problem I have - in fact changer() and run() will be a bit
> > > > more complex thus executing a bit longer and perhaps causing a 
> > > > dead-lock.
>
> > > Put both variables into one shared object with a lock (see the docs for
> > > threading.RLock()).  Acquire the lock before modifying or reading the
> > > variables, and release it afterwards.  That is the traditional way.
>
> > Thanks for the reply! And at the same time, please bear with me.
>
> > If I understand correctly: when one thread acquires the lock, every
> > other thread has to wait. If so, this is not exacly what I would like
> > to have since the thread might take a bit longer to finish.
>
> > The reason why I try so hard to use local variables is that they are
> > inherently thread-safe. So I don't even mind to copy changer() every
> > time run() is called - run() has it's own local variables i, j, no one
> > has to touch them except it's ("local") function changer(). But the
> > problem is, I don't know how to propagate run()'s variables into
> > changer() without declarating them as changer()'s arguments (it would
> > be ok to append the declaration during run-time, though, if I only
> > knew how).
>
> In Python, names are bound to objects.  The parameter names passed to
> a function *are not inherently thread safe*!  Python parameters are
> not passed-by-value.  To show you what I mean:
>
> >>> spam = ["delicious"]
> >>> def test(meal):
>
> ...  global spam
> ...  if spam is meal:
> ...print "Spam is the same object as meal"
> ...>>> test(spam)
>
> Spam is the same object as meal
>
> (While the "global spam" statement is optional in this case, I wanted
> to make it painfully obvious where the "spam" name in function test is
> coming from.)
>
> It is thread-safe to rebind the name "meal" in the function test (ie,
> meal = "Green eggs").   It is not thread-safe to mutate or modify the
> object that meal is bound to.  In the example given above, appending
> data to the list, removing data, changing elements, and other
> operations will cause potential race conditions across multiple
> threads.
>
> Follow Paul's advice and get acquainted with the issues of concurrent
> and threaded programming.  Judicious locking will help avoid most race
> conditions.  If you don't want to keep other threads waiting, make a
> copy of your data then release the data lock.
>
> Depending on the data, you can usually have multiple threads "reading"
> the data, as long as no other threads write to the data while there
> are any readers.  A writer can be allowed to change the data, but only
> if there are no readers and no other writers.  (This is commonly known
> as a read/write lock.)  I didn't see a read/write lock in the Python
> documentation with some casual browsing, but one can be implemented
> from the existing thread locking mechanisms.
>
> Your description of what you want to do is rather vague, so I can't
> get too specific.  You've described how you want to do things, but I
> don't know what you're trying to accomplish.  Where possible, simplify
> your design.
>
> --Jason

All I was trying to do, was to get rid of those 'k's in changer():



def change_i(k, arg):
k[0] = arg

def change_j(k, arg):
k[1] = arg

def changer(k):
change_i(k, 'changed_i')
change_j(k, 'changed_j')

def run(i='', j=''):
k = [i, j]
changer(k)
[i, j] = k
return i, j

print run() == ('changed_i', 'changed_j')



Maybe I made a mistake, I should have asked this first, sorry. If the
only way to accomplish this is through locks, then I guess I better
use those 'k's, what do you think?

Thanks Jason, thanks Paul!

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


Re: script for seconds in given month?

2007-04-16 Thread pythoncurious
On Apr 16, 6:22 pm, "edfialk" <[EMAIL PROTECTED]> wrote:
> Hi, does anyone happen to know of a script that would return the
> number of seconds in a month if I give it a month and a year?
>

something like this might work, it should event handle DST correctly.
You could read up on mktime() if you want to make sure.

from time import mktime
def secondsInMonth(year, month):
s1 = mktime((year,month,1,0,0,0,0,0,-1))
s2 = mktime((year,month+1,1,0,0,0,0,0,-1))
return s2-s1

/Matt

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


Re: tuples, index method, Python's design

2007-04-16 Thread Chris Mellon
On 4/12/07, Alan Isaac <[EMAIL PROTECTED]> wrote:
> Chris Mellon said:
> > Sure. I have never done this. In fact, I have only ever written code
> > that converted a tuple to a list once, and it was because I wanted
> > pop(), not index()
>
> Well then you apparently made a *mistake*: you chose a tuple when you
> wanted a mutable object.  That is really beside the point.
>

The tuple in question was function varargs. Yes, I wanted a mutable
object, thats why I made a list out of it. Whether varargs should be a
list or a tuple to begin with is
open to debate, but it's not likely you'd want to use index() on it either way.

> And you missed the point of my query.  It is not that existing code will
> contain such a conversion to get access to the index method.  It is that
> if you choose tuples to represent immutable sequences, sooner or later
> you will find you need to change your code to use a list not because you
> really want a mutable sequence but because you want the ``index`` method.
>

That may have been your point, but it's not what you said. I've never
converted a tuple to a list because I needed index(). I've never used
a list where a tuple would be "more natural" soley because I needed to
search it, either. I have never used index() in a situation where the
sequence in question wasn't both a) mutable and b) actually was
mutated in the course of program.

> Note that it has become clear that some people do not use tuples hardly
> ever, regardless whether their sequence is naturally mutable or
> immutable.  Why?  Because they want access the the list methods.
> **All** of these people fall in the category I am talking about.
> I do not really care if you reach mentally and then fix or actually type it.
> The avoidance of tuples, so carefully defended in other terms,
> is often rooted (I claim) in habits formed from need for list methods like
> ``index`` and ``count``.  Indeed, I predict that Python tuples
> will eventually have these methods and that these same people
> will then defend *that* status quo.
>

I use tuples all the time. There are more incidences of tuple usage
than list usage in my current codebase. My opinions on tuples still
stand. I use tuples when I already know what goes into them and in
what order. index() and count() are totally useless when you use
tuples (or, indeed, any sequence) in this manner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: script for seconds in given month?

2007-04-16 Thread Jim
On Apr 16, 12:22 pm, "edfialk" <[EMAIL PROTECTED]> wrote:
> Hi, does anyone happen to know of a script that would return the
> number of seconds in a month if I give it a month and a year?
>
> My python is a little weak, but if anyone could offer some suggestions
> I think I could handle it myself, or if anyone happens to know of a
> script already written that performs this I would be extremely
> grateful.
Probably there are sophisticated answers, but have you tried
something like:

monthDays={'Jan':31,'Feb':28, ..}
secs=60*60*24*monthDays[thisMonth]
if (thisMonth=='Feb'
and isLeap(thisYear)):
secs+=60*60*24
return secs

?

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


Re: tuples, index method, Python's design

2007-04-16 Thread Donn Cave
In article <[EMAIL PROTECTED]>,
 "Hendrik van Rooyen" <[EMAIL PROTECTED]> wrote:

>  "Donn Cave" <[EMAIL PROTECTED]> wrote:
> 
> > 
> > Well, yes - consider for example the "tm" tuple returned
> > from time.localtime() - it's all integers, but heterogeneous
> > as could be - tm[0] is Year, tm[1] is Month, etc., and it
> > turns out that not one of them is alike.  The point is exactly
> > that we can't discover these differences from the items itself -
> > so it isn't about Python types - but rather from the position
> > of the item in the struct/tuple.  (For the person who is about
> > to write to me that localtime() doesn't exactly return a tuple:  QED)
> 
> This is the point where the whole thing falls apart in my head and 
> I get real confused - I can't find a reason why, list or tuple, the first
> item can't be something, the second something else, etc...

Of course, you may do what you like.  Don't forget, though,
that there's no "index" method for a tuple.

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


C++ extension problem

2007-04-16 Thread pythoncurious
Hi,

I'm having a bit of trouble when writing a python extension. I can't
seem to figure out what I did wrong.
I tried to make a minimal example, but it's still quite a bit of
code.
It would be very appreciated if anyone could tell me what I've done
wrong.

First a short description of what I've done. The extension just wraps
a string and the class in it will just hold the string data. A 'get'
method is suppsed to just return the string value.
There's a python part that will call C/C++ functions in the
extension.
I've tried using the same approach SWIG has, so the class in the
extension doesn't really have any methods,
it's all done in methods in the module.

This is what it looks like when I try it out (also tried with
different python version and compiler):
% python
Python 2.4.3 (#1, Aug  1 2006, 16:54:29)
[GCC 3.4.6] on sunos5
Type "help", "copyright", "credits" or "license" for more information.
>>> from example import StringWrapper
>>> s = StringWrapper("S")
>>> s.get()
Traceback (most recent call last):
  File "", line 1, in ?
  File "example.py", line 7, in get
def get(self): return _example.get(self._s)
TypeError: argument 1 must be SillyString, not SillyString

Now this is what confuses me: Why does it say that I have the wrong
type when it's the same type as it suggests?

setup.py file:
###
from distutils.core import setup, Extension
module1 = Extension('_example',
sources = ['_example.cc'])
setup (name = 'example',
   ext_modules = [module1])

example.py file:

#!/usr/bin/env python
import _example

class StringWrapper(object):
def __init__(self, value):
self._s = _example.new_string(value)
def get(self): return _example.get(self._s)


and finally, the c/c++ file '_example.cc':
(I need to use c++ compiler which means I couldn't use
'staticforward'
and the 'cstring is used instead of 'string.h' )

#include "Python.h"
#include 

// forward declaration
extern PyTypeObject SillyStringType;

typedef struct {
  PyObject_HEAD
  char s[21];
} SillyStringObject;

PyObject *
new_string(PyTypeObject *type, PyObject *args)
{
char *value = 0;

if (!PyArg_ParseTuple(args, "s", &value))
return NULL;
SillyStringObject *self = PyObject_NEW(SillyStringObject,
&SillyStringType);
if (self != NULL) {
strncpy(self->s, value, 20);
}
return (PyObject *)self;
}

PyObject *
get(PyTypeObject *type, PyObject *args)
{
SillyStringObject *o;

if (!PyArg_ParseTuple(args, "O!", SillyStringType, &o))
return NULL;
return (PyObject *)PyString_FromString(o->s);
}

PyMethodDef SillyStringMethods[] = {
 {"get", (PyCFunction)get, METH_VARARGS,
  ""
 },
 {"new_string", (PyCFunction)new_string, METH_VARARGS,
  ""
 },
{NULL, NULL, 0, NULL}/* Sentinel */
};

PyTypeObject SillyStringType = {
PyObject_HEAD_INIT(NULL)
0,  /* ob_size */
(char *)"SillyString",  /* tp_name */
sizeof(SillyStringObject),  /* tp_basicsize */
0,  /* tp_itemsize */
(destructor)0,  /* tp_dealloc */
(printfunc)0,   /* tp_print */
(getattrfunc)0, /* tp_getattr */
(setattrfunc)0, /* tp_setattr */
(cmpfunc)0, /* tp_compare */
(reprfunc)0,/* tp_repr */
0,  /* tp_as_number */
0,  /* tp_as_sequence */
0,  /* tp_as_mapping */
(hashfunc)0,/* tp_hash */
(ternaryfunc)0, /* tp_call */
(reprfunc)0,/* tp_str */
0,  /* tp_getattro */
0,  /* tp_setattro */
0,  /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
"SillyString class."   /* tp_doc */
};

extern "C"
{
PyMODINIT_FUNC
init_example(void)
{
PyObject* m;
SillyStringType.tp_new = PyType_GenericNew;
if (PyType_Ready(&SillyStringType) < 0)
return;
m = Py_InitModule3("_example", SillyStringMethods,
   "_example module.");
Py_INCREF(&SillyStringType);
PyModule_AddObject(m, "SillyStringObject", (PyObject
*)&SillyStringType);
}
}

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


Python + ogr module?

2007-04-16 Thread Szkandera . Karel
Hi,
I need to do web service, which will be convert vector formats, like shapefile, 
dgn, mapinfo..(and other formats, which are supported in gdal - ogr2ogr). I 
want to do it with using ogr2ogr in the ogr python module, but i am newbie in 
python, so here is my questions. Is here anybody, who wrote any similar scripts 
and can give it me? If not, can at least anyone point me to few examples of 
using ogr2ogr in the ogr
python module?

Thank you for every answer, K.Szkandera
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Authenticating clients and servers

2007-04-16 Thread Goldfish
On Apr 15, 2:40 pm, Chaz Ginger <[EMAIL PROTECTED]> wrote:
> Thomas Krüger wrote:
> > Chaz Ginger schrieb:
> >> I am writing a distributed server system using Python. I need to support
> >> authentication and was wondering what approaches are available under
> >> Python and what are the best practices.

Spring Python has a section concerning Application Security you may be
interested in. (http://springpython.python-hosting.com/wiki/
ApplicationSecurity). This offers the ability to authenticate users,
but also manage what functions they can execute based on granted roles
through aspect oriented programming.

Right now, the current release supports flat-file user systems, but
the next release will also include database user stores. There are
future plans to integrate with other user stores like LDAP and so
forth.

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


script for seconds in given month?

2007-04-16 Thread edfialk
Hi, does anyone happen to know of a script that would return the
number of seconds in a month if I give it a month and a year?

My python is a little weak, but if anyone could offer some suggestions
I think I could handle it myself, or if anyone happens to know of a
script already written that performs this I would be extremely
grateful.

Thanks!
-Ed

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


Re: Lame wrapper for Python

2007-04-16 Thread kyosohma
On Apr 16, 11:04 am, "Harlin Seritt" <[EMAIL PROTECTED]> wrote:
> Is there any type of lame_enc.dll wrapper for Python that's available?
>
> Thanks,
>
> Harlin Seritt

If you are talking about the LAME codec, then you might be able to use
py-lame:

http://sourceforge.net/project/showfiles.php?group_id=290&release_id=122796

And here's a post that looks like it may be related:

http://mail.python.org/pipermail/tutor/2004-January/027379.html

Mike

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


moving multiple directories

2007-04-16 Thread DataSmash
Hi,
I need to organize thousands of directories full of files.
I want to move these directories into other subdirectories.
For example, all the directories that start with 01, move to
a directory named "one", all directories that start with 02, move
to a directory name "two", and so on

I can't seem to find any easy way to do this.
Looks like shutil.move only lets you move if the subdirectory DOES
NOT exist, so after the first directory moves, the script blows up on
the second move.
I guess you could use shutil.copy or shutil.copytree but then you have
to
delete as well.  Much longer process when you have hundreds of
gigabytes of data.

Thanks for your help!
R.D.

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


Re: Python and SSL

2007-04-16 Thread kyosohma
On Apr 16, 10:24 am, "billiejoex" <[EMAIL PROTECTED]> wrote:
> Hi,
> I developed an ftp-server library and now I would like to add support
> for SSL/TLS as described in RFC 2228:http://tools.ietf.org/html/rfc2228
> Currenlty I'm searching for documentation about this subject and I
> would like to start to ask some questions:
>
> - I noticed that socket module provides an SSL class (socket.ssl) but
> even if documentation reports that it does not do any certificate
> verification a lot of stdlib modules (imaplib, poplib, smtplib,
> httplib and urllib2) provides SSL extension classes wherein socket.ssl
> is used. What does it mean?
>
> - On top of that why such extension classes [examples: 1, 2, 3]
> accepts key-files and cert-files as optional argouments if no
> certificate verification occurs?
> [1] poplib.POP3_SSL( host[, port[, keyfile[, certfile]]])
> [2] imaplib.IMAP4_SSL( [host[, port[, keyfile[, certfile)
> [3] smtplib.starttls( [keyfile[, certfile]])
>
> - By searching through the web I found some daemons supporting SSL
> such as this 
> one:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442473
> By looking at the code I notice that pyopenssl package is used and
> that a certificate file is required. Why do I need to use pyopenssl
> and how do I generate the cert file?
>
> Could someone point me in the right direction?
>
> Thanks in advance.

I don't know if this will help you or not, but we use the httplib
module's "HTTPSConnection" method to connect with SSL. We use
urlencode from the urllib module to encode the username and password
we send to a server. Since I didn't write this particular bit of code,
I don't completely understand it. But I hope it will give you some
ideas.

Mike

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


  1   2   >