Re: split a list based on a predicate

2008-10-09 Thread beginner
Hi,

On Oct 8, 6:36 pm, "Rajanikanth Jammalamadaka" <[EMAIL PROTECTED]>
wrote:
> Hi!
>
> Is there a functional way to do this?
>
> I have an array [0,1,2,3,0,1,2,2,3] and I want the first chunk of
> non-decreasing values from this array (eg: In this case I want
> [0,1,2,3])
>
> Thanks,
>
> Rajanikanth

Here is an idea. It is not the most efficient code!

def combine(l, a):
if not l or l[-1]http://mail.python.org/mailman/listinfo/python-list


Re: first of not None

2008-10-09 Thread Serge Matveenko
On 10/9/08, Serge Matveenko <[EMAIL PROTECTED]> wrote:
> I need to put in the var property of the first object from the list
> that is not None. Somth like:
>
> foo = first_of([any, beny, riki,]).name
>
> Dont want to ugly if-cascade:
>
> foo = any.name if name is not None else beny.name if beny is not None \
> else riki.name if riki is not None

after some play with interpreter and Python logic i've got this:

objs = [None, 'dfgh', None,]
obj_l = [obj.__len__() for obj in objs if obj is not None][0]

Now the question is this is lazy or not? And how could i make it lazy?


-- 
Serge Matveenko
mailto:[EMAIL PROTECTED]
http://serge.matveenko.ru/
--
http://mail.python.org/mailman/listinfo/python-list


Re: first of not None

2008-10-09 Thread Diez B. Roggisch

Serge Matveenko schrieb:

On 10/9/08, Serge Matveenko <[EMAIL PROTECTED]> wrote:

I need to put in the var property of the first object from the list
that is not None. Somth like:

foo = first_of([any, beny, riki,]).name

Dont want to ugly if-cascade:

foo = any.name if name is not None else beny.name if beny is not None \
else riki.name if riki is not None


after some play with interpreter and Python logic i've got this:

objs = [None, 'dfgh', None,]
obj_l = [obj.__len__() for obj in objs if obj is not None][0]



The usual way to compute the len is to use

len(obj)



Now the question is this is lazy or not? And how could i make it lazy?


No, it's not. You could make it a generator expression:


obj_l = (len(obj) for obj in objs if obj is not None).next()

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


Re: Inefficient summing

2008-10-09 Thread Matt Nordhoff
Chris Rebert wrote:
> I personally would probably do:
> 
> from collections import defaultdict
> 
> label2sum = defaultdict(lambda: 0)

FWIW, you can just use:

label2sum = defaultdict(int)

You don't need a lambda.

> for r in rec:
> for key, value in r.iteritems():
> label2sum[key] += value
> 
> ratio = label2sum["F1"] / label2sum["F2"]
> 
> This iterates through each 'r' only once, and (imho) is pretty
> readable provided you know how defaultdicts work. Not everything has
> to unnecessarily be made a one-liner. Coding is about readability
> first, optimization second. And optimized code should not be
> abbreviated, which would make it even harder to understand.
> 
> I probably would have gone with your second solution if performance
> was no object.
> 
> Cheers,
> Chris
-- 
--
http://mail.python.org/mailman/listinfo/python-list


Clever way of sorting strings containing integers?

2008-10-09 Thread Holger
I tried to do this elegantly, but did not come up with a good solution

Sort strings like
foo1bar2
foo10bar10
foo2bar3
foo10bar2

So that they come out:
foo1bar2
foo2bar3
foo10bar2
foo10bar10

I.e. isolate integer parts and sort them according to integer value.

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


default value in __init__

2008-10-09 Thread kenneth
Dear all,

I have encountered this weird problem.

I have a class definition with an __init__ argument 'd'
which defaults to {}. This argument is put in the 'self.d'
attribute at initialization

I create two independent instances of this class; the code
is as follows.

class C:
  def __init__(self, i=10, d = {}):
self.d = d
self.i = i
  def get(self):
print
print self.d
  def set(self, dval, ival):
self.d.update(dval)
self.i+=ival

c1=C()
c1.set({'one':1},3)
c1.get()

del c1

c2=C()
c2.set({'two':2},4)
c2.get()


If I run the code I obtain:

{'one': 1}

{'two': 2, 'one': 1}

It seems that the 'self.d' argument of the second instance is the
same of the 'self.d' of the first (deleted!) instance.

Running the code in a debugger I discovered that, when I enter the
__init__ at the second initialization, before doing

self.d = d

the 'd' variable already contains the 'self.d' value of the first
instance and not the default argument {}.

Am I doing some stupid error, or this is a problem ?

Thanks in advance for any help,
Paolo
--
http://mail.python.org/mailman/listinfo/python-list


replace numbers in a string

2008-10-09 Thread Beema Shafreen
hi All,

i have few lines in file
"ttccatttctggacatgacgtctgt6901ggtttaagctttgtgaaagaatgtgctttgattcg"
i need to replace the number and get only the alphabet in such a case what
should i do.
Can any body suggest me

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


Re: default value in __init__

2008-10-09 Thread Chris Rebert
See Pitfall #5 on http://zephyrfalcon.org/labs/python_pitfalls.html
It also applies to dictionaries (and sets, any mutable object really).

On Thu, Oct 9, 2008 at 1:03 AM, kenneth <[EMAIL PROTECTED]> wrote:
> Dear all,
>
> I have encountered this weird problem.
>
> I have a class definition with an __init__ argument 'd'
> which defaults to {}. This argument is put in the 'self.d'
> attribute at initialization
>
> I create two independent instances of this class; the code
> is as follows.
>
> class C:
>  def __init__(self, i=10, d = {}):

Change 'd = {}' to 'd=None'
Add the line:
if d is None: d = {}

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

>self.d = d
>self.i = i
>  def get(self):
>print
>print self.d
>  def set(self, dval, ival):
>self.d.update(dval)
>self.i+=ival
>
> c1=C()
> c1.set({'one':1},3)
> c1.get()
>
> del c1
>
> c2=C()
> c2.set({'two':2},4)
> c2.get()
>
>
> If I run the code I obtain:
>
> {'one': 1}
>
> {'two': 2, 'one': 1}
>
> It seems that the 'self.d' argument of the second instance is the
> same of the 'self.d' of the first (deleted!) instance.
>
> Running the code in a debugger I discovered that, when I enter the
> __init__ at the second initialization, before doing
>
> self.d = d
>
> the 'd' variable already contains the 'self.d' value of the first
> instance and not the default argument {}.
>
> Am I doing some stupid error, or this is a problem ?
>
> Thanks in advance for any help,
> Paolo
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: default value in __init__

2008-10-09 Thread Christian Heimes

kenneth wrote:

the 'd' variable already contains the 'self.d' value of the first
instance and not the default argument {}.

Am I doing some stupid error, or this is a problem ?


No, it always contains the default argument because default values are 
created just ONE TIME. 
http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm


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


Re: Clever way of sorting strings containing integers?

2008-10-09 Thread Holger
On 9 Okt., 09:41, Holger <[EMAIL PROTECTED]> wrote:
> I tried to do this elegantly, but did not come up with a good solution
>
> Sort strings like
> foo1bar2
> foo10bar10
> foo2bar3
> foo10bar2
>
> So that they come out:
> foo1bar2
> foo2bar3
> foo10bar2
> foo10bar10
>
> I.e. isolate integer parts and sort them according to integer value.
>
> Thx
> Holger

or even:
foo1bar2
foo10bar10
foo2bar3
foo10bar2
fo
bar1000
777

To:
777
bar1000
fo
foo1bar2
foo2bar3
foo10bar2
foo10bar10

Here's my own take, but it doesn't quite work yet:
txtline = re.compile(r'(\D*)(\d+)')

lines = [x.strip() for x in sys.stdin.readlines()]
res = []
for l in [ x for x in lines if x]:
groups = txtline.findall(l)
res.append([[[x[0], int(x[1],0)] for x in groups],l])

res.sort()
for x in res:
print x[1]
--
http://mail.python.org/mailman/listinfo/python-list


Traceback not going all the way to the exception?

2008-10-09 Thread sert
I just got an exception and the traceback wouldn't go all the 
way to the statement that threw the exception. I found that out 
by using the debugger.

Contrast the traceback:

http://tinyurl.com/5xglde

with the debugger output (notice the arrow pointing to the last 
statement the traceback showed and how the execution went on 
beyond it):

http://tinyurl.com/3fjgrl

Is this a known issue or should I submit a bug report?
--
http://mail.python.org/mailman/listinfo/python-list


Re: replace numbers in a string

2008-10-09 Thread Gary Herron
Beema Shafreen wrote:
> hi All,
>
> i have few lines in file
> "ttccatttctggacatgacgtctgt6901ggtttaagctttgtgaaagaatgtgctttgattcg"
> i need to replace the number and get only the alphabet in such a case
> what should i do.
> Can any body suggest me
>From the regular expression module, use re.sub like this:


>>> import re
>>> re.sub('[0-9]', '',
"ttccatttctggacatgacgtctgt6901ggtttaagctttgtgaaagaatgtgctttgattcg")
'ttccatttctggacatgacgtctgtggtttaagctttgtgaaagaatgtgctttgattcg'


Gary Herron



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

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


Re: Inefficient summing

2008-10-09 Thread bieffe62
On 8 Ott, 22:23, beginner <[EMAIL PROTECTED]> wrote:
> Hi All,
>
> I have a list of records like below:
>
> rec=[{"F1":1, "F2":2}, {"F1":3, "F2":4} ]
>
> Now I want to write code to find out the ratio of the sums of the two
> fields.
>
> One thing I can do is:
>
> sum(r["F1"] for r in rec)/sum(r["F2"] for r in rec)
>
> But this is slow because I have to iterate through the list twice.
> Also, in the case where rec is an iterator, it does not work.
>
> I can also do this:
>
> sum1, sum2= reduce(lambda x, y: (x[0]+y[0], x[1]+y[1]), ((r["F1"],
> r["F2"]) for r in rec))
> sum1/sum2
>
> This loops through the list only once, and is probably more efficient,
> but it is less readable.
>
> I can of course use an old-fashioned loop. This is more readable, but
> also more verbose.
>
> What is the best way, I wonder?
>
> -a new python programmer

The loop way is probably the right choice.
OTHA, you could try to make more readable the 'reduce' approach,
writing it like this:

def add_r( sums, r ): return sums[0]+r['F1'], sums[1]+r['F2']
sum_f1, sum_f2 = reduce( add_r, rec, (0,0) )
result = sum_f1/sum_f2

Less verbose than the for loop, but IMO almost as understandable : one
only needs to know the semantic
of 'reduce' (which for a python programmer is not big thing) and most
important the code does only one thing per line.


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


Re: default value in __init__

2008-10-09 Thread Chris Rebert
On Thu, Oct 9, 2008 at 1:39 AM, kenneth <[EMAIL PROTECTED]> wrote:
> On Oct 9, 10:14 am, Christian Heimes <[EMAIL PROTECTED]> wrote:
>> kenneth wrote:
>> > the 'd' variable already contains the 'self.d' value of the first
>> > instance and not the default argument {}.
>>
>> > Am I doing some stupid error, or this is a problem ?
>>
>> No, it always contains the default argument because default values are
>> created just ONE 
>> TIME.http://effbot.org/pyfaq/why-are-default-values-shared-between-objects...
>
>
> Wow, it's a very "dangerous" behavior ...
>
> Just to know, is this written somewhere in the python documentation or
> one has to discover it when his programs fails to work ;-) ?

It's mentioned in the tutorial (note the "Important warning"):
http://docs.python.org/tutorial/controlflow.html#default-argument-values

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

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


Re: ssh problem using paramiko?

2008-10-09 Thread Diez B. Roggisch
Steve Holden wrote:

> Diez B. Roggisch wrote:
>> sa6113 wrote:
>> 
>>> I couldn't find any good source for download Openssh on the net?
>>> Would you please introduce a URL for download that?
>> 
>> http://www.vapor.com/amtelnet/
>> 
>> it supports only SSHv1, but I guess that's ok.
>> 
> No, you really don't want to use SSHv1. Amtelnet won't do, it's an SSH
> *server* the OP needs, I understand. Why not openssh.org?

The post was not intended to be meant serious. The OP has not provided
*anything* on the system he uses, what he actually needs, and so forth. So
I just searched for the most unlikely implementation.

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


Re: Reading from stdin

2008-10-09 Thread Hendrik van Rooyen
Luis Zarrabeitia wrote:

>But it doesn't say how to put the file object in non-blocking mode. (I was 
>trying to put the file object in non-blocking mode to test next()'s 
>behavior). ??Ideas?

# Some magic to make a file non blocking - from the internet

