Commit 4117e542 authored by Guido van Rossum's avatar Guido van Rossum

nannified

parent f9a6d7d4
......@@ -18,22 +18,22 @@ def main():
tn = telnetlib.Telnet(host, 0)
#
try:
vt.send(tn.read_until('login: ', 10))
tn.write('cwilib\r')
#
vt.send(tn.read_until('Hit <RETURN> to continue...', 10))
tn.write('\r')
#
vt.send(tn.read_until('QUIT', 20))
vt.send(tn.read_until('login: ', 10))
tn.write('cwilib\r')
#
vt.send(tn.read_until('Hit <RETURN> to continue...', 10))
tn.write('\r')
#
vt.send(tn.read_until('QUIT', 20))
except EOFError:
sys.stderr.write('Connection closed prematurely\n')
sys.exit(1)
sys.stderr.write('Connection closed prematurely\n')
sys.exit(1)
#
define_screens(vt)
matches = vt.which_screens()
if 'menu' not in matches:
sys.stderr.write('Main menu does not appear\n')
sys.exit(1)
sys.stderr.write('Main menu does not appear\n')
sys.exit(1)
#
tn.write('\r\r')
vt.open('Progress -- CWI Library')
......@@ -41,109 +41,109 @@ def main():
ui = UserInterface()
#
while 1:
try:
data = tn.read_very_eager()
except EOFError:
stdwin.message('Connection closed--goodbye')
break
if data:
print 'send...'
vt.send(data)
print 'send...done'
continue
event = stdwin.pollevent()
if event:
type, window, detail = event
if window == None and type == WE_LOST_SEL:
window = ui.queryform.window
event = type, window, detail
if type == WE_CLOSE:
break
if window in ui.windows:
ui.dispatch(type, window, detail)
elif window == vt.window:
if type == WE_NULL:
pass
elif type == WE_COMMAND:
if detail == WC_RETURN:
tn.write('\r')
elif detail == WC_BACKSPACE:
tn.write('\b')
elif detail == WC_TAB:
tn.write('\t')
elif detail == WC_UP:
tn.write('\033[A')
elif detail == WC_DOWN:
tn.write('\033[B')
elif detail == WC_RIGHT:
tn.write('\033[C')
elif detail == WC_LEFT:
tn.write('\033[D')
else:
print '*** Command:', detail
elif type == WE_CHAR:
tn.write(detail)
elif type == WE_DRAW:
vt.draw(detail)
elif type in (WE_ACTIVATE, WE_DEACTIVATE):
pass
else:
print '*** VT100 event:', type, detail
else:
print '*** Alien event:', type, window, detail
continue
rfd, wfd, xfd = select.select([tn, stdwin], [], [])
try:
data = tn.read_very_eager()
except EOFError:
stdwin.message('Connection closed--goodbye')
break
if data:
print 'send...'
vt.send(data)
print 'send...done'
continue
event = stdwin.pollevent()
if event:
type, window, detail = event
if window == None and type == WE_LOST_SEL:
window = ui.queryform.window
event = type, window, detail
if type == WE_CLOSE:
break
if window in ui.windows:
ui.dispatch(type, window, detail)
elif window == vt.window:
if type == WE_NULL:
pass
elif type == WE_COMMAND:
if detail == WC_RETURN:
tn.write('\r')
elif detail == WC_BACKSPACE:
tn.write('\b')
elif detail == WC_TAB:
tn.write('\t')
elif detail == WC_UP:
tn.write('\033[A')
elif detail == WC_DOWN:
tn.write('\033[B')
elif detail == WC_RIGHT:
tn.write('\033[C')
elif detail == WC_LEFT:
tn.write('\033[D')
else:
print '*** Command:', detail
elif type == WE_CHAR:
tn.write(detail)
elif type == WE_DRAW:
vt.draw(detail)
elif type in (WE_ACTIVATE, WE_DEACTIVATE):
pass
else:
print '*** VT100 event:', type, detail
else:
print '*** Alien event:', type, window, detail
continue
rfd, wfd, xfd = select.select([tn, stdwin], [], [])
# Subroutine to define our screen recognition patterns
def define_screens(vt):
vt.define_screen('menu', {
'title': ('search', 0, 0, 80,
' SEARCH FUNCTIONS +OTHER FUNCTIONS '),
})
'title': ('search', 0, 0, 80,
' SEARCH FUNCTIONS +OTHER FUNCTIONS '),
})
vt.define_screen('search', {
'title': ('search', 0, 0, 80, ' Search '),
})
'title': ('search', 0, 0, 80, ' Search '),
})
vt.define_screen('shortlist', {'title': ('search', 0, 0, 80,
' Short-list')})
' Short-list')})
vt.define_screen('showrecord', {
'title': ('search', 0, 0, 80, ' Show record '),
})
'title': ('search', 0, 0, 80, ' Show record '),
})
vt.define_screen('timelimit', {
'limit': ('search', 12, 0, 80, ' TIME LIMIT '),
})
'limit': ('search', 12, 0, 80, ' TIME LIMIT '),
})
vt.define_screen('attention', {
'BASE': ('copy', 0, 0, 0, 'search'),
'title': ('search', 10, 0, 80, ' ATTENTION ')})
'BASE': ('copy', 0, 0, 0, 'search'),
'title': ('search', 10, 0, 80, ' ATTENTION ')})
vt.define_screen('syntaxerror', {
'BASE': ('copy', 0, 0, 0, 'attention'),
'message': ('search', 12, 0, 80, ' Syntax error'),
})
'BASE': ('copy', 0, 0, 0, 'attention'),
'message': ('search', 12, 0, 80, ' Syntax error'),
})
vt.define_screen('emptyerror', {
'BASE': ('copy', 0, 0, 0, 'attention'),
'message': ('search', 12, 0, 80,
' Check your input. Search at least one term'),
})
'BASE': ('copy', 0, 0, 0, 'attention'),
'message': ('search', 12, 0, 80,
' Check your input. Search at least one term'),
})
vt.define_screen('unsortedwarning', {
'BASE': ('copy', 0, 0, 0, 'attention'),
'message': ('search', 12, 0, 80,
' Number of records exceeds sort limit'),
})
'BASE': ('copy', 0, 0, 0, 'attention'),
'message': ('search', 12, 0, 80,
' Number of records exceeds sort limit'),
})
vt.define_screen('thereismore', {
'BASE': ('copy', 0, 0, 0, 'showrecord'),
'message': ('search', 15, 0, 80,
'There is more within this record. Use the arrow keys'),
})
'BASE': ('copy', 0, 0, 0, 'showrecord'),
'message': ('search', 15, 0, 80,
'There is more within this record. Use the arrow keys'),
})
vt.define_screen('nofurther', {
'BASE': ('copy', 0, 0, 0, 'showrecord'),
'message': ('search', 17, 0, 80, 'You cannot go further\.'),
})
'BASE': ('copy', 0, 0, 0, 'showrecord'),
'message': ('search', 17, 0, 80, 'You cannot go further\.'),
})
vt.define_screen('nofurtherback', {
'BASE': ('copy', 0, 0, 0, 'showrecord'),
'message': ('search', 17, 0, 80,
'You cannot go further back'),
})
'BASE': ('copy', 0, 0, 0, 'showrecord'),
'message': ('search', 17, 0, 80,
'You cannot go further back'),
})
# Class to implement our user interface.
......@@ -151,29 +151,29 @@ def define_screens(vt):
class UserInterface:
def __init__(self):
stdwin.setfont('7x14')
self.queryform = QueryForm()
self.listform = ListForm()
self.recordform = RecordForm()
self.forms = [self.queryform, self.listform, self.recordform]
define_query_fields(self.queryform)
self.windows = []
for form in self.forms:
if form.formheight > 0:
form.open()
self.windows.append(form.window)
stdwin.setfont('7x14')
self.queryform = QueryForm()
self.listform = ListForm()
self.recordform = RecordForm()
self.forms = [self.queryform, self.listform, self.recordform]
define_query_fields(self.queryform)
self.windows = []
for form in self.forms:
if form.formheight > 0:
form.open()
self.windows.append(form.window)
def __del__(self):
self.close()
self.close()
def close(self):
for form in self.forms:
form.close()
for form in self.forms:
form.close()
def dispatch(self, type, window, detail):
for form in self.forms:
if window == form.window:
form.dispatch(type, detail)
for form in self.forms:
if window == form.window:
form.dispatch(type, detail)
def define_query_fields(f):
......@@ -189,25 +189,25 @@ def define_query_fields(f):
class QueryForm(Form):
def __init__(self):
Form.__init__(self, 'Query form -- CWI Library')
Form.__init__(self, 'Query form -- CWI Library')
def dispatch(self, type, detail):
if type == WE_COMMAND and detail == WC_RETURN:
print '*** SUBMIT ***'
else:
Form.dispatch(self, type, detail)
if type == WE_COMMAND and detail == WC_RETURN:
print '*** SUBMIT ***'
else:
Form.dispatch(self, type, detail)
class ListForm(Form):
def __init__(self):
Form.__init__(self, 'Short list -- CWI Library')
Form.__init__(self, 'Short list -- CWI Library')
class RecordForm(Form):
def __init__(self):
Form.__init__(self, 'Record detail -- CWI Library')
Form.__init__(self, 'Record detail -- CWI Library')
main()
......@@ -7,7 +7,7 @@ import socket
import select
def main():
server = 'cnri.reston.va.us' # How?
server = 'cnri.reston.va.us' # How?
port = 53
opcode = dnsopcode.QUERY
rd = 0
......@@ -15,21 +15,21 @@ def main():
qname = sys.argv[1:] and sys.argv[1] or 'www.python.org'
m = dnslib.Mpacker()
m.addHeader(0,
0, opcode, 0, 0, rd, 0, 0, 0,
1, 0, 0, 0)
0, opcode, 0, 0, rd, 0, 0, 0,
1, 0, 0, 0)
m.addQuestion(qname, qtype, dnsclass.IN)
request = m.getbuf()
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((server, port))
s.send(request)
while 1:
r, w, x = [s], [], []
r, w, x = select.select(r, w, x, 0.333)
print r, w, x
if r:
reply = s.recv(1024)
u = dnslib.Munpacker(reply)
dnslib.dumpM(u)
break
r, w, x = [s], [], []
r, w, x = select.select(r, w, x, 0.333)
print r, w, x
if r:
reply = s.recv(1024)
u = dnslib.Munpacker(reply)
dnslib.dumpM(u)
break
main()
......@@ -4,19 +4,19 @@ For example,
class C:
def m1(self, arg):
require arg > 0
return whatever
require arg > 0
return whatever
ensure Result > arg
can be written (clumsily, I agree) as:
class C(Eiffel):
def m1(self, arg):
return whatever
return whatever
def m1_pre(self, arg):
assert arg > 0
assert arg > 0
def m1_post(self, Result, arg):
assert Result > arg
assert Result > arg
Pre- and post-conditions for a method, being implemented as methods
themselves, are inherited independently from the method. This gives
......@@ -28,10 +28,10 @@ post-condition with that defined in the derived class', for example:
class D(C):
def m1(self, arg):
return whatever**2
return whatever**2
def m1_post(self, Result, arg):
C.m1_post(self, Result, arg)
assert Result < 100
C.m1_post(self, Result, arg)
assert Result < 100
This gives derived classes more freedom but also more responsibility
than in Eiffel, where the compiler automatically takes care of this.
......@@ -42,13 +42,13 @@ up to the derived class. For example, a derived class that takes away
the requirement that arg > 0 could write:
def m1_pre(self, arg):
pass
pass
but one could equally write a derived class that makes a stronger
requirement:
def m1_pre(self, arg):
require arg > 50
require arg > 50
It would be easy to modify the classes shown here so that pre- and
post-conditions can be disabled (separately, on a per-class basis).
......@@ -66,27 +66,27 @@ from Meta import MetaClass, MetaHelper, MetaMethodWrapper
class EiffelMethodWrapper(MetaMethodWrapper):
def __init__(self, func, inst):
MetaMethodWrapper.__init__(self, func, inst)
# Note that the following causes recursive wrappers around
# the pre-/post-condition testing methods. These are harmless
# but inefficient; to avoid them, the lookup must be done
# using the class.
try:
self.pre = getattr(inst, self.__name__ + "_pre")
except AttributeError:
self.pre = None
try:
self.post = getattr(inst, self.__name__ + "_post")
except AttributeError:
self.post = None
MetaMethodWrapper.__init__(self, func, inst)
# Note that the following causes recursive wrappers around
# the pre-/post-condition testing methods. These are harmless
# but inefficient; to avoid them, the lookup must be done
# using the class.
try:
self.pre = getattr(inst, self.__name__ + "_pre")
except AttributeError:
self.pre = None
try:
self.post = getattr(inst, self.__name__ + "_post")
except AttributeError:
self.post = None
def __call__(self, *args, **kw):
if self.pre:
apply(self.pre, args, kw)
Result = apply(self.func, (self.inst,) + args, kw)
if self.post:
apply(self.post, (Result,) + args, kw)
return Result
if self.pre:
apply(self.pre, args, kw)
Result = apply(self.func, (self.inst,) + args, kw)
if self.post:
apply(self.post, (Result,) + args, kw)
return Result
class EiffelHelper(MetaHelper):
__methodwrapper__ = EiffelMethodWrapper
......@@ -99,12 +99,12 @@ Eiffel = EiffelMetaClass('Eiffel', (), {})
def _test():
class C(Eiffel):
def m1(self, arg):
return arg+1
def m1_pre(self, arg):
assert arg > 0, "precondition for m1 failed"
def m1_post(self, Result, arg):
assert Result > arg
def m1(self, arg):
return arg+1
def m1_pre(self, arg):
assert arg > 0, "precondition for m1 failed"
def m1_post(self, Result, arg):
assert Result > arg
x = C()
x.m1(12)
## x.m1(-1)
......
......@@ -12,9 +12,9 @@ class EnumMetaClass:
To define your own enumeration, do something like
class Color(Enum):
red = 1
green = 2
blue = 3
red = 1
green = 2
blue = 3
Now, Color.red, Color.green and Color.blue behave totally
different: they are enumerated values, not integers.
......@@ -25,66 +25,66 @@ class EnumMetaClass:
"""
def __init__(self, name, bases, dict):
"""Constructor -- create an enumeration.
Called at the end of the class statement. The arguments are
the name of the new class, a tuple containing the base
classes, and a dictionary containing everything that was
entered in the class' namespace during execution of the class
statement. In the above example, it would be {'red': 1,
'green': 2, 'blue': 3}.
"""
for base in bases:
if base.__class__ is not EnumMetaClass:
raise TypeError, "Enumeration base class must be enumeration"
bases = filter(lambda x: x is not Enum, bases)
self.__name__ = name
self.__bases__ = bases
self.__dict = {}
for key, value in dict.items():
self.__dict[key] = EnumInstance(name, key, value)
"""Constructor -- create an enumeration.
Called at the end of the class statement. The arguments are
the name of the new class, a tuple containing the base
classes, and a dictionary containing everything that was
entered in the class' namespace during execution of the class
statement. In the above example, it would be {'red': 1,
'green': 2, 'blue': 3}.
"""
for base in bases:
if base.__class__ is not EnumMetaClass:
raise TypeError, "Enumeration base class must be enumeration"
bases = filter(lambda x: x is not Enum, bases)
self.__name__ = name
self.__bases__ = bases
self.__dict = {}
for key, value in dict.items():
self.__dict[key] = EnumInstance(name, key, value)
def __getattr__(self, name):
"""Return an enumeration value.
"""Return an enumeration value.
For example, Color.red returns the value corresponding to red.
For example, Color.red returns the value corresponding to red.
XXX Perhaps the values should be created in the constructor?
XXX Perhaps the values should be created in the constructor?
This looks in the class dictionary and if it is not found
there asks the base classes.
This looks in the class dictionary and if it is not found
there asks the base classes.
The special attribute __members__ returns the list of names
defined in this class (it does not merge in the names defined
in base classes).
The special attribute __members__ returns the list of names
defined in this class (it does not merge in the names defined
in base classes).
"""
if name == '__members__':
return self.__dict.keys()
"""
if name == '__members__':
return self.__dict.keys()
try:
return self.__dict[name]
except KeyError:
for base in self.__bases__:
try:
return getattr(base, name)
except AttributeError:
continue
try:
return self.__dict[name]
except KeyError:
for base in self.__bases__:
try:
return getattr(base, name)
except AttributeError:
continue
raise AttributeError, name
raise AttributeError, name
def __repr__(self):
s = self.__name__
if self.__bases__:
s = s + '(' + string.join(map(lambda x: x.__name__,
self.__bases__), ", ") + ')'
if self.__dict:
list = []
for key, value in self.__dict.items():
list.append("%s: %s" % (key, int(value)))
s = "%s: {%s}" % (s, string.join(list, ", "))
return s
s = self.__name__
if self.__bases__:
s = s + '(' + string.join(map(lambda x: x.__name__,
self.__bases__), ", ") + ')'
if self.__dict:
list = []
for key, value in self.__dict.items():
list.append("%s: %s" % (key, int(value)))
s = "%s: {%s}" % (s, string.join(list, ", "))
return s
class EnumInstance:
......@@ -99,23 +99,23 @@ class EnumInstance:
"""
def __init__(self, classname, enumname, value):
self.__classname = classname
self.__enumname = enumname
self.__value = value
self.__classname = classname
self.__enumname = enumname
self.__value = value
def __int__(self):
return self.__value
return self.__value
def __repr__(self):
return "EnumInstance(%s, %s, %s)" % (`self.__classname`,
`self.__enumname`,
`self.__value`)
return "EnumInstance(%s, %s, %s)" % (`self.__classname`,
`self.__enumname`,
`self.__value`)
def __str__(self):
return "%s.%s" % (self.__classname, self.__enumname)
return "%s.%s" % (self.__classname, self.__enumname)
def __cmp__(self, other):
return cmp(self.__value, int(other))
return cmp(self.__value, int(other))
# Create the base class for enumerations.
......@@ -126,9 +126,9 @@ Enum = EnumMetaClass("Enum", (), {})
def _test():
class Color(Enum):
red = 1
green = 2
blue = 3
red = 1
green = 2
blue = 3
print Color.red
print dir(Color)
......@@ -139,11 +139,11 @@ def _test():
print Color.red == 2
class ExtendedColor(Color):
white = 0
orange = 4
yellow = 5
purple = 6
black = 7
white = 0
orange = 4
yellow = 5
purple = 6
black = 7
print ExtendedColor.orange
print ExtendedColor.red
......@@ -151,11 +151,11 @@ def _test():
print Color.red == ExtendedColor.red
class OtherColor(Enum):
white = 4
blue = 5
white = 4
blue = 5
class MergedColor(Color, OtherColor):
pass
pass
print MergedColor.red
print MergedColor.white
......
......@@ -9,33 +9,33 @@ import types
class MetaMethodWrapper:
def __init__(self, func, inst):
self.func = func
self.inst = inst
self.__name__ = self.func.__name__
self.func = func
self.inst = inst
self.__name__ = self.func.__name__
def __call__(self, *args, **kw):
return apply(self.func, (self.inst,) + args, kw)
return apply(self.func, (self.inst,) + args, kw)
class MetaHelper:
__methodwrapper__ = MetaMethodWrapper # For derived helpers to override
def __helperinit__(self, formalclass):
self.__formalclass__ = formalclass
self.__formalclass__ = formalclass
def __getattr__(self, name):
# Invoked for any attr not in the instance's __dict__
try:
raw = self.__formalclass__.__getattr__(name)
except AttributeError:
try:
ga = self.__formalclass__.__getattr__('__usergetattr__')
except KeyError:
raise AttributeError, name
return ga(self, name)
if type(raw) != types.FunctionType:
return raw
return self.__methodwrapper__(raw, self)
# Invoked for any attr not in the instance's __dict__
try:
raw = self.__formalclass__.__getattr__(name)
except AttributeError:
try:
ga = self.__formalclass__.__getattr__('__usergetattr__')
except KeyError:
raise AttributeError, name
return ga(self, name)
if type(raw) != types.FunctionType:
return raw
return self.__methodwrapper__(raw, self)
class MetaClass:
......@@ -45,49 +45,49 @@ class MetaClass:
"""
__helper__ = MetaHelper # For derived metaclasses to override
__helper__ = MetaHelper # For derived metaclasses to override
__inited = 0
def __init__(self, name, bases, dict):
try:
ga = dict['__getattr__']
except KeyError:
pass
else:
dict['__usergetattr__'] = ga
del dict['__getattr__']
self.__name__ = name
self.__bases__ = bases
self.__realdict__ = dict
self.__inited = 1
try:
ga = dict['__getattr__']
except KeyError:
pass
else:
dict['__usergetattr__'] = ga
del dict['__getattr__']
self.__name__ = name
self.__bases__ = bases
self.__realdict__ = dict
self.__inited = 1
def __getattr__(self, name):
try:
return self.__realdict__[name]
except KeyError:
for base in self.__bases__:
try:
return base.__getattr__(name)
except AttributeError:
pass
raise AttributeError, name
try:
return self.__realdict__[name]
except KeyError:
for base in self.__bases__:
try:
return base.__getattr__(name)
except AttributeError:
pass
raise AttributeError, name
def __setattr__(self, name, value):
if not self.__inited:
self.__dict__[name] = value
else:
self.__realdict__[name] = value
if not self.__inited:
self.__dict__[name] = value
else:
self.__realdict__[name] = value
def __call__(self, *args, **kw):
inst = self.__helper__()
inst.__helperinit__(self)
try:
init = inst.__getattr__('__init__')
except AttributeError:
init = lambda: None
apply(init, args, kw)
return inst
inst = self.__helper__()
inst.__helperinit__(self)
try:
init = inst.__getattr__('__init__')
except AttributeError:
init = lambda: None
apply(init, args, kw)
return inst
Meta = MetaClass('Meta', (), {})
......@@ -95,18 +95,18 @@ Meta = MetaClass('Meta', (), {})
def _test():
class C(Meta):
def __init__(self, *args):
print "__init__, args =", args
def m1(self, x):
print "m1(x=%s)" %`x`
def __init__(self, *args):
print "__init__, args =", args
def m1(self, x):
print "m1(x=%s)" %`x`
print C
x = C()
print x
x.m1(12)
class D(C):
def __getattr__(self, name):
if name[:2] == '__': raise AttributeError, name
return "getattr:%s" % name
def __getattr__(self, name):
if name[:2] == '__': raise AttributeError, name
return "getattr:%s" % name
x = D()
print x.foo
print x._foo
......
This diff is collapsed.
......@@ -20,38 +20,38 @@ class TraceMetaClass:
__inited = 0
def __init__(self, name, bases, dict):
self.__name__ = name
self.__bases__ = bases
self.__dict = dict
# XXX Can't define __dict__, alas
self.__inited = 1
self.__name__ = name
self.__bases__ = bases
self.__dict = dict
# XXX Can't define __dict__, alas
self.__inited = 1
def __getattr__(self, name):
try:
return self.__dict[name]
except KeyError:
for base in self.__bases__:
try:
return base.__getattr__(name)
except AttributeError:
pass
raise AttributeError, name
try:
return self.__dict[name]
except KeyError:
for base in self.__bases__:
try:
return base.__getattr__(name)
except AttributeError:
pass
raise AttributeError, name
def __setattr__(self, name, value):
if not self.__inited:
self.__dict__[name] = value
else:
self.__dict[name] = value
if not self.__inited:
self.__dict__[name] = value
else:
self.__dict[name] = value
def __call__(self, *args, **kw):
inst = TracingInstance()
inst.__meta_init__(self)
try:
init = inst.__getattr__('__init__')
except AttributeError:
init = lambda: None
apply(init, args, kw)
return inst
inst = TracingInstance()
inst.__meta_init__(self)
try:
init = inst.__getattr__('__init__')
except AttributeError:
init = lambda: None
apply(init, args, kw)
return inst
__trace_output__ = None
......@@ -59,52 +59,52 @@ class TracingInstance:
"""Helper class to represent an instance of a tracing class."""
def __trace_call__(self, fp, fmt, *args):
fp.write((fmt+'\n') % args)
fp.write((fmt+'\n') % args)
def __meta_init__(self, klass):
self.__class = klass
self.__class = klass
def __getattr__(self, name):
# Invoked for any attr not in the instance's __dict__
try:
raw = self.__class.__getattr__(name)
except AttributeError:
raise AttributeError, name
if type(raw) != types.FunctionType:
return raw
# It's a function
fullname = self.__class.__name__ + "." + name
if not self.__trace_output__ or name == '__trace_call__':
return NotTracingWrapper(fullname, raw, self)
else:
return TracingWrapper(fullname, raw, self)
# Invoked for any attr not in the instance's __dict__
try:
raw = self.__class.__getattr__(name)
except AttributeError:
raise AttributeError, name
if type(raw) != types.FunctionType:
return raw
# It's a function
fullname = self.__class.__name__ + "." + name
if not self.__trace_output__ or name == '__trace_call__':
return NotTracingWrapper(fullname, raw, self)
else:
return TracingWrapper(fullname, raw, self)
class NotTracingWrapper:
def __init__(self, name, func, inst):
self.__name__ = name
self.func = func
self.inst = inst
self.__name__ = name
self.func = func
self.inst = inst
def __call__(self, *args, **kw):
return apply(self.func, (self.inst,) + args, kw)
return apply(self.func, (self.inst,) + args, kw)
class TracingWrapper(NotTracingWrapper):
def __call__(self, *args, **kw):
self.inst.__trace_call__(self.inst.__trace_output__,
"calling %s, inst=%s, args=%s, kw=%s",
self.__name__, self.inst, args, kw)
try:
rv = apply(self.func, (self.inst,) + args, kw)
except:
t, v, tb = sys.exc_info()
self.inst.__trace_call__(self.inst.__trace_output__,
"returning from %s with exception %s: %s",
self.__name__, t, v)
raise t, v, tb
else:
self.inst.__trace_call__(self.inst.__trace_output__,
"returning from %s with value %s",
self.__name__, rv)
return rv
self.inst.__trace_call__(self.inst.__trace_output__,
"calling %s, inst=%s, args=%s, kw=%s",
self.__name__, self.inst, args, kw)
try:
rv = apply(self.func, (self.inst,) + args, kw)
except:
t, v, tb = sys.exc_info()
self.inst.__trace_call__(self.inst.__trace_output__,
"returning from %s with exception %s: %s",
self.__name__, t, v)
raise t, v, tb
else:
self.inst.__trace_call__(self.inst.__trace_output__,
"returning from %s with value %s",
self.__name__, rv)
return rv
Traced = TraceMetaClass('Traced', (), {'__trace_output__': None})
......@@ -112,13 +112,13 @@ Traced = TraceMetaClass('Traced', (), {'__trace_output__': None})
def _test():
global C, D
class C(Traced):
def __init__(self, x=0): self.x = x
def m1(self, x): self.x = x
def m2(self, y): return self.x + y
__trace_output__ = sys.stdout
def __init__(self, x=0): self.x = x
def m1(self, x): self.x = x
def m2(self, y): return self.x + y
__trace_output__ = sys.stdout
class D(C):
def m2(self, y): print "D.m2(%s)" % `y`; return C.m2(self, y)
__trace_output__ = None
def m2(self, y): print "D.m2(%s)" % `y`; return C.m2(self, y)
__trace_output__ = None
x = C(4321)
print x
print x.x
......
......@@ -14,7 +14,7 @@ def get_docs(fileName):
"""Retrieve information from the parse tree of a source file.
fileName
Name of the file to read Python source code from.
Name of the file to read Python source code from.
"""
source = open(fileName).read()
import os
......@@ -30,86 +30,86 @@ class SuiteInfoBase:
_name = ''
def __init__(self, tree = None):
self._class_info = {}
self._function_info = {}
if tree:
self._extract_info(tree)
self._class_info = {}
self._function_info = {}
if tree:
self._extract_info(tree)
def _extract_info(self, tree):
# extract docstring
if len(tree) == 2:
found, vars = match(DOCSTRING_STMT_PATTERN[1], tree[1])
else:
found, vars = match(DOCSTRING_STMT_PATTERN, tree[3])
if found:
self._docstring = eval(vars['docstring'])
# discover inner definitions
for node in tree[1:]:
found, vars = match(COMPOUND_STMT_PATTERN, node)
if found:
cstmt = vars['compound']
if cstmt[0] == symbol.funcdef:
name = cstmt[2][1]
self._function_info[name] = FunctionInfo(cstmt)
elif cstmt[0] == symbol.classdef:
name = cstmt[2][1]
self._class_info[name] = ClassInfo(cstmt)
# extract docstring
if len(tree) == 2:
found, vars = match(DOCSTRING_STMT_PATTERN[1], tree[1])
else:
found, vars = match(DOCSTRING_STMT_PATTERN, tree[3])
if found:
self._docstring = eval(vars['docstring'])
# discover inner definitions
for node in tree[1:]:
found, vars = match(COMPOUND_STMT_PATTERN, node)
if found:
cstmt = vars['compound']
if cstmt[0] == symbol.funcdef:
name = cstmt[2][1]
self._function_info[name] = FunctionInfo(cstmt)
elif cstmt[0] == symbol.classdef:
name = cstmt[2][1]
self._class_info[name] = ClassInfo(cstmt)
def get_docstring(self):
return self._docstring
return self._docstring
def get_name(self):
return self._name
return self._name
def get_class_names(self):
return self._class_info.keys()
return self._class_info.keys()
def get_class_info(self, name):
return self._class_info[name]
return self._class_info[name]
def __getitem__(self, name):
try:
return self._class_info[name]
except KeyError:
return self._function_info[name]
try:
return self._class_info[name]
except KeyError:
return self._function_info[name]
class SuiteFuncInfo:
# Mixin class providing access to function names and info.
def get_function_names(self):
return self._function_info.keys()
return self._function_info.keys()
def get_function_info(self, name):
return self._function_info[name]
return self._function_info[name]
class FunctionInfo(SuiteInfoBase, SuiteFuncInfo):
def __init__(self, tree = None):
self._name = tree[2][1]
SuiteInfoBase.__init__(self, tree and tree[-1] or None)
self._name = tree[2][1]
SuiteInfoBase.__init__(self, tree and tree[-1] or None)
class ClassInfo(SuiteInfoBase):
def __init__(self, tree = None):
self._name = tree[2][1]
SuiteInfoBase.__init__(self, tree and tree[-1] or None)
self._name = tree[2][1]
SuiteInfoBase.__init__(self, tree and tree[-1] or None)
def get_method_names(self):
return self._function_info.keys()
return self._function_info.keys()
def get_method_info(self, name):
return self._function_info[name]
return self._function_info[name]
class ModuleInfo(SuiteInfoBase, SuiteFuncInfo):
def __init__(self, tree = None, name = "<string>"):
self._name = name
SuiteInfoBase.__init__(self, tree)
if tree:
found, vars = match(DOCSTRING_STMT_PATTERN, tree[1])
if found:
self._docstring = vars["docstring"]
self._name = name
SuiteInfoBase.__init__(self, tree)
if tree:
found, vars = match(DOCSTRING_STMT_PATTERN, tree[1])
if found:
self._docstring = vars["docstring"]
from types import ListType, TupleType
......@@ -118,14 +118,14 @@ def match(pattern, data, vars=None):
"""Match `data' to `pattern', with variable extraction.
pattern
Pattern to match against, possibly containing variables.
Pattern to match against, possibly containing variables.
data
Data to be checked and against which variables are extracted.
Data to be checked and against which variables are extracted.
vars
Dictionary of variables which have already been found. If not
provided, an empty dictionary is created.
Dictionary of variables which have already been found. If not
provided, an empty dictionary is created.
The `pattern' value may contain variables of the form ['varname'] which
are allowed to match anything. The value that is matched is returned as
......@@ -138,18 +138,18 @@ def match(pattern, data, vars=None):
values.
"""
if vars is None:
vars = {}
if type(pattern) is ListType: # 'variables' are ['varname']
vars[pattern[0]] = data
return 1, vars
vars = {}
if type(pattern) is ListType: # 'variables' are ['varname']
vars[pattern[0]] = data
return 1, vars
if type(pattern) is not TupleType:
return (pattern == data), vars
return (pattern == data), vars
if len(data) != len(pattern):
return 0, vars
return 0, vars
for pattern, data in map(None, pattern, data):
same, vars = match(pattern, data, vars)
if not same:
break
same, vars = match(pattern, data, vars)
if not same:
break
return same, vars
......@@ -172,21 +172,21 @@ DOCSTRING_STMT_PATTERN = (
(symbol.small_stmt,
(symbol.expr_stmt,
(symbol.testlist,
(symbol.test,
(symbol.and_test,
(symbol.not_test,
(symbol.comparison,
(symbol.expr,
(symbol.xor_expr,
(symbol.and_expr,
(symbol.shift_expr,
(symbol.arith_expr,
(symbol.term,
(symbol.factor,
(symbol.power,
(symbol.atom,
(token.STRING, ['docstring'])
)))))))))))))))),
(symbol.test,
(symbol.and_test,
(symbol.not_test,
(symbol.comparison,
(symbol.expr,
(symbol.xor_expr,
(symbol.and_expr,
(symbol.shift_expr,
(symbol.arith_expr,
(symbol.term,
(symbol.factor,
(symbol.power,
(symbol.atom,
(token.STRING, ['docstring'])
)))))))))))))))),
(token.NEWLINE, '')
))
......
......@@ -9,18 +9,18 @@ class Simple:
"This class does very little."
def method(self):
"This method does almost nothing."
return 1
"This method does almost nothing."
return 1
class Nested:
"This is a nested class."
"This is a nested class."
def nested_method(self):
"Method of Nested class."
def nested_function():
"Function in method of Nested class."
pass
return nested_function
def nested_method(self):
"Method of Nested class."
def nested_function():
"Function in method of Nested class."
pass
return nested_function
def function():
"This function lives at the module level."
......
......@@ -11,24 +11,24 @@ def testChunk(t, fileName):
global _numFailed
print '----', fileName,
try:
ast = parser.suite(t)
tup = parser.ast2tuple(ast)
# this discards the first AST; a huge memory savings when running
# against a large source file like Tkinter.py.
ast = None
new = parser.tuple2ast(tup)
ast = parser.suite(t)
tup = parser.ast2tuple(ast)
# this discards the first AST; a huge memory savings when running
# against a large source file like Tkinter.py.
ast = None
new = parser.tuple2ast(tup)
except parser.ParserError, err:
print
print 'parser module raised exception on input file', fileName + ':'
traceback.print_exc()
_numFailed = _numFailed + 1
print
print 'parser module raised exception on input file', fileName + ':'
traceback.print_exc()
_numFailed = _numFailed + 1
else:
if tup != parser.ast2tuple(new):
print
print 'parser module failed on input file', fileName
_numFailed = _numFailed + 1
else:
print 'o.k.'
if tup != parser.ast2tuple(new):
print
print 'parser module failed on input file', fileName
_numFailed = _numFailed + 1
else:
print 'o.k.'
def testFile(fileName):
t = open(fileName).read()
......@@ -38,8 +38,8 @@ def test():
import sys
args = sys.argv[1:]
if not args:
import glob
args = glob.glob("*.py")
import glob
args = glob.glob("*.py")
map(testFile, args)
sys.exit(_numFailed != 0)
......
......@@ -31,147 +31,147 @@ import rcslib
class DirSupport:
def __init__(self):
self._dirstack = []
self._dirstack = []
def __del__(self):
self._close()
self._close()
def _close(self):
while self._dirstack:
self.back()
while self._dirstack:
self.back()
def pwd(self):
return os.getcwd()
return os.getcwd()
def cd(self, name):
save = os.getcwd()
os.chdir(name)
self._dirstack.append(save)
save = os.getcwd()
os.chdir(name)
self._dirstack.append(save)
def back(self):
if not self._dirstack:
raise os.error, "empty directory stack"
dir = self._dirstack[-1]
os.chdir(dir)
del self._dirstack[-1]
if not self._dirstack:
raise os.error, "empty directory stack"
dir = self._dirstack[-1]
os.chdir(dir)
del self._dirstack[-1]
def listsubdirs(self, pat = None):
files = os.listdir(os.curdir)
files = filter(os.path.isdir, files)
return self._filter(files, pat)
files = os.listdir(os.curdir)
files = filter(os.path.isdir, files)
return self._filter(files, pat)
def isdir(self, name):
return os.path.isdir(name)
return os.path.isdir(name)
def mkdir(self, name):
os.mkdir(name, 0777)
os.mkdir(name, 0777)
def rmdir(self, name):
os.rmdir(name)
os.rmdir(name)
class RCSProxyLocal(rcslib.RCS, DirSupport):
def __init__(self):
rcslib.RCS.__init__(self)
DirSupport.__init__(self)
rcslib.RCS.__init__(self)
DirSupport.__init__(self)
def __del__(self):
DirSupport.__del__(self)
rcslib.RCS.__del__(self)
DirSupport.__del__(self)
rcslib.RCS.__del__(self)
def sumlist(self, list = None):
return self._list(self.sum, list)
return self._list(self.sum, list)
def sumdict(self, list = None):
return self._dict(self.sum, list)
return self._dict(self.sum, list)
def sum(self, name_rev):
f = self._open(name_rev)
BUFFERSIZE = 1024*8
sum = md5.new()
while 1:
buffer = f.read(BUFFERSIZE)
if not buffer:
break
sum.update(buffer)
self._closepipe(f)
return sum.digest()
f = self._open(name_rev)
BUFFERSIZE = 1024*8
sum = md5.new()
while 1:
buffer = f.read(BUFFERSIZE)
if not buffer:
break
sum.update(buffer)
self._closepipe(f)
return sum.digest()
def get(self, name_rev):
f = self._open(name_rev)
data = f.read()
self._closepipe(f)
return data
f = self._open(name_rev)
data = f.read()
self._closepipe(f)
return data
def put(self, name_rev, data, message=None):
name, rev = self._unmangle(name_rev)
f = open(name, 'w')
f.write(data)
f.close()
self.checkin(name_rev, message)
self._remove(name)
name, rev = self._unmangle(name_rev)
f = open(name, 'w')
f.write(data)
f.close()
self.checkin(name_rev, message)
self._remove(name)
def _list(self, function, list = None):
"""INTERNAL: apply FUNCTION to all files in LIST.
"""INTERNAL: apply FUNCTION to all files in LIST.
Return a list of the results.
Return a list of the results.
The list defaults to all files in the directory if None.
The list defaults to all files in the directory if None.
"""
if list is None:
list = self.listfiles()
res = []
for name in list:
try:
res.append((name, function(name)))
except (os.error, IOError):
res.append((name, None))
return res
"""
if list is None:
list = self.listfiles()
res = []
for name in list:
try:
res.append((name, function(name)))
except (os.error, IOError):
res.append((name, None))
return res
def _dict(self, function, list = None):
"""INTERNAL: apply FUNCTION to all files in LIST.
"""INTERNAL: apply FUNCTION to all files in LIST.
Return a dictionary mapping files to results.
Return a dictionary mapping files to results.
The list defaults to all files in the directory if None.
The list defaults to all files in the directory if None.
"""
if list is None:
list = self.listfiles()
dict = {}
for name in list:
try:
dict[name] = function(name)
except (os.error, IOError):
pass
return dict
"""
if list is None:
list = self.listfiles()
dict = {}
for name in list:
try:
dict[name] = function(name)
except (os.error, IOError):
pass
return dict
class RCSProxyServer(RCSProxyLocal, server.SecureServer):
def __init__(self, address, verbose = server.VERBOSE):
RCSProxyLocal.__init__(self)
server.SecureServer.__init__(self, address, verbose)
RCSProxyLocal.__init__(self)
server.SecureServer.__init__(self, address, verbose)
def _close(self):
server.SecureServer._close(self)
RCSProxyLocal._close(self)
server.SecureServer._close(self)
RCSProxyLocal._close(self)
def _serve(self):
server.SecureServer._serve(self)
# Retreat into start directory
while self._dirstack: self.back()
server.SecureServer._serve(self)
# Retreat into start directory
while self._dirstack: self.back()
def test_server():
import string
import sys
if sys.argv[1:]:
port = string.atoi(sys.argv[1])
port = string.atoi(sys.argv[1])
else:
port = 4127
port = 4127
proxy = RCSProxyServer(('', port))
proxy._serverloop()
......@@ -179,19 +179,19 @@ def test_server():
def test():
import sys
if not sys.argv[1:] or sys.argv[1] and sys.argv[1][0] in '0123456789':
test_server()
sys.exit(0)
test_server()
sys.exit(0)
proxy = RCSProxyLocal()
what = sys.argv[1]
if hasattr(proxy, what):
attr = getattr(proxy, what)
if callable(attr):
print apply(attr, tuple(sys.argv[2:]))
else:
print `attr`
attr = getattr(proxy, what)
if callable(attr):
print apply(attr, tuple(sys.argv[2:]))
else:
print `attr`
else:
print "%s: no such attribute" % what
sys.exit(2)
print "%s: no such attribute" % what
sys.exit(2)
if __name__ == '__main__':
......
......@@ -15,25 +15,25 @@ def main():
opts, args = getopt.getopt(args, 'p:')
prefix = ''
for o, a in opts:
if p == '-p': prefix = a
if p == '-p': prefix = a
f = sys.stdin
allrevs = []
while 1:
file = getnextfile(f)
if not file: break
revs = []
while 1:
rev = getnextrev(f, file)
if not rev:
break
revs.append(rev)
if revs:
allrevs[len(allrevs):] = revs
file = getnextfile(f)
if not file: break
revs = []
while 1:
rev = getnextrev(f, file)
if not rev:
break
revs.append(rev)
if revs:
allrevs[len(allrevs):] = revs
allrevs.sort()
allrevs.reverse()
for rev in allrevs:
formatrev(rev, prefix)
formatrev(rev, prefix)
parsedateprog = regex.compile(
'^date: \([0-9]+\)/\([0-9]+\)/\([0-9]+\) ' +
......@@ -48,46 +48,46 @@ authormap = {
def formatrev(rev, prefix):
dateline, file, revline, log = rev
if parsedateprog.match(dateline) >= 0:
fields = parsedateprog.group(1, 2, 3, 4, 5, 6)
author = parsedateprog.group(7)
if authormap.has_key(author): author = authormap[author]
tfields = map(string.atoi, fields) + [0, 0, 0]
tfields[5] = tfields[5] - time.timezone
t = time.mktime(tuple(tfields))
print time.ctime(t), '', author
words = string.split(log)
words[:0] = ['*', prefix + file + ':']
maxcol = 72-8
col = maxcol
for word in words:
if col > 0 and col + len(word) >= maxcol:
print
print '\t' + word,
col = -1
else:
print word,
col = col + 1 + len(word)
print
print
fields = parsedateprog.group(1, 2, 3, 4, 5, 6)
author = parsedateprog.group(7)
if authormap.has_key(author): author = authormap[author]
tfields = map(string.atoi, fields) + [0, 0, 0]
tfields[5] = tfields[5] - time.timezone
t = time.mktime(tuple(tfields))
print time.ctime(t), '', author
words = string.split(log)
words[:0] = ['*', prefix + file + ':']
maxcol = 72-8
col = maxcol
for word in words:
if col > 0 and col + len(word) >= maxcol:
print
print '\t' + word,
col = -1
else:
print word,
col = col + 1 + len(word)
print
print
startprog = regex.compile("^Working file: \(.*\)$")
def getnextfile(f):
while 1:
line = f.readline()
if not line: return None
if startprog.match(line) >= 0:
file = startprog.group(1)
# Skip until first revision
while 1:
line = f.readline()
if not line: return None
if line[:10] == '='*10: return None
if line[:10] == '-'*10: break
## print "Skipped", line,
return file
## else:
## print "Ignored", line,
line = f.readline()
if not line: return None
if startprog.match(line) >= 0:
file = startprog.group(1)
# Skip until first revision
while 1:
line = f.readline()
if not line: return None
if line[:10] == '='*10: return None
if line[:10] == '-'*10: break
## print "Skipped", line,
return file
## else:
## print "Ignored", line,
def getnextrev(f, file):
# This is called when we are positioned just after a '---' separator
......@@ -95,14 +95,14 @@ def getnextrev(f, file):
dateline = f.readline()
log = ''
while 1:
line = f.readline()
if not line: break
if line[:10] == '='*10:
# Ignore the *last* log entry for each file since it
# is the revision since which we are logging.
return None
if line[:10] == '-'*10: break
log = log + line
line = f.readline()
if not line: break
if line[:10] == '='*10:
# Ignore the *last* log entry for each file since it
# is the revision since which we are logging.
return None
if line[:10] == '-'*10: break
log = log + line
return dateline, file, revline, log
if __name__ == '__main__':
......
......@@ -22,8 +22,8 @@ import client
class RCSProxyClient(client.SecureClient):
def __init__(self, address, verbose = client.VERBOSE):
client.SecureClient.__init__(self, address, verbose)
def __init__(self, address, verbose = client.VERBOSE):
client.SecureClient.__init__(self, address, verbose)
def openrcsclient(opts = []):
......
This diff is collapsed.
......@@ -14,30 +14,30 @@ can log in on your machine. Use with caution!
import sys, os, string, getopt, thread, socket, traceback
PORT = 4000 # Default port
PORT = 4000 # Default port
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "")
if len(args) > 1:
raise getopt.error, "Too many arguments."
opts, args = getopt.getopt(sys.argv[1:], "")
if len(args) > 1:
raise getopt.error, "Too many arguments."
except getopt.error, msg:
usage(msg)
usage(msg)
for o, a in opts:
pass
pass
if args:
try:
port = string.atoi(args[0])
except ValueError, msg:
usage(msg)
try:
port = string.atoi(args[0])
except ValueError, msg:
usage(msg)
else:
port = PORT
port = PORT
main_thread(port)
def usage(msg=None):
sys.stdout = sys.stderr
if msg:
print msg
print msg
print "\n", __doc__,
sys.exit(2)
......@@ -47,18 +47,18 @@ def main_thread(port):
sock.listen(5)
print "Listening on port", port, "..."
while 1:
(conn, addr) = sock.accept()
if addr[0] != conn.getsockname()[0]:
conn.close()
print "Refusing connection from non-local host", addr[0], "."
continue
thread.start_new_thread(service_thread, (conn, addr))
del conn, addr
(conn, addr) = sock.accept()
if addr[0] != conn.getsockname()[0]:
conn.close()
print "Refusing connection from non-local host", addr[0], "."
continue
thread.start_new_thread(service_thread, (conn, addr))
del conn, addr
def service_thread(conn, addr):
(caddr, cport) = addr
print "Thread %s has connection from %s.\n" % (str(thread.get_ident()),
caddr),
caddr),
stdin = conn.makefile("r")
stdout = conn.makefile("w", 0)
run_interpreter(stdin, stdout)
......@@ -67,57 +67,57 @@ def service_thread(conn, addr):
def run_interpreter(stdin, stdout):
globals = {}
try:
str(sys.ps1)
str(sys.ps1)
except:
sys.ps1 = ">>> "
sys.ps1 = ">>> "
source = ""
while 1:
stdout.write(sys.ps1)
line = stdin.readline()
if line[:2] == '\377\354':
line = ""
if not line and not source:
break
if line[-2:] == '\r\n':
line = line[:-2] + '\n'
source = source + line
try:
code = compile_command(source)
except SyntaxError, err:
source = ""
traceback.print_exception(SyntaxError, err, None, file=stdout)
continue
if not code:
continue
source = ""
try:
run_command(code, stdin, stdout, globals)
except SystemExit, how:
if how:
try:
how = str(how)
except:
how = ""
stdout.write("Exit %s\n" % how)
break
stdout.write(sys.ps1)
line = stdin.readline()
if line[:2] == '\377\354':
line = ""
if not line and not source:
break
if line[-2:] == '\r\n':
line = line[:-2] + '\n'
source = source + line
try:
code = compile_command(source)
except SyntaxError, err:
source = ""
traceback.print_exception(SyntaxError, err, None, file=stdout)
continue
if not code:
continue
source = ""
try:
run_command(code, stdin, stdout, globals)
except SystemExit, how:
if how:
try:
how = str(how)
except:
how = ""
stdout.write("Exit %s\n" % how)
break
stdout.write("\nGoodbye.\n")
def run_command(code, stdin, stdout, globals):
save = sys.stdin, sys.stdout, sys.stderr
try:
sys.stdout = sys.stderr = stdout
sys.stdin = stdin
try:
exec code in globals
except SystemExit, how:
raise SystemExit, how, sys.exc_info()[2]
except:
type, value, tb = sys.exc_info()
if tb: tb = tb.tb_next
traceback.print_exception(type, value, tb)
del tb
finally:
sys.stdin, sys.stdout, sys.stderr = save
save = sys.stdin, sys.stdout, sys.stderr
try:
sys.stdout = sys.stderr = stdout
sys.stdin = stdin
try:
exec code in globals
except SystemExit, how:
raise SystemExit, how, sys.exc_info()[2]
except:
type, value, tb = sys.exc_info()
if tb: tb = tb.tb_next
traceback.print_exception(type, value, tb)
del tb
finally:
sys.stdin, sys.stdout, sys.stderr = save
from code import compile_command
......
......@@ -96,22 +96,22 @@ class NFSUnpacker(MountUnpacker):
return status, attributes
def unpack_fattr(self):
type = self.unpack_enum()
mode = self.unpack_uint()
nlink = self.unpack_uint()
uid = self.unpack_uint()
gid = self.unpack_uint()
size = self.unpack_uint()
blocksize = self.unpack_uint()
rdev = self.unpack_uint()
blocks = self.unpack_uint()
fsid = self.unpack_uint()
fileid = self.unpack_uint()
atime = self.unpack_timeval()
mtime = self.unpack_timeval()
ctime = self.unpack_timeval()
return (type, mode, nlink, uid, gid, size, blocksize, \
rdev, blocks, fsid, fileid, atime, mtime, ctime)
type = self.unpack_enum()
mode = self.unpack_uint()
nlink = self.unpack_uint()
uid = self.unpack_uint()
gid = self.unpack_uint()
size = self.unpack_uint()
blocksize = self.unpack_uint()
rdev = self.unpack_uint()
blocks = self.unpack_uint()
fsid = self.unpack_uint()
fileid = self.unpack_uint()
atime = self.unpack_timeval()
mtime = self.unpack_timeval()
ctime = self.unpack_timeval()
return (type, mode, nlink, uid, gid, size, blocksize, \
rdev, blocks, fsid, fileid, atime, mtime, ctime)
def unpack_timeval(self):
secs = self.unpack_uint()
......
......@@ -53,44 +53,45 @@ def main():
bytype = {}
lineno = 0
try:
while 1:
line = f.readline()
if not line: break
lineno = lineno + 1
if search and string.find(line, search) < 0:
continue
if prog.match(line) < 0:
print 'Bad line', lineno, ':', `line`
continue
items = prog.group(1, 2, 3, 4, 5, 6)
logtime, loguser, loghost, logfile, logbytes, logxxx2 = items
## print logtime
## print '-->', loguser
## print '--> -->', loghost
## print '--> --> -->', logfile
## print '--> --> --> -->', logbytes
## print '--> --> --> --> -->', logxxx2
## for i in logtime, loghost, logbytes, logxxx2:
## if '!' in i: print '???', i
add(bydate, logtime[-4:] + ' ' + logtime[:6], items)
add(bytime, logtime[7:9] + ':00-59', items)
direction, logfile = logfile[0], logfile[1:]
# The real path probably starts at the last //...
while 1:
i = string.find(logfile, '//')
if i < 0: break
logfile = logfile[i+1:]
add(byfile, logfile + ' ' + direction, items)
logdir = os.path.dirname(logfile)
line = f.readline()
if not line: break
lineno = lineno + 1
if search and string.find(line, search) < 0:
continue
if prog.match(line) < 0:
print 'Bad line', lineno, ':', `line`
continue
items = prog.group(1, 2, 3, 4, 5, 6)
(logtime, loguser, loghost, logfile, logbytes,
logxxx2) = items
## print logtime
## print '-->', loguser
## print '--> -->', loghost
## print '--> --> -->', logfile
## print '--> --> --> -->', logbytes
## print '--> --> --> --> -->', logxxx2
## for i in logtime, loghost, logbytes, logxxx2:
## if '!' in i: print '???', i
add(bydate, logtime[-4:] + ' ' + logtime[:6], items)
add(bytime, logtime[7:9] + ':00-59', items)
direction, logfile = logfile[0], logfile[1:]
# The real path probably starts at the last //...
while 1:
i = string.find(logfile, '//')
if i < 0: break
logfile = logfile[i+1:]
add(byfile, logfile + ' ' + direction, items)
logdir = os.path.dirname(logfile)
## logdir = os.path.normpath(logdir) + '/.'
while 1:
add(bydir, logdir + ' ' + direction, items)
dirhead = os.path.dirname(logdir)
if dirhead == logdir: break
logdir = dirhead
add(byhost, loghost, items)
add(byuser, loguser, items)
add(bytype, direction, items)
while 1:
add(bydir, logdir + ' ' + direction, items)
dirhead = os.path.dirname(logdir)
if dirhead == logdir: break
logdir = dirhead
add(byhost, loghost, items)
add(byuser, loguser, items)
add(bytype, direction, items)
except KeyboardInterrupt:
print 'Interrupted at line', lineno
show(bytype, 'by transfer direction', maxitems)
......
......@@ -96,11 +96,11 @@ sublistsize = 4
#######################################################################
for dir in os.curdir, os.environ['HOME']:
rcfile = os.path.join(dir, '.newslistrc.py')
if os.path.exists(rcfile):
print rcfile
execfile(rcfile)
break
rcfile = os.path.join(dir, '.newslistrc.py')
if os.path.exists(rcfile):
print rcfile
execfile(rcfile)
break
from nntplib import NNTP
from stat import *
......@@ -120,8 +120,8 @@ page = os.path.join(topdir,pagedir)
def addtotree(tree, groups):
print 'Updating tree...'
for i in groups:
parts = string.splitfields(i,'.')
makeleaf(tree, parts)
parts = string.splitfields(i,'.')
makeleaf(tree, parts)
# Makeleaf makes a leaf and the branch leading to it if necessary
def makeleaf(tree,path):
......@@ -135,7 +135,7 @@ def makeleaf(tree,path):
if l > 1:
makeleaf(tree[j],path[1:])
# Then the bits for outputting trees as pages ----------------
# Then the bits for outputting trees as pages ----------------
# Createpage creates an HTML file named <root>.html containing links
# to those groups beginning with <root>.
......@@ -177,24 +177,24 @@ def printtree(f, tree, indent, p):
if l > 1:
kl.sort()
if indent > 0:
# Create a sub-list
f.write('<LI>'+p[1:]+'\n<UL>')
# Create a sub-list
f.write('<LI>'+p[1:]+'\n<UL>')
else:
# Create a main list
f.write('<UL>')
# Create a main list
f.write('<UL>')
indent = indent + 1
for i in kl:
if i == '.':
# Output a newsgroup
f.write('<LI><A HREF="news:' + p[1:] + '">'+ p[1:] + '</A> ')
if desc.has_key(p[1:]):
f.write(' <I>'+desc[p[1:]]+'</I>\n')
else:
f.write('\n')
# Output a newsgroup
f.write('<LI><A HREF="news:' + p[1:] + '">'+ p[1:] + '</A> ')
if desc.has_key(p[1:]):
f.write(' <I>'+desc[p[1:]]+'</I>\n')
else:
f.write('\n')
else:
# Output a hierarchy
printtree(f,tree[i], indent, p+'.'+i)
# Output a hierarchy
printtree(f,tree[i], indent, p+'.'+i)
if l > 1:
f.write('\n</UL>')
......@@ -209,7 +209,7 @@ def readdesc(descfile):
desc = {}
if descfile == '':
return
return
try:
d = open(descfile, 'r')
......@@ -221,12 +221,12 @@ def readdesc(descfile):
while l != '':
bits = string.split(l)
try:
grp = bits[0]
dsc = string.join(bits[1:])
if len(dsc)>1:
desc[grp] = dsc
grp = bits[0]
dsc = string.join(bits[1:])
if len(dsc)>1:
desc[grp] = dsc
except (IndexError):
pass
pass
l = d.readline()
# Check that ouput directory exists, ------------------------------
......@@ -237,14 +237,14 @@ def checkopdir(pagedir):
print 'Directory '+pagedir+' does not exist.'
print 'Shall I create it for you? (y/n)'
if sys.stdin.readline()[0] == 'y':
try:
os.mkdir(pagedir,0777)
except:
print 'Sorry - failed!'
sys.exit(1)
try:
os.mkdir(pagedir,0777)
except:
print 'Sorry - failed!'
sys.exit(1)
else:
print 'OK. Exiting.'
sys.exit(1)
print 'OK. Exiting.'
sys.exit(1)
# Read and write current local tree ----------------------------------
......@@ -252,19 +252,19 @@ def readlocallist(treefile):
print 'Reading current local group list...'
tree = {}
try:
treetime = time.localtime(os.stat(treefile)[ST_MTIME])
treetime = time.localtime(os.stat(treefile)[ST_MTIME])
except:
print '\n*** Failed to open local group cache '+treefile
print 'If this is the first time you have run newslist, then'
print 'use the -a option to create it.'
sys.exit(1)
print '\n*** Failed to open local group cache '+treefile
print 'If this is the first time you have run newslist, then'
print 'use the -a option to create it.'
sys.exit(1)
treedate = '%02d%02d%02d' % (treetime[0] % 100 ,treetime[1], treetime[2])
try:
dump = open(treefile,'r')
tree = marshal.load(dump)
dump.close()
dump = open(treefile,'r')
tree = marshal.load(dump)
dump.close()
except (IOError):
print 'Cannot open local group list ' + treefile
print 'Cannot open local group list ' + treefile
return (tree, treedate)
def writelocallist(treefile, tree):
......@@ -291,9 +291,9 @@ def getallgroups(server):
for i in info:
grpname = string.split(i[0])[0]
if skipempty and string.atoi(i[1]) < string.atoi(i[2]):
print grpname+' ',
print grpname+' ',
else:
groups.append(grpname)
groups.append(grpname)
print '\n'
if skipempty:
print '(End of empty groups)'
......@@ -326,9 +326,9 @@ def main():
try:
print 'Connecting to '+newshost+'...'
if sys.version[0] == '0':
s = NNTP.init(newshost)
s = NNTP.init(newshost)
else:
s = NNTP(newshost)
s = NNTP(newshost)
connected = 1
except (nntplib.error_temp, nntplib.error_perm), x:
print 'Error connecting to host:', x
......@@ -346,7 +346,7 @@ def main():
(tree, treedate) = readlocallist(treefile)
if connected:
groups = getnewgroups(s, treedate)
groups = getnewgroups(s, treedate)
if connected:
addtotree(tree, groups)
......
......@@ -217,108 +217,108 @@ commands['\b'] = WC_BACKSPACE
commands['\t'] = WC_TAB
#
def getevent():
while 1:
#
# Get next event from the processed queue, if any
#
if G.queue:
event = G.queue[0]
del G.queue[0]
#print 'getevent from queue -->', event
return event
#
# Get next event from the draw queue, if any,
# but only if there is nothing in the system queue.
#
if G.drawqueue and not gl.qtest():
win = G.drawqueue[0]
del G.drawqueue[0]
gl.winset(win._gid)
gl.color(win._bg)
gl.clear()
event = WE_DRAW, win, win._area
#print 'getevent from drawqueue -->', event
return event
#
# Get next event from system queue, blocking if necessary
# until one is available.
# Some cases immediately return the event, others do nothing
# or append one or more events to the processed queue.
#
dev, val = gl.qread()
#
if dev == REDRAW:
win = G.windowmap[`val`]
old_area = win._area
win._fixviewport()
win._needredraw()
if old_area <> win._area:
#print 'getevent --> WE_SIZE'
return WE_SIZE, win, None
elif dev == KEYBD:
if val == 3:
raise KeyboardInterrupt # Control-C in window
character = chr(val)
if commands.has_key(character):
return WE_COMMAND, G.focus, commands[character]
return WE_CHAR, G.focus, character
elif dev == LEFTARROWKEY:
if val:
return WE_COMMAND, G.focus, WC_LEFT
elif dev == RIGHTARROWKEY:
if val:
return WE_COMMAND, G.focus, WC_RIGHT
elif dev == UPARROWKEY:
if val:
return WE_COMMAND, G.focus, WC_UP
elif dev == DOWNARROWKEY:
if val:
return WE_COMMAND, G.focus, WC_DOWN
elif dev in (LEFTALTKEY, RIGHTALTKEY):
if val:
for code in codelist:
gl.qdevice(code)
while 1:
#
# Get next event from the processed queue, if any
#
if G.queue:
event = G.queue[0]
del G.queue[0]
#print 'getevent from queue -->', event
return event
#
# Get next event from the draw queue, if any,
# but only if there is nothing in the system queue.
#
if G.drawqueue and not gl.qtest():
win = G.drawqueue[0]
del G.drawqueue[0]
gl.winset(win._gid)
gl.color(win._bg)
gl.clear()
event = WE_DRAW, win, win._area
#print 'getevent from drawqueue -->', event
return event
#
# Get next event from system queue, blocking if necessary
# until one is available.
# Some cases immediately return the event, others do nothing
# or append one or more events to the processed queue.
#
dev, val = gl.qread()
#
if dev == REDRAW:
win = G.windowmap[`val`]
old_area = win._area
win._fixviewport()
win._needredraw()
if old_area <> win._area:
#print 'getevent --> WE_SIZE'
return WE_SIZE, win, None
elif dev == KEYBD:
if val == 3:
raise KeyboardInterrupt # Control-C in window
character = chr(val)
if commands.has_key(character):
return WE_COMMAND, G.focus, commands[character]
return WE_CHAR, G.focus, character
elif dev == LEFTARROWKEY:
if val:
return WE_COMMAND, G.focus, WC_LEFT
elif dev == RIGHTARROWKEY:
if val:
return WE_COMMAND, G.focus, WC_RIGHT
elif dev == UPARROWKEY:
if val:
return WE_COMMAND, G.focus, WC_UP
elif dev == DOWNARROWKEY:
if val:
return WE_COMMAND, G.focus, WC_DOWN
elif dev in (LEFTALTKEY, RIGHTALTKEY):
if val:
for code in codelist:
gl.qdevice(code)
else:
for code in codelist:
gl.unqdevice(code)
elif dev in codelist:
if val:
event = G.focus._doshortcut(code2key[`dev`])
if event:
return event
elif dev == LEFTMOUSE:
G.mousex = gl.getvaluator(MOUSEX)
G.mousey = gl.getvaluator(MOUSEY)
if val:
type = WE_MOUSE_DOWN
gl.qdevice(MOUSEX)
gl.qdevice(MOUSEY)
else:
type = WE_MOUSE_UP
gl.unqdevice(MOUSEX)
gl.unqdevice(MOUSEY)
return _mouseevent(type)
elif dev == MOUSEX:
G.mousex = val
return _mouseevent(WE_MOUSE_MOVE)
elif dev == MOUSEY:
G.mousey = val
return _mouseevent(WE_MOUSE_MOVE)
elif dev == RIGHTMOUSE: # Menu button press/release
if val: # Press
event = G.focus._domenu()
if event:
return event
elif dev == INPUTCHANGE:
if G.focus:
G.queue.append(WE_DEACTIVATE, G.focus, None)
G.focus = G.windowmap[`val`]
if G.focus:
G.queue.append(WE_ACTIVATE, G.focus, None)
elif dev in (WINSHUT, WINQUIT):
return WE_CLOSE, G.windowmap[`val`], None
else:
for code in codelist:
gl.unqdevice(code)
elif dev in codelist:
if val:
event = G.focus._doshortcut(code2key[`dev`])
if event:
return event
elif dev == LEFTMOUSE:
G.mousex = gl.getvaluator(MOUSEX)
G.mousey = gl.getvaluator(MOUSEY)
if val:
type = WE_MOUSE_DOWN
gl.qdevice(MOUSEX)
gl.qdevice(MOUSEY)
else:
type = WE_MOUSE_UP
gl.unqdevice(MOUSEX)
gl.unqdevice(MOUSEY)
return _mouseevent(type)
elif dev == MOUSEX:
G.mousex = val
return _mouseevent(WE_MOUSE_MOVE)
elif dev == MOUSEY:
G.mousey = val
return _mouseevent(WE_MOUSE_MOVE)
elif dev == RIGHTMOUSE: # Menu button press/release
if val: # Press
event = G.focus._domenu()
if event:
return event
elif dev == INPUTCHANGE:
if G.focus:
G.queue.append(WE_DEACTIVATE, G.focus, None)
G.focus = G.windowmap[`val`]
if G.focus:
G.queue.append(WE_ACTIVATE, G.focus, None)
elif dev in (WINSHUT, WINQUIT):
return WE_CLOSE, G.windowmap[`val`], None
else:
print '*** qread() --> dev:', dev, 'val:', val
print '*** qread() --> dev:', dev, 'val:', val
# Helper routine to construct a mouse (up, move or down) event
#
......
This diff is collapsed.
......@@ -474,16 +474,16 @@ class mrsw:
self.rwOK.release()
def write_to_read(self):
self.rwOK.acquire()
if not self.writing:
raise ValueError, \
'.write_to_read() invoked without an active writer'
self.writing = 0
self.nw = self.nw - 1
self.nr = self.nr + 1
if not self.nw:
self.readOK.broadcast()
self.rwOK.release()
self.rwOK.acquire()
if not self.writing:
raise ValueError, \
'.write_to_read() invoked without an active writer'
self.writing = 0
self.nw = self.nw - 1
self.nr = self.nr + 1
if not self.nw:
self.readOK.broadcast()
self.rwOK.release()
# The rest of the file is a test case, that runs a number of parallelized
# quicksorts in parallel. If it works, you'll get about 600 lines of
......
......@@ -31,64 +31,64 @@ input=open(filename) ; output=open(outputname, 'w')
if compressing:
output.write('\037\213\010') # Write the header, ...
output.write(chr(FNAME)) # ... flag byte ...
output.write(chr(FNAME)) # ... flag byte ...
import os # ... modification time ...
import os # ... modification time ...
statval=os.stat(filename)
mtime=statval[8]
write32(output, mtime)
output.write('\002') # ... slowest compression alg. ...
output.write('\377') # ... OS (=unknown) ...
output.write(filename+'\000') # ... original filename ...
output.write('\002') # ... slowest compression alg. ...
output.write('\377') # ... OS (=unknown) ...
output.write(filename+'\000') # ... original filename ...
crcval=zlib.crc32("")
compobj=zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS,
zlib.DEF_MEM_LEVEL, 0)
zlib.DEF_MEM_LEVEL, 0)
while (1):
data=input.read(1024)
if data=="": break
crcval=zlib.crc32(data, crcval)
output.write(compobj.compress(data))
data=input.read(1024)
if data=="": break
crcval=zlib.crc32(data, crcval)
output.write(compobj.compress(data))
output.write(compobj.flush())
write32(output, crcval) # ... the CRC ...
write32(output, statval[6]) # and the file size.
write32(output, crcval) # ... the CRC ...
write32(output, statval[6]) # and the file size.
else:
magic=input.read(2)
if magic!='\037\213':
print 'Not a gzipped file' ; sys.exit(0)
print 'Not a gzipped file' ; sys.exit(0)
if ord(input.read(1))!=8:
print 'Unknown compression method' ; sys.exit(0)
print 'Unknown compression method' ; sys.exit(0)
flag=ord(input.read(1))
input.read(4+1+1) # Discard modification time,
# extra flags, and OS byte.
input.read(4+1+1) # Discard modification time,
# extra flags, and OS byte.
if flag & FEXTRA:
# Read & discard the extra field, if present
xlen=ord(input.read(1))
xlen=xlen+256*ord(input.read(1))
input.read(xlen)
# Read & discard the extra field, if present
xlen=ord(input.read(1))
xlen=xlen+256*ord(input.read(1))
input.read(xlen)
if flag & FNAME:
# Read and discard a null-terminated string containing the filename
while (1):
s=input.read(1)
if s=='\000': break
# Read and discard a null-terminated string containing the filename
while (1):
s=input.read(1)
if s=='\000': break
if flag & FCOMMENT:
# Read and discard a null-terminated string containing a comment
while (1):
s=input.read(1)
if s=='\000': break
# Read and discard a null-terminated string containing a comment
while (1):
s=input.read(1)
if s=='\000': break
if flag & FHCRC:
input.read(2) # Read & discard the 16-bit header CRC
input.read(2) # Read & discard the 16-bit header CRC
decompobj=zlib.decompressobj(-zlib.MAX_WBITS)
crcval=zlib.crc32("")
length=0
while (1):
data=input.read(1024)
if data=="": break
decompdata=decompobj.decompress(data)
print len(decompdata)
output.write(decompdata) ; length=length+len(decompdata)
crcval=zlib.crc32(decompdata, crcval)
data=input.read(1024)
if data=="": break
decompdata=decompobj.decompress(data)
print len(decompdata)
output.write(decompdata) ; length=length+len(decompdata)
crcval=zlib.crc32(decompdata, crcval)
decompdata=decompobj.flush()
output.write(decompdata) ; length=length+len(decompdata)
crcval=zlib.crc32(decompdata, crcval)
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment