appending file

2007-06-29 Thread Kuo
Hi,
I'm trying to read a file (fileA) and append to another file(fileB). 
However, I always get "^M" at the end. Does anyone know why ? Here is my 
code ?

os.system("../syn/pin_assign.pl customer_netlist.txt")
shutil.copy("../fileB", "fileB")
ucf = open("fileB", "a")
pin = open("fileA", "r")
ucf.write(pin.read())
ucf.close;
pin.close;
sys.exit(0);

Here is what I get.

# FPGA CLOCK^M
NET "SYSCLK_A"  loc = N16  | TNM_NET = SYSCLK_A;^M
NET "SYSCLK_AN" loc = M16  | TNM_NET = SYSCLK_A;^M


Note that if I don't do "ucf.write(pin.read())", everything is ok.

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


Re: subprocess cwd keyword.

2006-10-26 Thread attn . steven . kuo
Ivan Vinogradov wrote:
> Dear All,
>
> I would greatly appreciate a nudge in the right direction concerning
> the use of cwd argument in the call function from subprocess module.
>
> The setup is as follows:
>
> driver.py <- python script
> core/ <- directory
>   main<- fortran executable in the core directory
>
>
> driver script generates some input files in the core directory. Main
> should do its thing and dump the output files back into core.
> The problem is, I can't figure out how to do this properly.
>
> call("core/main") works but uses .. of core for input/output.
>
> call("core/main",cwd="core") and call("main",cwd="core") both result in
>File "driver.py", line 47, in 
>  main()
>File "driver.py", line 40, in main
>  print "OUT", call("core/main", cwd="core")
>File "/Library/Frameworks/Python.framework/Versions/2.5/lib/
> python2.5/subprocess.py", line 443, in call
>  return Popen(*popenargs, **kwargs).wait()
>File "/Library/Frameworks/Python.framework/Versions/2.5/lib/
> python2.5/subprocess.py", line 593, in __init__
>  errread, errwrite)
>File "/Library/Frameworks/Python.framework/Versions/2.5/lib/
> python2.5/subprocess.py", line 1051, in _execute_child
>  raise child_exception
> OSError: [Errno 2] No such file or directory
>
> perhaps if subprocess would indicate the abs path of the object in
> question I could figure it out, but as is I'm lost.


Perhaps you're looking for os.path.abspath?

import subprocess
import os

subdir = os.path.join(*[ os.path.dirname(os.path.abspath(__file__)),
"core" ])
print subdir

try:
retcode = subprocess.call(["./main"], cwd=subdir)
except:
raise
 
print retcode

-- 
Hope this helps,
Steven

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


Re: re question

2006-11-01 Thread attn . steven . kuo
Schüle Daniel wrote:

(snipped)

> I am trying to construct a case where a greedy and
> non greedy operation produce different result.
> I dont see the difference between 'a??b' and 'a?b'
> As far I understand is that ? will first try to match a
> (it's greedy) and only if it fails then it step back
> and lets a unmatched. The other doesn't match a at first,
> only if the pattern fails to match it steps back and match a.
>
> But don't they do eventually the same thing?
> Can someone provide an example where 2 patterns yield
> different results.
>

Perhaps this sheds some light
on the matter:


>>> import re
>>> string = "aaaba"

>>> one =  re.findall(r'a?b?', string)
>>> two =  re.findall(r'a??b?', string)

>>> print one, two

Yields:

['a', 'a', 'ab', 'a', ''] ['', '', '', 'b', '', '']


-- 
Hope this helps,
Steven

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


Re: Lists of lists and tuples, and finding things within them

2006-11-09 Thread attn . steven . kuo
Daniel Nogradi wrote:
> > I have a program that keeps some of its data in a list of tuples.
> > Sometimes, I want to be able to find that data out of the list.  Here is
> > the list in question:
> >
> > [('password01', 'unk'), ('host', 'dragonstone.org'), ('port', '1234'),
> > ('character01', 'Thessalus')]
> >
> > For a regular list, I could do something like x.index('host') and find
> > the index of it, but I don't know how to do this for a tuple where the
> > data item isn't known in advance.  For example, I want to get the "host"
> > entry from the list above; but I can only retrieve it if I know what it
> > contains (e.g., x.index(('host', 'dragonstone.org'))).
> >
> > Is there a better way to do this than a construct similar the following?
> >
> > for key, value in x:
> > if key == 'host':
> > print value
> >
>
> If I were you I would use a dictionary for such a thing:
>

(snipped)


The sequence of tuples may have repeated "keys"; if
that's the case, then you may use a filter/iterator instead.
Using a dictionary would otherwise cause you to lose
"values":

import itertools

mytuple = (('foo', 'bar'), ('foo', 'foobar'), ('baz', 'qux'))

it = itertools.ifilter(lambda t : t[0] == 'foo', mytuple)
 
for t in it:
print t


-- 
Hope this helps,
Steven

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


Re: example: 40286 -> 68204

2007-06-03 Thread attn . steven . kuo
On Jun 3, 5:23 pm, Shihpin <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> Is there a fuction that reverse the digits of a number?
>
> Many thanks,
>
> Shihpin Lin


One can use int, str and a slice:

print int(str(40286)[::-1])

--
Hope this helps,
Steven

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


Re: Help With Better Design

2007-06-19 Thread attn . steven . kuo
On Jun 19, 6:34 pm, [EMAIL PROTECTED] wrote:
> Greetings,
>
> I have been working on a little project today to help me better
> understand classes in Python (I really like Python). I am a self
> taught programmer and consider myself to fall in the "beginner"
> category for sure. It was initially sparked by reading about "state
> machines". This was my attempt at it however I feel it is not quite
> where it should be:
>
> ON  = "ON"
> OFF = "OFF"
>
> class LightBulb:
> def __init__(self, initial_state):
> self.state = initial_state
>
> def TurnOn(self):
> if self.state == OFF:
> self.state = ON
> else:
> print "The Bulb Is Already ON!"
>
> def TurnOff(self):
> if self.state == ON:
> self.state = OFF
> else:
> print "The Bulb Is Aleady OFF!"
>
> if __name__== "__main__":
> light = LightBulb(OFF)
> simulation_running = True
> while simulation_running:
> print "The light is", light.state
> print ""
> print "Please choose an action:"
> print ""
> print "[1] Turn Light On"
> print "[2] Turn Light Off"
> print "[3] Exit Simulation"
> print ""
> u_choice = raw_input("Please Enter Your Choice: ")
> if u_choice == '1':
> light.TurnOn()
> if u_choice == '2':
> light.TurnOff()
> elif u_choice == '3':
> break
> else:
> continue
>
> The test portion of the code is actually longer than the class
> itself :-) I would like to be able to get a good hold of the concept
> with this example before I try to model a more complex problem. Would
> someone be willing to give me some feedback on this class and whether
> I am on the right track or how I might better go about it?



If all you're implementing is on-or-off logic, then
I'd use the boolean values in Python (True and False),
rather than defining my own 'ON' and 'OFF'.  Here
I use __str__ for printing and a _toggle function
to cut down on the possibility of coding errors:


class LightBulb:
def __init__(self, bool):
self.on = bool
def __str__(self):
return self.on and "On" or "Off"
def _toggle(self):
self.on = not self.on
def TurnOn(self):
if self.on: print "\tThe Bulb is ready %s" % self
else: self._toggle()
def TurnOff(self):
if not self.on: print "\tThe Bulb is ready %s" % self
else: self._toggle()

if __name__ == "__main__":
light = LightBulb(False)
while True:
print """
The light is %s

Please choose an action:

[1] Turn Light On
[2] Turn Light Off
[3] Exit
""" % light
u_choice = raw_input("Please Enter Your Choice: ")
if u_choice == '1':
light.TurnOn()
elif u_choice == '2':
light.TurnOff()
elif u_choice == '3':
break
else:
continue



If you're really coding a state machine
wherein many states are possible and many
choices are availble to the user, then I'd refactor.
Rather than having a long sequence of if ... elif ...
elif ... else, perhaps I'd use something like:


import sys

class LightBulb:
def __init__(self, bool):
self.on = bool
def process_instruction(self, wanted):
""" Pass self to unbound method """
try:
LightBulb.instructions[wanted][1](self)
except IndexError:
pass
def __str__(self):
return self.on and "On" or "Off"
def _toggle(self):
self.on = not self.on
def TurnOn(self):
if self.on: print "\n\t** The Bulb is already %s **" % self
else: self._toggle()
def TurnOff(self):
if not self.on: print "\n\t** The Bulb is already %s **" %
self
else: self._toggle()

instructions = ( \
("Exit", sys.exit),
("Turn Light On", TurnOn),
("Turn Light Off", TurnOff),)

if __name__ == "__main__":
light=LightBulb(False)
usage=["\t%d: %s" % (i,t[0]) for i,t in
enumerate(LightBulb.instructions)]
usage.insert(0, "\n\tThe light is %s\n\tPlease choose an action:")
prompt = "\n".join(usage)

while True:
print prompt % light
u_choice = raw_input("\nPlease Enter Your Choice: ")
try:
light.process_instruction(int(u_choice))
except ValueError:
pass



Note that I can add intructions as needed to
LightBulb.instructions and not have to change the
user interface.

--
Hope this helps,
Steven

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


Re: Adding method to a class on the fly

2007-06-22 Thread attn . steven . kuo
On Jun 22, 2:44 pm, John Henry <[EMAIL PROTECTED]> wrote:
> On Jun 22, 2:28 pm, askel <[EMAIL PROTECTED]> wrote:
>

(snipped)

>
> The above doesn't exactly do I what need.  I was looking for a way to
> add method to a class at run time.


I'm not sure what you mean by this.  Bind an attribute -- a method --
to class Dummy if and only if an instance of this class is created?



> What does work, is to define an entire sub-class at run time.  Like:
>
> class DummyParent:
> def __init__(self):
> return
>
> def method_static(self, text):
> print text
> return
>
> text = "class Dummy(DummyParent):"
> text += "\n\t" + "def __init(self):"
> text += "\n\t" + "\tDummyParent.__init__(self)"
> text += "\n\t" + "def method_dynamic(self):"
> text += "\n\t" + "\tself.method_static(\"it's me\")"
>
> exec text
>
> dum=Dummy().method_dynamic()
>
> Thanks again.


I tend to avoid exec if possible.  Also, you
seem to be a bit inexact with regard to the
term "static".