def unblock(f):
"""Given file 'f', sets its unblock flag to true."""

fcntl.fcntl(f.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)

- Hendrik


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


SimpleXmlRpcServer and character encoding

2008-10-09 Thread shymon


I'm using SimpleXmlRpcServer class. Although I set encoding parameter in the
constructor, I have to return all strings in default platform encoding
(windows-1250/win32 or iso-8859-2/linux in my case). When I send values in,
for example, UTF-8, string received by client is messed up.

The client is written in java using Apache XmlRpc library 2.0.

Is there any solution other than sending all string values in Base64
encoding?
-- 
View this message in context: 
http://www.nabble.com/SimpleXmlRpcServer-and-character-encoding-tp19896427p19896427.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Inefficient summing

2008-10-09 Thread bearophileHUGS
FB:
> def add_r( sums, r ): return sums[0]+r['F1'], sums[1]+r['F2']
> sum_f1, sum_f2 = reduce( add_r, rec, (0,0) )
> result = sum_f1/sum_f2

Until this feature vanishes I think it's better to use it (untested):

add_r = lambda (a, b), r: (a + r['F1'], b + r['F2'])

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to calculate two time?

2008-10-09 Thread skip

lookon> Thank you for your help.It works.  However, I am using Google
lookon> App Engine and cannot import dateutil and epsilon.

I don't know how Google App Engine works, but are you not able to install
pure Python modules?

lookon> Are there any other ways?

Take a look at the time.strptime function to generate a tuple, then use

t = time.strptime(timestamp, format)
t1 = datetime.datetime(*t[0:6])

Note that with this solution you will have to handle the timezone offset
yourself.

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


Re: ABCs -> infix syntax for isinstance() ?

2008-10-09 Thread Boris Borcic

Terry Reedy wrote:

Boris Borcic wrote:

...


- allowing containment tests, ie "x in Number" to invoke isinstance() 
in the background when the container is of type . My brain is 
too muddled by flu at the moment, to see whether Guido's fabled time 
machine allowed him to already provide all the necessities in py26.

Any takers ?


I believe this could be done by adding a __contains__ method to type.
(It does not have one now).  Then x in X should work for all classes 
that are instances of type or a subclass thereof.


Can this be done short of patching the source and recompiling (eg, with ctypes 
perhaps) ?


Cheers, BB

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


Efficient Bit addressing in Python.

2008-10-09 Thread Hendrik van Rooyen

Is there a canonical way to address the bits in a structure
like an array or string or struct?

Or alternatively, is there a good way to combine eight
ints that represent bits into one of the bytes in some
array or string or whatever?

It seems to me that there is a dilemma here :

if you can write:

bit3 = 1

Then you have to jump through hoops to get
bit0 through bit7 into some byte that you can send
to an i/o routine.

On the other hand, if you keep the bits "in" the 
byte, then you can write:

byte[3] = '\x7e'

but you have to jump through hoops to get at 
the individual bits.

Is there a "best" way?

It would be nice to be able to write:

if io.byte2.bit3:
   do_something()

if io.byte2 == alarm_value:
  do_something_else()

where:

 io.byte2 & 8   "is"  io.byte2.bit3

Is this possible?

- Hendrik

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


Re: SimpleXmlRpcServer and character encoding

2008-10-09 Thread shymon



Diez B. Roggisch-2 wrote:
> 
> shymon wrote:
> 
>> I'm using SimpleXmlRpcServer class. Although I set encoding parameter in
>> the constructor, I have to return all strings in default platform
>> encoding
>> (windows-1250/win32 or iso-8859-2/linux in my case). When I send values
>> in, for example, UTF-8, string received by client is messed up.
>> 
>> The client is written in java using Apache XmlRpc library 2.0.
>> 
>> Is there any solution other than sending all string values in Base64
>> encoding?
> 
> Use unicode-objects. And unicode IS NOT utf-8. The encoding parameter will
> affect the xml generated & send over the wire - *not* what strings you
> pass/return to your implementation.
> 
> So I think you should remove the encoding parameter alltogether, as this
> will make the transport being in utf-8. Then use only unicode-objects in
> your python code. And on the java-side, things *should* be in order.
> 
> Diez
> --
> http://mail.python.org/mailman/listinfo/python-list
> 
> 


I have tried unicode strings also, let's say u"miłość".
Result received by the client was the same as if I sent UTF-8 encoded
string.


-- 
View this message in context: 
http://www.nabble.com/SimpleXmlRpcServer-and-character-encoding-tp19896427p19898136.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: template strings for matching?

2008-10-09 Thread Tino Wildenhain

Joe Strout wrote:
Catching up on what's new in Python since I last used it a decade ago, 
I've just been reading up on template strings.  These are pretty cool!  
However, just as a template string has some advantages over % 
substitution for building a string, it seems like it would have 
advantages over manually constructing a regex for string matching.


So... is there any way to use a template string for matching?  I 
expected something like:


 templ = Template("The $object in $location falls mainly in the $subloc.")
 d = templ.match(s)

