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

nannified

parent f9a6d7d4
...@@ -18,22 +18,22 @@ def main(): ...@@ -18,22 +18,22 @@ def main():
tn = telnetlib.Telnet(host, 0) tn = telnetlib.Telnet(host, 0)
# #
try: try:
vt.send(tn.read_until('login: ', 10)) vt.send(tn.read_until('login: ', 10))
tn.write('cwilib\r') tn.write('cwilib\r')
# #
vt.send(tn.read_until('Hit <RETURN> to continue...', 10)) vt.send(tn.read_until('Hit <RETURN> to continue...', 10))
tn.write('\r') tn.write('\r')
# #
vt.send(tn.read_until('QUIT', 20)) vt.send(tn.read_until('QUIT', 20))
except EOFError: except EOFError:
sys.stderr.write('Connection closed prematurely\n') sys.stderr.write('Connection closed prematurely\n')
sys.exit(1) sys.exit(1)
# #
define_screens(vt) define_screens(vt)
matches = vt.which_screens() matches = vt.which_screens()
if 'menu' not in matches: if 'menu' not in matches:
sys.stderr.write('Main menu does not appear\n') sys.stderr.write('Main menu does not appear\n')
sys.exit(1) sys.exit(1)
# #
tn.write('\r\r') tn.write('\r\r')
vt.open('Progress -- CWI Library') vt.open('Progress -- CWI Library')
...@@ -41,109 +41,109 @@ def main(): ...@@ -41,109 +41,109 @@ def main():
ui = UserInterface() ui = UserInterface()
# #
while 1: while 1:
try: try:
data = tn.read_very_eager() data = tn.read_very_eager()
except EOFError: except EOFError:
stdwin.message('Connection closed--goodbye') stdwin.message('Connection closed--goodbye')
break break
if data: if data:
print 'send...' print 'send...'
vt.send(data) vt.send(data)
print 'send...done' print 'send...done'
continue continue
event = stdwin.pollevent() event = stdwin.pollevent()
if event: if event:
type, window, detail = event type, window, detail = event
if window == None and type == WE_LOST_SEL: if window == None and type == WE_LOST_SEL:
window = ui.queryform.window window = ui.queryform.window
event = type, window, detail event = type, window, detail
if type == WE_CLOSE: if type == WE_CLOSE:
break break
if window in ui.windows: if window in ui.windows:
ui.dispatch(type, window, detail) ui.dispatch(type, window, detail)
elif window == vt.window: elif window == vt.window:
if type == WE_NULL: if type == WE_NULL:
pass pass
elif type == WE_COMMAND: elif type == WE_COMMAND:
if detail == WC_RETURN: if detail == WC_RETURN:
tn.write('\r') tn.write('\r')
elif detail == WC_BACKSPACE: elif detail == WC_BACKSPACE:
tn.write('\b') tn.write('\b')
elif detail == WC_TAB: elif detail == WC_TAB:
tn.write('\t') tn.write('\t')
elif detail == WC_UP: elif detail == WC_UP:
tn.write('\033[A') tn.write('\033[A')
elif detail == WC_DOWN: elif detail == WC_DOWN:
tn.write('\033[B') tn.write('\033[B')
elif detail == WC_RIGHT: elif detail == WC_RIGHT:
tn.write('\033[C') tn.write('\033[C')
elif detail == WC_LEFT: elif detail == WC_LEFT:
tn.write('\033[D') tn.write('\033[D')
else: else:
print '*** Command:', detail print '*** Command:', detail
elif type == WE_CHAR: elif type == WE_CHAR:
tn.write(detail) tn.write(detail)
elif type == WE_DRAW: elif type == WE_DRAW:
vt.draw(detail) vt.draw(detail)
elif type in (WE_ACTIVATE, WE_DEACTIVATE): elif type in (WE_ACTIVATE, WE_DEACTIVATE):
pass pass
else: else:
print '*** VT100 event:', type, detail print '*** VT100 event:', type, detail
else: else:
print '*** Alien event:', type, window, detail print '*** Alien event:', type, window, detail
continue continue
rfd, wfd, xfd = select.select([tn, stdwin], [], []) rfd, wfd, xfd = select.select([tn, stdwin], [], [])
# Subroutine to define our screen recognition patterns # Subroutine to define our screen recognition patterns
def define_screens(vt): def define_screens(vt):
vt.define_screen('menu', { vt.define_screen('menu', {
'title': ('search', 0, 0, 80, 'title': ('search', 0, 0, 80,
' SEARCH FUNCTIONS +OTHER FUNCTIONS '), ' SEARCH FUNCTIONS +OTHER FUNCTIONS '),
}) })
vt.define_screen('search', { 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, vt.define_screen('shortlist', {'title': ('search', 0, 0, 80,
' Short-list')}) ' Short-list')})
vt.define_screen('showrecord', { vt.define_screen('showrecord', {
'title': ('search', 0, 0, 80, ' Show record '), 'title': ('search', 0, 0, 80, ' Show record '),
}) })
vt.define_screen('timelimit', { vt.define_screen('timelimit', {
'limit': ('search', 12, 0, 80, ' TIME LIMIT '), 'limit': ('search', 12, 0, 80, ' TIME LIMIT '),
}) })
vt.define_screen('attention', { vt.define_screen('attention', {
'BASE': ('copy', 0, 0, 0, 'search'), 'BASE': ('copy', 0, 0, 0, 'search'),
'title': ('search', 10, 0, 80, ' ATTENTION ')}) 'title': ('search', 10, 0, 80, ' ATTENTION ')})
vt.define_screen('syntaxerror', { vt.define_screen('syntaxerror', {
'BASE': ('copy', 0, 0, 0, 'attention'), 'BASE': ('copy', 0, 0, 0, 'attention'),
'message': ('search', 12, 0, 80, ' Syntax error'), 'message': ('search', 12, 0, 80, ' Syntax error'),
}) })
vt.define_screen('emptyerror', { vt.define_screen('emptyerror', {
'BASE': ('copy', 0, 0, 0, 'attention'), 'BASE': ('copy', 0, 0, 0, 'attention'),
'message': ('search', 12, 0, 80, 'message': ('search', 12, 0, 80,
' Check your input. Search at least one term'), ' Check your input. Search at least one term'),
}) })
vt.define_screen('unsortedwarning', { vt.define_screen('unsortedwarning', {
'BASE': ('copy', 0, 0, 0, 'attention'), 'BASE': ('copy', 0, 0, 0, 'attention'),
'message': ('search', 12, 0, 80, 'message': ('search', 12, 0, 80,
' Number of records exceeds sort limit'), ' Number of records exceeds sort limit'),
}) })
vt.define_screen('thereismore', { vt.define_screen('thereismore', {
'BASE': ('copy', 0, 0, 0, 'showrecord'), 'BASE': ('copy', 0, 0, 0, 'showrecord'),
'message': ('search', 15, 0, 80, 'message': ('search', 15, 0, 80,
'There is more within this record. Use the arrow keys'), 'There is more within this record. Use the arrow keys'),
}) })
vt.define_screen('nofurther', { vt.define_screen('nofurther', {
'BASE': ('copy', 0, 0, 0, 'showrecord'), 'BASE': ('copy', 0, 0, 0, 'showrecord'),
'message': ('search', 17, 0, 80, 'You cannot go further\.'), 'message': ('search', 17, 0, 80, 'You cannot go further\.'),
}) })
vt.define_screen('nofurtherback', { vt.define_screen('nofurtherback', {
'BASE': ('copy', 0, 0, 0, 'showrecord'), 'BASE': ('copy', 0, 0, 0, 'showrecord'),
'message': ('search', 17, 0, 80, 'message': ('search', 17, 0, 80,
'You cannot go further back'), 'You cannot go further back'),
}) })
# Class to implement our user interface. # Class to implement our user interface.
...@@ -151,29 +151,29 @@ def define_screens(vt): ...@@ -151,29 +151,29 @@ def define_screens(vt):
class UserInterface: class UserInterface:
def __init__(self): def __init__(self):
stdwin.setfont('7x14') stdwin.setfont('7x14')
self.queryform = QueryForm() self.queryform = QueryForm()
self.listform = ListForm() self.listform = ListForm()
self.recordform = RecordForm() self.recordform = RecordForm()
self.forms = [self.queryform, self.listform, self.recordform] self.forms = [self.queryform, self.listform, self.recordform]
define_query_fields(self.queryform) define_query_fields(self.queryform)
self.windows = [] self.windows = []
for form in self.forms: for form in self.forms:
if form.formheight > 0: if form.formheight > 0:
form.open() form.open()
self.windows.append(form.window) self.windows.append(form.window)
def __del__(self): def __del__(self):
self.close() self.close()
def close(self): def close(self):
for form in self.forms: for form in self.forms:
form.close() form.close()
def dispatch(self, type, window, detail): def dispatch(self, type, window, detail):
for form in self.forms: for form in self.forms:
if window == form.window: if window == form.window:
form.dispatch(type, detail) form.dispatch(type, detail)
def define_query_fields(f): def define_query_fields(f):
...@@ -189,25 +189,25 @@ def define_query_fields(f): ...@@ -189,25 +189,25 @@ def define_query_fields(f):
class QueryForm(Form): class QueryForm(Form):
def __init__(self): def __init__(self):
Form.__init__(self, 'Query form -- CWI Library') Form.__init__(self, 'Query form -- CWI Library')
def dispatch(self, type, detail): def dispatch(self, type, detail):
if type == WE_COMMAND and detail == WC_RETURN: if type == WE_COMMAND and detail == WC_RETURN:
print '*** SUBMIT ***' print '*** SUBMIT ***'
else: else:
Form.dispatch(self, type, detail) Form.dispatch(self, type, detail)
class ListForm(Form): class ListForm(Form):
def __init__(self): def __init__(self):
Form.__init__(self, 'Short list -- CWI Library') Form.__init__(self, 'Short list -- CWI Library')
class RecordForm(Form): class RecordForm(Form):
def __init__(self): def __init__(self):
Form.__init__(self, 'Record detail -- CWI Library') Form.__init__(self, 'Record detail -- CWI Library')
main() main()
...@@ -7,7 +7,7 @@ import socket ...@@ -7,7 +7,7 @@ import socket
import select import select
def main(): def main():
server = 'cnri.reston.va.us' # How? server = 'cnri.reston.va.us' # How?
port = 53 port = 53
opcode = dnsopcode.QUERY opcode = dnsopcode.QUERY
rd = 0 rd = 0
...@@ -15,21 +15,21 @@ def main(): ...@@ -15,21 +15,21 @@ def main():
qname = sys.argv[1:] and sys.argv[1] or 'www.python.org' qname = sys.argv[1:] and sys.argv[1] or 'www.python.org'
m = dnslib.Mpacker() m = dnslib.Mpacker()
m.addHeader(0, m.addHeader(0,
0, opcode, 0, 0, rd, 0, 0, 0, 0, opcode, 0, 0, rd, 0, 0, 0,
1, 0, 0, 0) 1, 0, 0, 0)
m.addQuestion(qname, qtype, dnsclass.IN) m.addQuestion(qname, qtype, dnsclass.IN)
request = m.getbuf() request = m.getbuf()
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((server, port)) s.connect((server, port))
s.send(request) s.send(request)
while 1: while 1:
r, w, x = [s], [], [] r, w, x = [s], [], []
r, w, x = select.select(r, w, x, 0.333) r, w, x = select.select(r, w, x, 0.333)
print r, w, x print r, w, x
if r: if r:
reply = s.recv(1024) reply = s.recv(1024)
u = dnslib.Munpacker(reply) u = dnslib.Munpacker(reply)
dnslib.dumpM(u) dnslib.dumpM(u)
break break
main() main()
...@@ -4,19 +4,19 @@ For example, ...@@ -4,19 +4,19 @@ For example,
class C: class C:
def m1(self, arg): def m1(self, arg):
require arg > 0 require arg > 0
return whatever return whatever
ensure Result > arg ensure Result > arg
can be written (clumsily, I agree) as: can be written (clumsily, I agree) as:
class C(Eiffel): class C(Eiffel):
def m1(self, arg): def m1(self, arg):
return whatever return whatever
def m1_pre(self, arg): def m1_pre(self, arg):
assert arg > 0 assert arg > 0
def m1_post(self, Result, arg): def m1_post(self, Result, arg):
assert Result > arg assert Result > arg
Pre- and post-conditions for a method, being implemented as methods Pre- and post-conditions for a method, being implemented as methods
themselves, are inherited independently from the method. This gives themselves, are inherited independently from the method. This gives
...@@ -28,10 +28,10 @@ post-condition with that defined in the derived class', for example: ...@@ -28,10 +28,10 @@ post-condition with that defined in the derived class', for example:
class D(C): class D(C):
def m1(self, arg): def m1(self, arg):
return whatever**2 return whatever**2
def m1_post(self, Result, arg): def m1_post(self, Result, arg):
C.m1_post(self, Result, arg) C.m1_post(self, Result, arg)
assert Result < 100 assert Result < 100
This gives derived classes more freedom but also more responsibility This gives derived classes more freedom but also more responsibility
than in Eiffel, where the compiler automatically takes care of this. 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 ...@@ -42,13 +42,13 @@ up to the derived class. For example, a derived class that takes away
the requirement that arg > 0 could write: the requirement that arg > 0 could write:
def m1_pre(self, arg): def m1_pre(self, arg):
pass pass
but one could equally write a derived class that makes a stronger but one could equally write a derived class that makes a stronger
requirement: requirement:
def m1_pre(self, arg): 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 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). post-conditions can be disabled (separately, on a per-class basis).
...@@ -66,27 +66,27 @@ from Meta import MetaClass, MetaHelper, MetaMethodWrapper ...@@ -66,27 +66,27 @@ from Meta import MetaClass, MetaHelper, MetaMethodWrapper
class EiffelMethodWrapper(MetaMethodWrapper): class EiffelMethodWrapper(MetaMethodWrapper):
def __init__(self, func, inst): def __init__(self, func, inst):
MetaMethodWrapper.__init__(self, func, inst) MetaMethodWrapper.__init__(self, func, inst)
# Note that the following causes recursive wrappers around # Note that the following causes recursive wrappers around
# the pre-/post-condition testing methods. These are harmless # the pre-/post-condition testing methods. These are harmless
# but inefficient; to avoid them, the lookup must be done # but inefficient; to avoid them, the lookup must be done
# using the class. # using the class.
try: try:
self.pre = getattr(inst, self.__name__ + "_pre") self.pre = getattr(inst, self.__name__ + "_pre")
except AttributeError: except AttributeError:
self.pre = None self.pre = None
try: try:
self.post = getattr(inst, self.__name__ + "_post") self.post = getattr(inst, self.__name__ + "_post")
except AttributeError: except AttributeError:
self.post = None self.post = None
def __call__(self, *args, **kw): def __call__(self, *args, **kw):
if self.pre: if self.pre:
apply(self.pre, args, kw) apply(self.pre, args, kw)
Result = apply(self.func, (self.inst,) + args, kw) Result = apply(self.func, (self.inst,) + args, kw)
if self.post: if self.post:
apply(self.post, (Result,) + args, kw) apply(self.post, (Result,) + args, kw)
return Result return Result
class EiffelHelper(MetaHelper): class EiffelHelper(MetaHelper):
__methodwrapper__ = EiffelMethodWrapper __methodwrapper__ = EiffelMethodWrapper
...@@ -99,12 +99,12 @@ Eiffel = EiffelMetaClass('Eiffel', (), {}) ...@@ -99,12 +99,12 @@ Eiffel = EiffelMetaClass('Eiffel', (), {})
def _test(): def _test():
class C(Eiffel): class C(Eiffel):
def m1(self, arg): def m1(self, arg):
return arg+1 return arg+1
def m1_pre(self, arg): def m1_pre(self, arg):
assert arg > 0, "precondition for m1 failed" assert arg > 0, "precondition for m1 failed"
def m1_post(self, Result, arg): def m1_post(self, Result, arg):
assert Result > arg assert Result > arg
x = C() x = C()
x.m1(12) x.m1(12)
## x.m1(-1) ## x.m1(-1)
......
...@@ -12,9 +12,9 @@ class EnumMetaClass: ...@@ -12,9 +12,9 @@ class EnumMetaClass:
To define your own enumeration, do something like To define your own enumeration, do something like
class Color(Enum): class Color(Enum):
red = 1 red = 1
green = 2 green = 2
blue = 3 blue = 3
Now, Color.red, Color.green and Color.blue behave totally Now, Color.red, Color.green and Color.blue behave totally
different: they are enumerated values, not integers. different: they are enumerated values, not integers.
...@@ -25,66 +25,66 @@ class EnumMetaClass: ...@@ -25,66 +25,66 @@ class EnumMetaClass:
""" """
def __init__(self, name, bases, dict): def __init__(self, name, bases, dict):
"""Constructor -- create an enumeration. """Constructor -- create an enumeration.
Called at the end of the class statement. The arguments are Called at the end of the class statement. The arguments are
the name of the new class, a tuple containing the base the name of the new class, a tuple containing the base
classes, and a dictionary containing everything that was classes, and a dictionary containing everything that was
entered in the class' namespace during execution of the class entered in the class' namespace during execution of the class
statement. In the above example, it would be {'red': 1, statement. In the above example, it would be {'red': 1,
'green': 2, 'blue': 3}. 'green': 2, 'blue': 3}.
""" """
for base in bases: for base in bases:
if base.__class__ is not EnumMetaClass: if base.__class__ is not EnumMetaClass:
raise TypeError, "Enumeration base class must be enumeration" raise TypeError, "Enumeration base class must be enumeration"
bases = filter(lambda x: x is not Enum, bases) bases = filter(lambda x: x is not Enum, bases)
self.__name__ = name self.__name__ = name
self.__bases__ = bases self.__bases__ = bases
self.__dict = {} self.__dict = {}
for key, value in dict.items(): for key, value in dict.items():
self.__dict[key] = EnumInstance(name, key, value) self.__dict[key] = EnumInstance(name, key, value)
def __getattr__(self, name): 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 This looks in the class dictionary and if it is not found
there asks the base classes. there asks the base classes.
The special attribute __members__ returns the list of names The special attribute __members__ returns the list of names
defined in this class (it does not merge in the names defined defined in this class (it does not merge in the names defined
in base classes). in base classes).
""" """
if name == '__members__': if name == '__members__':
return self.__dict.keys() return self.__dict.keys()
try: try:
return self.__dict[name] return self.__dict[name]
except KeyError: except KeyError:
for base in self.__bases__: for base in self.__bases__:
try: try:
return getattr(base, name) return getattr(base, name)
except AttributeError: except AttributeError:
continue continue
raise AttributeError, name raise AttributeError, name
def __repr__(self): def __repr__(self):
s = self.__name__ s = self.__name__
if self.__bases__: if self.__bases__:
s = s + '(' + string.join(map(lambda x: x.__name__, s = s + '(' + string.join(map(lambda x: x.__name__,
self.__bases__), ", ") + ')' self.__bases__), ", ") + ')'
if self.__dict: if self.__dict:
list = [] list = []
for key, value in self.__dict.items(): for key, value in self.__dict.items():
list.append("%s: %s" % (key, int(value))) list.append("%s: %s" % (key, int(value)))
s = "%s: {%s}" % (s, string.join(list, ", ")) s = "%s: {%s}" % (s, string.join(list, ", "))
return s return s
class EnumInstance: class EnumInstance:
...@@ -99,23 +99,23 @@ class EnumInstance: ...@@ -99,23 +99,23 @@ class EnumInstance:
""" """
def __init__(self, classname, enumname, value): def __init__(self, classname, enumname, value):
self.__classname = classname self.__classname = classname
self.__enumname = enumname self.__enumname = enumname
self.__value = value self.__value = value
def __int__(self): def __int__(self):
return self.__value return self.__value
def __repr__(self): def __repr__(self):
return "EnumInstance(%s, %s, %s)" % (`self.__classname`, return "EnumInstance(%s, %s, %s)" % (`self.__classname`,
`self.__enumname`, `self.__enumname`,
`self.__value`) `self.__value`)
def __str__(self): def __str__(self):
return "%s.%s" % (self.__classname, self.__enumname) return "%s.%s" % (self.__classname, self.__enumname)
def __cmp__(self, other): def __cmp__(self, other):
return cmp(self.__value, int(other)) return cmp(self.__value, int(other))
# Create the base class for enumerations. # Create the base class for enumerations.
...@@ -126,9 +126,9 @@ Enum = EnumMetaClass("Enum", (), {}) ...@@ -126,9 +126,9 @@ Enum = EnumMetaClass("Enum", (), {})
def _test(): def _test():
class Color(Enum): class Color(Enum):
red = 1 red = 1
green = 2 green = 2
blue = 3 blue = 3
print Color.red print Color.red
print dir(Color) print dir(Color)
...@@ -139,11 +139,11 @@ def _test(): ...@@ -139,11 +139,11 @@ def _test():
print Color.red == 2 print Color.red == 2
class ExtendedColor(Color): class ExtendedColor(Color):
white = 0 white = 0
orange = 4 orange = 4
yellow = 5 yellow = 5
purple = 6 purple = 6
black = 7 black = 7
print ExtendedColor.orange print ExtendedColor.orange
print ExtendedColor.red print ExtendedColor.red
...@@ -151,11 +151,11 @@ def _test(): ...@@ -151,11 +151,11 @@ def _test():
print Color.red == ExtendedColor.red print Color.red == ExtendedColor.red
class OtherColor(Enum): class OtherColor(Enum):
white = 4 white = 4
blue = 5 blue = 5
class MergedColor(Color, OtherColor): class MergedColor(Color, OtherColor):
pass pass
print MergedColor.red print MergedColor.red
print MergedColor.white print MergedColor.white
......
...@@ -9,33 +9,33 @@ import types ...@@ -9,33 +9,33 @@ import types
class MetaMethodWrapper: class MetaMethodWrapper:
def __init__(self, func, inst): def __init__(self, func, inst):
self.func = func self.func = func
self.inst = inst self.inst = inst
self.__name__ = self.func.__name__ self.__name__ = self.func.__name__
def __call__(self, *args, **kw): def __call__(self, *args, **kw):
return apply(self.func, (self.inst,) + args, kw) return apply(self.func, (self.inst,) + args, kw)
class MetaHelper: class MetaHelper:
__methodwrapper__ = MetaMethodWrapper # For derived helpers to override __methodwrapper__ = MetaMethodWrapper # For derived helpers to override
def __helperinit__(self, formalclass): def __helperinit__(self, formalclass):
self.__formalclass__ = formalclass self.__formalclass__ = formalclass
def __getattr__(self, name): def __getattr__(self, name):
# Invoked for any attr not in the instance's __dict__ # Invoked for any attr not in the instance's __dict__
try: try:
raw = self.__formalclass__.__getattr__(name) raw = self.__formalclass__.__getattr__(name)
except AttributeError: except AttributeError:
try: try:
ga = self.__formalclass__.__getattr__('__usergetattr__') ga = self.__formalclass__.__getattr__('__usergetattr__')
except KeyError: except KeyError:
raise AttributeError, name raise AttributeError, name
return ga(self, name) return ga(self, name)
if type(raw) != types.FunctionType: if type(raw) != types.FunctionType:
return raw return raw
return self.__methodwrapper__(raw, self) return self.__methodwrapper__(raw, self)
class MetaClass: class MetaClass:
...@@ -45,49 +45,49 @@ class MetaClass: ...@@ -45,49 +45,49 @@ class MetaClass:
""" """
__helper__ = MetaHelper # For derived metaclasses to override __helper__ = MetaHelper # For derived metaclasses to override
__inited = 0 __inited = 0
def __init__(self, name, bases, dict): def __init__(self, name, bases, dict):
try: try:
ga = dict['__getattr__'] ga = dict['__getattr__']
except KeyError: except KeyError:
pass pass
else: else:
dict['__usergetattr__'] = ga dict['__usergetattr__'] = ga
del dict['__getattr__'] del dict['__getattr__']
self.__name__ = name self.__name__ = name
self.__bases__ = bases self.__bases__ = bases
self.__realdict__ = dict self.__realdict__ = dict
self.__inited = 1 self.__inited = 1
def __getattr__(self, name): def __getattr__(self, name):
try: try:
return self.__realdict__[name] return self.__realdict__[name]
except KeyError: except KeyError:
for base in self.__bases__: for base in self.__bases__:
try: try:
return base.__getattr__(name) return base.__getattr__(name)
except AttributeError: except AttributeError:
pass pass
raise AttributeError, name raise AttributeError, name
def __setattr__(self, name, value): def __setattr__(self, name, value):
if not self.__inited: if not self.__inited:
self.__dict__[name] = value self.__dict__[name] = value
else: else:
self.__realdict__[name] = value self.__realdict__[name] = value
def __call__(self, *args, **kw): def __call__(self, *args, **kw):
inst = self.__helper__() inst = self.__helper__()
inst.__helperinit__(self) inst.__helperinit__(self)
try: try:
init = inst.__getattr__('__init__') init = inst.__getattr__('__init__')
except AttributeError: except AttributeError:
init = lambda: None init = lambda: None
apply(init, args, kw) apply(init, args, kw)
return inst return inst
Meta = MetaClass('Meta', (), {}) Meta = MetaClass('Meta', (), {})
...@@ -95,18 +95,18 @@ Meta = MetaClass('Meta', (), {}) ...@@ -95,18 +95,18 @@ Meta = MetaClass('Meta', (), {})
def _test(): def _test():
class C(Meta): class C(Meta):
def __init__(self, *args): def __init__(self, *args):
print "__init__, args =", args print "__init__, args =", args
def m1(self, x): def m1(self, x):
print "m1(x=%s)" %`x` print "m1(x=%s)" %`x`
print C print C
x = C() x = C()
print x print x
x.m1(12) x.m1(12)
class D(C): class D(C):
def __getattr__(self, name): def __getattr__(self, name):
if name[:2] == '__': raise AttributeError, name if name[:2] == '__': raise AttributeError, name
return "getattr:%s" % name return "getattr:%s" % name
x = D() x = D()
print x.foo print x.foo
print x._foo print x._foo
......
...@@ -40,64 +40,64 @@ class Lock: ...@@ -40,64 +40,64 @@ class Lock:
""" """
def __init__(self): def __init__(self):
"""Constructor. Initialize all instance variables.""" """Constructor. Initialize all instance variables."""
self.__mutex = thread.allocate_lock() self.__mutex = thread.allocate_lock()
self.__wait = thread.allocate_lock() self.__wait = thread.allocate_lock()
self.__tid = None self.__tid = None
self.__count = 0 self.__count = 0
def acquire(self, flag=1): def acquire(self, flag=1):
"""Acquire the lock. """Acquire the lock.
If the optional flag argument is false, returns immediately If the optional flag argument is false, returns immediately
when it cannot acquire the __wait lock without blocking (it when it cannot acquire the __wait lock without blocking (it
may still block for a little while in order to acquire the may still block for a little while in order to acquire the
__mutex lock). __mutex lock).
The return value is only relevant when the flag argument is The return value is only relevant when the flag argument is
false; it is 1 if the lock is acquired, 0 if not. false; it is 1 if the lock is acquired, 0 if not.
""" """
self.__mutex.acquire() self.__mutex.acquire()
try: try:
if self.__tid == thread.get_ident(): if self.__tid == thread.get_ident():
self.__count = self.__count + 1 self.__count = self.__count + 1
return 1 return 1
finally: finally:
self.__mutex.release() self.__mutex.release()
locked = self.__wait.acquire(flag) locked = self.__wait.acquire(flag)
if not flag and not locked: if not flag and not locked:
return 0 return 0
try: try:
self.__mutex.acquire() self.__mutex.acquire()
assert self.__tid == None assert self.__tid == None
assert self.__count == 0 assert self.__count == 0
self.__tid = thread.get_ident() self.__tid = thread.get_ident()
self.__count = 1 self.__count = 1
return 1 return 1
finally: finally:
self.__mutex.release() self.__mutex.release()
def release(self): def release(self):
"""Release the lock. """Release the lock.
If this thread doesn't currently have the lock, an assertion If this thread doesn't currently have the lock, an assertion
error is raised. error is raised.
Only allow another thread to acquire the lock when the count Only allow another thread to acquire the lock when the count
reaches zero after decrementing it. reaches zero after decrementing it.
""" """
self.__mutex.acquire() self.__mutex.acquire()
try: try:
assert self.__tid == thread.get_ident() assert self.__tid == thread.get_ident()
assert self.__count > 0 assert self.__count > 0
self.__count = self.__count - 1 self.__count = self.__count - 1
if self.__count == 0: if self.__count == 0:
self.__tid = None self.__tid = None
self.__wait.release() self.__wait.release()
finally: finally:
self.__mutex.release() self.__mutex.release()
def _testLock(): def _testLock():
...@@ -105,23 +105,23 @@ def _testLock(): ...@@ -105,23 +105,23 @@ def _testLock():
done = [] done = []
def f2(lock, done=done): def f2(lock, done=done):
lock.acquire() lock.acquire()
print "f2 running in thread %d\n" % thread.get_ident(), print "f2 running in thread %d\n" % thread.get_ident(),
lock.release() lock.release()
done.append(1) done.append(1)
def f1(lock, f2=f2, done=done): def f1(lock, f2=f2, done=done):
lock.acquire() lock.acquire()
print "f1 running in thread %d\n" % thread.get_ident(), print "f1 running in thread %d\n" % thread.get_ident(),
try: try:
f2(lock) f2(lock)
finally: finally:
lock.release() lock.release()
done.append(1) done.append(1)
lock = Lock() lock = Lock()
lock.acquire() lock.acquire()
f1(lock) # Adds 2 to done f1(lock) # Adds 2 to done
lock.release() lock.release()
lock.acquire() lock.acquire()
...@@ -134,8 +134,8 @@ def _testLock(): ...@@ -134,8 +134,8 @@ def _testLock():
lock.release() lock.release()
import time import time
while len(done) < 9: while len(done) < 9:
print len(done) print len(done)
time.sleep(0.001) time.sleep(0.001)
print len(done) print len(done)
...@@ -147,19 +147,19 @@ from Meta import MetaClass, MetaHelper, MetaMethodWrapper ...@@ -147,19 +147,19 @@ from Meta import MetaClass, MetaHelper, MetaMethodWrapper
class LockingMethodWrapper(MetaMethodWrapper): class LockingMethodWrapper(MetaMethodWrapper):
def __call__(self, *args, **kw): def __call__(self, *args, **kw):
if self.__name__[:1] == '_' and self.__name__[1:] != '_': if self.__name__[:1] == '_' and self.__name__[1:] != '_':
return apply(self.func, (self.inst,) + args, kw) return apply(self.func, (self.inst,) + args, kw)
self.inst.__lock__.acquire() self.inst.__lock__.acquire()
try: try:
return apply(self.func, (self.inst,) + args, kw) return apply(self.func, (self.inst,) + args, kw)
finally: finally:
self.inst.__lock__.release() self.inst.__lock__.release()
class LockingHelper(MetaHelper): class LockingHelper(MetaHelper):
__methodwrapper__ = LockingMethodWrapper __methodwrapper__ = LockingMethodWrapper
def __helperinit__(self, formalclass): def __helperinit__(self, formalclass):
MetaHelper.__helperinit__(self, formalclass) MetaHelper.__helperinit__(self, formalclass)
self.__lock__ = Lock() self.__lock__ = Lock()
class LockingMetaClass(MetaClass): class LockingMetaClass(MetaClass):
__helper__ = LockingHelper __helper__ = LockingHelper
...@@ -169,73 +169,73 @@ Locking = LockingMetaClass('Locking', (), {}) ...@@ -169,73 +169,73 @@ Locking = LockingMetaClass('Locking', (), {})
def _test(): def _test():
# For kicks, take away the Locking base class and see it die # For kicks, take away the Locking base class and see it die
class Buffer(Locking): class Buffer(Locking):
def __init__(self, initialsize): def __init__(self, initialsize):
assert initialsize > 0 assert initialsize > 0
self.size = initialsize self.size = initialsize
self.buffer = [None]*self.size self.buffer = [None]*self.size
self.first = self.last = 0 self.first = self.last = 0
def put(self, item): def put(self, item):
# Do we need to grow the buffer? # Do we need to grow the buffer?
if (self.last+1) % self.size != self.first: if (self.last+1) % self.size != self.first:
# Insert the new item # Insert the new item
self.buffer[self.last] = item self.buffer[self.last] = item
self.last = (self.last+1) % self.size self.last = (self.last+1) % self.size
return return
# Double the buffer size # Double the buffer size
# First normalize it so that first==0 and last==size-1 # First normalize it so that first==0 and last==size-1
print "buffer =", self.buffer print "buffer =", self.buffer
print "first = %d, last = %d, size = %d" % ( print "first = %d, last = %d, size = %d" % (
self.first, self.last, self.size) self.first, self.last, self.size)
if self.first <= self.last: if self.first <= self.last:
temp = self.buffer[self.first:self.last] temp = self.buffer[self.first:self.last]
else: else:
temp = self.buffer[self.first:] + self.buffer[:self.last] temp = self.buffer[self.first:] + self.buffer[:self.last]
print "temp =", temp print "temp =", temp
self.buffer = temp + [None]*(self.size+1) self.buffer = temp + [None]*(self.size+1)
self.first = 0 self.first = 0
self.last = self.size-1 self.last = self.size-1
self.size = self.size*2 self.size = self.size*2
print "Buffer size doubled to", self.size print "Buffer size doubled to", self.size
print "new buffer =", self.buffer print "new buffer =", self.buffer
print "first = %d, last = %d, size = %d" % ( print "first = %d, last = %d, size = %d" % (
self.first, self.last, self.size) self.first, self.last, self.size)
self.put(item) # Recursive call to test the locking self.put(item) # Recursive call to test the locking
def get(self): def get(self):
# Is the buffer empty? # Is the buffer empty?
if self.first == self.last: if self.first == self.last:
raise EOFError # Avoid defining a new exception raise EOFError # Avoid defining a new exception
item = self.buffer[self.first] item = self.buffer[self.first]
self.first = (self.first+1) % self.size self.first = (self.first+1) % self.size
return item return item
def producer(buffer, wait, n=1000): def producer(buffer, wait, n=1000):
import time import time
i = 0 i = 0
while i < n: while i < n:
print "put", i print "put", i
buffer.put(i) buffer.put(i)
i = i+1 i = i+1
print "Producer: done producing", n, "items" print "Producer: done producing", n, "items"
wait.release() wait.release()
def consumer(buffer, wait, n=1000): def consumer(buffer, wait, n=1000):
import time import time
i = 0 i = 0
tout = 0.001 tout = 0.001
while i < n: while i < n:
try: try:
x = buffer.get() x = buffer.get()
if x != i: if x != i:
raise AssertionError, \ raise AssertionError, \
"get() returned %s, expected %s" % (x, i) "get() returned %s, expected %s" % (x, i)
print "got", i print "got", i
i = i+1 i = i+1
tout = 0.001 tout = 0.001
except EOFError: except EOFError:
time.sleep(tout) time.sleep(tout)
tout = tout*2 tout = tout*2
print "Consumer: done consuming", n, "items" print "Consumer: done consuming", n, "items"
wait.release() wait.release()
pwait = thread.allocate_lock() pwait = thread.allocate_lock()
pwait.acquire() pwait.acquire()
......
...@@ -20,38 +20,38 @@ class TraceMetaClass: ...@@ -20,38 +20,38 @@ class TraceMetaClass:
__inited = 0 __inited = 0
def __init__(self, name, bases, dict): def __init__(self, name, bases, dict):
self.__name__ = name self.__name__ = name
self.__bases__ = bases self.__bases__ = bases
self.__dict = dict self.__dict = dict
# XXX Can't define __dict__, alas # XXX Can't define __dict__, alas
self.__inited = 1 self.__inited = 1
def __getattr__(self, name): def __getattr__(self, name):
try: try:
return self.__dict[name] return self.__dict[name]
except KeyError: except KeyError:
for base in self.__bases__: for base in self.__bases__:
try: try:
return base.__getattr__(name) return base.__getattr__(name)
except AttributeError: except AttributeError:
pass pass
raise AttributeError, name raise AttributeError, name
def __setattr__(self, name, value): def __setattr__(self, name, value):
if not self.__inited: if not self.__inited:
self.__dict__[name] = value self.__dict__[name] = value
else: else:
self.__dict[name] = value self.__dict[name] = value
def __call__(self, *args, **kw): def __call__(self, *args, **kw):
inst = TracingInstance() inst = TracingInstance()
inst.__meta_init__(self) inst.__meta_init__(self)
try: try:
init = inst.__getattr__('__init__') init = inst.__getattr__('__init__')
except AttributeError: except AttributeError:
init = lambda: None init = lambda: None
apply(init, args, kw) apply(init, args, kw)
return inst return inst
__trace_output__ = None __trace_output__ = None
...@@ -59,52 +59,52 @@ class TracingInstance: ...@@ -59,52 +59,52 @@ class TracingInstance:
"""Helper class to represent an instance of a tracing class.""" """Helper class to represent an instance of a tracing class."""
def __trace_call__(self, fp, fmt, *args): def __trace_call__(self, fp, fmt, *args):
fp.write((fmt+'\n') % args) fp.write((fmt+'\n') % args)
def __meta_init__(self, klass): def __meta_init__(self, klass):
self.__class = klass self.__class = klass
def __getattr__(self, name): def __getattr__(self, name):
# Invoked for any attr not in the instance's __dict__ # Invoked for any attr not in the instance's __dict__
try: try:
raw = self.__class.__getattr__(name) raw = self.__class.__getattr__(name)
except AttributeError: except AttributeError:
raise AttributeError, name raise AttributeError, name
if type(raw) != types.FunctionType: if type(raw) != types.FunctionType:
return raw return raw
# It's a function # It's a function
fullname = self.__class.__name__ + "." + name fullname = self.__class.__name__ + "." + name
if not self.__trace_output__ or name == '__trace_call__': if not self.__trace_output__ or name == '__trace_call__':
return NotTracingWrapper(fullname, raw, self) return NotTracingWrapper(fullname, raw, self)
else: else:
return TracingWrapper(fullname, raw, self) return TracingWrapper(fullname, raw, self)
class NotTracingWrapper: class NotTracingWrapper:
def __init__(self, name, func, inst): def __init__(self, name, func, inst):
self.__name__ = name self.__name__ = name
self.func = func self.func = func
self.inst = inst self.inst = inst
def __call__(self, *args, **kw): def __call__(self, *args, **kw):
return apply(self.func, (self.inst,) + args, kw) return apply(self.func, (self.inst,) + args, kw)
class TracingWrapper(NotTracingWrapper): class TracingWrapper(NotTracingWrapper):
def __call__(self, *args, **kw): def __call__(self, *args, **kw):
self.inst.__trace_call__(self.inst.__trace_output__, self.inst.__trace_call__(self.inst.__trace_output__,
"calling %s, inst=%s, args=%s, kw=%s", "calling %s, inst=%s, args=%s, kw=%s",
self.__name__, self.inst, args, kw) self.__name__, self.inst, args, kw)
try: try:
rv = apply(self.func, (self.inst,) + args, kw) rv = apply(self.func, (self.inst,) + args, kw)
except: except:
t, v, tb = sys.exc_info() t, v, tb = sys.exc_info()
self.inst.__trace_call__(self.inst.__trace_output__, self.inst.__trace_call__(self.inst.__trace_output__,
"returning from %s with exception %s: %s", "returning from %s with exception %s: %s",
self.__name__, t, v) self.__name__, t, v)
raise t, v, tb raise t, v, tb
else: else:
self.inst.__trace_call__(self.inst.__trace_output__, self.inst.__trace_call__(self.inst.__trace_output__,
"returning from %s with value %s", "returning from %s with value %s",
self.__name__, rv) self.__name__, rv)
return rv return rv
Traced = TraceMetaClass('Traced', (), {'__trace_output__': None}) Traced = TraceMetaClass('Traced', (), {'__trace_output__': None})
...@@ -112,13 +112,13 @@ Traced = TraceMetaClass('Traced', (), {'__trace_output__': None}) ...@@ -112,13 +112,13 @@ Traced = TraceMetaClass('Traced', (), {'__trace_output__': None})
def _test(): def _test():
global C, D global C, D
class C(Traced): class C(Traced):
def __init__(self, x=0): self.x = x def __init__(self, x=0): self.x = x
def m1(self, x): self.x = x def m1(self, x): self.x = x
def m2(self, y): return self.x + y def m2(self, y): return self.x + y
__trace_output__ = sys.stdout __trace_output__ = sys.stdout
class D(C): class D(C):
def m2(self, y): print "D.m2(%s)" % `y`; return C.m2(self, y) def m2(self, y): print "D.m2(%s)" % `y`; return C.m2(self, y)
__trace_output__ = None __trace_output__ = None
x = C(4321) x = C(4321)
print x print x
print x.x print x.x
......
...@@ -14,7 +14,7 @@ def get_docs(fileName): ...@@ -14,7 +14,7 @@ def get_docs(fileName):
"""Retrieve information from the parse tree of a source file. """Retrieve information from the parse tree of a source file.
fileName 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() source = open(fileName).read()
import os import os
...@@ -30,86 +30,86 @@ class SuiteInfoBase: ...@@ -30,86 +30,86 @@ class SuiteInfoBase:
_name = '' _name = ''
def __init__(self, tree = None): def __init__(self, tree = None):
self._class_info = {} self._class_info = {}
self._function_info = {} self._function_info = {}
if tree: if tree:
self._extract_info(tree) self._extract_info(tree)
def _extract_info(self, tree): def _extract_info(self, tree):
# extract docstring # extract docstring
if len(tree) == 2: if len(tree) == 2:
found, vars = match(DOCSTRING_STMT_PATTERN[1], tree[1]) found, vars = match(DOCSTRING_STMT_PATTERN[1], tree[1])
else: else:
found, vars = match(DOCSTRING_STMT_PATTERN, tree[3]) found, vars = match(DOCSTRING_STMT_PATTERN, tree[3])
if found: if found:
self._docstring = eval(vars['docstring']) self._docstring = eval(vars['docstring'])
# discover inner definitions # discover inner definitions
for node in tree[1:]: for node in tree[1:]:
found, vars = match(COMPOUND_STMT_PATTERN, node) found, vars = match(COMPOUND_STMT_PATTERN, node)
if found: if found:
cstmt = vars['compound'] cstmt = vars['compound']
if cstmt[0] == symbol.funcdef: if cstmt[0] == symbol.funcdef:
name = cstmt[2][1] name = cstmt[2][1]
self._function_info[name] = FunctionInfo(cstmt) self._function_info[name] = FunctionInfo(cstmt)
elif cstmt[0] == symbol.classdef: elif cstmt[0] == symbol.classdef:
name = cstmt[2][1] name = cstmt[2][1]
self._class_info[name] = ClassInfo(cstmt) self._class_info[name] = ClassInfo(cstmt)
def get_docstring(self): def get_docstring(self):
return self._docstring return self._docstring
def get_name(self): def get_name(self):
return self._name return self._name
def get_class_names(self): def get_class_names(self):
return self._class_info.keys() return self._class_info.keys()
def get_class_info(self, name): def get_class_info(self, name):
return self._class_info[name] return self._class_info[name]
def __getitem__(self, name): def __getitem__(self, name):
try: try:
return self._class_info[name] return self._class_info[name]
except KeyError: except KeyError:
return self._function_info[name] return self._function_info[name]
class SuiteFuncInfo: class SuiteFuncInfo:
# Mixin class providing access to function names and info. # Mixin class providing access to function names and info.
def get_function_names(self): def get_function_names(self):
return self._function_info.keys() return self._function_info.keys()
def get_function_info(self, name): def get_function_info(self, name):
return self._function_info[name] return self._function_info[name]
class FunctionInfo(SuiteInfoBase, SuiteFuncInfo): class FunctionInfo(SuiteInfoBase, SuiteFuncInfo):
def __init__(self, tree = None): def __init__(self, tree = None):
self._name = tree[2][1] self._name = tree[2][1]
SuiteInfoBase.__init__(self, tree and tree[-1] or None) SuiteInfoBase.__init__(self, tree and tree[-1] or None)
class ClassInfo(SuiteInfoBase): class ClassInfo(SuiteInfoBase):
def __init__(self, tree = None): def __init__(self, tree = None):
self._name = tree[2][1] self._name = tree[2][1]
SuiteInfoBase.__init__(self, tree and tree[-1] or None) SuiteInfoBase.__init__(self, tree and tree[-1] or None)
def get_method_names(self): def get_method_names(self):
return self._function_info.keys() return self._function_info.keys()
def get_method_info(self, name): def get_method_info(self, name):
return self._function_info[name] return self._function_info[name]
class ModuleInfo(SuiteInfoBase, SuiteFuncInfo): class ModuleInfo(SuiteInfoBase, SuiteFuncInfo):
def __init__(self, tree = None, name = "<string>"): def __init__(self, tree = None, name = "<string>"):
self._name = name self._name = name
SuiteInfoBase.__init__(self, tree) SuiteInfoBase.__init__(self, tree)
if tree: if tree:
found, vars = match(DOCSTRING_STMT_PATTERN, tree[1]) found, vars = match(DOCSTRING_STMT_PATTERN, tree[1])
if found: if found:
self._docstring = vars["docstring"] self._docstring = vars["docstring"]
from types import ListType, TupleType from types import ListType, TupleType
...@@ -118,14 +118,14 @@ def match(pattern, data, vars=None): ...@@ -118,14 +118,14 @@ def match(pattern, data, vars=None):
"""Match `data' to `pattern', with variable extraction. """Match `data' to `pattern', with variable extraction.
pattern pattern
Pattern to match against, possibly containing variables. Pattern to match against, possibly containing variables.
data data
Data to be checked and against which variables are extracted. Data to be checked and against which variables are extracted.
vars vars
Dictionary of variables which have already been found. If not Dictionary of variables which have already been found. If not
provided, an empty dictionary is created. provided, an empty dictionary is created.
The `pattern' value may contain variables of the form ['varname'] which The `pattern' value may contain variables of the form ['varname'] which
are allowed to match anything. The value that is matched is returned as are allowed to match anything. The value that is matched is returned as
...@@ -138,18 +138,18 @@ def match(pattern, data, vars=None): ...@@ -138,18 +138,18 @@ def match(pattern, data, vars=None):
values. values.
""" """
if vars is None: if vars is None:
vars = {} vars = {}
if type(pattern) is ListType: # 'variables' are ['varname'] if type(pattern) is ListType: # 'variables' are ['varname']
vars[pattern[0]] = data vars[pattern[0]] = data
return 1, vars return 1, vars
if type(pattern) is not TupleType: if type(pattern) is not TupleType:
return (pattern == data), vars return (pattern == data), vars
if len(data) != len(pattern): if len(data) != len(pattern):
return 0, vars return 0, vars
for pattern, data in map(None, pattern, data): for pattern, data in map(None, pattern, data):
same, vars = match(pattern, data, vars) same, vars = match(pattern, data, vars)
if not same: if not same:
break break
return same, vars return same, vars
...@@ -172,21 +172,21 @@ DOCSTRING_STMT_PATTERN = ( ...@@ -172,21 +172,21 @@ DOCSTRING_STMT_PATTERN = (
(symbol.small_stmt, (symbol.small_stmt,
(symbol.expr_stmt, (symbol.expr_stmt,
(symbol.testlist, (symbol.testlist,
(symbol.test, (symbol.test,
(symbol.and_test, (symbol.and_test,
(symbol.not_test, (symbol.not_test,
(symbol.comparison, (symbol.comparison,
(symbol.expr, (symbol.expr,
(symbol.xor_expr, (symbol.xor_expr,
(symbol.and_expr, (symbol.and_expr,
(symbol.shift_expr, (symbol.shift_expr,
(symbol.arith_expr, (symbol.arith_expr,
(symbol.term, (symbol.term,
(symbol.factor, (symbol.factor,
(symbol.power, (symbol.power,
(symbol.atom, (symbol.atom,
(token.STRING, ['docstring']) (token.STRING, ['docstring'])
)))))))))))))))), )))))))))))))))),
(token.NEWLINE, '') (token.NEWLINE, '')
)) ))
......
...@@ -9,18 +9,18 @@ class Simple: ...@@ -9,18 +9,18 @@ class Simple:
"This class does very little." "This class does very little."
def method(self): def method(self):
"This method does almost nothing." "This method does almost nothing."
return 1 return 1
class Nested: class Nested:
"This is a nested class." "This is a nested class."
def nested_method(self): def nested_method(self):
"Method of Nested class." "Method of Nested class."
def nested_function(): def nested_function():
"Function in method of Nested class." "Function in method of Nested class."
pass pass
return nested_function return nested_function
def function(): def function():
"This function lives at the module level." "This function lives at the module level."
......
...@@ -11,24 +11,24 @@ def testChunk(t, fileName): ...@@ -11,24 +11,24 @@ def testChunk(t, fileName):
global _numFailed global _numFailed
print '----', fileName, print '----', fileName,
try: try:
ast = parser.suite(t) ast = parser.suite(t)
tup = parser.ast2tuple(ast) tup = parser.ast2tuple(ast)
# this discards the first AST; a huge memory savings when running # this discards the first AST; a huge memory savings when running
# against a large source file like Tkinter.py. # against a large source file like Tkinter.py.
ast = None ast = None
new = parser.tuple2ast(tup) new = parser.tuple2ast(tup)
except parser.ParserError, err: except parser.ParserError, err:
print print
print 'parser module raised exception on input file', fileName + ':' print 'parser module raised exception on input file', fileName + ':'
traceback.print_exc() traceback.print_exc()
_numFailed = _numFailed + 1 _numFailed = _numFailed + 1
else: else:
if tup != parser.ast2tuple(new): if tup != parser.ast2tuple(new):
print print
print 'parser module failed on input file', fileName print 'parser module failed on input file', fileName
_numFailed = _numFailed + 1 _numFailed = _numFailed + 1
else: else:
print 'o.k.' print 'o.k.'
def testFile(fileName): def testFile(fileName):
t = open(fileName).read() t = open(fileName).read()
...@@ -38,8 +38,8 @@ def test(): ...@@ -38,8 +38,8 @@ def test():
import sys import sys
args = sys.argv[1:] args = sys.argv[1:]
if not args: if not args:
import glob import glob
args = glob.glob("*.py") args = glob.glob("*.py")
map(testFile, args) map(testFile, args)
sys.exit(_numFailed != 0) sys.exit(_numFailed != 0)
......
...@@ -31,147 +31,147 @@ import rcslib ...@@ -31,147 +31,147 @@ import rcslib
class DirSupport: class DirSupport:
def __init__(self): def __init__(self):
self._dirstack = [] self._dirstack = []
def __del__(self): def __del__(self):
self._close() self._close()
def _close(self): def _close(self):
while self._dirstack: while self._dirstack:
self.back() self.back()
def pwd(self): def pwd(self):
return os.getcwd() return os.getcwd()
def cd(self, name): def cd(self, name):
save = os.getcwd() save = os.getcwd()
os.chdir(name) os.chdir(name)
self._dirstack.append(save) self._dirstack.append(save)
def back(self): def back(self):
if not self._dirstack: if not self._dirstack:
raise os.error, "empty directory stack" raise os.error, "empty directory stack"
dir = self._dirstack[-1] dir = self._dirstack[-1]
os.chdir(dir) os.chdir(dir)
del self._dirstack[-1] del self._dirstack[-1]
def listsubdirs(self, pat = None): def listsubdirs(self, pat = None):
files = os.listdir(os.curdir) files = os.listdir(os.curdir)
files = filter(os.path.isdir, files) files = filter(os.path.isdir, files)
return self._filter(files, pat) return self._filter(files, pat)
def isdir(self, name): def isdir(self, name):
return os.path.isdir(name) return os.path.isdir(name)
def mkdir(self, name): def mkdir(self, name):
os.mkdir(name, 0777) os.mkdir(name, 0777)
def rmdir(self, name): def rmdir(self, name):
os.rmdir(name) os.rmdir(name)
class RCSProxyLocal(rcslib.RCS, DirSupport): class RCSProxyLocal(rcslib.RCS, DirSupport):
def __init__(self): def __init__(self):
rcslib.RCS.__init__(self) rcslib.RCS.__init__(self)
DirSupport.__init__(self) DirSupport.__init__(self)
def __del__(self): def __del__(self):
DirSupport.__del__(self) DirSupport.__del__(self)
rcslib.RCS.__del__(self) rcslib.RCS.__del__(self)
def sumlist(self, list = None): def sumlist(self, list = None):
return self._list(self.sum, list) return self._list(self.sum, list)
def sumdict(self, list = None): def sumdict(self, list = None):
return self._dict(self.sum, list) return self._dict(self.sum, list)
def sum(self, name_rev): def sum(self, name_rev):
f = self._open(name_rev) f = self._open(name_rev)
BUFFERSIZE = 1024*8 BUFFERSIZE = 1024*8
sum = md5.new() sum = md5.new()
while 1: while 1:
buffer = f.read(BUFFERSIZE) buffer = f.read(BUFFERSIZE)
if not buffer: if not buffer:
break break
sum.update(buffer) sum.update(buffer)
self._closepipe(f) self._closepipe(f)
return sum.digest() return sum.digest()
def get(self, name_rev): def get(self, name_rev):
f = self._open(name_rev) f = self._open(name_rev)
data = f.read() data = f.read()
self._closepipe(f) self._closepipe(f)
return data return data
def put(self, name_rev, data, message=None): def put(self, name_rev, data, message=None):
name, rev = self._unmangle(name_rev) name, rev = self._unmangle(name_rev)
f = open(name, 'w') f = open(name, 'w')
f.write(data) f.write(data)
f.close() f.close()
self.checkin(name_rev, message) self.checkin(name_rev, message)
self._remove(name) self._remove(name)
def _list(self, function, list = None): 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: if list is None:
list = self.listfiles() list = self.listfiles()
res = [] res = []
for name in list: for name in list:
try: try:
res.append((name, function(name))) res.append((name, function(name)))
except (os.error, IOError): except (os.error, IOError):
res.append((name, None)) res.append((name, None))
return res return res
def _dict(self, function, list = None): 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: if list is None:
list = self.listfiles() list = self.listfiles()
dict = {} dict = {}
for name in list: for name in list:
try: try:
dict[name] = function(name) dict[name] = function(name)
except (os.error, IOError): except (os.error, IOError):
pass pass
return dict return dict
class RCSProxyServer(RCSProxyLocal, server.SecureServer): class RCSProxyServer(RCSProxyLocal, server.SecureServer):
def __init__(self, address, verbose = server.VERBOSE): def __init__(self, address, verbose = server.VERBOSE):
RCSProxyLocal.__init__(self) RCSProxyLocal.__init__(self)
server.SecureServer.__init__(self, address, verbose) server.SecureServer.__init__(self, address, verbose)
def _close(self): def _close(self):
server.SecureServer._close(self) server.SecureServer._close(self)
RCSProxyLocal._close(self) RCSProxyLocal._close(self)
def _serve(self): def _serve(self):
server.SecureServer._serve(self) server.SecureServer._serve(self)
# Retreat into start directory # Retreat into start directory
while self._dirstack: self.back() while self._dirstack: self.back()
def test_server(): def test_server():
import string import string
import sys import sys
if sys.argv[1:]: if sys.argv[1:]:
port = string.atoi(sys.argv[1]) port = string.atoi(sys.argv[1])
else: else:
port = 4127 port = 4127
proxy = RCSProxyServer(('', port)) proxy = RCSProxyServer(('', port))
proxy._serverloop() proxy._serverloop()
...@@ -179,19 +179,19 @@ def test_server(): ...@@ -179,19 +179,19 @@ def test_server():
def test(): def test():
import sys import sys
if not sys.argv[1:] or sys.argv[1] and sys.argv[1][0] in '0123456789': if not sys.argv[1:] or sys.argv[1] and sys.argv[1][0] in '0123456789':
test_server() test_server()
sys.exit(0) sys.exit(0)
proxy = RCSProxyLocal() proxy = RCSProxyLocal()
what = sys.argv[1] what = sys.argv[1]
if hasattr(proxy, what): if hasattr(proxy, what):
attr = getattr(proxy, what) attr = getattr(proxy, what)
if callable(attr): if callable(attr):
print apply(attr, tuple(sys.argv[2:])) print apply(attr, tuple(sys.argv[2:]))
else: else:
print `attr` print `attr`
else: else:
print "%s: no such attribute" % what print "%s: no such attribute" % what
sys.exit(2) sys.exit(2)
if __name__ == '__main__': if __name__ == '__main__':
......
...@@ -15,25 +15,25 @@ def main(): ...@@ -15,25 +15,25 @@ def main():
opts, args = getopt.getopt(args, 'p:') opts, args = getopt.getopt(args, 'p:')
prefix = '' prefix = ''
for o, a in opts: for o, a in opts:
if p == '-p': prefix = a if p == '-p': prefix = a
f = sys.stdin f = sys.stdin
allrevs = [] allrevs = []
while 1: while 1:
file = getnextfile(f) file = getnextfile(f)
if not file: break if not file: break
revs = [] revs = []
while 1: while 1:
rev = getnextrev(f, file) rev = getnextrev(f, file)
if not rev: if not rev:
break break
revs.append(rev) revs.append(rev)
if revs: if revs:
allrevs[len(allrevs):] = revs allrevs[len(allrevs):] = revs
allrevs.sort() allrevs.sort()
allrevs.reverse() allrevs.reverse()
for rev in allrevs: for rev in allrevs:
formatrev(rev, prefix) formatrev(rev, prefix)
parsedateprog = regex.compile( parsedateprog = regex.compile(
'^date: \([0-9]+\)/\([0-9]+\)/\([0-9]+\) ' + '^date: \([0-9]+\)/\([0-9]+\)/\([0-9]+\) ' +
...@@ -48,46 +48,46 @@ authormap = { ...@@ -48,46 +48,46 @@ authormap = {
def formatrev(rev, prefix): def formatrev(rev, prefix):
dateline, file, revline, log = rev dateline, file, revline, log = rev
if parsedateprog.match(dateline) >= 0: if parsedateprog.match(dateline) >= 0:
fields = parsedateprog.group(1, 2, 3, 4, 5, 6) fields = parsedateprog.group(1, 2, 3, 4, 5, 6)
author = parsedateprog.group(7) author = parsedateprog.group(7)
if authormap.has_key(author): author = authormap[author] if authormap.has_key(author): author = authormap[author]
tfields = map(string.atoi, fields) + [0, 0, 0] tfields = map(string.atoi, fields) + [0, 0, 0]
tfields[5] = tfields[5] - time.timezone tfields[5] = tfields[5] - time.timezone
t = time.mktime(tuple(tfields)) t = time.mktime(tuple(tfields))
print time.ctime(t), '', author print time.ctime(t), '', author
words = string.split(log) words = string.split(log)
words[:0] = ['*', prefix + file + ':'] words[:0] = ['*', prefix + file + ':']
maxcol = 72-8 maxcol = 72-8
col = maxcol col = maxcol
for word in words: for word in words:
if col > 0 and col + len(word) >= maxcol: if col > 0 and col + len(word) >= maxcol:
print print
print '\t' + word, print '\t' + word,
col = -1 col = -1
else: else:
print word, print word,
col = col + 1 + len(word) col = col + 1 + len(word)
print print
print print
startprog = regex.compile("^Working file: \(.*\)$") startprog = regex.compile("^Working file: \(.*\)$")
def getnextfile(f): def getnextfile(f):
while 1: while 1:
line = f.readline() line = f.readline()
if not line: return None if not line: return None
if startprog.match(line) >= 0: if startprog.match(line) >= 0:
file = startprog.group(1) file = startprog.group(1)
# Skip until first revision # Skip until first revision
while 1: while 1:
line = f.readline() line = f.readline()
if not line: return None if not line: return None
if line[:10] == '='*10: return None if line[:10] == '='*10: return None
if line[:10] == '-'*10: break if line[:10] == '-'*10: break
## print "Skipped", line, ## print "Skipped", line,
return file return file
## else: ## else:
## print "Ignored", line, ## print "Ignored", line,
def getnextrev(f, file): def getnextrev(f, file):
# This is called when we are positioned just after a '---' separator # This is called when we are positioned just after a '---' separator
...@@ -95,14 +95,14 @@ def getnextrev(f, file): ...@@ -95,14 +95,14 @@ def getnextrev(f, file):
dateline = f.readline() dateline = f.readline()
log = '' log = ''
while 1: while 1:
line = f.readline() line = f.readline()
if not line: break if not line: break
if line[:10] == '='*10: if line[:10] == '='*10:
# Ignore the *last* log entry for each file since it # Ignore the *last* log entry for each file since it
# is the revision since which we are logging. # is the revision since which we are logging.
return None return None
if line[:10] == '-'*10: break if line[:10] == '-'*10: break
log = log + line log = log + line
return dateline, file, revline, log return dateline, file, revline, log
if __name__ == '__main__': if __name__ == '__main__':
......
...@@ -22,8 +22,8 @@ import client ...@@ -22,8 +22,8 @@ import client
class RCSProxyClient(client.SecureClient): class RCSProxyClient(client.SecureClient):
def __init__(self, address, verbose = client.VERBOSE): def __init__(self, address, verbose = client.VERBOSE):
client.SecureClient.__init__(self, address, verbose) client.SecureClient.__init__(self, address, verbose)
def openrcsclient(opts = []): def openrcsclient(opts = []):
......
...@@ -36,304 +36,304 @@ class RCS: ...@@ -36,304 +36,304 @@ class RCS:
okchars = string.letters + string.digits + '-_=+.' okchars = string.letters + string.digits + '-_=+.'
def __init__(self): def __init__(self):
"""Constructor.""" """Constructor."""
pass pass
def __del__(self): def __del__(self):
"""Destructor.""" """Destructor."""
pass pass
# --- Informational methods about a single file/revision --- # --- Informational methods about a single file/revision ---
def log(self, name_rev, otherflags = ''): def log(self, name_rev, otherflags = ''):
"""Return the full log text for NAME_REV as a string. """Return the full log text for NAME_REV as a string.
Optional OTHERFLAGS are passed to rlog. Optional OTHERFLAGS are passed to rlog.
""" """
f = self._open(name_rev, 'rlog ' + otherflags) f = self._open(name_rev, 'rlog ' + otherflags)
data = f.read() data = f.read()
status = self._closepipe(f) status = self._closepipe(f)
if status: if status:
data = data + "%s: %s" % status data = data + "%s: %s" % status
elif data[-1] == '\n': elif data[-1] == '\n':
data = data[:-1] data = data[:-1]
return data return data
def head(self, name_rev): def head(self, name_rev):
"""Return the head revision for NAME_REV""" """Return the head revision for NAME_REV"""
dict = self.info(name_rev) dict = self.info(name_rev)
return dict['head'] return dict['head']
def info(self, name_rev): def info(self, name_rev):
"""Return a dictionary of info (from rlog -h) for NAME_REV """Return a dictionary of info (from rlog -h) for NAME_REV
The dictionary's keys are the keywords that rlog prints The dictionary's keys are the keywords that rlog prints
(e.g. 'head' and its values are the corresponding data (e.g. 'head' and its values are the corresponding data
(e.g. '1.3'). (e.g. '1.3').
XXX symbolic names and locks are not returned XXX symbolic names and locks are not returned
""" """
f = self._open(name_rev, 'rlog -h') f = self._open(name_rev, 'rlog -h')
dict = {} dict = {}
while 1: while 1:
line = f.readline() line = f.readline()
if not line: break if not line: break
if line[0] == '\t': if line[0] == '\t':
# XXX could be a lock or symbolic name # XXX could be a lock or symbolic name
# Anything else? # Anything else?
continue continue
i = string.find(line, ':') i = string.find(line, ':')
if i > 0: if i > 0:
key, value = line[:i], string.strip(line[i+1:]) key, value = line[:i], string.strip(line[i+1:])
dict[key] = value dict[key] = value
status = self._closepipe(f) status = self._closepipe(f)
if status: if status:
raise IOError, status raise IOError, status
return dict return dict
# --- Methods that change files --- # --- Methods that change files ---
def lock(self, name_rev): def lock(self, name_rev):
"""Set an rcs lock on NAME_REV.""" """Set an rcs lock on NAME_REV."""
name, rev = self.checkfile(name_rev) name, rev = self.checkfile(name_rev)
cmd = "rcs -l%s %s" % (rev, name) cmd = "rcs -l%s %s" % (rev, name)
return self._system(cmd) return self._system(cmd)
def unlock(self, name_rev): def unlock(self, name_rev):
"""Clear an rcs lock on NAME_REV.""" """Clear an rcs lock on NAME_REV."""
name, rev = self.checkfile(name_rev) name, rev = self.checkfile(name_rev)
cmd = "rcs -u%s %s" % (rev, name) cmd = "rcs -u%s %s" % (rev, name)
return self._system(cmd) return self._system(cmd)
def checkout(self, name_rev, withlock=0, otherflags=""): def checkout(self, name_rev, withlock=0, otherflags=""):
"""Check out NAME_REV to its work file. """Check out NAME_REV to its work file.
If optional WITHLOCK is set, check out locked, else unlocked. If optional WITHLOCK is set, check out locked, else unlocked.
The optional OTHERFLAGS is passed to co without The optional OTHERFLAGS is passed to co without
interpretation. interpretation.
Any output from co goes to directly to stdout. Any output from co goes to directly to stdout.
""" """
name, rev = self.checkfile(name_rev) name, rev = self.checkfile(name_rev)
if withlock: lockflag = "-l" if withlock: lockflag = "-l"
else: lockflag = "-u" else: lockflag = "-u"
cmd = 'co %s%s %s %s' % (lockflag, rev, otherflags, name) cmd = 'co %s%s %s %s' % (lockflag, rev, otherflags, name)
return self._system(cmd) return self._system(cmd)
def checkin(self, name_rev, message=None, otherflags=""): def checkin(self, name_rev, message=None, otherflags=""):
"""Check in NAME_REV from its work file. """Check in NAME_REV from its work file.
The optional MESSAGE argument becomes the checkin message The optional MESSAGE argument becomes the checkin message
(default "<none>" if None); or the file description if this is (default "<none>" if None); or the file description if this is
a new file. a new file.
The optional OTHERFLAGS argument is passed to ci without The optional OTHERFLAGS argument is passed to ci without
interpretation. interpretation.
Any output from ci goes to directly to stdout. Any output from ci goes to directly to stdout.
""" """
name, rev = self._unmangle(name_rev) name, rev = self._unmangle(name_rev)
new = not self.isvalid(name) new = not self.isvalid(name)
if not message: message = "<none>" if not message: message = "<none>"
if message and message[-1] != '\n': if message and message[-1] != '\n':
message = message + '\n' message = message + '\n'
lockflag = "-u" lockflag = "-u"
textfile = None textfile = None
try: try:
if new: if new:
textfile = tempfile.mktemp() textfile = tempfile.mktemp()
f = open(textfile, 'w') f = open(textfile, 'w')
f.write(message) f.write(message)
f.close() f.close()
cmd = 'ci %s%s -t%s %s %s' % \ cmd = 'ci %s%s -t%s %s %s' % \
(lockflag, rev, textfile, otherflags, name) (lockflag, rev, textfile, otherflags, name)
else: else:
message = regsub.gsub('\([\\"$`]\)', '\\\\\\1', message) message = regsub.gsub('\([\\"$`]\)', '\\\\\\1', message)
cmd = 'ci %s%s -m"%s" %s %s' % \ cmd = 'ci %s%s -m"%s" %s %s' % \
(lockflag, rev, message, otherflags, name) (lockflag, rev, message, otherflags, name)
return self._system(cmd) return self._system(cmd)
finally: finally:
if textfile: self._remove(textfile) if textfile: self._remove(textfile)
# --- Exported support methods --- # --- Exported support methods ---
def listfiles(self, pat = None): def listfiles(self, pat = None):
"""Return a list of all version files matching optional PATTERN.""" """Return a list of all version files matching optional PATTERN."""
files = os.listdir(os.curdir) files = os.listdir(os.curdir)
files = filter(self._isrcs, files) files = filter(self._isrcs, files)
if os.path.isdir('RCS'): if os.path.isdir('RCS'):
files2 = os.listdir('RCS') files2 = os.listdir('RCS')
files2 = filter(self._isrcs, files2) files2 = filter(self._isrcs, files2)
files = files + files2 files = files + files2
files = map(self.realname, files) files = map(self.realname, files)
return self._filter(files, pat) return self._filter(files, pat)
def isvalid(self, name): def isvalid(self, name):
"""Test whether NAME has a version file associated.""" """Test whether NAME has a version file associated."""
namev = self.rcsname(name) namev = self.rcsname(name)
return (os.path.isfile(namev) or return (os.path.isfile(namev) or
os.path.isfile(os.path.join('RCS', namev))) os.path.isfile(os.path.join('RCS', namev)))
def rcsname(self, name): def rcsname(self, name):
"""Return the pathname of the version file for NAME. """Return the pathname of the version file for NAME.
The argument can be a work file name or a version file name. The argument can be a work file name or a version file name.
If the version file does not exist, the name of the version If the version file does not exist, the name of the version
file that would be created by "ci" is returned. file that would be created by "ci" is returned.
""" """
if self._isrcs(name): namev = name if self._isrcs(name): namev = name
else: namev = name + ',v' else: namev = name + ',v'
if os.path.isfile(namev): return namev if os.path.isfile(namev): return namev
namev = os.path.join('RCS', os.path.basename(namev)) namev = os.path.join('RCS', os.path.basename(namev))
if os.path.isfile(namev): return namev if os.path.isfile(namev): return namev
if os.path.isdir('RCS'): if os.path.isdir('RCS'):
return os.path.join('RCS', namev) return os.path.join('RCS', namev)
else: else:
return namev return namev
def realname(self, namev): def realname(self, namev):
"""Return the pathname of the work file for NAME. """Return the pathname of the work file for NAME.
The argument can be a work file name or a version file name. The argument can be a work file name or a version file name.
If the work file does not exist, the name of the work file If the work file does not exist, the name of the work file
that would be created by "co" is returned. that would be created by "co" is returned.
""" """
if self._isrcs(namev): name = namev[:-2] if self._isrcs(namev): name = namev[:-2]
else: name = namev else: name = namev
if os.path.isfile(name): return name if os.path.isfile(name): return name
name = os.path.basename(name) name = os.path.basename(name)
return name return name
def islocked(self, name_rev): def islocked(self, name_rev):
"""Test whether FILE (which must have a version file) is locked. """Test whether FILE (which must have a version file) is locked.
XXX This does not tell you which revision number is locked and XXX This does not tell you which revision number is locked and
ignores any revision you may pass in (by virtue of using rlog ignores any revision you may pass in (by virtue of using rlog
-L -R). -L -R).
""" """
f = self._open(name_rev, 'rlog -L -R') f = self._open(name_rev, 'rlog -L -R')
line = f.readline() line = f.readline()
status = self._closepipe(f) status = self._closepipe(f)
if status: if status:
raise IOError, status raise IOError, status
if not line: return None if not line: return None
if line[-1] == '\n': if line[-1] == '\n':
line = line[:-1] line = line[:-1]
return self.realname(name_rev) == self.realname(line) return self.realname(name_rev) == self.realname(line)
def checkfile(self, name_rev): def checkfile(self, name_rev):
"""Normalize NAME_REV into a (NAME, REV) tuple. """Normalize NAME_REV into a (NAME, REV) tuple.
Raise an exception if there is no corresponding version file. Raise an exception if there is no corresponding version file.
""" """
name, rev = self._unmangle(name_rev) name, rev = self._unmangle(name_rev)
if not self.isvalid(name): if not self.isvalid(name):
raise os.error, 'not an rcs file %s' % `name` raise os.error, 'not an rcs file %s' % `name`
return name, rev return name, rev
# --- Internal methods --- # --- Internal methods ---
def _open(self, name_rev, cmd = 'co -p', rflag = '-r'): def _open(self, name_rev, cmd = 'co -p', rflag = '-r'):
"""INTERNAL: open a read pipe to NAME_REV using optional COMMAND. """INTERNAL: open a read pipe to NAME_REV using optional COMMAND.
Optional FLAG is used to indicate the revision (default -r). Optional FLAG is used to indicate the revision (default -r).
Default COMMAND is "co -p". Default COMMAND is "co -p".
Return a file object connected by a pipe to the command's Return a file object connected by a pipe to the command's
output. output.
""" """
name, rev = self.checkfile(name_rev) name, rev = self.checkfile(name_rev)
namev = self.rcsname(name) namev = self.rcsname(name)
if rev: if rev:
cmd = cmd + ' ' + rflag + rev cmd = cmd + ' ' + rflag + rev
return os.popen("%s %s" % (cmd, `namev`)) return os.popen("%s %s" % (cmd, `namev`))
def _unmangle(self, name_rev): def _unmangle(self, name_rev):
"""INTERNAL: Normalize NAME_REV argument to (NAME, REV) tuple. """INTERNAL: Normalize NAME_REV argument to (NAME, REV) tuple.
Raise an exception if NAME contains invalid characters. Raise an exception if NAME contains invalid characters.
A NAME_REV argument is either NAME string (implying REV='') or A NAME_REV argument is either NAME string (implying REV='') or
a tuple of the form (NAME, REV). a tuple of the form (NAME, REV).
""" """
if type(name_rev) == type(''): if type(name_rev) == type(''):
name_rev = name, rev = name_rev, '' name_rev = name, rev = name_rev, ''
else: else:
name, rev = name_rev name, rev = name_rev
for c in rev: for c in rev:
if c not in self.okchars: if c not in self.okchars:
raise ValueError, "bad char in rev" raise ValueError, "bad char in rev"
return name_rev return name_rev
def _closepipe(self, f): def _closepipe(self, f):
"""INTERNAL: Close PIPE and print its exit status if nonzero.""" """INTERNAL: Close PIPE and print its exit status if nonzero."""
sts = f.close() sts = f.close()
if not sts: return None if not sts: return None
detail, reason = divmod(sts, 256) detail, reason = divmod(sts, 256)
if reason == 0: return 'exit', detail # Exit status if reason == 0: return 'exit', detail # Exit status
signal = reason&0x7F signal = reason&0x7F
if signal == 0x7F: if signal == 0x7F:
code = 'stopped' code = 'stopped'
signal = detail signal = detail
else: else:
code = 'killed' code = 'killed'
if reason&0x80: if reason&0x80:
code = code + '(coredump)' code = code + '(coredump)'
return code, signal return code, signal
def _system(self, cmd): def _system(self, cmd):
"""INTERNAL: run COMMAND in a subshell. """INTERNAL: run COMMAND in a subshell.
Standard input for the command is taken fron /dev/null. Standard input for the command is taken fron /dev/null.
Raise IOError when the exit status is not zero. Raise IOError when the exit status is not zero.
Return whatever the calling method should return; normally Return whatever the calling method should return; normally
None. None.
A derived class may override this method and redefine it to A derived class may override this method and redefine it to
capture stdout/stderr of the command and return it. capture stdout/stderr of the command and return it.
""" """
cmd = cmd + " </dev/null" cmd = cmd + " </dev/null"
sts = os.system(cmd) sts = os.system(cmd)
if sts: raise IOError, "command exit status %d" % sts if sts: raise IOError, "command exit status %d" % sts
def _filter(self, files, pat = None): def _filter(self, files, pat = None):
"""INTERNAL: Return a sorted copy of the given list of FILES. """INTERNAL: Return a sorted copy of the given list of FILES.
If a second PATTERN argument is given, only files matching it If a second PATTERN argument is given, only files matching it
are kept. No check for valid filenames is made. are kept. No check for valid filenames is made.
""" """
if pat: if pat:
def keep(name, pat = pat): def keep(name, pat = pat):
return fnmatch.fnmatch(name, pat) return fnmatch.fnmatch(name, pat)
files = filter(keep, files) files = filter(keep, files)
else: else:
files = files[:] files = files[:]
files.sort() files.sort()
return files return files
def _remove(self, fn): def _remove(self, fn):
"""INTERNAL: remove FILE without complaints.""" """INTERNAL: remove FILE without complaints."""
try: try:
os.unlink(fn) os.unlink(fn)
except os.error: except os.error:
pass pass
def _isrcs(self, name): def _isrcs(self, name):
"""INTERNAL: Test whether NAME ends in ',v'.""" """INTERNAL: Test whether NAME ends in ',v'."""
return name[-2:] == ',v' return name[-2:] == ',v'
...@@ -14,30 +14,30 @@ can log in on your machine. Use with caution! ...@@ -14,30 +14,30 @@ can log in on your machine. Use with caution!
import sys, os, string, getopt, thread, socket, traceback import sys, os, string, getopt, thread, socket, traceback
PORT = 4000 # Default port PORT = 4000 # Default port
def main(): def main():
try: try:
opts, args = getopt.getopt(sys.argv[1:], "") opts, args = getopt.getopt(sys.argv[1:], "")
if len(args) > 1: if len(args) > 1:
raise getopt.error, "Too many arguments." raise getopt.error, "Too many arguments."
except getopt.error, msg: except getopt.error, msg:
usage(msg) usage(msg)
for o, a in opts: for o, a in opts:
pass pass
if args: if args:
try: try:
port = string.atoi(args[0]) port = string.atoi(args[0])
except ValueError, msg: except ValueError, msg:
usage(msg) usage(msg)
else: else:
port = PORT port = PORT
main_thread(port) main_thread(port)
def usage(msg=None): def usage(msg=None):
sys.stdout = sys.stderr sys.stdout = sys.stderr
if msg: if msg:
print msg print msg
print "\n", __doc__, print "\n", __doc__,
sys.exit(2) sys.exit(2)
...@@ -47,18 +47,18 @@ def main_thread(port): ...@@ -47,18 +47,18 @@ def main_thread(port):
sock.listen(5) sock.listen(5)
print "Listening on port", port, "..." print "Listening on port", port, "..."
while 1: while 1:
(conn, addr) = sock.accept() (conn, addr) = sock.accept()
if addr[0] != conn.getsockname()[0]: if addr[0] != conn.getsockname()[0]:
conn.close() conn.close()
print "Refusing connection from non-local host", addr[0], "." print "Refusing connection from non-local host", addr[0], "."
continue continue
thread.start_new_thread(service_thread, (conn, addr)) thread.start_new_thread(service_thread, (conn, addr))
del conn, addr del conn, addr
def service_thread(conn, addr): def service_thread(conn, addr):
(caddr, cport) = addr (caddr, cport) = addr
print "Thread %s has connection from %s.\n" % (str(thread.get_ident()), print "Thread %s has connection from %s.\n" % (str(thread.get_ident()),
caddr), caddr),
stdin = conn.makefile("r") stdin = conn.makefile("r")
stdout = conn.makefile("w", 0) stdout = conn.makefile("w", 0)
run_interpreter(stdin, stdout) run_interpreter(stdin, stdout)
...@@ -67,57 +67,57 @@ def service_thread(conn, addr): ...@@ -67,57 +67,57 @@ def service_thread(conn, addr):
def run_interpreter(stdin, stdout): def run_interpreter(stdin, stdout):
globals = {} globals = {}
try: try:
str(sys.ps1) str(sys.ps1)
except: except:
sys.ps1 = ">>> " sys.ps1 = ">>> "
source = "" source = ""
while 1: while 1:
stdout.write(sys.ps1) stdout.write(sys.ps1)
line = stdin.readline() line = stdin.readline()
if line[:2] == '\377\354': if line[:2] == '\377\354':
line = "" line = ""
if not line and not source: if not line and not source:
break break
if line[-2:] == '\r\n': if line[-2:] == '\r\n':
line = line[:-2] + '\n' line = line[:-2] + '\n'
source = source + line source = source + line
try: try:
code = compile_command(source) code = compile_command(source)
except SyntaxError, err: except SyntaxError, err:
source = "" source = ""
traceback.print_exception(SyntaxError, err, None, file=stdout) traceback.print_exception(SyntaxError, err, None, file=stdout)
continue continue
if not code: if not code:
continue continue
source = "" source = ""
try: try:
run_command(code, stdin, stdout, globals) run_command(code, stdin, stdout, globals)
except SystemExit, how: except SystemExit, how:
if how: if how:
try: try:
how = str(how) how = str(how)
except: except:
how = "" how = ""
stdout.write("Exit %s\n" % how) stdout.write("Exit %s\n" % how)
break break
stdout.write("\nGoodbye.\n") stdout.write("\nGoodbye.\n")
def run_command(code, stdin, stdout, globals): def run_command(code, stdin, stdout, globals):
save = sys.stdin, sys.stdout, sys.stderr save = sys.stdin, sys.stdout, sys.stderr
try: try:
sys.stdout = sys.stderr = stdout sys.stdout = sys.stderr = stdout
sys.stdin = stdin sys.stdin = stdin
try: try:
exec code in globals exec code in globals
except SystemExit, how: except SystemExit, how:
raise SystemExit, how, sys.exc_info()[2] raise SystemExit, how, sys.exc_info()[2]
except: except:
type, value, tb = sys.exc_info() type, value, tb = sys.exc_info()
if tb: tb = tb.tb_next if tb: tb = tb.tb_next
traceback.print_exception(type, value, tb) traceback.print_exception(type, value, tb)
del tb del tb
finally: finally:
sys.stdin, sys.stdout, sys.stderr = save sys.stdin, sys.stdout, sys.stderr = save
from code import compile_command from code import compile_command
......
...@@ -96,22 +96,22 @@ class NFSUnpacker(MountUnpacker): ...@@ -96,22 +96,22 @@ class NFSUnpacker(MountUnpacker):
return status, attributes return status, attributes
def unpack_fattr(self): def unpack_fattr(self):
type = self.unpack_enum() type = self.unpack_enum()
mode = self.unpack_uint() mode = self.unpack_uint()
nlink = self.unpack_uint() nlink = self.unpack_uint()
uid = self.unpack_uint() uid = self.unpack_uint()
gid = self.unpack_uint() gid = self.unpack_uint()
size = self.unpack_uint() size = self.unpack_uint()
blocksize = self.unpack_uint() blocksize = self.unpack_uint()
rdev = self.unpack_uint() rdev = self.unpack_uint()
blocks = self.unpack_uint() blocks = self.unpack_uint()
fsid = self.unpack_uint() fsid = self.unpack_uint()
fileid = self.unpack_uint() fileid = self.unpack_uint()
atime = self.unpack_timeval() atime = self.unpack_timeval()
mtime = self.unpack_timeval() mtime = self.unpack_timeval()
ctime = self.unpack_timeval() ctime = self.unpack_timeval()
return (type, mode, nlink, uid, gid, size, blocksize, \ return (type, mode, nlink, uid, gid, size, blocksize, \
rdev, blocks, fsid, fileid, atime, mtime, ctime) rdev, blocks, fsid, fileid, atime, mtime, ctime)
def unpack_timeval(self): def unpack_timeval(self):
secs = self.unpack_uint() secs = self.unpack_uint()
......
...@@ -53,44 +53,45 @@ def main(): ...@@ -53,44 +53,45 @@ def main():
bytype = {} bytype = {}
lineno = 0 lineno = 0
try: 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: while 1:
i = string.find(logfile, '//') line = f.readline()
if i < 0: break if not line: break
logfile = logfile[i+1:] lineno = lineno + 1
add(byfile, logfile + ' ' + direction, items) if search and string.find(line, search) < 0:
logdir = os.path.dirname(logfile) 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) + '/.' ## logdir = os.path.normpath(logdir) + '/.'
while 1: while 1:
add(bydir, logdir + ' ' + direction, items) add(bydir, logdir + ' ' + direction, items)
dirhead = os.path.dirname(logdir) dirhead = os.path.dirname(logdir)
if dirhead == logdir: break if dirhead == logdir: break
logdir = dirhead logdir = dirhead
add(byhost, loghost, items) add(byhost, loghost, items)
add(byuser, loguser, items) add(byuser, loguser, items)
add(bytype, direction, items) add(bytype, direction, items)
except KeyboardInterrupt: except KeyboardInterrupt:
print 'Interrupted at line', lineno print 'Interrupted at line', lineno
show(bytype, 'by transfer direction', maxitems) show(bytype, 'by transfer direction', maxitems)
......
...@@ -96,11 +96,11 @@ sublistsize = 4 ...@@ -96,11 +96,11 @@ sublistsize = 4
####################################################################### #######################################################################
for dir in os.curdir, os.environ['HOME']: for dir in os.curdir, os.environ['HOME']:
rcfile = os.path.join(dir, '.newslistrc.py') rcfile = os.path.join(dir, '.newslistrc.py')
if os.path.exists(rcfile): if os.path.exists(rcfile):
print rcfile print rcfile
execfile(rcfile) execfile(rcfile)
break break
from nntplib import NNTP from nntplib import NNTP
from stat import * from stat import *
...@@ -120,8 +120,8 @@ page = os.path.join(topdir,pagedir) ...@@ -120,8 +120,8 @@ page = os.path.join(topdir,pagedir)
def addtotree(tree, groups): def addtotree(tree, groups):
print 'Updating tree...' print 'Updating tree...'
for i in groups: for i in groups:
parts = string.splitfields(i,'.') parts = string.splitfields(i,'.')
makeleaf(tree, parts) makeleaf(tree, parts)
# Makeleaf makes a leaf and the branch leading to it if necessary # Makeleaf makes a leaf and the branch leading to it if necessary
def makeleaf(tree,path): def makeleaf(tree,path):
...@@ -135,7 +135,7 @@ def makeleaf(tree,path): ...@@ -135,7 +135,7 @@ def makeleaf(tree,path):
if l > 1: if l > 1:
makeleaf(tree[j],path[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 # Createpage creates an HTML file named <root>.html containing links
# to those groups beginning with <root>. # to those groups beginning with <root>.
...@@ -177,24 +177,24 @@ def printtree(f, tree, indent, p): ...@@ -177,24 +177,24 @@ def printtree(f, tree, indent, p):
if l > 1: if l > 1:
kl.sort() kl.sort()
if indent > 0: if indent > 0:
# Create a sub-list # Create a sub-list
f.write('<LI>'+p[1:]+'\n<UL>') f.write('<LI>'+p[1:]+'\n<UL>')
else: else:
# Create a main list # Create a main list
f.write('<UL>') f.write('<UL>')
indent = indent + 1 indent = indent + 1
for i in kl: for i in kl:
if i == '.': if i == '.':
# Output a newsgroup # Output a newsgroup
f.write('<LI><A HREF="news:' + p[1:] + '">'+ p[1:] + '</A> ') f.write('<LI><A HREF="news:' + p[1:] + '">'+ p[1:] + '</A> ')
if desc.has_key(p[1:]): if desc.has_key(p[1:]):
f.write(' <I>'+desc[p[1:]]+'</I>\n') f.write(' <I>'+desc[p[1:]]+'</I>\n')
else: else:
f.write('\n') f.write('\n')
else: else:
# Output a hierarchy # Output a hierarchy
printtree(f,tree[i], indent, p+'.'+i) printtree(f,tree[i], indent, p+'.'+i)
if l > 1: if l > 1:
f.write('\n</UL>') f.write('\n</UL>')
...@@ -209,7 +209,7 @@ def readdesc(descfile): ...@@ -209,7 +209,7 @@ def readdesc(descfile):
desc = {} desc = {}
if descfile == '': if descfile == '':
return return
try: try:
d = open(descfile, 'r') d = open(descfile, 'r')
...@@ -221,12 +221,12 @@ def readdesc(descfile): ...@@ -221,12 +221,12 @@ def readdesc(descfile):
while l != '': while l != '':
bits = string.split(l) bits = string.split(l)
try: try:
grp = bits[0] grp = bits[0]
dsc = string.join(bits[1:]) dsc = string.join(bits[1:])
if len(dsc)>1: if len(dsc)>1:
desc[grp] = dsc desc[grp] = dsc
except (IndexError): except (IndexError):
pass pass
l = d.readline() l = d.readline()
# Check that ouput directory exists, ------------------------------ # Check that ouput directory exists, ------------------------------
...@@ -237,14 +237,14 @@ def checkopdir(pagedir): ...@@ -237,14 +237,14 @@ def checkopdir(pagedir):
print 'Directory '+pagedir+' does not exist.' print 'Directory '+pagedir+' does not exist.'
print 'Shall I create it for you? (y/n)' print 'Shall I create it for you? (y/n)'
if sys.stdin.readline()[0] == 'y': if sys.stdin.readline()[0] == 'y':
try: try:
os.mkdir(pagedir,0777) os.mkdir(pagedir,0777)
except: except:
print 'Sorry - failed!' print 'Sorry - failed!'
sys.exit(1) sys.exit(1)
else: else:
print 'OK. Exiting.' print 'OK. Exiting.'
sys.exit(1) sys.exit(1)
# Read and write current local tree ---------------------------------- # Read and write current local tree ----------------------------------
...@@ -252,19 +252,19 @@ def readlocallist(treefile): ...@@ -252,19 +252,19 @@ def readlocallist(treefile):
print 'Reading current local group list...' print 'Reading current local group list...'
tree = {} tree = {}
try: try:
treetime = time.localtime(os.stat(treefile)[ST_MTIME]) treetime = time.localtime(os.stat(treefile)[ST_MTIME])
except: except:
print '\n*** Failed to open local group cache '+treefile print '\n*** Failed to open local group cache '+treefile
print 'If this is the first time you have run newslist, then' print 'If this is the first time you have run newslist, then'
print 'use the -a option to create it.' print 'use the -a option to create it.'
sys.exit(1) sys.exit(1)
treedate = '%02d%02d%02d' % (treetime[0] % 100 ,treetime[1], treetime[2]) treedate = '%02d%02d%02d' % (treetime[0] % 100 ,treetime[1], treetime[2])
try: try:
dump = open(treefile,'r') dump = open(treefile,'r')
tree = marshal.load(dump) tree = marshal.load(dump)
dump.close() dump.close()
except (IOError): except (IOError):
print 'Cannot open local group list ' + treefile print 'Cannot open local group list ' + treefile
return (tree, treedate) return (tree, treedate)
def writelocallist(treefile, tree): def writelocallist(treefile, tree):
...@@ -291,9 +291,9 @@ def getallgroups(server): ...@@ -291,9 +291,9 @@ def getallgroups(server):
for i in info: for i in info:
grpname = string.split(i[0])[0] grpname = string.split(i[0])[0]
if skipempty and string.atoi(i[1]) < string.atoi(i[2]): if skipempty and string.atoi(i[1]) < string.atoi(i[2]):
print grpname+' ', print grpname+' ',
else: else:
groups.append(grpname) groups.append(grpname)
print '\n' print '\n'
if skipempty: if skipempty:
print '(End of empty groups)' print '(End of empty groups)'
...@@ -326,9 +326,9 @@ def main(): ...@@ -326,9 +326,9 @@ def main():
try: try:
print 'Connecting to '+newshost+'...' print 'Connecting to '+newshost+'...'
if sys.version[0] == '0': if sys.version[0] == '0':
s = NNTP.init(newshost) s = NNTP.init(newshost)
else: else:
s = NNTP(newshost) s = NNTP(newshost)
connected = 1 connected = 1
except (nntplib.error_temp, nntplib.error_perm), x: except (nntplib.error_temp, nntplib.error_perm), x:
print 'Error connecting to host:', x print 'Error connecting to host:', x
...@@ -346,7 +346,7 @@ def main(): ...@@ -346,7 +346,7 @@ def main():
(tree, treedate) = readlocallist(treefile) (tree, treedate) = readlocallist(treefile)
if connected: if connected:
groups = getnewgroups(s, treedate) groups = getnewgroups(s, treedate)
if connected: if connected:
addtotree(tree, groups) addtotree(tree, groups)
......
...@@ -217,108 +217,108 @@ commands['\b'] = WC_BACKSPACE ...@@ -217,108 +217,108 @@ commands['\b'] = WC_BACKSPACE
commands['\t'] = WC_TAB commands['\t'] = WC_TAB
# #
def getevent(): def getevent():
while 1: while 1:
# #
# Get next event from the processed queue, if any # Get next event from the processed queue, if any
# #
if G.queue: if G.queue:
event = G.queue[0] event = G.queue[0]
del G.queue[0] del G.queue[0]
#print 'getevent from queue -->', event #print 'getevent from queue -->', event
return event return event
# #
# Get next event from the draw queue, if any, # Get next event from the draw queue, if any,
# but only if there is nothing in the system queue. # but only if there is nothing in the system queue.
# #
if G.drawqueue and not gl.qtest(): if G.drawqueue and not gl.qtest():
win = G.drawqueue[0] win = G.drawqueue[0]
del G.drawqueue[0] del G.drawqueue[0]
gl.winset(win._gid) gl.winset(win._gid)
gl.color(win._bg) gl.color(win._bg)
gl.clear() gl.clear()
event = WE_DRAW, win, win._area event = WE_DRAW, win, win._area
#print 'getevent from drawqueue -->', event #print 'getevent from drawqueue -->', event
return event return event
# #
# Get next event from system queue, blocking if necessary # Get next event from system queue, blocking if necessary
# until one is available. # until one is available.
# Some cases immediately return the event, others do nothing # Some cases immediately return the event, others do nothing
# or append one or more events to the processed queue. # or append one or more events to the processed queue.
# #
dev, val = gl.qread() dev, val = gl.qread()
# #
if dev == REDRAW: if dev == REDRAW:
win = G.windowmap[`val`] win = G.windowmap[`val`]
old_area = win._area old_area = win._area
win._fixviewport() win._fixviewport()
win._needredraw() win._needredraw()
if old_area <> win._area: if old_area <> win._area:
#print 'getevent --> WE_SIZE' #print 'getevent --> WE_SIZE'
return WE_SIZE, win, None return WE_SIZE, win, None
elif dev == KEYBD: elif dev == KEYBD:
if val == 3: if val == 3:
raise KeyboardInterrupt # Control-C in window raise KeyboardInterrupt # Control-C in window
character = chr(val) character = chr(val)
if commands.has_key(character): if commands.has_key(character):
return WE_COMMAND, G.focus, commands[character] return WE_COMMAND, G.focus, commands[character]
return WE_CHAR, G.focus, character return WE_CHAR, G.focus, character
elif dev == LEFTARROWKEY: elif dev == LEFTARROWKEY:
if val: if val:
return WE_COMMAND, G.focus, WC_LEFT return WE_COMMAND, G.focus, WC_LEFT
elif dev == RIGHTARROWKEY: elif dev == RIGHTARROWKEY:
if val: if val:
return WE_COMMAND, G.focus, WC_RIGHT return WE_COMMAND, G.focus, WC_RIGHT
elif dev == UPARROWKEY: elif dev == UPARROWKEY:
if val: if val:
return WE_COMMAND, G.focus, WC_UP return WE_COMMAND, G.focus, WC_UP
elif dev == DOWNARROWKEY: elif dev == DOWNARROWKEY:
if val: if val:
return WE_COMMAND, G.focus, WC_DOWN return WE_COMMAND, G.focus, WC_DOWN
elif dev in (LEFTALTKEY, RIGHTALTKEY): elif dev in (LEFTALTKEY, RIGHTALTKEY):
if val: if val:
for code in codelist: for code in codelist:
gl.qdevice(code) 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: else:
for code in codelist: print '*** qread() --> dev:', dev, 'val:', val
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
# Helper routine to construct a mouse (up, move or down) event # Helper routine to construct a mouse (up, move or down) event
# #
......
...@@ -17,37 +17,37 @@ SPOTLIGHT = 104 ...@@ -17,37 +17,37 @@ SPOTLIGHT = 104
# Make a cylinder paralel with the Z axis with center (X,Y,0) # Make a cylinder paralel with the Z axis with center (X,Y,0)
# and radius 1 # and radius 1
def mkcyl(nslice, nparts, docircle): def mkcyl(nslice, nparts, docircle):
cyl = [] cyl = []
step = 2.0 / float(nslice) step = 2.0 / float(nslice)
z = -1.0 z = -1.0
for i in range(nslice): for i in range(nslice):
cyl.append(mkslice(z, z+step, nparts, docircle)) cyl.append(mkslice(z, z+step, nparts, docircle))
z = z + step z = z + step
return drawcylinder(cyl) return drawcylinder(cyl)
# #
# Make one part of a cylinder # Make one part of a cylinder
# #
def mkslice(z1, z2, nparts, docircle): def mkslice(z1, z2, nparts, docircle):
if docircle: if docircle:
w1 = z1 w1 = z1
w2 = z2 w2 = z2
w1 = sqrt(1.0-w1*w1) w1 = sqrt(1.0-w1*w1)
w2 = sqrt(1.0-w2*w2) w2 = sqrt(1.0-w2*w2)
normalz = 1.0 normalz = 1.0
else: else:
w1 = 1.0 w1 = 1.0
w2 = 1.0 w2 = 1.0
normalz = 0.0 normalz = 0.0
slice = [] slice = []
step = (2.0*pi)/float(nparts) step = (2.0*pi)/float(nparts)
angle = 0.0 angle = 0.0
for i in range(nparts+1): for i in range(nparts+1):
vx = cos(angle) vx = cos(angle)
vy = sin(angle) vy = sin(angle)
slice.append( ((vx*w1,vy*w1,z1), (vx*w1, vy*w1, z1*normalz)) ) slice.append( ((vx*w1,vy*w1,z1), (vx*w1, vy*w1, z1*normalz)) )
slice.append( ((vx*w2,vy*w2,z2), (vx*w2, vy*w2, z2*normalz)) ) slice.append( ((vx*w2,vy*w2,z2), (vx*w2, vy*w2, z2*normalz)) )
angle = angle + step angle = angle + step
return slice return slice
# #
# Drawcylinder : draw the cylinder # Drawcylinder : draw the cylinder
# #
...@@ -55,370 +55,370 @@ class struct: pass ...@@ -55,370 +55,370 @@ class struct: pass
curobj = struct() curobj = struct()
curobj.curobj = 1 curobj.curobj = 1
def drawcylinder(cyl): def drawcylinder(cyl):
obj = curobj.curobj obj = curobj.curobj
curobj.curobj = curobj.curobj+1 curobj.curobj = curobj.curobj+1
makeobj(obj) makeobj(obj)
for slice in cyl: for slice in cyl:
bgntmesh() bgntmesh()
vnarray(slice) vnarray(slice)
endtmesh() endtmesh()
closeobj() closeobj()
return obj return obj
# #
def drawnormals(cyl): def drawnormals(cyl):
for slice in cyl: for slice in cyl:
for triang in slice: for triang in slice:
bgnline() bgnline()
v3f(triang[0]) v3f(triang[0])
v3f(triang[0][0] + triang[1][0], triang[0][1] + triang[1][1], triang[0][2] + triang[1][2]) v3f(triang[0][0] + triang[1][0], triang[0][1] + triang[1][1], triang[0][2] + triang[1][2])
endline() endline()
def drawfloors(): def drawfloors():
obj = curobj.curobj obj = curobj.curobj
curobj.curobj = curobj.curobj+1 curobj.curobj = curobj.curobj+1
makeobj(obj) makeobj(obj)
bgnpolygon() bgnpolygon()
v3i(4,6,-6) v3i(4,6,-6)
v3i(-6,6,-6) v3i(-6,6,-6)
v3i(-6,-6,-6) v3i(-6,-6,-6)
v3i(4,-6,-6) v3i(4,-6,-6)
endpolygon() endpolygon()
for floor in range(3): for floor in range(3):
pos = -1 + 5*floor pos = -1 + 5*floor
bgnpolygon() bgnpolygon()
v3i(4,4,pos) v3i(4,4,pos)
v3i(-6,4,pos) v3i(-6,4,pos)
v3i(-6,6,pos) v3i(-6,6,pos)
v3i(4,6,pos) v3i(4,6,pos)
endpolygon() endpolygon()
bgnpolygon() bgnpolygon()
v3i(-4,4,pos) v3i(-4,4,pos)
v3i(-4,-4,pos) v3i(-4,-4,pos)
v3i(-6,-4,pos) v3i(-6,-4,pos)
v3i(-6,4,pos) v3i(-6,4,pos)
endpolygon() endpolygon()
bgnpolygon() bgnpolygon()
v3i(-6,-4,pos) v3i(-6,-4,pos)
v3i(-6,-6,pos) v3i(-6,-6,pos)
v3i(4,-6,pos) v3i(4,-6,pos)
v3i(4,-4,pos) v3i(4,-4,pos)
endpolygon() endpolygon()
closeobj() closeobj()
return obj return obj
def drawdoors(): def drawdoors():
obj = curobj.curobj obj = curobj.curobj
curobj.curobj = curobj.curobj+1 curobj.curobj = curobj.curobj+1
makeobj(obj) makeobj(obj)
for floor in range(3): for floor in range(3):
pos = -1+5*floor pos = -1+5*floor
bgnpolygon() bgnpolygon()
v3i(-2,6,pos) v3i(-2,6,pos)
v3i(-2,6,pos+3) v3i(-2,6,pos+3)
v3i(0,6,pos+3) v3i(0,6,pos+3)
v3i(0,6,pos) v3i(0,6,pos)
endpolygon() endpolygon()
closeobj() closeobj()
return obj return obj
def drawrailing(): def drawrailing():
obj = curobj.curobj obj = curobj.curobj
curobj.curobj = curobj.curobj+1 curobj.curobj = curobj.curobj+1
makeobj(obj) makeobj(obj)
for floor in range(3): for floor in range(3):
pos = -1 + 5*floor pos = -1 + 5*floor
bgnpolygon() bgnpolygon()
v3i(4,4,pos) v3i(4,4,pos)
v3i(4,4,pos-1) v3i(4,4,pos-1)
v3i(-4,4,pos-1) v3i(-4,4,pos-1)
v3i(-4,4,pos) v3i(-4,4,pos)
endpolygon() endpolygon()
bgnpolygon() bgnpolygon()
v3i(-4,4,pos) v3i(-4,4,pos)
v3i(-4,4,pos-1) v3i(-4,4,pos-1)
v3i(-4,-4,pos-1) v3i(-4,-4,pos-1)
v3i(-4,-4,pos) v3i(-4,-4,pos)
endpolygon() endpolygon()
bgnpolygon() bgnpolygon()
v3i(-4,-4,pos) v3i(-4,-4,pos)
v3i(-4,-4,pos-1) v3i(-4,-4,pos-1)
v3i(4,-4,pos-1) v3i(4,-4,pos-1)
v3i(4,-4,pos) v3i(4,-4,pos)
endpolygon() endpolygon()
closeobj() closeobj()
return obj return obj
def drawwalls(): def drawwalls():
obj = curobj.curobj obj = curobj.curobj
curobj.curobj = curobj.curobj+1 curobj.curobj = curobj.curobj+1
makeobj(obj) makeobj(obj)
bgnpolygon() bgnpolygon()
v3i(4,6,-6) v3i(4,6,-6)
v3i(4,6,18) v3i(4,6,18)
v3i(-6,6,18) v3i(-6,6,18)
v3i(-6,6,-6) v3i(-6,6,-6)
endpolygon() endpolygon()
bgnpolygon() bgnpolygon()
v3i(-6,6,-6) v3i(-6,6,-6)
v3i(-6,6,18) v3i(-6,6,18)
v3i(-6,-6,18) v3i(-6,-6,18)
v3i(-6,-6,-6) v3i(-6,-6,-6)
endpolygon() endpolygon()
bgnpolygon() bgnpolygon()
v3i(-6,-6,-6) v3i(-6,-6,-6)
v3i(-6,-6,18) v3i(-6,-6,18)
v3i(4,-6,18) v3i(4,-6,18)
v3i(4,-6,-6) v3i(4,-6,-6)
endpolygon() endpolygon()
bgnpolygon() bgnpolygon()
v3i(4,-6,-6) v3i(4,-6,-6)
v3i(4,-6,18) v3i(4,-6,18)
v3i(4,4,18) v3i(4,4,18)
v3i(4,4,-6) v3i(4,4,-6)
endpolygon() endpolygon()
closeobj() closeobj()
return obj return obj
def axis(): def axis():
bgnline() bgnline()
cpack(0xff0000) cpack(0xff0000)
v3i(-1,0,0) v3i(-1,0,0)
v3i(1,0,0) v3i(1,0,0)
v3f(1.0, 0.1, 0.1) v3f(1.0, 0.1, 0.1)
endline() endline()
bgnline() bgnline()
cpack(0xff00) cpack(0xff00)
v3i(0,-1,0) v3i(0,-1,0)
v3i(0,1,0) v3i(0,1,0)
v3f(0.1, 1.0, 0.1) v3f(0.1, 1.0, 0.1)
endline() endline()
bgnline() bgnline()
cpack(0xff) cpack(0xff)
v3i(0,0,-1) v3i(0,0,-1)
v3i(0,0,1) v3i(0,0,1)
v3f(0.1,0.1,1.0) v3f(0.1,0.1,1.0)
endline() endline()
# #
green_velvet = [ DIFFUSE, 0.05, 0.4, 0.05, LMNULL] green_velvet = [ DIFFUSE, 0.05, 0.4, 0.05, LMNULL]
silver = [ DIFFUSE, 0.3, 0.3, 0.3, SPECULAR, 0.9, 0.9, 0.95, \ silver = [ DIFFUSE, 0.3, 0.3, 0.3, SPECULAR, 0.9, 0.9, 0.95, \
SHININESS, 40.0, LMNULL] SHININESS, 40.0, LMNULL]
floormat = [ AMBIENT, 0.5, 0.25, 0.15, DIFFUSE, 0.5, 0.25, 0.15, SPECULAR, 0.6, 0.3, 0.2, SHININESS, 20.0, LMNULL] floormat = [ AMBIENT, 0.5, 0.25, 0.15, DIFFUSE, 0.5, 0.25, 0.15, SPECULAR, 0.6, 0.3, 0.2, SHININESS, 20.0, LMNULL]
wallmat = [ DIFFUSE, 0.4, 0.2, 0.1, AMBIENT, 0.4, 0.20, 0.10, SPECULAR, 0.0, 0.0, 0.0, SHININESS, 20.0, LMNULL] wallmat = [ DIFFUSE, 0.4, 0.2, 0.1, AMBIENT, 0.4, 0.20, 0.10, SPECULAR, 0.0, 0.0, 0.0, SHININESS, 20.0, LMNULL]
offwhite = [ DIFFUSE, 0.8, 0.8, 0.6, AMBIENT, 0.8, 0.8, 0.6, SPECULAR, 0.9, 0.9, 0.9, SHININESS, 30.0, LMNULL] offwhite = [ DIFFUSE, 0.8, 0.8, 0.6, AMBIENT, 0.8, 0.8, 0.6, SPECULAR, 0.9, 0.9, 0.9, SHININESS, 30.0, LMNULL]
doormat = [ DIFFUSE, 0.1, 0.2, 0.5, AMBIENT, 0.2, 0.4, 1.0, SPECULAR, 0.2, 0.4, 1.0, SHININESS, 60.0, LMNULL] doormat = [ DIFFUSE, 0.1, 0.2, 0.5, AMBIENT, 0.2, 0.4, 1.0, SPECULAR, 0.2, 0.4, 1.0, SHININESS, 60.0, LMNULL]
toplight = [ LCOLOR, 1.0, 1.0, 0.5, \ toplight = [ LCOLOR, 1.0, 1.0, 0.5, \
POSITION, 0.0, 0.0, 11.0, 1.0, LMNULL] POSITION, 0.0, 0.0, 11.0, 1.0, LMNULL]
floor1light = [ LCOLOR, 1.0, 1.0, 1.0, POSITION, 3.9, -3.9, 0.0, 1.0, \ floor1light = [ LCOLOR, 1.0, 1.0, 1.0, POSITION, 3.9, -3.9, 0.0, 1.0, \
SPOTDIRECTION, 1.0, 1.0, 0.0, SPOTLIGHT, 10.0, 90.0, LMNULL] SPOTDIRECTION, 1.0, 1.0, 0.0, SPOTLIGHT, 10.0, 90.0, LMNULL]
lmodel = [ AMBIENT, 0.92, 0.8, 0.5, LOCALVIEWER, 1.0, LMNULL] lmodel = [ AMBIENT, 0.92, 0.8, 0.5, LOCALVIEWER, 1.0, LMNULL]
# #
def lighting(): def lighting():
lmdef(DEFMATERIAL, 1, green_velvet) lmdef(DEFMATERIAL, 1, green_velvet)
lmdef(DEFMATERIAL, 2, silver) lmdef(DEFMATERIAL, 2, silver)
lmdef(DEFMATERIAL, 3, floormat) lmdef(DEFMATERIAL, 3, floormat)
lmdef(DEFMATERIAL, 4, wallmat) lmdef(DEFMATERIAL, 4, wallmat)
lmdef(DEFMATERIAL, 5, offwhite) lmdef(DEFMATERIAL, 5, offwhite)
lmdef(DEFMATERIAL, 6, doormat) lmdef(DEFMATERIAL, 6, doormat)
lmdef(DEFLIGHT, 1, toplight) lmdef(DEFLIGHT, 1, toplight)
lmdef(DEFLIGHT, 2, floor1light) lmdef(DEFLIGHT, 2, floor1light)
lmdef(DEFLMODEL, 1, lmodel) lmdef(DEFLMODEL, 1, lmodel)
lmbind(MATERIAL, 1) lmbind(MATERIAL, 1)
lmbind(LIGHT0, 1) lmbind(LIGHT0, 1)
lmbind(LIGHT1, 2) lmbind(LIGHT1, 2)
lmbind(LMODEL, 1) lmbind(LMODEL, 1)
IdMat=[1.0,0.0,0.0,0.0, 0.0,1.0,0.0,0.0, 0.0,0.0,1.0,0.0, 0.0,0.0,0.0,1.0] IdMat=[1.0,0.0,0.0,0.0, 0.0,1.0,0.0,0.0, 0.0,0.0,1.0,0.0, 0.0,0.0,0.0,1.0]
# #
def defun(axis): def defun(axis):
done = 0 done = 0
while not done: while not done:
print 'F'+axis+'(t) = ', print 'F'+axis+'(t) = ',
s = sys.stdin.readline(100) s = sys.stdin.readline(100)
print print
try: try:
s = 'def f'+axis+'(t): return '+s s = 'def f'+axis+'(t): return '+s
exec(s, main_dict) exec(s, main_dict)
done = 1 done = 1
except RuntimeError: except RuntimeError:
print 'Sorry, there is a syntax error in your expression' print 'Sorry, there is a syntax error in your expression'
def getfunctions(): def getfunctions():
print 'Welcome to the CWI art simulator. You can now enter X, Y and Z' print 'Welcome to the CWI art simulator. You can now enter X, Y and Z'
print 'coordinates as a function of t.' print 'coordinates as a function of t.'
print 'Normal trig functions are available. Please use floating point' print 'Normal trig functions are available. Please use floating point'
print 'values only (so 0.0 for 0). Comments to jack@cwi.nl' print 'values only (so 0.0 for 0). Comments to jack@cwi.nl'
defun('x') defun('x')
defun('y') defun('y')
defun('z') defun('z')
print 'Ok, here you go. Use mouse+right button to move up/down,' print 'Ok, here you go. Use mouse+right button to move up/down,'
print 'mouse+middle to speed up/slow down time. type ESC to quit simulation' print 'mouse+middle to speed up/slow down time. type ESC to quit simulation'
def main(): def main():
getfunctions() getfunctions()
foreground() foreground()
prefposition(100,600,100,600) prefposition(100,600,100,600)
void = winopen('cyl') void = winopen('cyl')
qdevice(ESCKEY) qdevice(ESCKEY)
qdevice(MOUSE1) qdevice(MOUSE1)
qdevice(MOUSE2) qdevice(MOUSE2)
qdevice(PKEY) qdevice(PKEY)
RGBmode() RGBmode()
doublebuffer() doublebuffer()
gconfig() gconfig()
zbuffer(1) zbuffer(1)
mmode(MVIEWING) mmode(MVIEWING)
perspective(400, 1.0, 1.0, 20.0) perspective(400, 1.0, 1.0, 20.0)
loadmatrix(IdMat) loadmatrix(IdMat)
vx = 0.0 vx = 0.0
vy = -6.0 vy = -6.0
vz = 0.0 vz = 0.0
lookat(0.0, -6.0, 0.0, 0.0, 0.0, 0.0, 0) lookat(0.0, -6.0, 0.0, 0.0, 0.0, 0.0, 0)
lighting() lighting()
t = -1.0 t = -1.0
step = 1.0 step = 1.0
bol = mkcyl(12,24, 1) bol = mkcyl(12,24, 1)
cable = mkcyl(1, 6, 0) cable = mkcyl(1, 6, 0)
floors = drawfloors() floors = drawfloors()
walls = drawwalls() walls = drawwalls()
pillar = mkcyl(1,4,0) pillar = mkcyl(1,4,0)
railing = drawrailing() railing = drawrailing()
doors = drawdoors() doors = drawdoors()
shademodel(GOURAUD) shademodel(GOURAUD)
mousing = -1 mousing = -1
pausing = 0 pausing = 0
while 1: while 1:
# #
# Check for some user input # Check for some user input
# #
if qtest(): if qtest():
dev, value = qread() dev, value = qread()
if dev == PKEY and value == 1: if dev == PKEY and value == 1:
pausing = 1 pausing = 1
if dev == ESCKEY: if dev == ESCKEY:
break break
elif (dev==MOUSE1 or dev==MOUSE2) and value == 1: elif (dev==MOUSE1 or dev==MOUSE2) and value == 1:
if mousing > 0: if mousing > 0:
vx = 0.0 vx = 0.0
vy = -6.0 vy = -6.0
vz = 0.0 vz = 0.0
mousing = dev mousing = dev
oldx = getvaluator(MOUSEX) oldx = getvaluator(MOUSEX)
oldy = getvaluator(MOUSEY) oldy = getvaluator(MOUSEY)
elif (dev==MOUSE1 or dev==MOUSE2): elif (dev==MOUSE1 or dev==MOUSE2):
mousing = -1 mousing = -1
if mousing >= 0: if mousing >= 0:
newx = getvaluator(MOUSEX) newx = getvaluator(MOUSEX)
newy = getvaluator(MOUSEY) newy = getvaluator(MOUSEY)
if newy <> oldy and mousing==MOUSE1: if newy <> oldy and mousing==MOUSE1:
vz = vz + float(newy - oldy)/100.0 vz = vz + float(newy - oldy)/100.0
dist = sqrt(vx*vx + vy*vy + vz*vz) dist = sqrt(vx*vx + vy*vy + vz*vz)
perspective(400, 1.0, 1.0, dist+16.0) perspective(400, 1.0, 1.0, dist+16.0)
loadmatrix(IdMat) loadmatrix(IdMat)
if vz < 0.0: if vz < 0.0:
lookat(vx, vy, vz, 0.0, 0.0, 0.0, 1800) lookat(vx, vy, vz, 0.0, 0.0, 0.0, 1800)
else: else:
lookat(vx, vy, vz, 0.0, 0.0, 0.0, 0) lookat(vx, vy, vz, 0.0, 0.0, 0.0, 0)
if newy <> oldy and mousing==MOUSE2: if newy <> oldy and mousing==MOUSE2:
step = step * exp(float(newy-oldy)/400.0) step = step * exp(float(newy-oldy)/400.0)
if getbutton(CTRLKEY) == 0: if getbutton(CTRLKEY) == 0:
t = t + step t = t + step
else: else:
t = t - step t = t - step
if getbutton(LEFTSHIFTKEY) == 0: if getbutton(LEFTSHIFTKEY) == 0:
shademodel(GOURAUD) shademodel(GOURAUD)
else: else:
shademodel(FLAT) shademodel(FLAT)
# #
# Draw background and axis # Draw background and axis
cpack(0x105090) cpack(0x105090)
clear() clear()
zclear() zclear()
cpack(0x905010) cpack(0x905010)
axis() axis()
# #
# Draw object # Draw object
# #
bolx = fx(t) bolx = fx(t)
boly = fy(t) boly = fy(t)
bolz = fz(t) bolz = fz(t)
err = '' err = ''
if bolx < -4.0 or bolx > 4.0: if bolx < -4.0 or bolx > 4.0:
err = 'X('+`bolx`+') out of range [-4,4]' err = 'X('+`bolx`+') out of range [-4,4]'
if boly < -4.0 or boly > 4.0: if boly < -4.0 or boly > 4.0:
err = 'Y('+`boly`+') out of range [-4,4]' err = 'Y('+`boly`+') out of range [-4,4]'
if bolz < -4.0 or bolz > 8.0: if bolz < -4.0 or bolz > 8.0:
err = 'Z('+`bolz`+') out of range [-4,8]' err = 'Z('+`bolz`+') out of range [-4,8]'
if not err: if not err:
pushmatrix() pushmatrix()
translate(bolx, boly, bolz) translate(bolx, boly, bolz)
scale(0.3, 0.3, 0.3) scale(0.3, 0.3, 0.3)
lmbind(MATERIAL, 2) lmbind(MATERIAL, 2)
callobj(bol) callobj(bol)
popmatrix() popmatrix()
# #
# Draw the cables # Draw the cables
# #
bolz = bolz + 0.3 bolz = bolz + 0.3
pushmatrix() pushmatrix()
linesmooth(SML_ON) linesmooth(SML_ON)
bgnline() bgnline()
v3i(-4,-4,9) v3i(-4,-4,9)
v3f(bolx, boly, bolz) v3f(bolx, boly, bolz)
endline() endline()
bgnline() bgnline()
v3i(-4,4,9) v3i(-4,4,9)
v3f(bolx, boly, bolz) v3f(bolx, boly, bolz)
endline() endline()
bgnline() bgnline()
v3i(4,-4,9) v3i(4,-4,9)
v3f(bolx, boly, bolz) v3f(bolx, boly, bolz)
endline() endline()
bgnline() bgnline()
v3i(4,4,9) v3i(4,4,9)
v3f(bolx, boly, bolz) v3f(bolx, boly, bolz)
endline() endline()
popmatrix() popmatrix()
# #
# draw the floors # draw the floors
# #
lmbind(MATERIAL, 3) lmbind(MATERIAL, 3)
callobj(floors) callobj(floors)
lmbind(MATERIAL, 4) lmbind(MATERIAL, 4)
callobj(walls) callobj(walls)
lmbind(MATERIAL, 5) lmbind(MATERIAL, 5)
pushmatrix() pushmatrix()
translate(-4.5,4.5,3.0) translate(-4.5,4.5,3.0)
scale(0.2,0.2,9.0) scale(0.2,0.2,9.0)
rotate(450,'z') rotate(450,'z')
callobj(pillar) callobj(pillar)
popmatrix() popmatrix()
callobj(railing) callobj(railing)
lmbind(MATERIAL, 6) lmbind(MATERIAL, 6)
pushmatrix() pushmatrix()
translate(0.0, -0.01, 0.0) translate(0.0, -0.01, 0.0)
callobj(doors) callobj(doors)
popmatrix() popmatrix()
if mousing == MOUSE2 or err: if mousing == MOUSE2 or err:
cpack(0xff0000) cpack(0xff0000)
cmov(0.0, 0.0, 0.4) cmov(0.0, 0.0, 0.4)
charstr('t='+`t`) charstr('t='+`t`)
if mousing == MOUSE2: if mousing == MOUSE2:
cpack(0xff0000) cpack(0xff0000)
cmov(0.0, 0.0, 0.2) cmov(0.0, 0.0, 0.2)
charstr('delta-t='+`step`) charstr('delta-t='+`step`)
if err: if err:
cpack(0xff00) cpack(0xff00)
cmov(0.0, 0.0, 0.2) cmov(0.0, 0.0, 0.2)
print err print err
charstr(err) charstr(err)
pausing = 1 pausing = 1
if pausing: if pausing:
cpack(0xff00) cpack(0xff00)
cmov(0.0, 0.0, 0.0) cmov(0.0, 0.0, 0.0)
charstr('Pausing, type P to continue') charstr('Pausing, type P to continue')
swapbuffers() swapbuffers()
if pausing: if pausing:
while 1: while 1:
dv=qread() dv=qread()
if dv==(PKEY,1): if dv==(PKEY,1):
break break
if dv==(ESCKEY,1): if dv==(ESCKEY,1):
sys.exit(0) sys.exit(0)
pausing = 0 pausing = 0
# #
try: try:
main() main()
......
...@@ -474,16 +474,16 @@ class mrsw: ...@@ -474,16 +474,16 @@ class mrsw:
self.rwOK.release() self.rwOK.release()
def write_to_read(self): def write_to_read(self):
self.rwOK.acquire() self.rwOK.acquire()
if not self.writing: if not self.writing:
raise ValueError, \ raise ValueError, \
'.write_to_read() invoked without an active writer' '.write_to_read() invoked without an active writer'
self.writing = 0 self.writing = 0
self.nw = self.nw - 1 self.nw = self.nw - 1
self.nr = self.nr + 1 self.nr = self.nr + 1
if not self.nw: if not self.nw:
self.readOK.broadcast() self.readOK.broadcast()
self.rwOK.release() self.rwOK.release()
# The rest of the file is a test case, that runs a number of parallelized # 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 # quicksorts in parallel. If it works, you'll get about 600 lines of
......
...@@ -31,64 +31,64 @@ input=open(filename) ; output=open(outputname, 'w') ...@@ -31,64 +31,64 @@ input=open(filename) ; output=open(outputname, 'w')
if compressing: if compressing:
output.write('\037\213\010') # Write the header, ... 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) statval=os.stat(filename)
mtime=statval[8] mtime=statval[8]
write32(output, mtime) write32(output, mtime)
output.write('\002') # ... slowest compression alg. ... output.write('\002') # ... slowest compression alg. ...
output.write('\377') # ... OS (=unknown) ... output.write('\377') # ... OS (=unknown) ...
output.write(filename+'\000') # ... original filename ... output.write(filename+'\000') # ... original filename ...
crcval=zlib.crc32("") crcval=zlib.crc32("")
compobj=zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS, compobj=zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS,
zlib.DEF_MEM_LEVEL, 0) zlib.DEF_MEM_LEVEL, 0)
while (1): while (1):
data=input.read(1024) data=input.read(1024)
if data=="": break if data=="": break
crcval=zlib.crc32(data, crcval) crcval=zlib.crc32(data, crcval)
output.write(compobj.compress(data)) output.write(compobj.compress(data))
output.write(compobj.flush()) output.write(compobj.flush())
write32(output, crcval) # ... the CRC ... write32(output, crcval) # ... the CRC ...
write32(output, statval[6]) # and the file size. write32(output, statval[6]) # and the file size.
else: else:
magic=input.read(2) magic=input.read(2)
if magic!='\037\213': 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: 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)) flag=ord(input.read(1))
input.read(4+1+1) # Discard modification time, input.read(4+1+1) # Discard modification time,
# extra flags, and OS byte. # extra flags, and OS byte.
if flag & FEXTRA: if flag & FEXTRA:
# Read & discard the extra field, if present # Read & discard the extra field, if present
xlen=ord(input.read(1)) xlen=ord(input.read(1))
xlen=xlen+256*ord(input.read(1)) xlen=xlen+256*ord(input.read(1))
input.read(xlen) input.read(xlen)
if flag & FNAME: if flag & FNAME:
# Read and discard a null-terminated string containing the filename # Read and discard a null-terminated string containing the filename
while (1): while (1):
s=input.read(1) s=input.read(1)
if s=='\000': break if s=='\000': break
if flag & FCOMMENT: if flag & FCOMMENT:
# Read and discard a null-terminated string containing a comment # Read and discard a null-terminated string containing a comment
while (1): while (1):
s=input.read(1) s=input.read(1)
if s=='\000': break if s=='\000': break
if flag & FHCRC: 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) decompobj=zlib.decompressobj(-zlib.MAX_WBITS)
crcval=zlib.crc32("") crcval=zlib.crc32("")
length=0 length=0
while (1): while (1):
data=input.read(1024) data=input.read(1024)
if data=="": break if data=="": break
decompdata=decompobj.decompress(data) decompdata=decompobj.decompress(data)
print len(decompdata) print len(decompdata)
output.write(decompdata) ; length=length+len(decompdata) output.write(decompdata) ; length=length+len(decompdata)
crcval=zlib.crc32(decompdata, crcval) crcval=zlib.crc32(decompdata, crcval)
decompdata=decompobj.flush() decompdata=decompobj.flush()
output.write(decompdata) ; length=length+len(decompdata) output.write(decompdata) ; length=length+len(decompdata)
crcval=zlib.crc32(decompdata, crcval) 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