class Dummy(object):
def __init__(self):
new_method_name = 'method_dynamic'
try:
getattr(Dummy, new_method_name)
except AttributeError:
print "Creating an instance method..."
def newf(self):
"""Something Descriptive Here"""
return self.method_static("it's me")
newf.__name__ = new_method_name
setattr(Dummy, new_method_name, newf)
def method_static(self, text):
"""I hate this name.  Do not confuse this with a staticmethod;
what you probably meant was that this is an attribute (a
method)
bound within the class body as opposed to elsewhere"""
print text
return # is this necessary?

d1 = Dummy()
d1.method_dynamic()
d2 = Dummy()
d2.method_dynamic()
print d1.method_dynamic.im_func.__name__
print d1.method_dynamic.im_func.__dict__
print d1.method_dynamic.im_func.__doc__
print d1.method_dynamic.im_func.__module__
print d1.method_dynamic.im_self

--
Hope this helps,
Steven

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


Re: newb: Scope Question

2007-06-22 Thread attn . steven . kuo
On Jun 22, 3:53 pm, johnny <[EMAIL PROTECTED]> wrote:
> Scope of ids:
> When I print "ids", it's always empty string '', as I have intialized
> before.  That's not what I want. I want the ids to have
> str(r['id']).join(',')
>
> if res:
> ids = ''
> for r in res['key']:
> ids = str(r['id']).join(',')
>
> print("ids: %s" %(ids))




"""
1.  You haven't posted enough code to allow someone else to reproduce
the problem.

2.  Are you sure that res['key'] isn't an empty sequence?

3.  The 'join' operation looks funny.  The syntax is
.join().  Since ',' is a sequence of length
one, you'll get, if anything, a comma (',') as the value of ids.
"""

res = { 'key': [dict(id=value) for value in range(10)] }

if res:
ids = ''
for r in res['key']:
ids = str(r['id']).join(',')
print ("ids : %s" % (ids))


# Wild guess -- perhaps you really wanted:


if res:
ids = ','.join(str(r['id']) for r in res['key'])
print "ids : %s" % ids


--
Hope this helps,
Steven

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


Re: regular expressions eliminating filenames of type foo.thumbnail.jpg

2007-06-25 Thread attn . steven . kuo
On Jun 25, 2:41 pm, oscartheduck <[EMAIL PROTECTED]> wrote:
> I eventually went with:
>
> #!/usr/bin/env python
> from PIL import Image
> import glob, os, re
>
> size = 128, 128
>
> def thumbnailer(dir, filenameRx):
>  for picture in [ p for p in os.listdir(dir) if
> os.path.isfile(os.path.join(
>  dir,p)) and filenameRx.match(p) if 'thumbnail' not in p]:
>  file, ext = os.path.splitext(picture)


(snipped)

Or, one can forego regular expressions:

prefix = '.thumbnail'
for p in os.listdir(dir):
root, ext = os.path.splitext(p)
if not os.path.isfile(os.path.join(dir, p)) \
or ext.lower() not in ('.jpg', '.jpeg') \
or root[-10:].lower() == prefix:
continue
if os.path.isfile(os.path.join(dir, "%s%s%s"  % (root, prefix,
ext))):
print "A thumbnail of %s already exists" % p
else:
print "Making a thumbnail of %s" % os.path.join(dir, "%s%s%s"
%
(root, prefix, ext))


--
Hope this helps,
Steven

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


Re: Help needed with translating perl to python

2007-06-26 Thread attn . steven . kuo
On Jun 26, 8:04 am, vj <[EMAIL PROTECTED]> wrote:
> I have a perl script which connect to network stream using sockets.
> The scripts first logins in to the server and then parses the data
> comming from the socket.
>
> Statement 1:
>   my $today = sprintf("%4s%02s%02s", [localtime()]->[5]+1900,
> [localtime()]->[4]+1, [localtime()]->[3]) ;


Perl has "Do What I Mean" features that allow you to
treat strings and number interchangeably.  Python's
time.localtime returns a tuple of integers so you'll
have to use the proper format conversion characters:

import time
today = "%04d%02d%02d" % time.localtime()[0:3]

# No need to add offsets of 1900 and 1 because Python
# does this for you



>
> Statement 2:
>   my $password = md5_hex("$today$username") ;


You should have added that md5_hex is comes from
Digest::MD5, not a core Perl module.  Regardless:


import md5
password = md5.new("%s%s" % (today, username)).hexdigest()

# seems to be what you wanted



> Statement group 3:
>
> $msglen = bcdlen(length($msg)) ;
>
> sub bcdlen {
>   my $strlen = sprintf("%04s", shift) ;
>   my $firstval = substr($strlen, 2, 1)*16 + substr($strlen, 3, 1) ;
>   my $lastval  = substr($strlen, 0, 1)*16 + substr($strlen, 1, 1) ;
>   return chr($firstval) . chr($lastval) ;
>
> }




You can have a variadic function in Python but the parameters
are passed via a tuple.  Because a tuple is immutable, one cannot
"shift" elements out of a tuple.  Here I've used the first parameter
via selection by index.  Perl's substr is replaced by slice notation;
chr is, well, chr.  Concatenation (Perl's '.' operator) is replaced
by string formatting:

>>> def bcdlen(*args):
... strlen = "%04s" % str(args[0])
... firstval = int(strlen[2:3]) * 16 + int(strlen[3:4])
... lastval  = int(strlen[0:1]) * 16 + int(strlen[1:2])
... return "%s%s" % (chr(firstval), chr(lastval))
...
>>> bcdlen(4546)
'FE'


--
Hope this helps,
Steven

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


Re: Help needed with translating perl to python

2007-06-26 Thread attn . steven . kuo
On Jun 26, 8:59 am, [EMAIL PROTECTED] wrote:

(snipped)

>
> >>> def bcdlen(*args):
>
> ... strlen = "%04s" % str(args[0])
> ... firstval = int(strlen[2:3]) * 16 + int(strlen[3:4])
> ... lastval  = int(strlen[0:1]) * 16 + int(strlen[1:2])
> ... return "%s%s" % (chr(firstval), chr(lastval))
> ...>>> bcdlen(4546)
>
> 'FE'


Let me add that instead of an an-close-as-possible translation
from the  original Perl code, one can rewrite this as:

>>> def bcdlen(length):
... strlen = "%04s" % length
... return chr(int(strlen[2:4], 16)) + chr(int(strlen[0:2], 16))


which is more "Pythonic" to me.

--
Hope this helps,
Steven

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


Re: log caller

2007-06-27 Thread attn . steven . kuo
On Jun 27, 2:42 pm, Matthew Peter <[EMAIL PROTECTED]> wrote:
> Is it possible to print the function calls to a module? Like:
>
> test.py
> import mymod
> print mymod.x()
>
> mymod.py
> # each time a function is called we print out the called function and module
> print 'Func call: %s from %s' % (???, ???)
>
> def x():
>  return 'hello'
>
> Where would I pick up the ??? variables? A brief example would be nice too :) 
> Thanks
> in advance!



You can use a decorator to wrap the function.  You can use
sys._getframe or
inspect.stack to get information about the caller.  The examples from
the decorator module are very useful:

http://www.phyast.pitt.edu/~micheles/python/documentation.html

If for some reason you can't edit mymod.py to add the decorators, you
can still wrap the function:

import mymod
import inspect

try:
from functools import update_wrapper
except ImportError:
def decorator_trace(f):
def newf():
caller = inspect.stack()[1]
print 'Caller is line %d of %s' % (caller[2], caller[1])
print 'Calling: %s from %s' % (f.__name__, f.__module__)
return f()
newf.__name__ = f.__name__
newf.__dict__.update(f.__dict__)
newf.__doc__ = f.__doc__
newf.__module__ = f.__module__
return newf
else:
def decorator_trace(f):
def newf():
caller = inspect.stack()[1]
print 'Caller is line %d of %s' % (caller[2], caller[1])
print 'Calling: %s from %s' % (f.__name__, f.__module__)
return f()
return update_wrapper(newf, f)


mymod.x = decorator_trace(mymod.x)
greetings = mymod.x()
print greetings


but this approach has the shortcoming mentioned in the article.

--
Hope this helps,
Steven

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


Re: Programming Idiomatic Code

2007-07-02 Thread attn . steven . kuo
On Jul 2, 5:22 pm, "Nathan Harmston" <[EMAIL PROTECTED]>
wrote:
> Hi,
>
> I m sorry but I m bored at work (and no ones looking so I can write
> some Python) and following a job advertisement post,I decided to write
> the code to do its for the one entitled Ninjas or something like that.
> I was wondering what could be done to my following code to make it
> more idiomatic...or whether it was idiomatic and to be honest what
> idiomatic really means. All comments greatly appreciated and welcomed.
>
> Thanks in advance
>
> Nathan
>
> import urllib2,sys
> from elementtree.ElementTree import parse
>
> base_url = "http://api.etsy.com/feeds/xml_user_details.php?id=";
>
> def read_id_file(filename):
> """ reads a file and generates a list of ids from it"""
> ids = [ ]
> try:
> id_file = open(filename, "r")
> for l in id_file:
> ids.append( l.strip("\n") )
> id_file.close()
> except e:
> print e
> os._exit(99)
> return ids
>




The expression in the except clause should
evaluate to an object that "matches" the exception.

For example,

import sys

try:
idfile = open(filename, "r")
except IOError, e
print >> sys.stderr, str(e)
# or look into the warnings module
# etc.


--
Hope this helps,
Steven

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


python-list@python.org

2007-04-18 Thread attn . steven . kuo
On Apr 18, 12:23 pm, Anton Vredegoor <[EMAIL PROTECTED]>
wrote:

(snipped)

> But still, the 'while True:' loop and the 'try-except' clause and the
> explicit StopIteration are not necessary ...
>
> from collections import deque
>
> def xsplitter(seq, pred):
>  Q = deque(),deque()
>  it = iter(seq)
>  def gen(p):
>  while Q[p]:  yield Q[p].popleft()
>  for x in it:
>  if pred(x) == p: yield x
>  else:
>  Q[~p].append(x)
>  for x in gen(p):  yield x
>  return gen(1),gen(0)
>
> def test():
>  L = 1, 'a', 3, 'a', 4, 5, 6, 'a'
>  it1, it2 = xsplitter(L, lambda x: x == 'a')
>  print it1.next()
>  print it2.next()
>  print it1.next()
>
> if __name__=='__main__':
>  test()
>
> A.



Try it with

def test():
L = 'a', 1, 2, 'a'
it1, it2 = xsplitter(L, lambda x: x == 'a')
print it1.next()
print it2.next()
print it1.next()
print it2.next()


The last print statement raises StopIteration...
We, however, expected each iterator to contain
two elements (one yielding 'a' then 'a', and
the other yielding 1 then 2).

--
Regards,
Steven

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


python-list@python.org

2007-04-19 Thread attn . steven . kuo
On Apr 19, 9:13 am, Anton Vredegoor <[EMAIL PROTECTED]> wrote:


(snipped)

>
> > How about this one?
>
> No that can result in an infinite loop after yet another
>
> print it1.next()
>
> This one however ...
>
> from collections import deque
>
> class sentinel(object):
>  pass
>
> class myiter(object):
>
>  def __init__(self,seq):
>  self.seq = seq
>  self.index = -1
>
>  def __iter__(self):
>  return self
>
>  def next(self):
>  self.index +=1
>  if self.index < len(self.seq):
>  return self.seq[self.index]
>  else:
>  return sentinel
>
> def xsplitter(seq, pred):
>  Q = deque(),deque()
>  it = myiter(seq)
>  def gen(p):
>  for x in it:
>  while Q[p]:  yield Q[p].popleft()
>  if x is sentinel:  break
>  if pred(x) == p:  yield x
>  else:
>  Q[~p].append(x)
>  for x in gen(p):  yield x
>  return gen(1),gen(0)
>
> def test():
>  L = 'a', 1, 2, 'a'
>  it1, it2 = xsplitter(L, lambda x: x == 'a')
>  print it1.next()
>  print it2.next()
>  print it1.next()
>  print it2.next()
>
> if __name__=='__main__':
>  test()
>
> A.


Um, no.  That one stops prematurely if
your input sequence is:

L = 1, 2, 3, 'a', 'a'


You get points for persistence, however.  :)

--
Regards,
Steven


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


python-list@python.org

2007-04-19 Thread attn . steven . kuo
On Apr 19, 3:37 pm, Anton Vredegoor <[EMAIL PROTECTED]> wrote:
> Anton Vredegoor wrote:
> > Maybe this one is better?
>
> No, this one keeps generating output.
>
> But this one stops at least:
>
> from collections import deque
> from itertools import chain, repeat
>
> def xsplitter(seq, pred):
>  Q = deque(),deque()
>  sentinel = object()
>  it = chain(seq,repeat(sentinel))
>  def gen(p):
>  for x in it:
>  if x is sentinel:
>  while Q[p]:  yield Q[p].popleft()
>  break
>  elif pred(x) == p:
>  while Q[p]:  yield Q[p].popleft()
>  yield x
>  else:
>  Q[~p].append(x)
>  for x in gen(p):  yield x
>  return gen(1),gen(0)
>
> def test():
>  L = 1, 2, 3, 'a', 'a'
> #L = 'a', 1, 2, 'a'
> #L = 1, 'a', 3, 'a', 4, 5, 6, 'a'
>  it1, it2 = xsplitter(L, lambda x: x == 'a')
>  print it1.next()
>  print it2.next()
>  print it1.next()
>  print it2.next()
>
> if __name__=='__main__':
>  test()
>
> Are there any other cases this doesn't cover?
>
> A.



This one gets the order wrong. With

def test():
L = 1, 2, 3, 'a', 4, 'a', 5, 'a', 6, 'a'
it1, it2 = xsplitter(L, lambda x: x == 'a')
print it1.next()
print it2.next()
print it1.next()
print it2.next()
print it1.next()
print it2.next()
print it1.next()
print it2.next()

5 will appear before 4.

--
Regards,
Steven

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


Re: Suggestion: str.itersplit()

2007-04-21 Thread attn . steven . kuo
On Apr 21, 5:58 am, Dustan <[EMAIL PROTECTED]> wrote:
> >From my searches here, there is no equivalent to java's
>
> StringTokenizer in python, which seems like a real shame to me.
>
> However, str.split() works just as well, except for the fact that it
> creates it all at one go. I suggest an itersplit be introduced for
> lazy evaluation, if you don't want to take up recourses, and it could
> be used just like java's StringTokenizer.
>
> Comments?



If your delimiter is a non-empty string, you
can use an iterator like:

def it(S, sub):
start = 0
sublen = len(sub)
while True:
idx = S.find(sub,start)
if idx == -1:
yield S[start:]
raise StopIteration
else:
yield S[start:idx]
start = idx + sublen

target_string = 'abcabcabc'
for subs in it(target_string,'b'):
print subs


For something more complex,
you may be able to use
re.finditer.

--
Hope this helps,
Steven

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


Re: function minimization