and then d would either by None (if s doesn't match), or a dictionary 
with values for 'object', 'location', and 'subloc'.


But I couldn't find anything like that in the docs.  Am I overlooking 
something?


Yeah, its a bit hard to spot:

http://docs.python.org/library/stdtypes.html#string-formatting-operations

HTH
Tino


smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list


Re: template strings for matching?

2008-10-09 Thread skip
Joe>   templ = Template("The $object in $location falls mainly in the  
$subloc.")
Joe>   d = templ.match(s)

Joe> and then d would either by None (if s doesn't match), or a
Joe> dictionary with values for 'object', 'location', and 'subloc'.

Joe> But I couldn't find anything like that in the docs.  Am I
Joe> overlooking something?

Nope, you're not missing anything.

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


Re: How to calculate two time?

2008-10-09 Thread lookon
I have solved the problem. thank you

On Oct 9, 7:20 pm, [EMAIL PROTECTED] wrote:
>     lookon> Thank you for your help.It works.  However, I am using Google
>     lookon> App Engine and cannot import dateutil and epsilon.
>
> I don't know how Google App Engine works, but are you not able to install
> pure Python modules?
>
>     lookon> Are there any other ways?
>
> Take a look at the time.strptime function to generate a tuple, then use
>
>     t = time.strptime(timestamp, format)
>     t1 = datetime.datetime(*t[0:6])
>
> Note that with this solution you will have to handle the timezone offset
> yourself.
>
> Skip

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


Re: Access to Google Calendar

2008-10-09 Thread eliben
On Oct 8, 4:04 pm, pepitovadecurt <[EMAIL PROTECTED]> wrote:
> Hi I need to access to the Google Calendar under python.
> Is posible?

Yes:
http://code.google.com/p/gdata-python-client/

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


Re: How to calculate two time?

2008-10-09 Thread skip

lookon> but can you tell me what format is it?

Read the strftime man page on your computer or Google for strftime or read
the Python docs about the time.strftime function.  (strftime and strptime
strive to have the same set of format characters.)

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


Re: inspect feature

2008-10-09 Thread Bruno Desthuilliers

Aaron "Castironpi" Brady a écrit :

Hello,

The 'inspect' module has this method:

inspect.getargvalues(frame)

It takes a frame and returns the parameters used to call it, including
the locals as defined in the frame, as shown.


def f( a, b, d= None, *c, **e ):

... import inspect
... return inspect.getargvalues( inspect.currentframe() )
...

f( 0, 1, 'abc', 'def', ( 3, 2 ), h= 'ghi' )

(['a', 'b', 'd'], 'c', 'e', {'a': 0, 'c': ('def', (3, 2)), 'b': 1,
'e': {'h': 'g
hi'}, 'd': 'abc', 'inspect': })

However, if you wanted a decorator that examines the parameters to a
function, you're out of luck.  By the time you have a frame, you're
already in the function.


Hem...

def decorator(func):
def _decorator(*args, *kw):
print "func args are ", *args, **kw
return func(*args, **kw)
return _decorator


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


Re: Clever way of sorting strings containing integers?

2008-10-09 Thread Holger
On 9 Okt., 10:57, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Thu, 09 Oct 2008 00:41:27 -0700, Holger wrote:
> > I tried to do this elegantly, but did not come up with a good solution
>
> > Sort strings like
> > foo1bar2
> > foo10bar10
> > foo2bar3
> > foo10bar2
>
> > So that they come out:
> > foo1bar2
> > foo2bar3
> > foo10bar2
> > foo10bar10
>
> > I.e. isolate integer parts and sort them according to integer value.
>
> import re
>
> def key_func(string):
>     result = re.split(r'(\d+)', string)
>     for i in xrange(1, len(result), 2):
>         result[i] = int(result[i])
>     return result
>
> def main():
>     lines = ['foo1bar2',
>              'foo10bar10',
>              'foo2bar3',
>              'foo10bar2',
>              'fo',
>              'bar1000',
>              '777']
>     lines.sort(key=key_func)
>     print '\n'.join(lines)

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


Twisted Matrix and multicast broadcast

2008-10-09 Thread Stodge
I'm trying to get a simple multicast application working using
Twisted; so far I have:

from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
from twisted.application.internet import MulticastServer

class MulticastServerUDP(DatagramProtocol):
def startProtocol(self):
print 'Started Listening'
# Join a specific multicast group, which is the IP we will
respond to
self.transport.joinGroup('224.0.0.1')

def datagramReceived(self, datagram, address):
# The uniqueID check is to ensure we only service requests
from
# ourselves
if datagram == 'UniqueID':
print "Server Received: " + repr(datagram)
self.transport.write("data", address)

# Listen for multicast on 224.0.0.1:8005
reactor.listenMulticast(8005, MulticastServerUDP())
reactor.run()


and:



from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
from twisted.application.internet import MulticastServer

class MulticastClientUDP(DatagramProtocol):
def startProtocol(self):
print 'Started Listening'
# Join a specific multicast group, which is the IP we will
respond to
self.transport.joinGroup('224.0.0.1')

self.transport.write('UniqueID',('224.0.0.1', 8005))

def datagramReceived(self, datagram, address):
print "Received:" + repr(datagram)

# Send multicast on 224.0.0.1:8005, on our dynamically allocated port
reactor.listenMulticast(0, MulticastClientUDP())
reactor.run()



No surprises there! But how do I get the server to send to all clients
using multicast? transport.write requires an address. Any suggestions
appreciated.

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


Re: template strings for matching?

2008-10-09 Thread skip

Tino> Yeah, its a bit hard to spot:

Tino> 
http://docs.python.org/library/stdtypes.html#string-formatting-operations

That shows how to use the template formatting as it currently exists.  To my
knowledge there is no support for the inverse operation, which is what Joe
asked about.  Given a string and a format string assign the elements of the
string which correspond to the template elements to key/value pairs in a
dictionary.

Skip

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


Re: Efficient Bit addressing in Python.

2008-10-09 Thread Tino Wildenhain

Hi,

Hendrik van Rooyen wrote:

Is there a canonical way to address the bits in a structure
like an array or string or struct?

Or alternatively, is there a good way to combine eight
ints that represent bits into one of the bytes in some
array or string or whatever?

It seems to me that there is a dilemma here :

if you can write:

bit3 = 1

Then you have to jump through hoops to get
bit0 through bit7 into some byte that you can send
to an i/o routine.

On the other hand, if you keep the bits "in" the 
byte, then you can write:


byte[3] = '\x7e'

but you have to jump through hoops to get at 
the individual bits.


Is there a "best" way?

It would be nice to be able to write:

if io.byte2.bit3:
   do_something()

if io.byte2 == alarm_value:
  do_something_else()

where:

 io.byte2 & 8   "is"  io.byte2.bit3


byte1 byte2? this does not look very practical
to me. In the simplest form of storing
your values in a text string, you could just
use ord() to get the byte value and
operate on it with 1<<0 1<<1 1<<3 and so on.

If you want, put a module in which defines the
constants

bit1=1<<0
bit2=1<<1

and so on and use it via
if byte & bit1: ...

more efficiently for operations on really big
bit strings is probably just using integers.

HTH
Tino



Is this possible?

- Hendrik

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




smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list


Re: default value in __init__

2008-10-09 Thread kenneth
On Oct 9, 10:14 am, Christian Heimes <[EMAIL PROTECTED]> wrote:
> kenneth wrote:
> > the 'd' variable already contains the 'self.d' value of the first
> > instance and not the default argument {}.
>
> > Am I doing some stupid error, or this is a problem ?
>
> No, it always contains the default argument because default values are
> created just ONE 
> TIME.http://effbot.org/pyfaq/why-are-default-values-shared-between-objects...


Wow, it's a very "dangerous" behavior ...

Just to know, is this written somewhere in the python documentation or
one has to discover it when his programs fails to work ;-) ?

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


Re: no unbound methods in py3k

2008-10-09 Thread Thomas Heller
Christian Heimes schrieb:
> Thomas Heller wrote:
>> but this is very ugly, imo.  Is there another way?
>> The raw_func instances that I have are not descriptors (they
>> do not implement a __get__() method...)
> 
> I've written PyInstanceMethod_Type for this use case. It's not (yet) 
> available for Python code. Barry hasn't decided whether he should expose 
> the type so late in the release cycle or not. See 
> http://bugs.python.org/issue3787 and 
> http://docs.python.org/dev/3.0/c-api/method.html?highlight=pyinstancemethod#PyInstanceMethod_Type
> 

Ok, so one has to write an extension to access or expose it.

Oh, wait - there's ctypes:

Python 3.0rc1 (r30rc1:66507, Sep 18 2008, 14:47:08) [MSC v.1500 32 bit (Intel)] 
on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from ctypes import *
>>> pythonapi.PyInstanceMethod_New.restype = py_object
>>> pythonapi.PyInstanceMethod_New.argtypes = [py_object]
>>> instancemethod = pythonapi.PyInstanceMethod_New
>>>
>>> class Example:
... pass
...
>>> Example.id = instancemethod(id)
>>>
>>> x = Example()
>>> x.id()
12597296
>>> id(x)
12597296
>>>

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


Re: Python/Django hosting on "normal" hosting plans

2008-10-09 Thread Steve Holden
Tim Chase wrote:
[In response t David Lyon]
>> My questions are:
>>
>>   - can most everyday vanilla linux web hosts run a django site ?
>>
>>   - can most everyday vanilla linux web hosts run python web scripts?
> 
> Depends on your definition of "most everyday vanilla linux web hosts".  :)
> 
> The bottom-of-the-barrel hosts will often (but not always) offer Python
> CGI.  Django "can" run in a CGI (google for "django cgi"[0]), but it's
> an unpleasant experience because the entire Django framework gets
> reloaded for *every* request. Doable/tolerable for a private
> development/family page, but it will likely flounder under the slightest
> load.
> 
> This is like strapping a jet engine (Django) on a bicycle (CGI).  [1] 
> Doable, but more for the macho-factor of "I got it working" rather than
> the practical aspects.
> 
> Your lowest-end hosting services won't offer mod_python or WSGI (either
> Apache with mod_wsgi, or others like lighttpd with a wsgi interface)
> though WSGI is becoming more popular.  There are still some
> shared-hosting solutions that facilitate using Django[2] pretty well. 
> They're not super-cheap, but they're affordable. The canonical catalog
> of Django-friendly & Django-capable hosting services can be found at
> [3].  If you're just starting out with Django, it might help to pay a
> bit more for one of the click-n-go hosts, while others you'll have to do
> some of the heavy lifting (installing Django, as well as possibly other
> components, assembling your wsgi startup script, etc) yourself.
> 
There's recently been a discussion about hosting on the django-users
list, which I recommend you think about joining. Both WebFaction and
SliceHost got high marks from many users. I personally use OpenHosting,
who are very Python-friendly and mostly just let you ge on with what you
want to do, which is great if you are comfortable managing your own
email and web services.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: ssh problem using paramiko?

2008-10-09 Thread Steve Holden
Diez B. Roggisch wrote:
> Steve Holden wrote:
> 
>> Diez B. Roggisch wrote:
>>> sa6113 wrote:
>>>
 I couldn't find any good source for download Openssh on the net?
 Would you please introduce a URL for download that?
>>> http://www.vapor.com/amtelnet/
>>>
>>> it supports only SSHv1, but I guess that's ok.
>>>
>> No, you really don't want to use SSHv1. Amtelnet won't do, it's an SSH
>> *server* the OP needs, I understand. Why not openssh.org?
> 
> The post was not intended to be meant serious. The OP has not provided
> *anything* on the system he uses, what he actually needs, and so forth. So
> I just searched for the most unlikely implementation.
> 
Pardon my seriousness :)

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: re : do something in time interval

2008-10-09 Thread Hendrik van Rooyen
Lawrence D'Oliveiro wrote:
>Hendrik van Rooyen wrote:
>
>> import time
>> while True:
>> end_time = time.time() + 5
>> while time.time() < end_time:
>> do_the_in_between_stuff()
>> do_the_every_five_second_stuff()
>
>Maybe I'm dense, but ... where do you stop the busy-waiting?

The above is an endless loop, doing something every
five seconds, and something else in the in between times.

I don't think you are dense - its a good point,
leading to the following analysis:

The do_the_in_between_stuff call either takes
less than, or more than, or exactly five
seconds to do.

In the unlikely exact case, there is no problem, we
have a synchronous machine. (assuming the every five
seconds code takes zero time - else five has to
be diminished to 5 less the time of the periodic
routine, but the argument stays the same)

If it takes more than five seconds, we fail in our
endeavour to do something every five seconds,
and we need threads or interrupts or something else
more advanced to get some apparent simultaneity.

If it takes less than five seconds, we will enter it
more than once.  I wrote the above under the twin assumptions
that multiple entry does not matter, and that the routine
is short enough in time that the overrun error at the end
does not significantly change the timing of the five second
interval call. If it perversely takes say 4 seconds to do
the in between stuff, the above code will do the five second
stuff at intervals of eight seconds or so. - Conversely, if the
in between code takes a millisec, then we will be almost
spot-on.

Now if multiple entry does matter, and it has to be done
only once in between calls to the five second stuff,
then it properly belongs with the five second stuff,
and we are back to sleeping for
time.sleep(5 - time_to_do_the_work) to get a call every
five seconds.  Obviously, if time_to_do_the_work is
bigger than 5, then you can't get there from here.

And these, as far as I can see, are the only alternatives.

- Hendrik




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


Re: Clever way of sorting strings containing integers?

2008-10-09 Thread Marc 'BlackJack' Rintsch
On Thu, 09 Oct 2008 00:41:27 -0700, Holger wrote:

> I tried to do this elegantly, but did not come up with a good solution
> 
> Sort strings like
> foo1bar2
> foo10bar10
> foo2bar3
> foo10bar2
> 
> So that they come out:
> foo1bar2
> foo2bar3
> foo10bar2
> foo10bar10
> 
> I.e. isolate integer parts and sort them according to integer value.

import re


def key_func(string):
result = re.split(r'(\d+)', string)
for i in xrange(1, len(result), 2):
result[i] = int(result[i])
return result


def main():
lines = ['foo1bar2',
 'foo10bar10',
 'foo2bar3',
 'foo10bar2',
 'fo',
 'bar1000',
 '777']
lines.sort(key=key_func)
print '\n'.join(lines)


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


Can anyone Pythonize this lexical algorithm?

2008-10-09 Thread ShashiGowda
I am writing a package manager and stuck unable to write the version
sorting function the algorithm is here 
http://www.linux.gr/cgi-bin/man/man2html?deb-version+5
and all other info is also in it please tell me how to do lexical
comparision in python it'll be cool if you just write the code!
--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: python-aspects 1.2 released

2008-10-09 Thread Stef Mientki

Antti Kervinen wrote:

Hello!

aspects.py is a lightweight and low-level library for intercepting
function calls. Functions and methods (also in Python standard library
and third party code) can be wrapped so that when they are called, the
wrap is invoked first. Depending on the wrap, the execution of the
original function can be omitted, or the function can be called
arbitrarily many times. Wraps are able to modify the call arguments
and the return values of wrapped functions and handle
exceptions. There can be many wraps on the same function. The wraps
can be enabled, disabled and removed in any order.
  

thanks Antti,
this is a wonderful tool, I've always been looking for !!

I've a few questions:
- does wrap work correctly with debuggers like pdb and rpdb2 ?
- is there a way to wrap modules, for problem finding with other users 
of my program,
I would log when a module is imported (and it's code is executed) and 
when a module
reaches it's end. I now realize that by calling a global function at the 
end of each module,

that in the debug mode writes a line to a log file.

cheers,
Stef Mientki

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


Re: template strings for matching?

2008-10-09 Thread Robin Becker

Joe Strout wrote:
Catching up on what's new in Python since I last used it a decade ago, 
I've just been reading up on template strings.  These are pretty cool!  
However, just as a template string has some advantages over % 
substitution for building a string, it seems like it would have 
advantages over manually constructing a regex for string matching.


So... is there any way to use a template string for matching?  I 
expected something like:

...

you could use something like this to record the lookups

>>> class XDict(dict):
... def __new__(cls,*args,**kwds):
... self = dict.__new__(cls,*args,**kwds)
... self.__record = set()
... return self
... def _record_clear(self):
... self.__record.clear()
... def __getitem__(self,k):
... v = dict.__getitem__(self,k)
... self.__record.add(k)
... return v
... def _record(self):
... return self.__record
...
>>> x=XDict()
>>> x._record()
set([])
>>> x=XDict(a=1,b=2,c=3)
>>> x
{'a': 1, 'c': 3, 'b': 2}
>>> '%(a)s %(c)s' % x
'1 3'
>>> x._record()
set(['a', 'c'])
>>>

a slight modification would allow your template match function to work even when 
some keys were missing in the dict. That would allow you to see which lookups 
failed as well.

--
Robin Becker

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


Re: Twisted Matrix and multicast broadcast

2008-10-09 Thread Jean-Paul Calderone

On Thu, 9 Oct 2008 06:03:44 -0700 (PDT), Stodge <[EMAIL PROTECTED]> wrote:

[snip]
class MulticastServerUDP(DatagramProtocol):
   def startProtocol(self):
   print 'Started Listening'
   # Join a specific multicast group, which is the IP we will
respond to
   self.transport.joinGroup('224.0.0.1')

[snip]

class MulticastClientUDP(DatagramProtocol):
   def startProtocol(self):
   print 'Started Listening'
   # Join a specific multicast group, which is the IP we will
respond to
   self.transport.joinGroup('224.0.0.1')

[snip]

No surprises there! But how do I get the server to send to all clients
using multicast? transport.write requires an address. Any suggestions
appreciated.


Your server and client are both listening on the multicast address
224.0.0.1.  Traffic sent to that address will be delivered to both
of them.  If you want to send something to all clients listening on
that address, then that's the address to pass to transport.write.

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


About print exception message

2008-10-09 Thread WaterWalk
Until Python 2.5, the exception object still uses ansi string.  Thus,
in the following example:

f = open(u"\u6d4b.log")

Suppose the file to open does not exist, the output message of the
exception maybe like:
[Errno 2] No such file or directory: u'\u6d4b.log'

This is not a clear message.

I finally work out a rough solution. Since the unicode string in the
exception message is always in the form of "\u" or maybe
"\U", it's possible to manual convert those unicode escape
sequence into the "real" unicode character. The following is the code:

import StringIO
import locale

STATE_NORMAL = 0
STATE_BACK_SLASH = 1
STATE_LOWER_U = 2
STATE_UPPER_U = 3

def ansiu2u(s, enc):
'"convert  '\u' or '\U' sequences in a non-unicode string
to their coresponding unicode characters'''
i = 0
state = STATE_NORMAL
s = unicode(s, enc)
result = StringIO.StringIO()
while i < len(s):
c = s[i]
if state == STATE_NORMAL:
if c == u'\\':
state = STATE_BACK_SLASH
else:
result.write(c)
i += 1
elif state == STATE_BACK_SLASH:
if c == u'u':
state = STATE_LOWER_U
elif c == u'U':
state = STATE_UPPER_U
else:
state = STATE_NORMAL
result.write(u'\\')
result.write(c)
i += 1
elif state == STATE_LOWER_U:
unic = int(s[i : i + 4], 16)
unic = unichr(unic)
result.write(unic)
i += 4
state = STATE_NORMAL
elif state == STATE_UPPER_U:
unic = int(s[i : i + 8], 16)
unic = unichr(unic)
result.write(unic)
i += 8
state = STATE_NORMAL
r = result.getvalue()
result.close()
return r

def obj2unicode(obj):
s = str(obj)
return ansiu2u(s, locale.getdefaultlocale())

Using this function, when printing exceptions, the result will always
be in "good" forms. Any comments?
--
http://mail.python.org/mailman/listinfo/python-list


Re: SimpleXmlRpcServer and character encoding

2008-10-09 Thread Diez B. Roggisch
shymon wrote:

> 
> 
> 
> Diez B. Roggisch-2 wrote:
>> 
>> shymon wrote:
>> 
>>> I'm using SimpleXmlRpcServer class. Although I set encoding parameter in
>>> the constructor, I have to return all strings in default platform
>>> encoding
>>> (windows-1250/win32 or iso-8859-2/linux in my case). When I send values
>>> in, for example, UTF-8, string received by client is messed up.
>>> 
>>> The client is written in java using Apache XmlRpc library 2.0.
>>> 
>>> Is there any solution other than sending all string values in Base64
>>> encoding?
>> 
>> Use unicode-objects. And unicode IS NOT utf-8. The encoding parameter
>> will affect the xml generated & send over the wire - *not* what strings
>> you pass/return to your implementation.
>> 
>> So I think you should remove the encoding parameter alltogether, as this
>> will make the transport being in utf-8. Then use only unicode-objects in
>> your python code. And on the java-side, things *should* be in order.
>> 
>> Diez
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>> 
>> 
> 
> 
> I have tried unicode strings also, let's say u"miłość".
> Result received by the client was the same as if I sent UTF-8 encoded
> string.


Please show concrete code-examples, and the results, preferably as
repr-string, as these contain the hex-chars: 

repr("ö") -> "'\\xc3\\xb6'"

The above shows that the ö is encoded in utf-8.

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


Re: template strings for matching?

2008-10-09 Thread Paul McGuire
Pyparsing makes building expressions with named fields pretty easy.

from pyparsing import Word, alphas

wrd = Word(alphas)

templ = "The" + wrd("object") + "in" + wrd("location") + \
"stays mainly in the" + wrd("subloc") + "."

tests = """\
The rain in Spain stays mainly in the plain.
The snake in plane stays mainly in the cabin.
In Hempstead, Haverford and Hampshire hurricanes hardly ever
happen.
""".splitlines()
for t in tests:
t = t.strip()
try:
match = templ.parseString(t)
print match.object
print match.location
print match.subloc
print "Fields are: %(object)s %(location)s %(subloc)s" % match
except:
print "'" + t + "' is not a match."
print

Read more about pyparsing at http://pyparsing.wikispaces.com.
-- Paul

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


On the indexing order in (numpy) arrays

2008-10-09 Thread Almar Klein
Hi,
I was wondering...

Say we have a np.ndarray A of two dimensions (a grayscale image for
example). If we want to access x:2, y:3, we have to do A[3,2]. Why is
the order of x and y reversed?

This is reversed in Matlab too, because Matlab is a matrix package and
matrix are often used this way. (In Matlab the data is actually stored
last-dimensions-first too.)

I suspect numpy has good reasons to do so too, but they are not clear to
me. I find myself quite a lot wondering if I have to use (or implement) a
method with order x-y-z, or the other way around. And I suspect this can
cause quite a lot of confusion and bugs!

If I make a function to do some image operation in a certain dimension:
def some_operation(image, dim):

Would it make more sense if dim=0 means x, or y?

Can anyone shed some light on why this is and how I can determine which
order to adopt when I create a function like the one above?

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


Re: Twisted Matrix and multicast broadcast

2008-10-09 Thread Stodge
On Oct 9, 9:33 am, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
> On Thu, 9 Oct 2008 06:03:44 -0700 (PDT), Stodge <[EMAIL PROTECTED]> wrote:
> > [snip]
> >class MulticastServerUDP(DatagramProtocol):
> >    def startProtocol(self):
> >        print 'Started Listening'
> >        # Join a specific multicast group, which is the IP we will
> >respond to
> >        self.transport.joinGroup('224.0.0.1')
>
> > [snip]
>
> >class MulticastClientUDP(DatagramProtocol):
> >    def startProtocol(self):
> >        print 'Started Listening'
> >        # Join a specific multicast group, which is the IP we will
> >respond to
> >        self.transport.joinGroup('224.0.0.1')
>
> > [snip]
>
> >No surprises there! But how do I get the server to send to all clients
> >using multicast? transport.write requires an address. Any suggestions
> >appreciated.
>
> Your server and client are both listening on the multicast address
> 224.0.0.1.  Traffic sent to that address will be delivered to both
> of them.  If you want to send something to all clients listening on
> that address, then that's the address to pass to transport.write.
>
> Jean-Paul

Thanks. So the server write should be:

self.transport.write("data", ('224.0.0.1', 8005))

I guess I can't run multiple peers on the same PC as they'll all be
listening on port 8005.
--
http://mail.python.org/mailman/listinfo/python-list


Re: template strings for matching?

2008-10-09 Thread Tino Wildenhain

[EMAIL PROTECTED] wrote:

Tino> Yeah, its a bit hard to spot:

Tino> 
http://docs.python.org/library/stdtypes.html#string-formatting-operations

That shows how to use the template formatting as it currently exists.  To my
knowledge there is no support for the inverse operation, which is what Joe
asked about.  Given a string and a format string assign the elements of the
string which correspond to the template elements to key/value pairs in a
dictionary.


??? can you elaborate? I don't see the problem.

"%(foo)s" % mapping

just calls get("foo") on mapping so if you have a dictionary
with all possible values it just works. If you want to do
some fancy stuff just subclass and change the method
call appropriately.

Regards
Tino


smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list


How to do regular BASH work in Python?

2008-10-09 Thread Frantisek Malina
What is the best way to do the regular bash commands in native python?

- create directory
- create file
- make a symlink
- copy a file to another directory
- move a file
- set permissions

I need to write a program that creates real application/FTP accounts
and make regular backups to external disk and I think its best to do
it all consistently with my application in Python.
This way I can easily link it to the customer database and front-end
web application. I'd want to avoid BASH/SHELL if that's possible.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to do regular BASH work in Python?

2008-10-09 Thread Frantisek Malina
Hey,
I found it. Python rocks:
http://www.python.org/doc/2.5.2/lib/os-file-dir.html

If you have any further links that provide some lively code examples
and recipes, please pass them on.

Thank you

Frank Malina
http://vizualbod.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: template strings for matching?

2008-10-09 Thread Joe Strout

On Oct 9, 2008, at 7:05 AM, [EMAIL PROTECTED] wrote:


   Tino> 
http://docs.python.org/library/stdtypes.html#string-formatting-operations

That shows how to use the template formatting as it currently  
exists.  To my
knowledge there is no support for the inverse operation, which is  
what Joe
asked about.  Given a string and a format string assign the elements  
of the
string which correspond to the template elements to key/value pairs  
in a

dictionary.


Right.

Well, what do y'all think?  It wouldn't be too hard to write this for  
myself, but it seems like the sort of thing Python ought to have built  
in.  Right on the Template class, so it doesn't add anything new to  
the global namespace; it just makes this class more useful.


I took a look at PEP 3101, which is more of a high-powered string  
formatter (as the title says, Advanced String Formatting), and will be  
considerably more intimidating for a beginner than Template.  So, even  
if that goes through, perhaps Template will stick around, and being  
able to use it in both directions could be quite handy.


Oh boy!  Could this be my very first PEP?  :)

Thanks for any opinions,
- Joe


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


Re: How to do regular BASH work in Python?

2008-10-09 Thread jdd
On Oct 9, 10:13 am, Frantisek Malina <[EMAIL PROTECTED]> wrote:
> Hey,
> I found it. Python rocks:http://www.python.org/doc/2.5.2/lib/os-file-dir.html
>
> If you have any further links that provide some lively code examples
> and recipes, please pass them on.
>
> Thank you
>
> Frank Malinahttp://vizualbod.com

http://examples.oreilly.com/python3/ has some good examples, although
they may be a little tough to read through if you don't have a copy of
"programming python", the book they're from.
--
http://mail.python.org/mailman/listinfo/python-list


Re: template strings for matching?

2008-10-09 Thread Peter Otten
Joe Strout wrote:

> Catching up on what's new in Python since I last used it a decade ago,
> I've just been reading up on template strings.  These are pretty
> cool!  

I don't think they've gained much traction and expect them to be superseded
by PEP 3101 (see http://www.python.org/dev/peps/pep-3101/ )

> However, just as a template string has some advantages over % 
> substitution for building a string, it seems like it would have
> advantages over manually constructing a regex for string matching.
> 
> So... is there any way to use a template string for matching?  I
> expected something like:
> 
>   templ = Template("The $object in $location falls mainly in the
> $subloc.")
>   d = templ.match(s)
> 
> and then d would either by None (if s doesn't match), or a dictionary
> with values for 'object', 'location', and 'subloc'.
> 
> But I couldn't find anything like that in the docs.  Am I overlooking
> something?

I don't think so. Here's a DIY implementation:

import re

def _replace(match):
word = match.group(2)
if word == "$":
return "[$]"
return "(?P<%s>.*)" % word

def extract(template, text):
r = re.compile(r"([$]([$]|\w+))")
r = r.sub(_replace, template)
return re.compile(r).match(text).groupdict()


print extract("My $$ is on the $object in $location...",
  "My $ is on the biggest bird in the highest tree...")

As always with regular expressions I may be missing some corner cases...

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


Re: template strings for matching?

2008-10-09 Thread skip

Tino> ??? can you elaborate? I don't see the problem.

Tino> "%(foo)s" % mapping

Joe wants to go in the other direction.  Using your example, he wants a
function which takes a string and a template string and returns a dict.
Here's a concrete example:

s = "My dog has fleas"
fmt = "My $pet has $parasites"
d = fmt_extract(fmt, s)
assert d['pet'] == 'dog'
assert d['parasites'] == 'fleas'

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


authenticated problem for paramiko

2008-10-09 Thread sa6113

I am using this code to connect to a windows machine using paramiko, I have
installed sshd on the machine and it works properly:

sock.connect((hostname, port))
t = paramiko.Transport(sock)
event = threading.Event()
t.start_client(event) 
event.wait()
if not t.is_active():
print 'SSH negotiation failed.'
sys.exit(1)
else:
print "SSH negotiation sucessful" 
event.clear()
t.auth_password(username=username, password=password,event=event) 

if not t.is_authenticated():
print "Authentication failed"

output:

SSH negotiation successful
Authentication failed

I uploaded log file I am sure about username and password on that machine.

What is the problem?

  http://www.nabble.com/file/p19898048/paramiko.log paramiko.log 
-- 
View this message in context: 
http://www.nabble.com/authenticated-problem-for-paramiko-tp19898048p19898048.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


hi can someone help me i would like to run this program 3 times and would like to append the cPickle file as a high score table

2008-10-09 Thread garywood
hi,

Can someone help me i would like to run this program 3 times or more  and would 
like to append the cPickle file as a high score table keeping my top scores. 
Right now it only records the last score thanks. 


# Trivia Challenge
# Trivia game that reads a plain text file

def open_file(file_name, mode):
"""Open a file."""
try:
the_file = open(file_name, mode)
except(IOError), e:
print "Unable to open the file", file_name, "Ending program.\n", e
raw_input("\n\nPress the enter key to exit.")
sys.exit()
else:
return the_file

def next_line(the_file):
"""Return next line from the trivia file, formatted."""
line = the_file.readline()
line = line.replace("/", "\n")
return line

def next_block(the_file):
"""Return the next block of data from the trivia file."""
category = next_line(the_file)

question = next_line(the_file)

answers = []
for i in range(4):
answers.append(next_line(the_file))

correct = next_line(the_file)
if correct:
correct = correct[0]

explanation = next_line(the_file) 

return category, question, answers, correct, explanation

def welcome(title):
"""Welcome the player and get his/her name."""
print "\t\tWelcome to Trivia Challenge!\n"
print "\t\t", title, "\n"
 
def main():
trivia_file = open_file("trivia.txt", "r")
title = next_line(trivia_file)
welcome(title)
score = 0
bonus = 0
tries = 0

# get first block
category, question, answers, correct, explanation = next_block(trivia_file)
while category:
# ask a question
print category
print question
for i in range(4):
print "\t", i + 1, "-", answers[i]



# get answer
answer = raw_input("What's your answer?: ")
tries = tries + 1
# check answer
if answer == correct:
print "\nRight!",
score += 1
if tries == 1:
bonus = 5
elif tries == 2:
bonus = bonus + 10
elif tries == 3:
bonus = bonus + 20
elif tries == 4:
bonus = bonus + 30
elif tries == 5:
bonus = bonus + 40


else:
bonus = bonus
print "\nWrong.",
print explanation
print "Score:", score, "\n\n"


# get next block
category, question, answers, correct, explanation = 
next_block(trivia_file)

trivia_file.close()

print "That was the last question!"
print "You're score is:", score, "and your bonus", bonus
total = score + bonus
print "for a grand total ", total
import cPickle, shelve
name = raw_input("what is your name")
High_Score = [name, total]
pickle_file = open("pickles5.dat", "w")
cPickle.dump(High_Score, pickle_file)
pickle_file.close()
# to read the pickle_file
pickle_file = open("pickles5.dat", "r")
High_Score = cPickle.load(pickle_file)
print High_Score, "High Scores"
main()  
raw_input("\n\nPress the enter key to exit.")
--
http://mail.python.org/mailman/listinfo/python-list


Re: replace numbers in a string

2008-10-09 Thread Peter Otten
Gary Herron wrote:

> Beema Shafreen wrote:
>> hi All,
>>
>> i have few lines in file
>> "ttccatttctggacatgacgtctgt6901ggtttaagctttgtgaaagaatgtgctttgattcg"
>> i need to replace the number and get only the alphabet in such a case
>> what should i do.
>> Can any body suggest me
>>From the regular expression module, use re.sub like this:
> 
> 
 import re
 re.sub('[0-9]', '',
> "ttccatttctggacatgacgtctgt6901ggtttaagctttgtgaaagaatgtgctttgattcg")
> 'ttccatttctggacatgacgtctgtggtttaagctttgtgaaagaatgtgctttgattcg'

Or use str methods.
In Python 2.6:

>>> import string
>>> "tctgt6901ggtttaa".translate(None, string.digits) 
'tctgtggtttaa'

Older versione:

>>> "tctgt6901ggtttaa".translate(string.maketrans("", ""), string.digits)
'tctgtggtttaa'

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


Re: inspect bug

2008-10-09 Thread Gabriel Genellina
En Thu, 09 Oct 2008 00:24:20 -0300, Aaron "Castironpi" Brady  
<[EMAIL PROTECTED]> escribió:



Found this bug.  It's in 2.6, too bad.


Posting here is not going to help much, it just will be lost. Would be  
better to file a bug report at http://bugs.python.org/


--
Gabriel Genellina

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


Re: Access to Google Calendar

2008-10-09 Thread Grant Edwards
On 2008-10-08, pepitovadecurt <[EMAIL PROTECTED]> wrote:

> Hi I need to access to the Google Calendar under python.

Odd.  You'd think somebody who uses Google Calendar would know
how to use Google.

> Is posible?

http://www.google.com/search?q=google+calendar+python

First hit.

-- 
Grant Edwards   grante Yow! TONY RANDALL!  Is YOUR
  at   life a PATIO of FUN??
   visi.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to calculate two time?

2008-10-09 Thread lookon
but can you tell me what format is it?

in the str there is a float and I can not deal with it
On Oct 9, 7:20 pm, [EMAIL PROTECTED] wrote:
>     lookon> Thank you for your help.It works.  However, I am using Google
>     lookon> App Engine and cannot import dateutil and epsilon.
>
> I don't know how Google App Engine works, but are you not able to install
> pure Python modules?
>
>     lookon> Are there any other ways?
>
> Take a look at the time.strptime function to generate a tuple, then use
>
>     t = time.strptime(timestamp, format)
>     t1 = datetime.datetime(*t[0:6])
>
> Note that with this solution you will have to handle the timezone offset
> yourself.
>
> Skip

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


first of not None

2008-10-09 Thread Serge Matveenko
Hello, everybody!

Could someone help me with coding this thing?

I need to put in the var property of the first object from the list
that is not None. Somth like:

foo = first_of([any, beny, riki,]).name

Dont want to ugly if-cascade:

foo = any.name if name is not None else beny.name if beny is not None \
else riki.name if riki is not None


-- 
Serge Matveenko
mailto:[EMAIL PROTECTED]
http://serge.matveenko.ru/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Compiler, ast and forwards/backwards compatibility

2008-10-09 Thread Orestis Markou
On Wed, Oct 8, 2008 at 9:14 PM, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:
>> The documentation for the ast module states that it "helps to find out
>> programmatically what the current grammar looks like". I can't find
>> any reference (even when reading the code) on how you should go about
>> this, other than checking the sys.version number and reading up on the
>> changes.
>
> Not sure what "this" is, but if you mean what you quoted - what does
> that have to do with version numbers?
>
> To find out what the grammar looks like, just inspect the classes in
> the _ast module, e.g.
>
> py> _ast.For._fields
> ('target', 'iter', 'body', 'orelse')
> py> _ast.For._attributes
> ['lineno', 'col_offset']

Thanks, that clears things up a bit.

> In any case, you shouldn't look at sys.version, but at _ast.__version__

Right - the documentation says I should look at ast.__version__ (not
_ast.__version__), which doesn't exist. I've filed a bug report about
it.
>
> To see the source code version of that, look at Python/Parser.asdl.
>
>> My understanding is that there is no way to write, say, an ast visitor
>> that runs under Python 3.0 that targets 2.4 because the ast has
>> changed, and there's no way to indicate that you want to parse another
>> version.
>
> I wouldn't say that. The writer might not be trivial, but should be
> fairly simple. It can't be 1:1, because, as you say, the AST has
> changed.
>
>> I guess that Python 2.6 can target Python 2.3-6, and with specific
>> compiler flags it can also target 3.0, so it seems that the correct
>> thing to do is to use that.
>
> Depends on what you want to do. To transform source code so that
> people can still read and understand it, the _ast module might be
> inappropriate, as it drops all comments.
>
> For code-rewriting applications, look at lib2to3 instead.
>
>> Am I correct? Am I seriously confused? Please help!
>
> I think you are a little confused.

:) Hopefully as I start coding against ast I'll understand more about this.

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

Thanks,
Orestis
-- 
[EMAIL PROTECTED]
http://orestis.gr
--
http://mail.python.org/mailman/listinfo/python-list


Re: first of not None

2008-10-09 Thread Bruno Desthuilliers

Serge Matveenko a écrit :

Hello, everybody!

Could someone help me with coding this thing?

I need to put in the var property of the first object from the list
that is not None. Somth like:

foo = first_of([any, beny, riki,]).name

Dont want to ugly if-cascade:

foo = any.name if name is not None else beny.name if beny is not None \
else riki.name if riki is not None



def not_none(obj):
return obj is not None

def first_of(seq, predicate=not_none, default=None):
for obj in seq:
if predicate(obj):
return obj
else:
return default

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


Re: Safe eval of insecure strings containing Python data structures?

2008-10-09 Thread Orestis Markou
The ast module in 2.6 has something...

On Thu, Oct 9, 2008 at 1:34 AM, Warren DeLano <[EMAIL PROTECTED]> wrote:
>
> I would like to parse arbitrary insecure text string containing nested
> Python data structures in eval-compatible form:
>
> # For example, given a "config.txt" such as:
>
> {
>  'my_atom' : 1.20,
>  'my_dict' : { 2:50 , 'hi':'mom'},
>  'my_list' : [ (1,2,3), [4.5,6.9], 'foo', 0 ]
> }
>
> # I would like to do something like this:
>
> empty_space = {'__builtins__' : {}}
>
> try:
>config = eval(open("config.txt").read(), empty_space, empty_space)
> except:
>config = {}
>
> print config
>
> # But I know for certain that the above approach is NOT secure since
> object attributes can still be accessed...
>
> So is there an equally convenient yet secure alternative available for
> parsing strings containing Python data structure definitions?
>
> Thanks in advance for any pointers!
>
> Cheers,
> Warren
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
[EMAIL PROTECTED]
http://orestis.gr
--
http://mail.python.org/mailman/listinfo/python-list


Access to Google Calendar

2008-10-09 Thread pepitovadecurt

Hi I need to access to the Google Calendar under python.
Is posible?

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


Re: SimpleXmlRpcServer and character encoding

2008-10-09 Thread Diez B. Roggisch
shymon wrote:

> 
> 
> I'm using SimpleXmlRpcServer class. Although I set encoding parameter in
> the constructor, I have to return all strings in default platform encoding
> (windows-1250/win32 or iso-8859-2/linux in my case). When I send values
> in, for example, UTF-8, string received by client is messed up.
> 
> The client is written in java using Apache XmlRpc library 2.0.
> 
> Is there any solution other than sending all string values in Base64
> encoding?

Use unicode-objects. And unicode IS NOT utf-8. The encoding parameter will
affect the xml generated & send over the wire - *not* what strings you
pass/return to your implementation.

So I think you should remove the encoding parameter alltogether, as this
will make the transport being in utf-8. Then use only unicode-objects in
your python code. And on the java-side, things *should* be in order.

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


Re: Safe eval of insecure strings containing Python data structures?

2008-10-09 Thread franck
> I would like to parse arbitrary insecure text string containing nested
> Python data structures in eval-compatible form:  

Python 2.6 has ast.literal_eval to do exactly this. It handle lists,
tuples, dict, numbers, strings, bool and None, with arbitrary nesting.

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


Re: About print exception message

2008-10-09 Thread Jean-Paul Calderone

On Thu, 9 Oct 2008 06:37:04 -0700 (PDT), WaterWalk <[EMAIL PROTECTED]> wrote:

Until Python 2.5, the exception object still uses ansi string.  Thus,
in the following example:

f = open(u"\u6d4b.log")

Suppose the file to open does not exist, the output message of the
exception maybe like:
[Errno 2] No such file or directory: u'\u6d4b.log'

This is not a clear message.


I disagree.  But if you'd rather see the character (or a replacement character,
or possibly an empty box, depending on your environment's text rendering
capabilities), it's a bit easier than writing that big function:


try: open(u'\N{WHITE SMILING FACE}')

... except IOError, e: print str(e).decode('unicode-escape')
... 
[Errno 2] No such file or directory: u'☺'




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


template strings for matching?

2008-10-09 Thread Joe Strout
Catching up on what's new in Python since I last used it a decade ago,  
I've just been reading up on template strings.  These are pretty  
cool!  However, just as a template string has some advantages over %  
substitution for building a string, it seems like it would have  
advantages over manually constructing a regex for string matching.


So... is there any way to use a template string for matching?  I  
expected something like:


 templ = Template("The $object in $location falls mainly in the  
$subloc.")

 d = templ.match(s)

and then d would either by None (if s doesn't match), or a dictionary  
with values for 'object', 'location', and 'subloc'.


But I couldn't find anything like that in the docs.  Am I overlooking  
something?


Thanks,
- Joe

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


Re: first of not None

2008-10-09 Thread Tim Chase

I need to put in the var property of the first object from the list
that is not None. Somth like:

foo = first_of([any, beny, riki,]).name

Dont want to ugly if-cascade:

foo = any.name if name is not None else beny.name if beny is not None \
else riki.name if riki is not None



assuming you meant "foo = any.name if ***any*** is not None else 
beny.name..."


If you have a fixed/hard-coded list of elements, you could 
something like:


  foo = (any or beny or riki).name

If you have dynamic list of elements:

  class NoElementFound(Exception): pass
  def first(iterable):
for element in iterable:
  if element: return element
raise NoElementFound

  lst = [any, beny]
  if condition: lst.append(riki)
  print first(lst).name

This first() is about the functionality of the SQL Coalesce() 
function.


Hope this helps,

-tim



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


Re: How to calculate two time?

2008-10-09 Thread lookon
Thank you for your help.It works.

However, I am using Google App Engine and cannot import dateutil and
epsilon.

Are there any other ways?


On Oct 8, 10:06 pm, [EMAIL PROTECTED] wrote:
>     lookon> I have two string like "2007-03-27T08:54:43+08:00 " how do I get
>     lookon> the hours between these two time(string format)?
>
> Look in PyPI for dateutil, then:
>
>     >>> import dateutil.parser
>     >>> t1 = dateutil.parser.parse("2007-03-27T08:54:43+08:00")
>     >>> t1
>     datetime.datetime(2007, 3, 27, 8, 54, 43, tzinfo=tzoffset(None, 28800))
>     >>> t2 = dateutil.parser.parse("2007-03-29T10:00:00+02:00") >>> t2
>     datetime.datetime(2007, 3, 29, 10, 0, tzinfo=tzoffset(None, 7200))
>     >>> t2 - t1
>     datetime.timedelta(2, 25517)
>
> Skip

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


Re: Clever way of sorting strings containing integers?

2008-10-09 Thread bieffe62
On 9 Ott, 09:41, Holger <[EMAIL PROTECTED]> wrote:
> I tried to do this elegantly, but did not come up with a good solution
>
> Sort strings like
> foo1bar2
> foo10bar10
> foo2bar3
> foo10bar2
>
> So that they come out:
> foo1bar2
> foo2bar3
> foo10bar2
> foo10bar10
>
> I.e. isolate integer parts and sort them according to integer value.
>
> Thx
> Holger

This should work, if you have all stribngs in memory:

import re
REXP = re.compile( r'\d+' )
lines = ['foo1bar2', 'foo10bar10', 'foo2bar3', 'foo10bar2' ]
def key_function( s ): return map(int, re.findall(REXP, s ))
lines.sort( key=key_function)


Ciao

FB


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


Re: Efficient Bit addressing in Python.

2008-10-09 Thread Lie Ryan
On Fri, 10 Oct 2008 00:30:18 +0200, Hendrik van Rooyen wrote:

> Is there a canonical way to address the bits in a structure like an
> array or string or struct?
> 
> Or alternatively, is there a good way to combine eight ints that
> represent bits into one of the bytes in some array or string or
> whatever?
> 
> It seems to me that there is a dilemma here :
> 
> if you can write:
> 
> bit3 = 1
> 
> Then you have to jump through hoops to get bit0 through bit7 into some
> byte that you can send to an i/o routine.
> 
> On the other hand, if you keep the bits "in" the byte, then you can
> write:
> 
> byte[3] = '\x7e'
> 
> but you have to jump through hoops to get at the individual bits.
> 
> Is there a "best" way?
> 
> It would be nice to be able to write:
> 
> if io.byte2.bit3:
>do_something()
> 
> if io.byte2 == alarm_value:
>   do_something_else()
> 
> where:
> 
>  io.byte2 & 8   "is"  io.byte2.bit3
> 
> Is this possible?
> 
> - Hendrik

You'll find that in most cases, using integer or Boolean is enough. There 
are some edge cases, which requires bit addressing for speed or memory 
optimizations, in python, the usual response to that kind of optimization 
requirement is to move that part of the code to C.

If, for the more usual case, you require the bit addressing because the 
data structure is more convenient to work with that way, you could use a 
class that implements the __getitem__, __setitem__, and a "join" method.

anyway, if you used str, it isn't hard to have both behavior (easy 
indexing and easy joining) the bits:
>>> a = '01101010'
>>> a[0], a[1]
('0', '1')
>>> a
'01101010'
>>> int(a, 2)
106
>>> chr(int(a, 2))
'j'
>>> def bin2int(b): return int(a, 2)
...
>>> def bin2chr(b): return chr(int(a, 2))
...
>>>

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


Re: Safe eval of insecure strings containing Python data structures?

2008-10-09 Thread Lie Ryan
On Thu, 09 Oct 2008 13:26:17 +0100, Orestis Markou wrote:

> The ast module in 2.6 has something...
> 

in python 2.6, ast.literal_eval may be used to replace eval() for 
literals. It does not accepts statements and function calls, i.e.:

>>> a = set([1, 2, 3])
>>> repr(a)
set([1, 2, 3])
>>> ast.literal_eval(repr(a))
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/local/lib/python2.6/ast.py", line 67, in literal_eval
return _convert(node_or_string)
  File "/usr/local/lib/python2.6/ast.py", line 66, in _convert
raise ValueError('malformed string')
ValueError: malformed string

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


NameError question - def(self,master) - master not in namespace within class?

2008-10-09 Thread harijay
Hi I am new to writing module and object oriented python code. I am
trying to understand namespaces and classes in python.

I have the following test case given in three files runner , master
and child. I am getting an error within child where in one line it
understands variable master.name and in the next line it gives a
NameError as given here

"print "Reset name now from %s to %s , oldname %s is saved in
mastertrash" % (master.trash, master.name , master.trash)
NameError: name 'master' is not defined"


Sorry for a long post because I dont know how to  frame my question.
I am pasting the code contained in the three files and the error
message here
Thanks for your help
harijay


The detailed error I get is
hazel:tmp hari$ python runner.py
Traceback (most recent call last):
  File "runner.py", line 3, in 
import child
  File "/Users/hari/rpc-ccp4/tmp/child.py", line 1, in 
class child():
  File "/Users/hari/rpc-ccp4/tmp/child.py", line 9, in child
print "Reset name now from %s to %s , oldname %s is saved in
mastertrash" % (master.trash, master.name , master.trash)
NameError: name 'master' is not defined

#File runner.py
#!/usr/bin/python
import master
import child

if __name__=="__main__":
print "RUNNING RUNNER"
m = master.master("hj","oldhj")
s = child.child(m)
print "Now I have the variable master name %s and master.trash %s" %
(m.name , m.trash)

#File master.py
class master():
name=""
trash=""

def __init__(self,name,trash):
self.name = name
self.trash = trash


#File child.py
class child():
def __init__(self,master):
print "Master  name is %s" % master.name
print  "Now seeting master name to setnameinchild in child.py "
tmp = master.trash
master.trash = master.name
master.name = "setnameinchild"
print "Reset name now from %s to %s , oldname %s is saved in
mastertrash" % (master.trash, master.name , master.trash)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Efficient Bit addressing in Python.

2008-10-09 Thread George Sakkis
On Oct 9, 6:30 pm, "Hendrik van Rooyen" <[EMAIL PROTECTED]> wrote:

> Is there a canonical way to address the bits in a structure
> like an array or string or struct?

I don't know of a canonical way (bit hacking is not really common in
Python) but pehaps BitPacket [1] comes close to what you're after.

George

[1] http://hacks-galore.org/aleix/BitPacket/
--
http://mail.python.org/mailman/listinfo/python-list


Re: NameError question - def(self, master) - master not in namespace within class?

2008-10-09 Thread bieffe62
On 9 Ott, 17:43, harijay <[EMAIL PROTECTED]> wrote:
> Hi I am new to writing module and object oriented python code. I am
> trying to understand namespaces and classes in python.
>
> I have the following test case given in three files runner , master
> and child. I am getting an error within child where in one line it
> understands variable master.name and in the next line it gives a
> NameError as given here
>
> "    print "Reset name now from %s to %s , oldname %s is saved in
> mastertrash" % (master.trash, master.name , master.trash)
> NameError: name 'master' is not defined"
>
> Sorry for a long post because I dont know how to  frame my question.
> I am pasting the code contained in the three files and the error
> message here
> Thanks for your help
> harijay
>
> The detailed error I get is
> hazel:tmp hari$ python runner.py
> Traceback (most recent call last):
>   File "runner.py", line 3, in 
>     import child
>   File "/Users/hari/rpc-ccp4/tmp/child.py", line 1, in 
>     class child():
>   File "/Users/hari/rpc-ccp4/tmp/child.py", line 9, in child
>     print "Reset name now from %s to %s , oldname %s is saved in
> mastertrash" % (master.trash, master.name , master.trash)
> NameError: name 'master' is not defined
>
> #File runner.py
> #!/usr/bin/python
> import master
> import child
>
> if __name__=="__main__":
>         print "RUNNING RUNNER"
>         m = master.master("hj","oldhj")
>         s = child.child(m)
>         print "Now I have the variable master name %s and master.trash %s" %
> (m.name , m.trash)
>
> #File master.py
> class master():
>         name=""
>         trash=""
>
>         def __init__(self,name,trash):
>                 self.name = name
>                 self.trash = trash
>
> #File child.py
> class child():
>         def __init__(self,master):
>                 print "Master  name is %s" % master.name
>                 print  "Now seeting master name to setnameinchild in child.py 
> "
>                 tmp = master.trash
>                 master.trash = master.name
>                 master.name = "setnameinchild"
>         print "Reset name now from %s to %s , oldname %s is saved in
> mastertrash" % (master.trash, master.name , master.trash)


You need to have an import master in child.py too.

Ciao
-
FB

Ciao

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


Re: Safe eval of insecure strings containing Python data structures?

2008-10-09 Thread Paul Rubin
Lie Ryan <[EMAIL PROTECTED]> writes:
> in python 2.6, ast.literal_eval may be used to replace eval() for 
> literals. 

What happens on literal_eval('[1]*9') ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: NameError question - def(self, master) - master not in namespace within class?

2008-10-09 Thread Jerry Hill
On Thu, Oct 9, 2008 at 11:43 AM, harijay <[EMAIL PROTECTED]> wrote:
> Hi I am new to writing module and object oriented python code. I am
> trying to understand namespaces and classes in python.
>
> I have the following test case given in three files runner , master
> and child. I am getting an error within child where in one line it
> understands variable master.name and in the next line it gives a
> NameError as given here
>



> #File child.py
> class child():
>def __init__(self,master):
>print "Master  name is %s" % master.name
>print  "Now seeting master name to setnameinchild in child.py "
>tmp = master.trash
>master.trash = master.name
>master.name = "setnameinchild"
>print "Reset name now from %s to %s , oldname %s is saved in
> mastertrash" % (master.trash, master.name , master.trash)

The last line (starting with print), is not indented to the correct
level.  Assuming it's supposed to be part of the child class's
__init__ method, it needs to line up with the rest of that method.

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


Re: NameError question - def(self, master) - master not in namespace within class?

2008-10-09 Thread harijay
Thanks beiff for your prompt reply - But I shouldnt need to import
master in child.

Actually and very strangely. The problem fixed itself without any
change to my code.
I dont understand how. It may have been a problem with a bad *.pyc
lingering around . But now I cannot get the old NameError to repeat
itself..its very weird
Here is the new code and it runs just fine ..I am absolutely confused
as to why it failed several times in a row and then fixed itself.


Here is the new code just to convince myself that there is absolutely
no change;


#File runner.py
#!/usr/bin/python
import master
import child

if __name__=="__main__":
print "RUNNING RUNNER"
m = master.master("hj","oldhj")
s = child.child(m)
print "Now I have the variable master name %s and master.trash %s" %
(m.name , m.trash)


#File child.py
class child():

def __init__(self,master):
print "Master  name is %s" % master.name
print  "Now seeting master name to setnameinchild in child.py "
tmp = master.trash
master.trash = master.name
master.name = "setnameinchild"
print "Reset name now from %s to %s , oldname %s is saved in
mastertrash" % (master.trash, master.name , master.trash)

#File master.py
class master():
name=""
trash=""

def __init__(self,name,trash):
self.name = name
self.trash = trash

Produces the output:
hazel:tmp hari$ python runner.py
RUNNING RUNNER
Master  name is hj
Now seeting master name to setnameinchild in child.py
Reset name now from hj to setnameinchild , oldname hj is saved in
mastertrash
Now I have the variable master name setnameinchild and master.trash hj

On Oct 9, 11:54 am, [EMAIL PROTECTED] wrote:
> On 9 Ott, 17:43, harijay <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hi I am new to writing module and object oriented python code. I am
> > trying to understand namespaces and classes in python.
>
> > I have the following test case given in three files runner , master
> > and child. I am getting an error within child where in one line it
> > understands variable master.name and in the next line it gives a
> > NameError as given here
>
> > "    print "Reset name now from %s to %s , oldname %s is saved in
> > mastertrash" % (master.trash, master.name , master.trash)
> > NameError: name 'master' is not defined"
>
> > Sorry for a long post because I dont know how to  frame my question.
> > I am pasting the code contained in the three files and the error
> > message here
> > Thanks for your help
> > harijay
>
> > The detailed error I get is
> > hazel:tmp hari$ python runner.py
> > Traceback (most recent call last):
> >   File "runner.py", line 3, in 
> >     import child
> >   File "/Users/hari/rpc-ccp4/tmp/child.py", line 1, in 
> >     class child():
> >   File "/Users/hari/rpc-ccp4/tmp/child.py", line 9, in child
> >     print "Reset name now from %s to %s , oldname %s is saved in
> > mastertrash" % (master.trash, master.name , master.trash)
> > NameError: name 'master' is not defined
>
> > #File runner.py
> > #!/usr/bin/python
> > import master
> > import child
>
> > if __name__=="__main__":
> >         print "RUNNING RUNNER"
> >         m = master.master("hj","oldhj")
> >         s = child.child(m)
> >         print "Now I have the variable master name %s and master.trash %s" %
> > (m.name , m.trash)
>
> > #File master.py
> > class master():
> >         name=""
> >         trash=""
>
> >         def __init__(self,name,trash):
> >                 self.name = name
> >                 self.trash = trash
>
> > #File child.py
> > class child():
> >         def __init__(self,master):
> >                 print "Master  name is %s" % master.name
> >                 print  "Now seeting master name to setnameinchild in 
> > child.py "
> >                 tmp = master.trash
> >                 master.trash = master.name
> >                 master.name = "setnameinchild"
> >         print "Reset name now from %s to %s , oldname %s is saved in
> > mastertrash" % (master.trash, master.name , master.trash)
>
> You need to have an import master in child.py too.
>
> Ciao
> -
> FB
>
> Ciao
> 
> FB

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


Re: NameError question - def(self, master) - master not in namespace within class?

2008-10-09 Thread harijay
Thanks Jerry and beiff ,
Jerry was right, it was an indent problem . Between using my text
editor and running from commandline something went out of sync and I
didnt catch it probably.
I can now reproduce the error with a bad ident .

These are my first posts to comp.lang.python..and I am very grateful
to everyone for their time .

harijay

On Oct 9, 12:07 pm, "Jerry Hill" <[EMAIL PROTECTED]> wrote:
> On Thu, Oct 9, 2008 at 11:43 AM, harijay <[EMAIL PROTECTED]> wrote:
> > Hi I am new to writing module and object oriented python code. I am
> > trying to understand namespaces and classes in python.
>
> > I have the following test case given in three files runner , master
> > and child. I am getting an error within child where in one line it
> > understands variable master.name and in the next line it gives a
> > NameError as given here
>
> 
>
> > #File child.py
> > class child():
> >        def __init__(self,master):
> >                print "Master  name is %s" % master.name
> >                print  "Now seeting master name to setnameinchild in 
> > child.py "
> >                tmp = master.trash
> >                master.trash = master.name
> >                master.name = "setnameinchild"
> >        print "Reset name now from %s to %s , oldname %s is saved in
> > mastertrash" % (master.trash, master.name , master.trash)
>
> The last line (starting with print), is not indented to the correct
> level.  Assuming it's supposed to be part of the child class's
> __init__ method, it needs to line up with the rest of that method.
>
> --
> Jerry

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


Re: template strings for matching?

2008-10-09 Thread Joe Strout
Wow, this was harder than I thought (at least for a rusty Pythoneer  
like myself).  Here's my stab at an implementation.  Remember, the  
goal is to add a "match" method to Template which works like  
Template.substitute, but in reverse: given a string, if that string  
matches the template, then it should return a dictionary mapping each  
template field to the corresponding value in the given string.


Oh, and as one extra feature, I want to support a ".greedy" attribute  
on the Template object, which determines whether the matching of  
fields should be done in a greedy or non-greedy manner.



#!/usr/bin/python

from string import Template
import re

def templateMatch(self, s):
# start by finding the fields in our template, and building a map
# from field position (index) to field name.
posToName = {}
pos = 1
for item in self.pattern.findall(self.template):
# each item is a tuple where item 1 is the field name
posToName[pos] = item[1]
pos += 1

# determine if we should match greedy or non-greedy
greedy = False
if self.__dict__.has_key('greedy'):
greedy = self.greedy

# now, build a regex pattern to compare against s
# (taking care to escape any characters in our template that
# would have special meaning in regex)
pat = self.template.replace('.', '\\.')
pat = pat.replace('(', '\\(')
pat = pat.replace(')', '\\)') # there must be a better way...

if greedy:
pat = self.pattern.sub('(.*)', pat)
else:
pat = self.pattern.sub('(.*?)', pat)
p = re.compile(pat)

# try to match this to the given string
match = p.match(s)
if match is None: return None
out = {}
for i in posToName.keys():
out[posToName[i]] = match.group(i)
return out


Template.match = templateMatch

t = Template("The $object in $location falls mainly in the $subloc.")
print t.match( "The rain in Spain falls mainly in the train." )


This sort-of works, but it won't properly handle $$ in the template,  
and I'm not too sure whether it handles the ${fieldname} form,  
either.  Also, it only escapes '.', '(', and ')' in the template...  
there must be a better way of escaping all characters that have  
special meaning to RegEx, except for '$' (which is why I can't use  
re.escape).


Probably the rest of the code could be improved too.  I'm eager to  
hear your feedback.


Thanks,
- Joe


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


Re: How to do regular BASH work in Python?

2008-10-09 Thread Frank Malina @ vizualbod.com
On Oct 9, 3:22 pm, jdd <[EMAIL PROTECTED]> wrote:
> On Oct 9, 10:13 am, Frantisek Malina <[EMAIL PROTECTED]> wrote:
>
> > Hey,
> > I found it. Python 
> > rocks:http://www.python.org/doc/2.5.2/lib/os-file-dir.html
>
> > If you have any further links that provide some lively code examples
> > and recipes, please pass them on.
>
> > Thank you
>
> > Frank Malinahttp://vizualbod.com
>
> http://examples.oreilly.com/python3/has some good examples, although
> they may be a little tough to read through if you don't have a copy of
> "programming python", the book they're from.

Coming form PHP, I find Python is pleasure to read no matter what.
--
http://mail.python.org/mailman/listinfo/python-list


Re: split a list based on a predicate

2008-10-09 Thread Rajanikanth Jammalamadaka
Thanks for all of your replies.

Rajanikanth

On Wed, Oct 8, 2008 at 11:59 PM, beginner <[EMAIL PROTECTED]> wrote:
> Hi,
>
> On Oct 8, 6:36 pm, "Rajanikanth Jammalamadaka" <[EMAIL PROTECTED]>
> wrote:
>> Hi!
>>
>> Is there a functional way to do this?
>>
>> I have an array [0,1,2,3,0,1,2,2,3] and I want the first chunk of
>> non-decreasing values from this array (eg: In this case I want
>> [0,1,2,3])
>>
>> Thanks,
>>
>> Rajanikanth
>
> Here is an idea. It is not the most efficient code!
>
> def combine(l, a):
>if not l or l[-1]return l
>
> reduce(combine, [0,1,2,3,0,1,2,2,3], [])
>
> best regards,
> beginner
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



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


How to delete readonly and hidden files & directories on windows xp?

2008-10-09 Thread dudeja . rajat
Hi,

I'm using Windows XP and I'm looking for way out to remove .svn folders from
my directory. But I'm unable to do that.
Does any one one has written any script for removing the hidden / readonly
files or directories?


Regards,
Rajat
--
http://mail.python.org/mailman/listinfo/python-list


Re: Access to Google Calendar

2008-10-09 Thread Joshua Kugler
pepitovadecurt wrote:
> Hi I need to access to the Google Calendar under python.
> Is posible?

You mean this? 

http://code.google.com/apis/calendar/developers_guide_python.html

j

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


Re: utf-8 read/write file

2008-10-09 Thread gigs

Kent Johnson wrote:

On Oct 8, 5:55 pm, gigs <[EMAIL PROTECTED]> wrote:

Benjamin wrote:

On Oct 8, 12:49 pm, Bruno <[EMAIL PROTECTED]> wrote:

Hi!
I have big .txt file which i want to read, process and write to another .txt 
file.
I have done script for that, but im having problem with croatian characters
(©,Ð,®,È,Æ).

UnicodeDecodeError: 'utf8' codec can't decode byte 0x9e in position 0:
unexpected code byte


Are you sure you have UTF-8 data? I guess your file is encoded in
CP1250 or CP1252; in both of these charsets 0x9e represents LATIN
SMALL LETTER Z WITH CARON.

Kent


This data wasnt in utf-8 probably, today i get another one utf-8 and its working

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


Re: Pr. Euler 18, recursion problem

2008-10-09 Thread Lie Ryan
On Mon, 06 Oct 2008 00:14:37 -0700, process wrote:

> On Oct 6, 8:13 am, Aidan <[EMAIL PROTECTED]> wrote:
>> process wrote:
>> > I am trying to solve project euler problem 18 with brute force(I will
>> > move on to a better solution after I have done that for problem 67).
>> >http://projecteuler.net/index.php?section=problems&id=18
>>
>> > However I can't get the recursive function right.
>>
>> > I always have to use return right? Unless I am printing? So I canät
>> > stack to diffferent recursive calls after each other like so:
>> > recur_left(t, p)
>> > recur_right(t,p+1)
>>
>> > Some stuff I have tried:
>>
>> > def recur(tree, pos):
>> >     if not tree:
>> >         return []
>> >     else:
>> >         return [[tree[0][pos]] + recur(tree[1:], pos)] + \
>> >                [[tree[0][pos]] + recur(tree[1:], pos+1)]
>>
>>  recur([[1],[2,3],[4,5,6]],0)
>> > [[1, [2, [4], [4]], [2, [5], [5]]], [1, [3, [5], [5]], [3, [6],
>> > [6
>>
>> > SO it is kind of working, just not exactly like I want. A more easily
>> > parseable/readable result would be nice, I want to be able to sum()
>> > over each path preferrably.
>>
>> > So the result should be:
>> > [[1,2,4],[1,2,5],[1,3,5],[1,3,6]]
>>
>> > I know conceptually what has to be done. Base case: empty tree,
>> > return []
>> > Else: recur to the left and to the right.
>>
>> This is just my opinion, but I felt the non-brute force solution to
>> this problem was actually simpler than trying to define a brute force
>> recursive solution I tried to implement a brute force algorithm at
>> first, until I had an epiphany with regard to how simple the problem
>> actually was.  Then I faced palmed.
> 
> 
> 
> But let's say you have [[1],[1,10],[1,2,300],[10,1,1,1]].
> 
> you must check all solutions right? there is no pattern. if you start
> from the bottom and eliminate paths that seem to be losing can you
> regain that later up in the pyramid if it turns out one side gets bigg
> again?

A Wise Man once says: "When you're hopelessly stuck with a problem, 
reverse the problem"

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


Re: Python 2.6, GUI not working on vista?

2008-10-09 Thread Thorsten Kampe
* Lawrence D'Oliveiro (Wed, 08 Oct 2008 10:47:54 +1300)
> In message <[EMAIL PROTECTED]>, Thorsten
> Kampe wrote:
> > * Lawrence D'Oliveiro (Mon, 06 Oct 2008 23:18:10 +1300)
> >> In message <[EMAIL PROTECTED]>, Thorsten
> >> Kampe wrote:
> >>> * Lawrence D'Oliveiro (Sun, 05 Oct 2008 22:13:46 +1300)
> >>>
>  In message <[EMAIL PROTECTED]>, Michel Claveau -
>  NoSpam SVP ; merci wrote:
>  
> > Another way is to de-activate UAC.
>  
>  Please don't be stupid!
> >>> 
> >>> He's not stupid. Disabling UAC is the recommended way to get rid of
> >>> these problems.
> >> 
> >> Disabling UAC is NOT recommended.
> > 
> > YOU don't recommend it. I don't "recommend" it either - all the
> > people I know (and this includes Microsoft techsupport people) do it
> > anyway without recommendation.
> 
> I find that hard to believe. Any company that would spend so much time
> and effort developing and promoting such a feature on one hand, while
> quietly disabling it on the other hand, would have to be sick.

You can believe what you want. The people who developed UAC don't have 
to support it.

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


Re: Python 2.6, GUI not working on vista?

2008-10-09 Thread Thorsten Kampe
* Mensanator (Tue, 7 Oct 2008 10:58:24 -0700 (PDT))
> On Oct 7, 12:40 pm, Thorsten Kampe <[EMAIL PROTECTED]> wrote:
> > * Lawrence D'Oliveiro (Mon, 06 Oct 2008 23:18:10 +1300)
> > > In message <[EMAIL PROTECTED]>, Thorsten Kampe
> > > wrote:
> > > > * Lawrence D'Oliveiro (Sun, 05 Oct 2008 22:13:46 +1300)
> >
> > > >> In message <[EMAIL PROTECTED]>, Michel Claveau -
> > > >> NoSpam SVP ; merci wrote:
> >
> > > >> > Another way is to de-activate UAC.
> >
> > > >> Please don't be stupid!
> >
> > > > He's not stupid. Disabling UAC is the recommended way to get rid of
> > > > these problems.
> >
> > > Disabling UAC is NOT recommended.
> >
> > YOU don't recommend it. I don't "recommend" it either - all the people I
> > know (and this includes Microsoft techsupport people) do it anyway
> > without recommendation.
> 
> Be that as it may, it is still enabled by default, isn't it?
> 
> So advice that requires it to be disabled (or the Administrator
> account enabled) ought to mention such a pertinent fact, shouldn't it?

The fact that it's enabled by default is totally irrelevant for the 
advise.

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


Get High on Rave Pills

2008-10-09 Thread easta01
Many pills in the market today like Ecstasy are popular at rave
parties. These pills though effective in giving you a kick can also be
risky to consume & possess. Reactions to these drugs include teeth
gritting, nausea, hazy vision, chills, spasms & sweating. Increased
heart rate & high BP levels also occur due to these pills. You can
also suffer from sleep problems, anxiety & depression. Continued use
of these drugs may eventually harm your physical & psychological
functions. Apart from the effects, it's also illegal to keep such
drugs with you in most countries. You will be arrested if you are
found with these drugs on you in places that have banned such pills.
On the other hand, Rave is the safest option available to you without
the fear of nasty side-effects or a long time in jail. Rave gives you
the same buzz that the illegal ones do but without any proven side-
effects. It's absolutely non-addictive & is legal to possess in every
country. Rave gives you the freedom to carry it anywhere you go as it
also comes in a mini-pack of 10 capsules.

For an Out-of-the-World & Earth-Shattering Experience,
Try Rave Pills!!

Only the blend in each Rave energy boosting pill can make you happy &
give you an out-of-the-world high without any "come-down" effects that
are seen in most other party pills. When you are on the Rave trip,
your mind is detached from your body. You will experience a sensation
of entering into a complete new reality. Rave is sure to have an
impact even on the most zealous psychonaut. Rave is a fun and super-
safe pill to enjoy all nighters no matter which place in the universe
you are in.

http://fhurl.com/b15490
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.6, GUI not working on vista?

2008-10-09 Thread Mensanator
On Oct 9, 12:36 pm, Thorsten Kampe <[EMAIL PROTECTED]> wrote:
> * Mensanator (Tue, 7 Oct 2008 10:58:24 -0700 (PDT))
>
>
>
>
>
> > On Oct 7, 12:40 pm, Thorsten Kampe <[EMAIL PROTECTED]> wrote:
> > > * Lawrence D'Oliveiro (Mon, 06 Oct 2008 23:18:10 +1300)
> > > > In message <[EMAIL PROTECTED]>, Thorsten Kampe
> > > > wrote:
> > > > > * Lawrence D'Oliveiro (Sun, 05 Oct 2008 22:13:46 +1300)
>
> > > > >> In message <[EMAIL PROTECTED]>, Michel Claveau -
> > > > >> NoSpam SVP ; merci wrote:
>
> > > > >> > Another way is to de-activate UAC.
>
> > > > >> Please don't be stupid!
>
> > > > > He's not stupid. Disabling UAC is the recommended way to get rid of
> > > > > these problems.
>
> > > > Disabling UAC is NOT recommended.
>
> > > YOU don't recommend it. I don't "recommend" it either - all the people I
> > > know (and this includes Microsoft techsupport people) do it anyway
> > > without recommendation.
>
> > Be that as it may, it is still enabled by default, isn't it?
>
> > So advice that requires it to be disabled (or the Administrator
> > account enabled) ought to mention such a pertinent fact, shouldn't it?
>
> The fact that it's enabled by default is totally irrelevant for the
> advise.

You're talking about the wrong fact. The advice doesn't mention UAC.

Here, let me quote it to you:

Vista Note
Administrators installing Python for all users on
Windows Vista either need to be logged in as
Administrator, or use the runas command, as
in:

runas /user:Administrator "msiexec /i \.msi"


Now, how relevant is the state of the Administrator account
for this advice to work?

>
> T.

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


paramiko and stackless

2008-10-09 Thread Linnorm
I've written a port forwarding wrapper with paramiko for an app we use
and it works fine except that it consumes way too much processor.
(i.e. 25% +)  I'm trying to write a stackless-based server class to
replace the threading one but I can't get the tunnel the wrapper
creates to work for more than one instance of the app.  I based my
code on the example HTTP server on the stackless site.  Relevant code
follows.  The glovia variable is the result of subprocess.Popen().


class ForwardServer (SocketServer.TCPServer):
allow_reuse_address = True
def __init__(self, *args, **kwargs):
SocketServer.TCPServer.__init__(self, *args, **kwargs)
self.socket.setblocking(0)

def serve_forever(self, glovia):
while glovia.poll() is None:
verbose("Handle request")
self.handle_request()

def handle_request(self):
try:
request, client_address = self.get_request()
except socket.error:
return
verbose("Adding handler tasklet")
stackless.tasklet(self.handle_request_tasklet)(request,
client_address)

def handle_request_tasklet(self, request, client_address):
if self.verify_request(request, client_address):
try:
self.process_request(request, client_address)
except:
self.handle_error(request, client_address)
self.close_request(request)


class Handler (SocketServer.BaseRequestHandler):
def handle(self):
verbose("Entering Handler.handle")
peername = self.request.getpeername()
try:
chan = self.ssh_transport.open_channel('direct-tcpip',
   (self.chain_host,
self.chain_port), peername)
except Exception, e:
verbose('Incoming request to %s:%d failed: %s' %
(self.chain_host, self.chain_port, repr(e)))
return
if chan is None:
verbose('Incoming request to %s:%d was rejected by the SSH
server.' % (self.chain_host, self.chain_port))
return

verbose('Connected!  Tunnel open %r -> %r -> %r' % (peername,
 
chan.getpeername(), (self.chain_host, self.chain_port)))
while True:
r, w, x = select.select([self.request, chan], [], [])
if self.request in r:
data = self.request.recv(1024)
if len(data) == 0:
break
chan.send(data)
if chan in r:
data = chan.recv(1024)
if len(data) == 0:
break
self.request.send(data)
verbose("Current Task: %s" %
(str(stackless.getcurrent()),))
verbose("Scheduling Tasks: %s" %
(str(stackless.getruncount()),))
stackless.schedule()
chan.close()
self.request.close()
verbose("Exiting Handler.handle")
verbose('Tunnel closed from %r' % (peername,))


def forward_tunnel(glovia, local_port, remote_host, remote_port,
transport):
class SubHandler (Handler):
chain_host = remote_host
chain_port = remote_port
ssh_transport = transport
ForwardServer(('', local_port), SubHandler).serve_forever(glovia)

stackless.tasklet(forward_tunnel)(glovia, LOCAL_PORT, HOST,
REMOTE_PORT, client.get_transport())
stackless.run()

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


Re: Efficient Bit addressing in Python.

2008-10-09 Thread Mensanator
On Oct 9, 5:30 pm, "Hendrik van Rooyen" <[EMAIL PROTECTED]> wrote:
> Is there a canonical way to address the bits in a structure
> like an array or string or struct?
>
> Or alternatively, is there a good way to combine eight
> ints that represent bits into one of the bytes in some
> array or string or whatever?
>
> It seems to me that there is a dilemma here :
>
> if you can write:
>
> bit3 = 1
>
> Then you have to jump through hoops to get
> bit0 through bit7 into some byte that you can send
> to an i/o routine.
>
> On the other hand, if you keep the bits "in" the
> byte, then you can write:
>
> byte[3] = '\x7e'
>
> but you have to jump through hoops to get at
> the individual bits.
>
> Is there a "best" way?
>
> It would be nice to be able to write:
>
> if io.byte2.bit3:
>    do_something()
>
> if io.byte2 == alarm_value:
>   do_something_else()
>
> where:
>
>  io.byte2 & 8   "is"  io.byte2.bit3
>
> Is this possible?
>
> - Hendrik

I use the gmpy module for all my bit related work and
have been very satisfied with the results.

Examples of functions pertinent to bit operations:

digits(...)
digits(x[,base]): returns Python string representing x in the
given base (2 to 36, default 10 if omitted or 0); leading '-'
present if x<0, but no leading '+' if x>=0. x must be an mpz,
or else gets coerced into one.

getbit(...)
getbit(x,n): returns 0 or 1, the bit-value of bit n of x;
n must be an ordinary Python int, >=0; x is an mpz, or else
gets coerced to one.

hamdist(...)
hamdist(x,y): returns the Hamming distance (number of bit-
positions
where the bits differ) between x and y.  x and y must be mpz,
or else
get coerced to mpz.

lowbits(...)
lowbits(x,n): returns the n lowest bits of x; n must be an
ordinary Python int, >0; x must be an mpz, or else gets
coerced to one.

numdigits(...)
numdigits(x[,base]): returns length of string representing x
in
the given base (2 to 36, default 10 if omitted or 0); the
value
returned may sometimes be 1 more than necessary; no provision
for any 'sign' characte, nor leading '0' or '0x' decoration,
is made in the returned length.  x must be an mpz, or else
gets
coerced into one.

popcount(...)
popcount(x): returns the number of 1-bits set in x; note that
this is 'infinite' if x<0, and in that case, -1 is returned.
x must be an mpz, or else gets coerced to one.

scan0(...)
scan0(x, n=0): returns the bit-index of the first 0-bit of x
(that
is at least n); n must be an ordinary Python int, >=0.  If no
more
0-bits are in x at or above bit-index n (which can only happen
for
x<0, notionally extended with infinite 1-bits), None is
returned.
x must be an mpz, or else gets coerced to one.

scan1(...)
scan1(x, n=0): returns the bit-index of the first 1-bit of x
(that
is at least n); n must be an ordinary Python int, >=0.  If no
more
1-bits are in x at or above bit-index n (which can only happen
for
x>=0, notionally extended with infinite 0-bits), None is
returned.
x must be an mpz, or else gets coerced to one.

setbit(...)
setbit(x,n,v=1): returns a copy of the value of x, with bit n
set
to value v; n must be an ordinary Python int, >=0; v, 0 or !
=0;
x must be an mpz, or else gets coerced to one.

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


Re: A question about funcation parameter and self defined object

2008-10-09 Thread Wei Guo
Hi Terry,

Thanks for your reply. But the reason I want to have that is for not
changing the functions which already based on translation functions.

If there is any idea how to bring parameter in static method, that will be
great.

Wei
On Wed, Oct 8, 2008 at 8:24 PM, Terry Reedy <[EMAIL PROTECTED]> wrote:

> Wei Guo wrote:
>
>> Hi Chris,
>>  Thanks a lot for reply, you are right. I want to use this method as a
>> static method as:
>>  translation = staticmethod( translation )
>>
>
> static methods are mostly useless in Python.  Just put the definition of
> translation outside of any class.
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to do regular BASH work in Python?

2008-10-09 Thread Chris Rebert
You might also be interested in the 'shutil' module:
http://docs.python.org/library/shutil.html#module-shutil

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

On Thu, Oct 9, 2008 at 7:13 AM, Frantisek Malina <[EMAIL PROTECTED]> wrote:
> Hey,
> I found it. Python rocks:
> http://www.python.org/doc/2.5.2/lib/os-file-dir.html
>
> If you have any further links that provide some lively code examples
> and recipes, please pass them on.
>
> Thank you
>
> Frank Malina
> http://vizualbod.com
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: default value in __init__

2008-10-09 Thread Bruno Desthuilliers

kenneth a écrit :

On Oct 9, 10:14 am, Christian Heimes <[EMAIL PROTECTED]> wrote:

kenneth wrote:

the 'd' variable already contains the 'self.d' value of the first
instance and not the default argument {}.
Am I doing some stupid error, or this is a problem ?

No, it always contains the default argument because default values are
created just ONE 
TIME.http://effbot.org/pyfaq/why-are-default-values-shared-between-objects...



Wow, it's a very "dangerous" behavior ...


Well, that's usually something you only have to learn once - then you 
know !-)

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


Re: Safe eval of insecure strings containing Python data structures?

2008-10-09 Thread Jason Scheirer
On Oct 9, 9:01 am, Paul Rubin  wrote:
> Lie Ryan <[EMAIL PROTECTED]> writes:
> > in python 2.6, ast.literal_eval may be used to replace eval() for
> > literals.
>
> What happens on literal_eval('[1]*9') ?

The documentation clearly states that it will fail to evaluate and
raise a ValueError because there is an operation in the statement. 5*5
is NOT the literal 25, it is the equivalent to operator.mul(5, 5), and
the same is true to []*x
--
http://mail.python.org/mailman/listinfo/python-list


Re: inspect bug

2008-10-09 Thread Aaron "Castironpi" Brady
On Oct 9, 9:47 am, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
> En Thu, 09 Oct 2008 00:24:20 -0300, Aaron "Castironpi" Brady  
> <[EMAIL PROTECTED]> escribió:
>
> > Found this bug.  It's in 2.6, too bad.
>
> Posting here is not going to help much, it just will be lost. Would be  
> better to file a bug report athttp://bugs.python.org/
>
> --
> Gabriel Genellina

It is at bugs.python.  http://bugs.python.org/msg74595 .
--
http://mail.python.org/mailman/listinfo/python-list


Re: default value in __init__

2008-10-09 Thread David C. Ullrich
In article 
<[EMAIL PROTECTED]>,
 kenneth <[EMAIL PROTECTED]> wrote:

> On Oct 9, 10:14 am, Christian Heimes <[EMAIL PROTECTED]> wrote:
> > kenneth wrote:
> > > the 'd' variable already contains the 'self.d' value of the first
> > > instance and not the default argument {}.
> >
> > > Am I doing some stupid error, or this is a problem ?
> >
> > No, it always contains the default argument because default values are
> > created just ONE 
> > TIME.http://effbot.org/pyfaq/why-are-default-values-shared-between-objects..
> > .
> 
> 
> Wow, it's a very "dangerous" behavior ...
> 
> Just to know, is this written somewhere in the python documentation or
> one has to discover it when his programs fails to work ;-) ?

At least once a week someone discovers this "problem", makes a
post about it here, and then someone points to the spot in the
documentation where it's explained.

Seems to me that people often site the "important warning" in
the tutorial. Of course there's no reason anyone would bother
going through the tutorial - just for fun I looked in the
official Python Reference Manual to see whether they're explicit
about this or require the reader to figure it out from something
else they say.

There's a section titled "7.6 Function definitions". About halfway
through that section there's a _bold face_ statement 
"Default parameter values are evaluated when the function definition is 
executed.", followed by an explanation of how that can lead to
the sort of problem above.

So I guess it _is_ awfully dangerous. They should really explain
this aspect of the language's behavior to people who don't read
the formal definition and also don't work through the tutorial.


> Paolo

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


  1   2   >