2007-04-22 Thread attn . steven . kuo
On Apr 22, 6:55 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> Is anyone aware of python library that does function minimization a la
> Minuit (http://wwwasdoc.web.cern.ch/wwwasdoc/minuit/) used by CERN?
>
> thanks


If you have a C complier and the lapack, blas, and levmar
libraries, you could try pylevmar:

http://projects.liquidx.net/python/browser/pylevmar/trunk/setup.py

--
Hope this helps,
Steven

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


Re: python function in pipe

2007-04-28 Thread attn . steven . kuo
On Apr 28, 6:37 am, Bart <[EMAIL PROTECTED]> wrote:
> Hi everyone!
>
> Im using module that gives errors to stderr/stdout  (generated by SWIG)
> Problem is that I need to parse this errors/information from module.
>
> os.popen3 looks nice but this executes  command  not  function.
>
> Is there any solution?
>


Perhaps you're looking for the unittest module?

You can use assertRaises if an exception is raised
by the function.

You can also redirect sys.stderr and sys.stdout as needed
and test the captured strings with assertEquals.



Else you can wrap the module under test in another
module:

# mytest.py

import module_under_test

if __name__ == "__main__":
module_under_test.foo()

Then, using os.popen3 (or subprocess),
run "python mytest.py" as your command.

--
Hope this helps,
Steven

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


Re: sqlite for mac?

2007-05-01 Thread attn . steven . kuo
On May 1, 10:12 am, 7stud <[EMAIL PROTECTED]> wrote:
> On May 1, 4:08 am, "Daniel Nogradi" <[EMAIL PROTECTED]> wrote:
>
> > > Does sqlite come in a mac version?
>
> > The interface (pysqlite) is part of the python 2.5 standard library
> > but you need to install sqlite itself separately (as far as I
> > remember) fromwww.sqlite.org
>
> > Daniel
>
> I'm using python 2.4.4 because the download said there were more mac
> modules available for 2.4.4. than 2.5, and I can't seem to locate a
> place to download sqlite for mac.


Did you install Xcode on your Mac?  If so then you should have access
to a
C compiler allowing you to compile sqlite from source:

http://sqlite.org/download.html

I checked fink (finkproject.org) but that web site shows
no binary distributions for sqlite3:

http://pdb.finkproject.org/pdb/package.php/sqlite3

--
Hope this helps,
Steven


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


Re: How to check if a string is empty in python?

2007-05-02 Thread attn . steven . kuo
On May 2, 1:35 pm, [EMAIL PROTECTED] wrote:
> How to check if a string is empty in python?
> if(s == "") ??



Empty strings and containers are false; so
one can write

if (not s):
print "something..."


--
Hope this helps,
Steven

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


Re: Inheritance problem

2007-05-09 Thread attn . steven . kuo
On May 9, 11:33 am, Bjoern Schliessmann  wrote:
> [EMAIL PROTECTED] wrote:
> > class longList(shortList):
>
> > def __init__(self):
>
> > shortList.setList()
>
> > self.setList()
>
> Addition: Always call the base class __init__ in your constructor if
> there exists one, i. e.
>
> class longList(shortList)
> def __init__(self):
> shortlist.__init__()
> # [...]
>


Delegating to an ancestor class by
calling an unbound method is fine as
long as one remembers to pass an instance
as the first argument.  So, this means:

shortList.setList(self)

and

  shortList.__init__(self)

for the examples above.

--
Regards,
Steven


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


Re: matplotlib: howto set title of whole window?

2007-05-11 Thread attn . steven . kuo
On May 11, 3:44 pm, dmitrey <[EMAIL PROTECTED]> wrote:
> hi all,
> does anyone know howto set title of whole window? (I mean not just
> area above plot but string in the same line where buttons 'close',
> 'iconify', 'fullscreen' are situated)
>


Use coordinates to set a title for the current figure.
E.g.,

from pylab import *
from matplotlib.font_manager import FontProperties

figtitle = 'This is my title above all subplots'

t = gcf().text(0.5,
0.95, figtitle,
horizontalalignment='center',
fontproperties=FontProperties(size=16))

subplot(121)
subplot(122)
show()

--
Hope this helps,
Steven

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


Re: converting text and spans to an ElementTree

2007-05-22 Thread attn . steven . kuo
On May 21, 11:02 pm, Steven Bethard <[EMAIL PROTECTED]> wrote:
> I have some text and a list of Element objects and their offsets, e.g.::
>
>  >>> text = 'aaa aaa aaabbb bbbaaa'
>  >>> spans = [
>  ... (etree.Element('a'), 0, 21),
>  ... (etree.Element('b'), 11, 18),
>  ... (etree.Element('c'), 18, 18),
>  ... ]
>
> I'd like to produce the corresponding ElementTree. So I want to write a
> get_tree() function that works like::
>
>  >>> tree = get_tree(text, spans)
>  >>> etree.tostring(tree)
>  'aaa aaa aaabbb bbbaaa'
>
> Perhaps I just need some more sleep, but I can't see an obvious way to
> do this. Any suggestions?
>


It seems you're looking to construct an Interval Tree:

http://en.wikipedia.org/wiki/Interval_tree

--
Hope this helps,
Steven

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


Re: converting text and spans to an ElementTree

2007-05-22 Thread attn . steven . kuo
On May 21, 11:02 pm, Steven Bethard <[EMAIL PROTECTED]> wrote:
> I have some text and a list of Element objects and their offsets, e.g.::
>
>  >>> text = 'aaa aaa aaabbb bbbaaa'
>  >>> spans = [
>  ... (etree.Element('a'), 0, 21),
>  ... (etree.Element('b'), 11, 18),
>  ... (etree.Element('c'), 18, 18),
>  ... ]
>
> I'd like to produce the corresponding ElementTree. So I want to write a
> get_tree() function that works like::
>
>  >>> tree = get_tree(text, spans)
>  >>> etree.tostring(tree)
>  'aaa aaa aaabbb bbbaaa'
>
> Perhaps I just need some more sleep, but I can't see an obvious way to
> do this. Any suggestions?
>


It seems you're looking to construct an Interval Tree:

http://en.wikipedia.org/wiki/Interval_tree

--
Hope this helps,
Steven

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


Re: Usage of the __and__ method

2007-05-30 Thread attn . steven . kuo
On May 30, 10:11 pm, theju <[EMAIL PROTECTED]> wrote:
> Hello all,
> I've two objects (both instances of a class called Person) and I want
> to use the __and__ method and print the combined attributes of the two
> instances.
>
> To be precise, here is my code
>
> class Person:
> def __init__(self,name):
> self.name = name
> def print_name(self):
> print self.name
> def __and__(self,other):
> self.name = '%s AND %s' %(self.name,other.name)
> return self.name
>
> p = Person("John")
> q = Person("George")
>
> r = p and q
> print r.print_name()


Try:

class Person(object):
def __init__(self, name):
self.name = name
def __and__(self, other):
return '%s AND %s' % (self.name, other.name)

p = Person("John")
q = Person("George")

r = p & q
print r


(1) A "getter" method (like your print_name
method) is usually not needed, just access the
attribute of the instance.  Like,

print p.name

(2) I doubt that you want the __and__ special
method to alter the name attribute of an
instance.

(3) You want to use the '&' operator
to dispatch to the __and__ method; __and__
is typically used for Numeric objects.

(4) You misunderstood how the 'and' operator
is used.  The expression 'p and q' causes p to
be evaluated; if p is false, its value is returned;
otherwise q is evaluated and its value is returned.

--
Hope this helps,
Steven

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


Re: Matplotlib axes label

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

(snipped)

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





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

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

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

minorLocator = MultipleLocator(1.1)

# etc.

--
Hope this helps,
Steven

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


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

2007-03-03 Thread attn . steven . kuo
On Mar 2, 2:44 pm, "Shawn Milo" <[EMAIL PROTECTED]> wrote:

(snipped)

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


My attempts:

### Perl ###

#!/usr/bin/perl
use strict;
use warnings;

use List::Util qw/reduce/;
use constant {
STATE  => 1,
DATE   => 6,
TARGET => 5,
};

sub keep_best {
my ($best, $current) = @_;
if ($current->[STATE] eq $current->[TARGET]) {
   if ($best->[STATE] eq $best->[TARGET]) {
   if ($current->[DATE] gt $best->[DATE]) {
   return 0;
   }
   } else {
   return 0;
   }
} elsif (
   $best->[STATE] ne $best->[TARGET]
   and
   $current->[DATE] gt $best->[DATE]) {
   return 0;
}
return 1;
}


my %input;

# while uses less memory than for:
# the former is an iterator

while (<>)
{
chomp;
my @results = split(/\t/, $_);
my $key = $results[0];
push @{$input{$key}}, [ @results, $_ ];
}

# while uses less memory than for:
# the former is an iterator

while (my ($key, $aref ) = each %input)
{
my $best = reduce {
   keep_best( $a, $b ) ? $a : $b
} @$aref;

print $best->[-1], "\n";
}


### Python (re-working John's code) ###

import sys

def keep_best(best, current):

ACTUAL_STATE = 1
# John had these swapped
DESIRED_STATE = 5
EXPIRY_DATE = 6

keep = True
if current[ACTUAL_STATE] == current[DESIRED_STATE]:
if best[ACTUAL_STATE] == best[DESIRED_STATE]:
if current[EXPIRY_DATE] > best[EXPIRY_DATE]:
keep = False
else:
keep = False
else:
if (best[ACTUAL_STATE] != best[ACTUAL_STATE]
and current[EXPIRY_DATE] > best[EXPIRY_DATE]):
keep = False
return keep

def process_file(opened_file=sys.stdin):

PIID = 0
recs = {}

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

for piid in recs:
best = reduce(lambda b, c: keep_best(b, c) and b or c,
recs[piid])
print best[-1]

if __name__ == "__main__":
process_file()


# "reduce" seems to be Lispish, Pythonic, and Perlish!

--
Hope this helps,
Steve


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


Re: Reading a portion of a file

2007-03-08 Thread attn . steven . kuo
On Mar 8, 10:35 am, [EMAIL PROTECTED] wrote:

(snipped)


>
> Ok, regex was my first thought because I used to use grep with Perl
> and shell scripting to grab everything from one pattern to another
> pattern. The file is just an unformatted file. What is below is
> exactly what is in the file. There are no spaces between the beginning
> and ending tags and the content. Would you recommend using spaces
> there? And if so, why?
>
> A sample of the file:


You can use iterators:

import StringIO
import itertools

def group(line):
if line[-6:-1] == 'START':
group.current = group.current + 1
return group.current

group.current = 0

data = """
#VS:COMMAND:df:START
Filesystem   1K-blocks  Used Available Use% Mounted on
/dev/vzfs 20971520517652  20453868   3% /
tmpfs  201603244   2015988   1% /var/run
tmpfs  2016032 0   2016032   0% /var/lock
tmpfs  2016032 0   2016032   0% /dev/shm
tmpfs  201603244   2015988   1% /var/run
tmpfs  2016032 0   2016032   0% /var/lock
#VS:COMMAND:df:STOP

#VS:FILE:/proc/loadavg:START
0.00 0.00 0.00 1/32 14543
#VS:FILE:/proc/loadavg:STOP

#VS:FILE:/proc/meminfo:START
MemTotal:   524288 kB
MemFree:450448 kB
Buffers: 0 kB
Cached:  0 kB
SwapCached:  0 kB
Active:  0 kB
Inactive:0 kB
HighTotal:   0 kB
HighFree:0 kB
LowTotal:   524288 kB
LowFree:450448 kB
SwapTotal:   0 kB
SwapFree:0 kB
Dirty:   0 kB
Writeback:   0 kB
Mapped:  73840 kB
Slab:0 kB
CommitLimit: 0 kB
Committed_AS:   248704 kB
PageTables:  0 kB
VmallocTotal:0 kB
VmallocUsed: 0 kB
VmallocChunk:0 kB
#VS:FILE:/proc/meminfo:STOP

#VS:FILE:/proc/stat:START
cpu  67188 0 26366 391669264 656686 0 0
cpu0 24700 0 10830 195807826 373309 0 0
cpu1 42488 0 15536 195861438 283376 0 0
intr 0
swap 0 0
ctxt 18105366807
btime 1171391058
processes 26501285
procs_running 1
procs_blocked 0
#VS:FILE:/proc/stat:STOP

#VS:FILE:/proc/uptime:START
1962358.88 1577059.05
#VS:FILE:/proc/uptime:STOP
""".lstrip("\n");

fh = StringIO.StringIO(data)

sections = itertools.groupby(itertools.ifilter(lambda line: len(line)
> 1, fh),
lambda line: group(line))

for key, section in sections:
for line in section:
print key, line,


--
Hope this helps,
Steven

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


Re: Newbie Question : "grep"

2007-03-12 Thread attn . steven . kuo
On Mar 12, 10:01 am, "Erik Johnson" <[EMAIL PROTECTED]> wrote:
> Sorry, I forgot to paste the modified version of my code in the post:. I
> think this is the same behaviour:
>
> for line in lines:
> if "placed" in line:
> if "i_a/i_b/ROM/" in line:
> pos = (line.split()[4]).split("_")[1]
> found = False
>
> for (tag, (start, end)) in tags:
> if tag in line:
> found = True
> print "i_a/i_b/ROM/%s [%i:%i] LOC =" %\
> (pos, tag, start, end)
> break
>
> if not found:
> print "Error"



Instead of using a sentinal value (i.e., found),
one can use the 'else' clause of a 'for' loop...


pos = (line.split()[4]).split("_")[1]
for (tag, (start,end)) in tags:
if tag in line:
print "i_a/i_b/ROM/%s [%i:%i] LOC=%s" %\
(pos,tag,start,end)
break
else
print "Error"

--
Hope this helps,
Steven

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


Re: Request for a change in the csv module.

2007-03-12 Thread attn . steven . kuo
On Mar 12, 4:26 pm, Paulo da Silva <[EMAIL PROTECTED]> wrote:
> Hi.
>
> I have just seen that csv module, more exactly the Dialect class,
> does not have any variable to specify the "floating point" character!
> In portuguese this is ','. Not '.'. 3.1415 -> 3,1415.
> I think this is also the case of other languages/countries.
> If I am correct, i.e. if there is no such possibility, where can
> I file a request for a csv change? Excel, for example, automatically
> converts '.' to ',' and the separator from ',' to ';'.
>



Try using locale.format when writing:

import csv
import locale

locale.setlocale(locale.LC_NUMERIC, 'pt_BR.ISO8859-1')
csv_writer = csv.writer(open("foo.csv","w"), dialect='excel')
rows = (('testing', 1.23), ('testing', 2.34))
formatted_rows = ((string, locale.format('%g', number)) for
(string,number) in rows)
csv_writer.writerows(formatted_rows)


locale.atof and locale.atoi can convert a string back
to a number.

--
Hope this helps,
Steven


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


Re: How to capture environment state after running a shell script.

2007-03-13 Thread attn . steven . kuo
On Mar 13, 5:57 am, "Gerard Flanagan" <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I have a third party shell script which updates multiple environment
> values, and I want to investigate (and ultimately capture to python)
> the environment state after the script has run. But running the script
> as a child process only sets values for that process, which are lost
> after execution.  So I thought I could simply tack on an 'env' command
> line to the script input lines as shown below. However, using
> subprocess.Popen gives the error shown (even though the docs say that
> any file object may be used for stdin), and using popen2 hangs
> indefinitely. I think I'm missing something basic, any advice? Or is
> there a better approach?
>

(snipped)

> ## first method ##
> p = Popen('/bin/sh', stdin=buf)
> print p.stdout.readlines()
>
> Traceback (most recent call last):
>   File "scratch.py", line 36, in ?
> p = Popen('/bin/sh', stdin=buf)
>   File "/usr/local/lib/python2.4/subprocess.py", line 534, in __init__
> (p2cread, p2cwrite,
>   File "/usr/local/lib/python2.4/subprocess.py", line 830, in
> _get_handles
> p2cread = stdin.fileno()
> AttributeError: StringIO instance has no attribute 'fileno'
>
> ## second method ##
> cmdout, cmdin = popen2('/bin/sh')
> for line in buf:
> cmdin.write(line)
>
> ret = cmdout.readlines()
> cmdout.close()
> cmdin.close()
>
> print ret



First close the input so that the (sub) process
knows to terminate and flush the output.  Then,
you can read from the output:

import subprocess
import popen2

p = subprocess.Popen(["/bin/sh"], stdin=subprocess.PIPE,
stdout=subprocess.PIPE)

p.stdin.write("env -i FOO=BAR\n")
p.stdin.close()
status = p.wait()
ret = p.stdout.readlines()
p.stdout.close()

print ret

# Or

cmdout, cmdin = popen2.popen2("/bin/sh")
cmdin.write("env -i FOO=BAR\n")
cmdin.close()
ret = cmdout.readlines()
cmdout.close

print ret

--
Hope this helps,
Steven

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


Re: string formatting: engineering notation

2007-03-14 Thread attn . steven . kuo
On Mar 14, 1:14 pm, Darren Dale <[EMAIL PROTECTED]> wrote:
> Does anyone know if it is possible to represent a number as a string with
> engineering notation (like scientific notation, but with 10 raised to
> multiples of 3: 120e3, 12e-6, etc.). I know this is possible with the
> decimal.Decimal class, but repeatedly instantiating Decimals is inefficient
> for my application (matplotlib plotting library). If it is not currently
> possible, do you think the python devs would be receptive to including
> support for engineering notation in future releases?


Do you also consider this to be too inefficient?


import math

for exponent in xrange(-10, 11):
flt = 1.23 * math.pow(10, exponent)
l = math.log10(flt)
if l < 0:
l = l - 3
p3 = int(l / 3) * 3
multiplier = flt / pow(10, p3)
print '%e => %fe%d' % (flt, multiplier, p3)

--
Hope this helps,
Steven

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


Re: using regexp

2007-03-19 Thread attn . steven . kuo
On Mar 19, 10:33 pm, [EMAIL PROTECTED] wrote:
> hi
> how can i use regexp to group these digits into groups of 3?
>
> eg
> line 123456789123456789
>
> i have :
>
> pat = re.compile("line\s+(\d{3})" , re.M|re.DOTALL)
>
> but this only gives the first 3. I also tried
>
> "line\s+(\d{3})+"
> but also not working.
> I need output to be ['123' ,'456','789', '123','456','789', .]
> thanks.



Try:

import re

target_string = """not 123456789 but
try this line 987654321"""

try:
digits = re.compile(r'line\s+(\d
+)').search(target_string).group(1)
except AttributeError:
digits = ''

three_at_a_time = re.compile(r'\d{3}').findall(digits)
print three_at_a_time

--
Hope this helps,
Steven

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


Re: Daylight saving time question

2007-03-20 Thread attn . steven . kuo
On Mar 20, 12:53 pm, Mr Pekka Niiranen <[EMAIL PROTECTED]>
wrote:
> Hi,
>
> is it possible to get the two annual daylight saving times
> (day, month and time) from Python by giving location
> in some country/location string ("Europe/Finland" for example).
>
> I need to ask country in program and calculate daylight
> saving times for the next few years onwards somehow like this:
>
> for y in range(2007, 2017):
> (m1,d1,t1,m2,d2,t2) = daylight_change_epochs("Finland")
>
> -pekka-



A generator defined via recursion:

import dateutil.rrule, dateutil.tz
import datetime

mytz = dateutil.tz.tzfile("/usr/share/zoneinfo/Europe/Helsinki")

start = datetime.datetime(2007,1,1,0,0,0,tzinfo=mytz)
end = datetime.datetime(2017,1,1,0,0,0,tzinfo=mytz)

successively_finer = {
dateutil.rrule.WEEKLY: dateutil.rrule.DAILY,
dateutil.rrule.DAILY: dateutil.rrule.HOURLY,
dateutil.rrule.HOURLY: dateutil.rrule.MINUTELY,
dateutil.rrule.MINUTELY: dateutil.rrule.SECONDLY
}

# find week, then day, then hour, etc. that spans a change in DST

def sieve (start, end, freq):
dstflag = start.timetuple()[-1]
iter = dateutil.rrule.rrule(freq,dtstart=start,until=end)
tprior = start
for t in iter:
if t.timetuple()[-1] != dstflag:
dstflag = t.timetuple()[-1]
if freq == dateutil.rrule.SECONDLY:
yield tprior, t
else:
yield sieve(tprior, t,
successively_finer[freq]).next()
tprior = t
raise StopIteration

for before, after in sieve(start, end, dateutil.rrule.WEEKLY):
print "%s => %s" % (
before.strftime("%Y-%m-%d %H:%M:%S (%a) %Z"),
after.strftime("%Y-%m-%d %H:%M:%S (%a) %Z"))


I get:

2007-03-25 02:59:59 (Sun) EET => 2007-03-25 03:00:00 (Sun) EEST
2007-10-28 02:59:59 (Sun) EEST => 2007-10-28 03:00:00 (Sun) EET
2008-03-30 02:59:59 (Sun) EET => 2008-03-30 03:00:00 (Sun) EEST
2008-10-26 02:59:59 (Sun) EEST => 2008-10-26 03:00:00 (Sun) EET
2009-03-29 02:59:59 (Sun) EET => 2009-03-29 03:00:00 (Sun) EEST
2009-10-25 02:59:59 (Sun) EEST => 2009-10-25 03:00:00 (Sun) EET
2010-03-28 02:59:59 (Sun) EET => 2010-03-28 03:00:00 (Sun) EEST
2010-10-31 02:59:59 (Sun) EEST => 2010-10-31 03:00:00 (Sun) EET
2011-03-27 02:59:59 (Sun) EET => 2011-03-27 03:00:00 (Sun) EEST
2011-10-30 02:59:59 (Sun) EEST => 2011-10-30 03:00:00 (Sun) EET
2012-03-25 02:59:59 (Sun) EET => 2012-03-25 03:00:00 (Sun) EEST
2012-10-28 02:59:59 (Sun) EEST => 2012-10-28 03:00:00 (Sun) EET
2013-03-31 02:59:59 (Sun) EET => 2013-03-31 03:00:00 (Sun) EEST
2013-10-27 02:59:59 (Sun) EEST => 2013-10-27 03:00:00 (Sun) EET
2014-03-30 02:59:59 (Sun) EET => 2014-03-30 03:00:00 (Sun) EEST
2014-10-26 02:59:59 (Sun) EEST => 2014-10-26 03:00:00 (Sun) EET
2015-03-29 02:59:59 (Sun) EET => 2015-03-29 03:00:00 (Sun) EEST
2015-10-25 02:59:59 (Sun) EEST => 2015-10-25 03:00:00 (Sun) EET
2016-03-27 02:59:59 (Sun) EET => 2016-03-27 03:00:00 (Sun) EEST
2016-10-30 02:59:59 (Sun) EEST => 2016-10-30 03:00:00 (Sun) EET

--
Hope this helps,
Steven

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


Re: call to function by text variable

2007-03-25 Thread attn . steven . kuo
On Mar 25, 3:36 pm, "ianaré" <[EMAIL PROTECTED]> wrote:
> yeah the subject doesn't really make sense does it?
>
> anyway want I want to do is this:
> if n == 1:
>
> self.operations.insert(pos, operations.Replace.Panel(self, main))
>
> elif n == 2:
>
> self.operations.insert(pos, operations.ChangeCase.Panel(self,
> main))
>
> elif n == 3:
>
> self.operations.insert(pos, operations.Move.Panel(self, main))
>
> As you can see all the different functions have the same variables, so
> it would be easier if I could just make a list and use that.
>


# Your list would contain the unbound functions:

unbound_funcs = [operations.Replace.Panel,
operations.Change.Panel,
operations.Move.Panel]


# and invocation would be:

self.operations.insert(pos, unbound_funcs[n - 1](self, main))


--
Hope this helps,
Steven


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

Re: make RE more cleaver to avoid inappropriate : sre_constants.error: redefinition of group name

2007-03-29 Thread attn . steven . kuo
On Mar 29, 7:22 am, "aspineux" <[EMAIL PROTECTED]> wrote:
> I want to parse
>
> '[EMAIL PROTECTED]' or '<[EMAIL PROTECTED]>' and get the email address [EMAIL 
> PROTECTED]
>
> the regex is
>
> r'<[EMAIL PROTECTED]>|[EMAIL PROTECTED]'
>
> now, I want to give it a name
>
> r'<(?P[EMAIL PROTECTED])>|(?P[EMAIL PROTECTED])'
>
> sre_constants.error: redefinition of group name 'email' as group 2;
> was group 1
>
> BUT because I use a | , I will get only one group named 'email' !
>
> Any comment ?
>
> PS: I know the solution for this case is to use  r'(?P<)?(?P
> [EMAIL PROTECTED])(?(lt)>)'



Regular expressions, alternation, named groups ... oh my!

It tends to get quite complex especially if you need
to reject cases where the string contains a left bracket
and not the right, or visa-versa.

>>> pattern = re.compile(r'(?P<[EMAIL PROTECTED]>|(?>> PROTECTED](?!>))')
>>> for email in ('[EMAIL PROTECTED]' , '<[EMAIL PROTECTED]>', '<[EMAIL 
>>> PROTECTED]'):
... matched = pattern.search(email)
... if matched is not None:
... print matched.group('email')
...
[EMAIL PROTECTED]
<[EMAIL PROTECTED]>


I suggest you try some other solution (maybe pyparsing).

--
Hope this helps,
Steven

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


Re: Creating a new data structure while filtering its data origin.

2007-03-29 Thread attn . steven . kuo
On Mar 28, 1:44 pm, <[EMAIL PROTECTED]> wrote:
> Hi everyone.
>
> I'm trying to work with very simple data structures but I'm stuck in the very 
> first steps. If someone has the luxury of a few minutes and can give an 
> advice how to resolve this, I'll really appreciate it.
>
> 1- I have a list of tuples like this:
> lista= [(162, 141, 3), (162, 141, 3), (162, 141, 3), (168, 141, 2), (168, 
> 141, 2), (168, 141, 2), (201,  141, 1), (213, 141, 1), (203, 141, 1), (562, 
> 142, 4), (562, 142, 4), (562, 142, 4), (568, 142, 2), (568, 142, 2), (568, 
> 142, 2), (501,  142, 1), (513, 142, 1), (503, 142, 1)]
> and I want to end with a dict like this:
> {141: {1: [203, 213, 201], 2: [168, ], 3: [162, ]}, 142: {1: [503, 513, 501], 
> 2: [568, ], 4: [562, ]}}


(snipped)

I think you can use, with python 2.5, defaultdict for
this.  I only have access to 2.4.4 here, so my facsimile
is:

class defaultd(dict):
def __getitem__(self, k):
if k not in self:
self[k] = defaultd()
return dict.__getitem__(self, k)

lista = [(162, 141, 3), (162, 141, 3), (162, 141, 3), (168, 141, 2),
(168, 141, 2), (168, 141, 2), (201,  141, 1), (213, 141, 1), (203,
141,
1), (562, 142, 4), (562, 142, 4), (562, 142, 4), (568, 142, 2), (568,
142, 2), (568, 142, 2), (501,  142, 1), (513, 142, 1), (503, 142, 1)]

dd = defaultd()

for value, outerkey, innerkey in lista:
li = dd[outerkey].setdefault(innerkey, [])
if value not in li:
li.insert(0, value)
# or, li.append(value) if you want to reverse order

print dd

I happen to like the "autovivification" feature
found in perl and was pleased to see defaultdict in
python 2.5.  OTOH, python programmers more experienced
than I might see this and run away screaming.


--
Hope this helps,
Steven

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


Re: Weird gcc behaviour with function pointer types

2007-03-29 Thread attn . steven . kuo
On Mar 29, 6:05 am, greg <[EMAIL PROTECTED]> wrote:
> In my quest to eliminate C compiler warnings from
> Pyrex output, I've discovered some utterly bizarre
> behaviour from gcc 3.3.
>
> The following code:
>
>void g(struct foo *x) {
>}
>
>void f(void) {
>  void (*h)(struct foo *);
>  h = g;
>}
>
> produces the following warning:
>
>blarg.c: In function `f':
>blarg.c:6: warning: assignment from incompatible pointer type
>
> However, adding the following line at the top:
>
>typedef struct foo Foo;
>
> makes the warning go away. The mere *presence* of
> the typedef is all that's needed -- it doesn't even
> have to be used.
>
> This looks like a bug in gcc to me -- what do people
> think?



Was there no (forward) declaration nor
definition of struct foo ahead of your functions?

I get no warnings with this:


struct foo; /* forward declaration */

void g(struct foo *x) {
}

void f(void) {
void (*h)(struct foo *);
h = g;
}


Using:

Target: powerpc-apple-darwin8
Configured with: /private/var/tmp/gcc/gcc-5026.obj~19/src/configure --
disable-checking --prefix=/usr --mandir=/share/man --enable-
languages=c,objc,c++,obj-c++ --program-transform-name=/^[cg][^+.-]*$/s/
$/-4.0/ --with-gxx-include-dir=/include/gcc/darwin/4.0/c++ --
build=powerpc-apple-darwin8 --host=powerpc-apple-darwin8 --
target=powerpc-apple-darwin8
Thread model: posix

gcc version 4.0.0 (Apple Computer, Inc. build 5026)

--
Hope this helps,
Steven

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


Re: Sorting a multidimensional array by multiple keys

2007-03-31 Thread attn . steven . kuo
On Mar 31, 6:42 am, Rehceb Rotkiv <[EMAIL PROTECTED]> wrote:

(snipped)

> As each line consists of 5 words, I would break up the data into an array
> of five-field-arrays (Would you use lists or tuples or a combination in
> Python?). The word "BUT" would be in the middle, with two fields/words
> left and two fields/words right of it. I then want to sort this list by
>
> - field 3
> - field 4
> - field 1
> - field 0



import StringIO

buf = """
reaction is BUT by the
sodium , BUT it is
sea , BUT it is
this manner BUT the dissolved
pattern , BUT it is
rapid , BUT it is
""".lstrip()

mockfile = StringIO.StringIO(buf)

tokens = [ line.split() + [ line ] for line in mockfile ]
tokens.sort(key=lambda l: (l[3], l[4], l[1], l[0]))
for l in tokens:
print l[-1],


--
Hope this helps,
Steven

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


Re: Overlapping matches

2007-04-01 Thread attn . steven . kuo
On Apr 1, 1:38 pm, Rehceb Rotkiv <[EMAIL PROTECTED]> wrote:
> In the re documentation, it says that the matching functions return "non-
> overlapping" matches only, but I also need overlapping ones. Does anyone
> know how this can be done?


Perhaps lookahead assertions are what you're
looking for?

import re
import string

non_overlap = re.compile(r'[0-9a-fA-F]{2}')
pairs = [ match.group(0) for match in
non_overlap.finditer(string.hexdigits) ]
print pairs

overlap = re.compile(r'[0-9a-fA-F](?=([0-9a-fA-F]))')
pairs = [ match.group(0) + match.group(1) for match in
overlap.finditer(string.hexdigits) ]
print pairs

--
Hope this helps,
Steven

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


Re: calling super()

2007-04-04 Thread attn . steven . kuo
On Apr 4, 12:22 pm, [EMAIL PROTECTED] wrote:
> Hello, I have been trying to call the super constructor from my
> derived class but its not working as expected. See the code:
>
> class HTMLMain:
> def __init__(self):
> self.text = "";
> print(self.text);
> def __del__(self):
> self.text = "";
> print(self.text);
>
> class NewPage(HTMLMain):
> def __init__(self):
> print 'derive2 init'
> super(NewPage, self).__init__();
>
> N = NewPage();
> del N
>
> And here's the error message I get:


The error message is trying to tell
you that 'super' should be used with
new style classes.

So,

class HTMLMain:

should be

class HTMLMain(object):

--
Hope this helps,
Steven

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


Re: Newbie Question about sequence multiplication

2007-04-04 Thread attn . steven . kuo
On Apr 4, 3:19 pm, "Scott" <[EMAIL PROTECTED]> wrote:

(snipped)

>
> print
> print ' ' * left_margin + '+'   + '-' * (box_width-2)  +  '+'
> print ' ' * left_margin + '|  ' + ' ' * text_width + ' |'
> print ' ' * left_margin + '|  ' + ' '   sentence   + ' |'
> print ' ' * left_margin + '|  ' + ' ' * text_width + ' |'
> print ' ' * left_margin + '+'   + '-' * (box_width-2)  + ' |'
> print
>
> end code
>
> Now that, even though copied straight from "Beginning Python: From Novice to
> Professional", returns :
> There's an error in your program: invalid syntax
>

(snipped)


Others have pointed out the mistake.  I'll just add that in
this particular case, one might want to pad lines with some
whitespace and change the middle print statement to:

print
print ' ' * left_margin + '+' + '-' * box_width  + '+'
print ' ' * left_margin + '|' + '-' * box_width  + '|'
print ' ' * left_margin + '|' +  sentence.center(box_width)  + '|'
print ' ' * left_margin + '|' + '-' * box_width  + '|'
print ' ' * left_margin + '+' + '-' * box_width  + '+'

to improve legibility.

--
Hope this helps,
Steven

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


Re: how to remove multiple occurrences of a string within a list?

2007-04-05 Thread attn . steven . kuo
On Apr 4, 7:43 pm, [EMAIL PROTECTED] (Alex Martelli) wrote:

(snipped)

> A "we-don't-need-no-stinkin'-one-liners" more relaxed approach:
>
> import collections
> d = collections.defaultdict(int)
> for x in myList: d[x] += 1
> list(x for x in myList if d[x]==1)
>
> yields O(N) performance (give that dict-indexing is about O(1)...).
>
> Collapsing this kind of approach back into a "one-liner" while keeping
> the O(N) performance is not easy -- whether this is a fortunate or
> unfortunate ocurrence is of course debatable.  If we had a "turn
> sequence into bag" function somewhere (and it might be worth having it
> for other reasons):
>
> def bagit(seq):
>   import collections
>   d = collections.defaultdict(int)
>   for x in seq: d[x] += 1
>   return d
>
> then one-linerness might be achieved in the "gimme nonduplicated items"
> task via a dirty, rotten trick...:
>
> list(x for bag in [bagit(myList)] for x in myList if bag[x] == 1)
>
> ...which I would of course never mention in polite company...
>
> Alex



With a "context managed" set one could have, as a one-liner:

with cset() as s: retval = [ (x, s.add(x))[0] for x in myList if x not
in s ]

I've not looked at the underlying implementation of set(), but I
presume that checking set membership is also about O(1).

--
Cheers,
Steven


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


Re: elementary tuple question. (sorry)

2007-04-05 Thread attn . steven . kuo
On Apr 5, 2:08 pm, "Steven W. Orr" <[EMAIL PROTECTED]> wrote:
> I have a tuple that I got from struct.unpack. Now I want to pass the data
> from the returned tuple to struct.pack
>
> >>> fmt
>
> 'l 10l 11i h 4h c 47c 0l'>>>struct.pack(fmt, tup)
>
> Traceback (most recent call last):
>File "", line 1, in ?
> struct.error: required argument is not an integer
>
> What's the idiom to pass the data in tup?
>


Try

mystring = struct.pack(fmt, *tup)

--
Hope this helps,
Steven

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


Re: grandparent method with super

2007-04-05 Thread attn . steven . kuo
On Apr 5, 2:13 pm, Martin Manns <[EMAIL PROTECTED]> wrote:
> On Thu, 5 Apr 2007 16:55:38 -0400
>
>
>
> "John Clark" <[EMAIL PROTECTED]> wrote:
> > >That works, but when I replace A with something else, I do not get
> > >the
> > grandparent anymore
> > >without changing all the method calls. Basically, I would like to
> > >call the
> > method m in the first
> > >grandparent of D.
>
> > >Martin
>
> > I think the problem you may run into is with the term "first
> > grandparent" - when you look at the method resolution order of the
> > class D, you will find that the MRO goes "D, C, B, A"... I think it's
> > going to be difficult to figure out where the "first grandparent" is
> > in the MRO.
>
> > For example:
>
> > class A(object):
> >def m(self):
> >pass
> > class B(A):
> >def m(self):
> >pass
> > class C(B):
> >def m(self):
> >pass
> > class D(A):
> >def m(self):
> >pass
> > class E(C,D):
> >def m(self):
> >firstgrandparent(E,self).m() #Should call B.m
> > class F(D,C):
> >def m(self):
> >firstgrandparent(F,self).m() # Should call F.m
>
> > The mro for class E is going to be "E,C,B,D,A" where as the mro for
> > class F is going to be "F,D,C,B,A".  However, the first grandparent
> > for E should be B, where as the first grandparent for F should be A.
>
> > Because the MRO isn't just a depth first traversal, the term "first
> > grandparent" gets tricky to define...
>
> Not really. The first grandparent would be the first occurrence in the
> list from left to right, which satisfies the requirement that its
> shortest path to the current class is 2.
>
> The only problem: How do I get it?
>
> Martin



class E(C,D):
def m(self):
for cls in E.__mro__:
if cls != E and cls not in E.__bases__:
cls.m(self)
break


... but it's probably better that you
rethink your class hierarchy.

--
Hope this helps,
Steven

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


Re: Database Timestamp conversion error

2007-04-06 Thread attn . steven . kuo
On Apr 6, 1:48 pm, [EMAIL PROTECTED] wrote:

(snipped)

> If I look in the MS Access database, I see the timestamp as "5/6/112".
> Obviously some user didn't enter the correct date and the programmer
> before me didn't give Access strict enough rules to block bad dates.
> How do I test for a malformed date object so I can avoid this? There
> are thousands of records to transfer.
>

time.strptime ?


import time
for date in ("5/6/2008", "5/6/118"):
try:
struct_tm = time.strptime(date, "%m/%d/%Y")
print "Good date: " + date
print struct_tm
except ValueError:
print "Bad date: " + date

--
Hope this helps,
Steven

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


Re: python regular expression help

2007-04-11 Thread attn . steven . kuo
On Apr 11, 9:50 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Wed, 11 Apr 2007 23:14:01 -0300, Qilong Ren <[EMAIL PROTECTED]>
> escribió:
>
> > Thanks for reply. That actually is not what I want. Strings I am dealing
> > with may look like this:
> >  s = 'a = 4.5 b = 'h'  'd' c = 4.5 3.5'
> > What I want is
> >  a = 4.5
> >  b = 'h' 'd'
> >  c = 4.5 3.5
>
> That's a bit tricky. You have LHS = RHS where RHS includes all the
> following text *except* the very next word before the following = (which
> is the LHS of the next expression). Or something like that :)
>
> py> import re
> py> s = "a = 4.5 b = 'h'  'd' c = 4.5 3.5"
> py> r = re.compile(r"\w+\s*=\s*.*?(?=\w+\s*=|$)")
> py> for item in r.findall(s):
> ...   print item
> ...
> a = 4.5
> b = 'h'  'd'
> c = 4.5 3.5
>


Another way is to use split:

import re

lhs = re.compile(r'\s*(\b\w+\s*=)')
for s in [ "a = 4 b =3.4 5.4 c = 4.5",
"a = 4.5 b = 'h'  'd' c = 4.5 3.5"]:
tokens = lhs.split(s)
results = [tokens[_] + tokens[_+1] for _ in range(1,len(tokens),
2)]
print s
print results

--
Regards,
Steven


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


Re: "Cloning" file attributes and permissions

2007-04-12 Thread attn . steven . kuo
On Apr 12, 9:20 am, Paulo da Silva <[EMAIL PROTECTED]> wrote:
> Hi!
>
> I need to process a file to produce another file that *must* have
> *exactly* the same attributes and permissions of the former. What is the
> best way to do this? The file must not exist with contents (it may exist
> empty) unless it has the same attributes and permissions.
> I know how to do this using, let me call it, "C type code" (stat, chmod,
> chown, etc). I would like to hear some opinions on if and how it would
> be possible in a more elegant/python way.
>


Are you using a system that supports the creation
of a hard link?

If so, try os.link.

--
Hope this helps,
Steven

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


Re: "Cloning" file attributes and permissions

2007-04-12 Thread attn . steven . kuo
On Apr 12, 4:09 pm, Paulo da Silva <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] escreveu:
>
>
>
> > On Apr 12, 9:20 am, Paulo da Silva <[EMAIL PROTECTED]> wrote:
> >> Hi!
>
> >> I need to process a file to produce another file that *must* have
> >> *exactly* the same attributes and permissions of the former. What is the
> >> best way to do this? The file must not exist with contents (it may exist
> >> empty) unless it has the same attributes and permissions.
> >> I know how to do this using, let me call it, "C type code" (stat, chmod,
> >> chown, etc). I would like to hear some opinions on if and how it would
> >> be possible in a more elegant/python way.
>
> > Are you using a system that supports the creation
> > of a hard link?
>
> > If so, try os.link.
>
> May be I missed something exposing my q.
> I need to process an input file "foo" to produce a different contents
> file "bar". "bar" must have the same attributes/permissions of "foo".
> I forgot to say that the OS is Linux.



Sorry, I did misunderstand your question at first.
Well, you do have stat, chown, chmod in Python; but
if you're on Linux, you might just want to use
the "cp" command with the "-p" switch:

import subprocess
retcode = subprocess.call([ "/bin/cp", "-p", oldfile, newfile ])
On my system, this preserves the access permissions and ownership.

And if you modify the file after copying, you can alter
the access and modification times with posix.utime
to match that of the original.

--
Hope this helps,
Steven








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


Re: "Cloning" file attributes and permissions

2007-04-12 Thread attn . steven . kuo
On Apr 12, 5:19 pm, [EMAIL PROTECTED] wrote:
> On Apr 12, 4:09 pm, Paulo da Silva <[EMAIL PROTECTED]> wrote:
>

(snipped)

>
>
> import subprocess
> retcode = subprocess.call([ "/bin/cp", "-p", oldfile, newfile ])
> On my system, this preserves the access permissions and ownership.
>
> And if you modify the file after copying, you can alter
> the access and modification times with posix.utime
> to match that of the original.


After poking around a bit I also discovered the
shutil module.  It looks like you can use
shutil.copy2.  More Pythonic, yes?

--
Regards,
Steven







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


Re: script for seconds in given month?

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



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

--
Regards,
Steven


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


Re: unittest assertRaises Problem

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


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

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

to

self.assertRaises(ValueError, f.testException)

--
Hope this helps,
Steven

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


Re: list insertion question

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


Traverse the list from highest index
to lowest index:

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

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

print data

# OR

last_idx = len(data) - 1

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

print data

--
Hope this helps,
Steven

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


python-list@python.org

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


(snipped)

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


Scan once, two iterables:

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

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

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

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

--
Hope this helps,
Steven



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


python-list@python.org

2007-04-18 Thread attn . steven . kuo
On Apr 17, 3:52 pm, [EMAIL PROTECTED] wrote:


(snipped)

>
> So far I haven't succed using the coroutine Python 2.5 allows using
> the generators, and I think still that xsplitter can be done with two
> coroutines instead of two It objects. Despite Steven's code I am
> unable still to write a working code with coroutines (probably because
> I haven't understood how they work yet). This time I take a breath and
> I show my wrong code:
>
> import collections
>
> def xsplitter(iseq, pred):
> def it(parity):
> queue = collections.deque()
> while True:
> received = (yield)
> if received is not None:
> queue.append(received)
> if queue:
> yield queue.popleft()
> else:
> try:
> el = iseq.next()
> if pred(el) == parity:
> yield el
> else:
> its[not parity].send(el)
> except StopIteration:
> raise
>
> its = [it(False), it(True)]
> return its[True], its[False]
>
> idata = iter([1, 'a', 3, 'a', 4, 5, 6, 'a'])
> it1, it2 = xsplitter(idata, lambda x: x == 'a')
>
> from itertools import izip
> for el1, el2 in izip(it1, it2):
> print el1, el2
>
> It prints:
> None None
> None None
> a 3
> None None
> a 4
> None None
> None None
> None None
>
> Can it be fixed? Are you able to fix it for me? (If you want you can
> think of it as an exercise to understand Python coroutines :-) ).


I don't think coroutine are what's needed here.  In particular,
using 'send' will *deplete* the iterator -- the very iterator
to which one is trying to add an element.

If you don't wish to use objects, you can replace them with
a closure:

import collections

def xsplitter(iseq, pred):
queue = [ collections.deque(), collections.deque() ]
def it(parity):
while True:
if queue[parity]:
yield queue[parity].popleft()
else:
try:
el = iseq.next()
if pred(el) == parity:
yield el
else:
queue[not parity].append(el)
except StopIteration:
raise
its = [ it(False), it(True) ]
return its[True], its[False]


idata = iter([1, 'a', 3, 'a', 4, 5, 6, 'a'])
it1, it2 = xsplitter(idata, lambda x: x == 'a')

from itertools import izip
for el1, el2 in izip(it1, it2):
print el1, el2


Oh, I and do like your rewrite; it's much less
repetitive and cleaner than my original version.

--
Regards,
Steven



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


Re: grp.struct_group bug ?

2007-01-30 Thread attn . steven . kuo
On Jan 30, 5:42 pm, spam <[EMAIL PROTECTED]> wrote:
> Is this a bug ?
>
> Running the following script with Python 2.3.5:
> 
> #!/usr/bin/python
>
> import grp
>
> # groups = grp.getgrall()
>
> agroup = grp.getgrnam('wheel')
> print agroup
> print type(agroup)
>
> print agroup.__contains__('john')
> print agroup.__contains__('x')
> 
>
> This is the output I get:
> 
> ('wheel', 'x', 199, ['marcel', 'john', 'ben'])
> 
> False
> True
> 
>
> I expected __contains__ to tell me if a given user is part of a group, but
> it seems that it's checking the password field ??



The tuple returned by getgrnam contains four fields:
the group id (gr_gid), a list of group members (gr_grmem),
the group name (gr_name), and the group password (gr_passwd).

If you want to see if user 'john' is in the list of group members,
use:

if 'john' in agroup.gr_mem:
print "Found john in group wheel"

If you want to see if a password was set:

if agroup.gr_passwd == "":
print "No group password was set for group wheel"

and so on.

--
Hope this helps,
Steven


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


Re: Strings in Python

2007-02-08 Thread attn . steven . kuo
On Feb 8, 8:28 am, "Johny" <[EMAIL PROTECTED]> wrote:
> Playing a little more with strings, I found out that string.find
> function provides the position of
> the first occurance of the substring in the string.
> Is there a way how to find out all substring's position ?
> To explain more,
> let's suppose
>
> mystring='12341'
> import string
>
> >>> string.find(mystring ,'1')
>
> 0
>
> But I need to find the  possition the other '1' in mystring too.
> Is it possible?
> Or must I use regex?


In this case, you can use:

mystring = '12341'
indices = [ _ for _ in range(len(mystring)) if mystring[_] == '1' ]
print indices

--
Hope this helps,
Steven

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


Re: How to find all the same words in a text?

2007-02-11 Thread attn . steven . kuo
On Feb 11, 5:13 am, Samuel Karl Peterson
<[EMAIL PROTECTED]> wrote:
> "Johny" <[EMAIL PROTECTED]> on 10 Feb 2007 05:29:23 -0800 didst step
> forth and proclaim thus:
>
> > I need to find all the same words in a text .
> > What would be the best idea  to do that?
>
> I make no claims of this being the best approach:
>
> 
> def findOccurances(a_string, word):
> """
> Given a string and a word, returns a double:
> [0] = count [1] = list of indexes where word occurs
> """
> import re
> count = 0
> indexes = []
> start = 0 # offset for successive passes
> pattern = re.compile(r'\b%s\b' % word, re.I)
>
> while True:
> match = pattern.search(a_string)
> if not match: break
> count += 1;
> indexes.append(match.start() + start)
> start += match.end()
> a_string = a_string[match.end():]
>
> return (count, indexes)
> 
>
> Seems to work for me.  No guarantees.
>



More concisely:

import re

pattern = re.compile(r'\b324\b')
indices = [ match.start() for match in
pattern.finditer(target_string) ]
print "Indices", indices
print "Count: ", len(indices)

--
Cheers,
Steven

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


Re: how to compare...

2007-02-12 Thread attn . steven . kuo
On Feb 12, 8:03 pm, "jairodsl" <[EMAIL PROTECTED]> wrote:
> Hello everybody !
>
> I have two list, they are, S1=['A','B','C','D','E'], and
> S2=['F','G','H','I','J'], but i have to compare both in this way:
>
>  A  vs J
>  A  vs I,  B vs J
>  A  vs H, B vs I, C vs J
>  A  vs G, B vs H, C vs I,  D vs J
>  A  vs F, B vs G, C vs H, D vs I, E vs J
>  B  vs F, C vs G, D vs H, E vs I
>  C  vs F, D vs G, E vs H
>  D  vs F, E vs G
>  E vs F
>

(snipped)

> Could someone give me any idea how to compare(or print) both list in
> this way ??? Thanks a lot !!!
>
> jDSL



s1 = [ 'A', 'B', 'C', 'D', 'E' ]
s2 = [ 'F', 'G', 'H', 'I', 'J' ]
s3 = []

for count in xrange( len(s1) + len(s2) - 1 ):
try:
operand = s2.pop()
except IndexError:
operand = None
except:
raise
s3.insert(0,operand)
print [ t for t in zip(s1, s3) if t[1] is not None ]


--
Hope this helps,
Steven

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


Re: Bug in time module - %z works in perl, not in python?

2007-02-21 Thread attn . steven . kuo
On Feb 21, 6:17 pm, [EMAIL PROTECTED] wrote:
> Following python code prints out incorrect UTC Offset - the python
> docs say that %z is not fully supported on all platforms - but on
> Linux Fedora FC5, perl code works and python does not - is this a bug
> or is this expected behavior? For a EST timezone setup, Perl prints
> correct -0500, while Python prints + - this is Python 2.4.
>
> Perl:
> $now_string = strftime "%Y-%m-%d %H:%M:%S %Z%z", localtime;
> print $now_string, "(iso local)\n";
>
> 2007-02-21 21:16:16 EST-0500 (iso localtime, perl)
>
> Python:
> now_string = time.strftime("%Y-%m-%d %H:%M:%S %Z%z", time.localtime())
> print now_string, " (iso localtime, python)"
>
> 2007-02-21 21:15:58 EST+  (iso localtime, python)
>
> Is this expected behavior, or a bug?




Seems to be a bug.  I can duplicate the
problem here (Python 2.4.3, Red Hat Desktop release 4).

I do see the correct output, however, if I pass just
the format string to strftime:

>>> print time.strftime("%Y-%m-%d %H:%M:%S %Z %z")
2007-02-21 18:42:03 PST -0800

>>> print time.strftime("%Y-%m-%d %H:%M:%S %Z %z", time.localtime())
2007-02-21 18:42:11 PST +

--
Hope this helps,
Steven

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


Re: modifying a list while iterating through

2007-02-25 Thread attn . steven . kuo
On Feb 25, 5:12 pm, [EMAIL PROTECTED] wrote:
> consider the following working loop where Packet is a subclass of
> list, with Packet.insert(index, iterable) inserting each item in
> iterable into Packet at consecutive indexes starting at index.
>
> i=0
> while(i if packet[i:i+5]==Packet("01110"):
> packet.insert(i, "0")
> i+=10 #skip the 5 bits inserted, and skip the 5 bits just
> checked bc overlap should not trigger insertion
> else: i+=1
>
> is there a way to do this more elegantly?  seems like a big kludge.


If Packet consists of '0's and '1's, then it may be
easier to convert to, or base the class on str (strings):

packet = "101010011100111010001"
print "BEFORE ", packet
li = packet.split("01110")
packet = "011100".join(li)
print "AFTER  ", packet

--
Hope this helps,
Steven

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


Re: classobj?

2007-02-26 Thread attn . steven . kuo
On Feb 26, 5:43 pm, Venky <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I am trying to create classes at runtime based on input from a textfile.
> I am trying to use the function new.classobj. I am able to create the
> new classes successfully, however I fail to understand on how to add
> this new class to the current dictionary.
>
> cl = new.classobj('SomeClass', (BaseClass, ), {})
>
> After this call, how do I instantiate SomeClass?
>
> I understand cl() will instantiate this, however this defeats my
> purpose, since the name of the class is obtained at runtime.
>


Do you mean that you want to add it to globals()?

globals()['SomeClass'] = cl

myinst = SomeClass()
print isinstance(myinst, SomeClass)
print isinstance(myinst, BaseClass)

--
Hope this helps,
Steven


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


Re: Extract String From Enclosing Tuple

2007-02-28 Thread attn . steven . kuo
On Feb 28, 12:40 pm, [EMAIL PROTECTED] wrote:
>   I'm a bit embarrassed to have to ask for help on this, but I'm not finding
> the solution in the docs I have here.
>
>   Data are assembled for writing to a database table. A representative tuple
> looks like this:
>
> ('eco', "(u'Roads',)", 0.073969887301348305)
>
> Pysqlite doesn't like the format of the middle term:
> pysqlite2.dbapi2.InterfaceError: Error binding parameter 1 - probably
> unsupported type.
>
>   I want to extract the 'Roads', part from the double-quoted enclosing
> tuple.

(snipped)



Perhaps something like:

>>> t = ('eco', "(u'Roads',)", 0.073969887301348305)
>>> t2 = eval(t[1], { '__builtins__' : {} }, {} )
>>> t2
(u'Roads',)
>>> t2[0].encode('ascii')
'Roads'


>>> import itertools
>>> tuple(itertools.chain((t[0], t2[0].encode('ascii')), t[2:]))
('eco', 'Roads', 0.073969887301348305)

>>> tuple(itertools.chain((t[0], (t2[0].encode('ascii'),)), t[2:]))
('eco', ('Roads',), 0.073969887301348305)


--
Hope this helps,
Steven

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


Re: text wrapping help

2007-02-28 Thread attn . steven . kuo
On Feb 28, 4:06 pm, "Ryan K" <[EMAIL PROTECTED]> wrote:
> I'm trying to text wrap a string but not using the textwrap module. I
> have 24x9 "matrix"  and the string needs to be text wrapped according
> to those dimensions. Is there a known algorithm for this? Maybe some
> kind of regular expression? I'm having difficulty programming the
> algorithm.


Try:

import re
sample_text = """Personal firewall software may warn about the
connection IDLE makes to its subprocess using this computer's internal
loopback interface.  This connection is not visible on any external
interface and no data is sent to or received from the Internet."""

# assume 24 is sufficiently wide:

lines = map(lambda x: x.rstrip(),
re.findall(r'.{1,24}(?:(?<=\S)\s|$)', sample_text.replace("\n", " ")))

print "\n".join(lines)


--
Hope this helps,
Steven

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


Re: text wrapping help

2007-02-28 Thread attn . steven . kuo
On Feb 28, 5:50 pm, "Ryan K" <[EMAIL PROTECTED]> wrote:

> On Feb 28, 8:27 pm, [EMAIL PROTECTED] wrote:
>
> > Try:
>
> > import re
> > sample_text = """Personal firewall software may warn about the
> > connection IDLE makes to its subprocess using this computer's internal
> > loopback interface.  This connection is not visible on any external
> > interface and no data is sent to or received from the Internet."""
>
> > # assume 24 is sufficiently wide:
>
> > lines = map(lambda x: x.rstrip(),
> > re.findall(r'.{1,24}(?:(?<=\S)\s|$)', sample_text.replace("\n", " ")))
>
> > print "\n".join(lines)
>
> > --
> > Hope this helps,
> > Steven
>
> That works great but I need to replace the newlines with 24-(the index
> of the \n) spaces.
>



Just left-justify to the appropriate width with
the the padding character you wanted:

equally_long_lines = map(lambda x: x.ljust(24, ' '), lines)

print "\n".join(equally_long_lines)

--
Hope this helps,
Steven

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


Re: Matplotlib axes label

2007-03-01 Thread attn . steven . kuo
On Mar 1, 3:10 pm, "John Henry" <[EMAIL PROTECTED]> wrote:
> I've been asking this question at the matplotlib user list and never
> gotten an answer.  I am hoping that there are matplotlib users here
> that can help.
>
> My problem with matplotlib's way of handling axes label is illustrated
> by this example:
>
> http://www.scipy.org/Cookbook/Matplotlib/MulticoloredLine
>
> Notice that the y-axis goes from (-1.1, 1.1) but the first label is at
> -1.0.

(snipped)

> Is there a way to force the label to start at -1.1 instead of -1.0?
>
> Thanks,


You can try adjusting the labels and ticks
using matplotlib.ticker.

To the example you cited, one can add

from matplotlib.ticker import MultipleLocator, FormatStrFormatter

# ...

minorLocator = MultipleLocator(0.1)
minorFormattor = FormatStrFormatter('%0.1f')
ax.yaxis.set_minor_locator(minorLocator)
ax.yaxis.set_minor_formatter(minorFormattor)

show()

--
Hope this helps,
Steven

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