From 4cf83f4d128bd40ebe3b6e59ced4895f554d18de Mon Sep 17 00:00:00 2001 From: Georg Brandl Date: Thu, 30 Dec 2010 17:22:33 +0000 Subject: Remove some of the old demos. (Put a few somewhere else.) --- Demo/cgi/README | 10 - Demo/cgi/cgi0.sh | 8 - Demo/cgi/cgi1.py | 14 - Demo/cgi/cgi2.py | 22 - Demo/cgi/cgi3.py | 10 - Demo/cgi/wiki.py | 123 ------ Demo/comparisons/README | 60 --- Demo/comparisons/patterns | 4 - Demo/comparisons/regextest.py | 47 --- Demo/comparisons/sortingtest.py | 45 -- Demo/comparisons/systemtest.py | 74 ---- Demo/curses/ncurses.py | 273 ------------ Demo/curses/rain.py | 94 ----- Demo/curses/tclock.py | 147 ------- Demo/curses/xmas.py | 906 ---------------------------------------- Demo/md5test/README | 10 - Demo/md5test/foo | 1 - Demo/md5test/md5driver.py | 122 ------ Demo/parser/FILES | 6 - Demo/parser/README | 31 -- Demo/parser/docstring.py | 2 - Demo/parser/example.py | 190 --------- Demo/parser/simple.py | 1 - Demo/parser/source.py | 27 -- Demo/parser/test_parser.py | 48 --- Demo/parser/test_unparse.py | 240 ----------- Demo/parser/texipre.dat | 100 ----- Demo/parser/unparse.py | 600 -------------------------- Demo/pysvr/Makefile | 57 --- Demo/pysvr/README | 9 - Demo/pysvr/pysvr.c | 370 ---------------- Demo/pysvr/pysvr.py | 124 ------ Demo/rpc/MANIFEST | 10 - Demo/rpc/README | 31 -- Demo/rpc/T.py | 22 - Demo/rpc/mountclient.py | 202 --------- Demo/rpc/nfsclient.py | 201 --------- Demo/rpc/rnusersclient.py | 98 ----- Demo/rpc/rpc.py | 890 --------------------------------------- Demo/rpc/test | 24 -- Demo/rpc/xdr.py | 200 --------- Demo/scripts/eqfix.py | 198 --------- Demo/scripts/find-uname.py | 40 -- Demo/scripts/from.py | 35 -- Demo/scripts/lpwatch.py | 102 ----- Demo/scripts/makedir.py | 21 - Demo/scripts/mboxconvert.py | 124 ------ Demo/scripts/morse.py | 128 ------ Demo/scripts/newslist.doc | 59 --- Demo/scripts/newslist.py | 361 ---------------- Demo/scripts/pi.py | 33 -- Demo/scripts/pp.py | 125 ------ Demo/scripts/primes.py | 31 -- Demo/scripts/script.py | 42 -- Demo/scripts/update.py | 92 ---- Demo/threads/Coroutine.py | 159 ------- Demo/threads/Generator.py | 92 ---- Demo/threads/README | 11 - Demo/threads/fcmp.py | 64 --- Demo/threads/find.py | 154 ------- Demo/threads/squasher.py | 105 ----- Demo/threads/sync.py | 599 -------------------------- Demo/threads/telnet.py | 114 ----- Demo/xml/elem_count.py | 42 -- Demo/xml/roundtrip.py | 46 -- Demo/xml/rss2html.py | 97 ----- Demo/zlib/minigzip.py | 134 ------ Demo/zlib/zlibdemo.py | 47 --- Doc/library/pty.rst | 47 +++ Tools/parser/test_unparse.py | 240 +++++++++++ Tools/parser/unparse.py | 600 ++++++++++++++++++++++++++ Tools/scripts/find-uname.py | 40 ++ 72 files changed, 927 insertions(+), 8508 deletions(-) delete mode 100644 Demo/cgi/README delete mode 100755 Demo/cgi/cgi0.sh delete mode 100755 Demo/cgi/cgi1.py delete mode 100755 Demo/cgi/cgi2.py delete mode 100755 Demo/cgi/cgi3.py delete mode 100644 Demo/cgi/wiki.py delete mode 100644 Demo/comparisons/README delete mode 100755 Demo/comparisons/patterns delete mode 100755 Demo/comparisons/regextest.py delete mode 100755 Demo/comparisons/sortingtest.py delete mode 100755 Demo/comparisons/systemtest.py delete mode 100644 Demo/curses/ncurses.py delete mode 100644 Demo/curses/rain.py delete mode 100644 Demo/curses/tclock.py delete mode 100644 Demo/curses/xmas.py delete mode 100644 Demo/md5test/README delete mode 100755 Demo/md5test/foo delete mode 100644 Demo/md5test/md5driver.py delete mode 100644 Demo/parser/FILES delete mode 100644 Demo/parser/README delete mode 100644 Demo/parser/docstring.py delete mode 100644 Demo/parser/example.py delete mode 100644 Demo/parser/simple.py delete mode 100644 Demo/parser/source.py delete mode 100755 Demo/parser/test_parser.py delete mode 100644 Demo/parser/test_unparse.py delete mode 100644 Demo/parser/texipre.dat delete mode 100644 Demo/parser/unparse.py delete mode 100644 Demo/pysvr/Makefile delete mode 100644 Demo/pysvr/README delete mode 100644 Demo/pysvr/pysvr.c delete mode 100755 Demo/pysvr/pysvr.py delete mode 100644 Demo/rpc/MANIFEST delete mode 100644 Demo/rpc/README delete mode 100644 Demo/rpc/T.py delete mode 100644 Demo/rpc/mountclient.py delete mode 100644 Demo/rpc/nfsclient.py delete mode 100644 Demo/rpc/rnusersclient.py delete mode 100644 Demo/rpc/rpc.py delete mode 100755 Demo/rpc/test delete mode 100644 Demo/rpc/xdr.py delete mode 100755 Demo/scripts/eqfix.py delete mode 100755 Demo/scripts/find-uname.py delete mode 100755 Demo/scripts/from.py delete mode 100755 Demo/scripts/lpwatch.py delete mode 100755 Demo/scripts/makedir.py delete mode 100755 Demo/scripts/mboxconvert.py delete mode 100755 Demo/scripts/morse.py delete mode 100755 Demo/scripts/newslist.doc delete mode 100755 Demo/scripts/newslist.py delete mode 100755 Demo/scripts/pi.py delete mode 100755 Demo/scripts/pp.py delete mode 100755 Demo/scripts/primes.py delete mode 100755 Demo/scripts/script.py delete mode 100755 Demo/scripts/update.py delete mode 100644 Demo/threads/Coroutine.py delete mode 100644 Demo/threads/Generator.py delete mode 100644 Demo/threads/README delete mode 100644 Demo/threads/fcmp.py delete mode 100644 Demo/threads/find.py delete mode 100644 Demo/threads/squasher.py delete mode 100644 Demo/threads/sync.py delete mode 100644 Demo/threads/telnet.py delete mode 100644 Demo/xml/elem_count.py delete mode 100644 Demo/xml/roundtrip.py delete mode 100644 Demo/xml/rss2html.py delete mode 100755 Demo/zlib/minigzip.py delete mode 100755 Demo/zlib/zlibdemo.py create mode 100644 Tools/parser/test_unparse.py create mode 100644 Tools/parser/unparse.py create mode 100755 Tools/scripts/find-uname.py diff --git a/Demo/cgi/README b/Demo/cgi/README deleted file mode 100644 index c0631b6..0000000 --- a/Demo/cgi/README +++ /dev/null @@ -1,10 +0,0 @@ -CGI Examples ------------- - -Here are some example CGI programs. - -cgi0.sh -- A shell script to test your server is configured for CGI -cgi1.py -- A Python script to test your server is configured for CGI -cgi2.py -- A Python script showing how to parse a form -cgi3.py -- A Python script for driving an arbitrary CGI application -wiki.py -- Sample CGI application: a minimal Wiki implementation diff --git a/Demo/cgi/cgi0.sh b/Demo/cgi/cgi0.sh deleted file mode 100755 index 5cefcd3..0000000 --- a/Demo/cgi/cgi0.sh +++ /dev/null @@ -1,8 +0,0 @@ -#! /bin/sh - -# If you can't get this to work, your web server isn't set up right - -echo Content-type: text/plain -echo -echo Hello world -echo This is cgi0.sh diff --git a/Demo/cgi/cgi1.py b/Demo/cgi/cgi1.py deleted file mode 100755 index b4154df..0000000 --- a/Demo/cgi/cgi1.py +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env python3 - -"""CGI test 1 - check server setup.""" - -# Until you get this to work, your web server isn't set up right or -# your Python isn't set up right. - -# If cgi0.sh works but cgi1.py doesn't, check the #! line and the file -# permissions. The docs for the cgi.py module have debugging tips. - -print("Content-type: text/html") -print() -print("

Hello world

") -print("

This is cgi1.py") diff --git a/Demo/cgi/cgi2.py b/Demo/cgi/cgi2.py deleted file mode 100755 index 8aa57b3..0000000 --- a/Demo/cgi/cgi2.py +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env python3 - -"""CGI test 2 - basic use of cgi module.""" - -import cgitb; cgitb.enable() - -import cgi - -def main(): - form = cgi.FieldStorage() - print("Content-type: text/html") - print() - if not form: - print("

No Form Keys

") - else: - print("

Form Keys

") - for key in form.keys(): - value = form[key].value - print("

", cgi.escape(key), ":", cgi.escape(value)) - -if __name__ == "__main__": - main() diff --git a/Demo/cgi/cgi3.py b/Demo/cgi/cgi3.py deleted file mode 100755 index de8ef65..0000000 --- a/Demo/cgi/cgi3.py +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env python3 - -"""CGI test 3 (persistent data).""" - -import cgitb; cgitb.enable() - -from wiki import main - -if __name__ == "__main__": - main() diff --git a/Demo/cgi/wiki.py b/Demo/cgi/wiki.py deleted file mode 100644 index 6b97113..0000000 --- a/Demo/cgi/wiki.py +++ /dev/null @@ -1,123 +0,0 @@ -"""Wiki main program. Imported and run by cgi3.py.""" - -import os, re, cgi, sys, tempfile -escape = cgi.escape - -def main(): - form = cgi.FieldStorage() - print("Content-type: text/html") - print() - cmd = form.getvalue("cmd", "view") - page = form.getvalue("page", "FrontPage") - wiki = WikiPage(page) - method = getattr(wiki, 'cmd_' + cmd, None) or wiki.cmd_view - method(form) - -class WikiPage: - - homedir = tempfile.gettempdir() - scripturl = os.path.basename(sys.argv[0]) - - def __init__(self, name): - if not self.iswikiword(name): - raise ValueError("page name is not a wiki word") - self.name = name - self.load() - - def cmd_view(self, form): - print("

", escape(self.splitwikiword(self.name)), "

") - print("

") - for line in self.data.splitlines(): - line = line.rstrip() - if not line: - print("

") - else: - print(self.formatline(line)) - print("


") - print("

", self.mklink("edit", self.name, "Edit this page") + ";") - print(self.mklink("view", "FrontPage", "go to front page") + ".") - - def formatline(self, line): - words = [] - for word in re.split('(\W+)', line): - if self.iswikiword(word): - if os.path.isfile(self.mkfile(word)): - word = self.mklink("view", word, word) - else: - word = self.mklink("new", word, word + "*") - else: - word = escape(word) - words.append(word) - return "".join(words) - - def cmd_edit(self, form, label="Change"): - print("

", label, self.name, "

") - print('
' % self.scripturl) - s = '' - print(s % self.data) - print('') - print('' % self.name) - print('
') - print('' % label) - print("
") - - def cmd_create(self, form): - self.data = form.getvalue("text", "").strip() - error = self.store() - if error: - print("

I'm sorry. That didn't work

") - print("

An error occurred while attempting to write the file:") - print("

", escape(error)) - else: - # Use a redirect directive, to avoid "reload page" problems - print("") - s = '' - print(s % (self.scripturl + "?cmd=view&page=" + self.name)) - print("") - print("

OK

") - print("

If nothing happens, please click here:", end=' ') - print(self.mklink("view", self.name, self.name)) - - def cmd_new(self, form): - self.cmd_edit(form, label="Create") - - def iswikiword(self, word): - return re.match("[A-Z][a-z]+([A-Z][a-z]*)+", word) - - def splitwikiword(self, word): - chars = [] - for c in word: - if chars and c.isupper(): - chars.append(' ') - chars.append(c) - return "".join(chars) - - def mkfile(self, name=None): - if name is None: - name = self.name - return os.path.join(self.homedir, name + ".txt") - - def mklink(self, cmd, page, text): - link = self.scripturl + "?cmd=" + cmd + "&page=" + page - return '%s' % (link, text) - - def load(self): - try: - f = open(self.mkfile()) - data = f.read().strip() - f.close() - except IOError: - data = "" - self.data = data - - def store(self): - data = self.data - try: - f = open(self.mkfile(), "w") - f.write(data) - if data and not data.endswith('\n'): - f.write('\n') - f.close() - return "" - except IOError as err: - return "IOError: %s" % str(err) diff --git a/Demo/comparisons/README b/Demo/comparisons/README deleted file mode 100644 index 111667c..0000000 --- a/Demo/comparisons/README +++ /dev/null @@ -1,60 +0,0 @@ -Subject: Re: What language would you use? -From: Tom Christiansen -Date: 6 Nov 1994 15:14:51 GMT -Newsgroups: comp.lang.python,comp.lang.tcl,comp.lang.scheme,comp.lang.misc,comp.lang.perl -Message-Id: <39irtb$3t4@csnews.cs.Colorado.EDU> -References: <39b7ha$j9v@zeno.nscf.org> <39hhjp$lgn@csnews.cs.Colorado.EDU> <39hvsu$dus@mathserv.mps.ohio-state.edu> - -[...] -If you're really into benchmarks, I'd love it if someone were to code up -the following problems in tcl, python, and scheme (and whatever else you'd -like). Separate versions (one optimized for speed, one for beauty :-) are -ok. Post your code so we can time it on our own systems. - -0) Factorial Test (numerics and function calls) - - (we did this already) - -1) Regular Expressions Test - - Read a file of (extended per egrep) regular expressions (one per line), - and apply those to all files whose names are listed on the command line. - Basically, an 'egrep -f' simulator. Test it with 20 "vt100" patterns - against a five /etc/termcap files. Tests using more elaborate patters - would also be interesting. Your code should not break if given hundreds - of regular expressions or binary files to scan. - -2) Sorting Test - - Sort an input file that consists of lines like this - - var1=23 other=14 ditto=23 fred=2 - - such that each output line is sorted WRT to the number. Order - of output lines does not change. Resolve collisions using the - variable name. e.g. - - fred=2 other=14 ditto=23 var1=23 - - Lines may be up to several kilobytes in length and contain - zillions of variables. - -3) System Test - - Given a list of directories, report any bogus symbolic links contained - anywhere in those subtrees. A bogus symbolic link is one that cannot - be resolved because it points to a nonexistent or otherwise - unresolvable file. Do *not* use an external find executable. - Directories may be very very deep. Print a warning immediately if the - system you're running on doesn't support symbolic links. - - -I'll post perl solutions if people post the others. - - ---tom --- -Tom Christiansen Perl Consultant, Gamer, Hiker tchrist@mox.perl.com - - "But Billy! A *small* allowance prepares you for a lifetime of small - salaries and for your Social Security payments." --Family Circus diff --git a/Demo/comparisons/patterns b/Demo/comparisons/patterns deleted file mode 100755 index f4da846..0000000 --- a/Demo/comparisons/patterns +++ /dev/null @@ -1,4 +0,0 @@ -^def -^class -^import -^from diff --git a/Demo/comparisons/regextest.py b/Demo/comparisons/regextest.py deleted file mode 100755 index 547ee0d..0000000 --- a/Demo/comparisons/regextest.py +++ /dev/null @@ -1,47 +0,0 @@ -#! /usr/bin/env python3 - -# 1) Regular Expressions Test -# -# Read a file of (extended per egrep) regular expressions (one per line), -# and apply those to all files whose names are listed on the command line. -# Basically, an 'egrep -f' simulator. Test it with 20 "vt100" patterns -# against a five /etc/termcap files. Tests using more elaborate patters -# would also be interesting. Your code should not break if given hundreds -# of regular expressions or binary files to scan. - -# This implementation: -# - combines all patterns into a single one using ( ... | ... | ... ) -# - reads patterns from stdin, scans files given as command line arguments -# - produces output in the format :: -# - is only about 2.5 times as slow as egrep (though I couldn't run -# Tom's test -- this system, a vanilla SGI, only has /etc/terminfo) - -import string -import sys -import re - -def main(): - pats = list(map(chomp, sys.stdin.readlines())) - bigpat = '(' + '|'.join(pats) + ')' - prog = re.compile(bigpat) - - for file in sys.argv[1:]: - try: - fp = open(file, 'r') - except IOError as msg: - print("%s: %s" % (file, msg)) - continue - lineno = 0 - while 1: - line = fp.readline() - if not line: - break - lineno = lineno + 1 - if prog.search(line): - print("%s:%s:%s" % (file, lineno, line), end=' ') - -def chomp(s): - return s.rstrip('\n') - -if __name__ == '__main__': - main() diff --git a/Demo/comparisons/sortingtest.py b/Demo/comparisons/sortingtest.py deleted file mode 100755 index e826e81..0000000 --- a/Demo/comparisons/sortingtest.py +++ /dev/null @@ -1,45 +0,0 @@ -#! /usr/bin/env python3 - -# 2) Sorting Test -# -# Sort an input file that consists of lines like this -# -# var1=23 other=14 ditto=23 fred=2 -# -# such that each output line is sorted WRT to the number. Order -# of output lines does not change. Resolve collisions using the -# variable name. e.g. -# -# fred=2 other=14 ditto=23 var1=23 -# -# Lines may be up to several kilobytes in length and contain -# zillions of variables. - -# This implementation: -# - Reads stdin, writes stdout -# - Uses any amount of whitespace to separate fields -# - Allows signed numbers -# - Treats illegally formatted fields as field=0 -# - Outputs the sorted fields with exactly one space between them -# - Handles blank input lines correctly - -import re -import sys - -def main(): - prog = re.compile('^(.*)=([-+]?[0-9]+)') - def makekey(item, prog=prog): - match = prog.match(item) - if match: - var, num = match.groups() - return int(num), var - else: - # Bad input -- pretend it's a var with value 0 - return 0, item - for line in sys.stdin: - items = sorted(makekey(item) for item in line.split()) - for num, var in items: - print("%s=%s" % (var, num), end=' ') - print() - -main() diff --git a/Demo/comparisons/systemtest.py b/Demo/comparisons/systemtest.py deleted file mode 100755 index 8276333..0000000 --- a/Demo/comparisons/systemtest.py +++ /dev/null @@ -1,74 +0,0 @@ -#! /usr/bin/env python3 - -# 3) System Test -# -# Given a list of directories, report any bogus symbolic links contained -# anywhere in those subtrees. A bogus symbolic link is one that cannot -# be resolved because it points to a nonexistent or otherwise -# unresolvable file. Do *not* use an external find executable. -# Directories may be very very deep. Print a warning immediately if the -# system you're running on doesn't support symbolic links. - -# This implementation: -# - takes one optional argument, using the current directory as default -# - uses chdir to increase performance -# - sorts the names per directory -# - prints output lines of the form "path1 -> path2" as it goes -# - prints error messages about directories it can't list or chdir into - -import os -import sys -from stat import * - -def main(): - try: - # Note: can't test for presence of lstat -- it's always there - dummy = os.readlink - except AttributeError: - print("This system doesn't have symbolic links") - sys.exit(0) - if sys.argv[1:]: - prefix = sys.argv[1] - else: - prefix = '' - if prefix: - os.chdir(prefix) - if prefix[-1:] != '/': prefix = prefix + '/' - reportboguslinks(prefix) - else: - reportboguslinks('') - -def reportboguslinks(prefix): - try: - names = os.listdir('.') - except os.error as msg: - print("%s%s: can't list: %s" % (prefix, '.', msg)) - return - names.sort() - for name in names: - if name == os.curdir or name == os.pardir: - continue - try: - mode = os.lstat(name)[ST_MODE] - except os.error: - print("%s%s: can't stat: %s" % (prefix, name, msg)) - continue - if S_ISLNK(mode): - try: - os.stat(name) - except os.error: - print("%s%s -> %s" % \ - (prefix, name, os.readlink(name))) - elif S_ISDIR(mode): - try: - os.chdir(name) - except os.error as msg: - print("%s%s: can't chdir: %s" % \ - (prefix, name, msg)) - continue - try: - reportboguslinks(prefix + name + '/') - finally: - os.chdir('..') - -main() diff --git a/Demo/curses/ncurses.py b/Demo/curses/ncurses.py deleted file mode 100644 index dedde29..0000000 --- a/Demo/curses/ncurses.py +++ /dev/null @@ -1,273 +0,0 @@ -#!/usr/bin/env python3 -# -# $Id$ -# -# (n)curses exerciser in Python, an interactive test for the curses -# module. Currently, only the panel demos are ported. - -import curses -from curses import panel - -def wGetchar(win = None): - if win is None: win = stdscr - return win.getch() - -def Getchar(): - wGetchar() - -# -# Panels tester -# -def wait_a_while(): - if nap_msec == 1: - Getchar() - else: - curses.napms(nap_msec) - -def saywhat(text): - stdscr.move(curses.LINES - 1, 0) - stdscr.clrtoeol() - stdscr.addstr(text) - -def mkpanel(color, rows, cols, tly, tlx): - win = curses.newwin(rows, cols, tly, tlx) - pan = panel.new_panel(win) - if curses.has_colors(): - if color == curses.COLOR_BLUE: - fg = curses.COLOR_WHITE - else: - fg = curses.COLOR_BLACK - bg = color - curses.init_pair(color, fg, bg) - win.bkgdset(ord(' '), curses.color_pair(color)) - else: - win.bkgdset(ord(' '), curses.A_BOLD) - - return pan - -def pflush(): - panel.update_panels() - curses.doupdate() - -def fill_panel(pan): - win = pan.window() - num = pan.userptr()[1] - - win.move(1, 1) - win.addstr("-pan%c-" % num) - win.clrtoeol() - win.box() - - maxy, maxx = win.getmaxyx() - for y in range(2, maxy - 1): - for x in range(1, maxx - 1): - win.move(y, x) - win.addch(num) - -def demo_panels(win): - global stdscr, nap_msec, mod - stdscr = win - nap_msec = 1 - mod = ["test", "TEST", "(**)", "*()*", "<-->", "LAST"] - - stdscr.refresh() - - for y in range(0, curses.LINES - 1): - for x in range(0, curses.COLS): - stdscr.addstr("%d" % ((y + x) % 10)) - for y in range(0, 1): - p1 = mkpanel(curses.COLOR_RED, - curses.LINES // 2 - 2, - curses.COLS // 8 + 1, - 0, - 0) - p1.set_userptr("p1") - - p2 = mkpanel(curses.COLOR_GREEN, - curses.LINES // 2 + 1, - curses.COLS // 7, - curses.LINES // 4, - curses.COLS // 10) - p2.set_userptr("p2") - - p3 = mkpanel(curses.COLOR_YELLOW, - curses.LINES // 4, - curses.COLS // 10, - curses.LINES // 2, - curses.COLS // 9) - p3.set_userptr("p3") - - p4 = mkpanel(curses.COLOR_BLUE, - curses.LINES // 2 - 2, - curses.COLS // 8, - curses.LINES // 2 - 2, - curses.COLS // 3) - p4.set_userptr("p4") - - p5 = mkpanel(curses.COLOR_MAGENTA, - curses.LINES // 2 - 2, - curses.COLS // 8, - curses.LINES // 2, - curses.COLS // 2 - 2) - p5.set_userptr("p5") - - fill_panel(p1) - fill_panel(p2) - fill_panel(p3) - fill_panel(p4) - fill_panel(p5) - p4.hide() - p5.hide() - pflush() - saywhat("press any key to continue") - wait_a_while() - - saywhat("h3 s1 s2 s4 s5;press any key to continue") - p1.move(0, 0) - p3.hide() - p1.show() - p2.show() - p4.show() - p5.show() - pflush() - wait_a_while() - - saywhat("s1; press any key to continue") - p1.show() - pflush() - wait_a_while() - - saywhat("s2; press any key to continue") - p2.show() - pflush() - wait_a_while() - - saywhat("m2; press any key to continue") - p2.move(curses.LINES // 3 + 1, curses.COLS // 8) - pflush() - wait_a_while() - - saywhat("s3; press any key to continue") - p3.show() - pflush() - wait_a_while() - - saywhat("m3; press any key to continue") - p3.move(curses.LINES // 4 + 1, curses.COLS // 15) - pflush() - wait_a_while() - - saywhat("b3; press any key to continue") - p3.bottom() - pflush() - wait_a_while() - - saywhat("s4; press any key to continue") - p4.show() - pflush() - wait_a_while() - - saywhat("s5; press any key to continue") - p5.show() - pflush() - wait_a_while() - - saywhat("t3; press any key to continue") - p3.top() - pflush() - wait_a_while() - - saywhat("t1; press any key to continue") - p1.show() - pflush() - wait_a_while() - - saywhat("t2; press any key to continue") - p2.show() - pflush() - wait_a_while() - - saywhat("t3; press any key to continue") - p3.show() - pflush() - wait_a_while() - - saywhat("t4; press any key to continue") - p4.show() - pflush() - wait_a_while() - - for itmp in range(0, 6): - w4 = p4.window() - w5 = p5.window() - - saywhat("m4; press any key to continue") - w4.move(curses.LINES // 8, 1) - w4.addstr(mod[itmp]) - p4.move(curses.LINES // 6, itmp * curses.COLS // 8) - w5.move(curses.LINES // 6, 1) - w5.addstr(mod[itmp]) - pflush() - wait_a_while() - - saywhat("m5; press any key to continue") - w4.move(curses.LINES // 6, 1) - w4.addstr(mod[itmp]) - p5.move(curses.LINES // 3 - 1, itmp * 10 + 6) - w5.move(curses.LINES // 8, 1) - w5.addstr(mod[itmp]) - pflush() - wait_a_while() - - saywhat("m4; press any key to continue") - p4.move(curses.LINES // 6, (itmp + 1) * curses.COLS // 8) - pflush() - wait_a_while() - - saywhat("t5; press any key to continue") - p5.top() - pflush() - wait_a_while() - - saywhat("t2; press any key to continue") - p2.top() - pflush() - wait_a_while() - - saywhat("t1; press any key to continue") - p1.top() - pflush() - wait_a_while() - - saywhat("d2; press any key to continue") - del p2 - pflush() - wait_a_while() - - saywhat("h3; press any key to continue") - p3.hide() - pflush() - wait_a_while() - - saywhat("d1; press any key to continue") - del p1 - pflush() - wait_a_while() - - saywhat("d4; press any key to continue") - del p4 - pflush() - wait_a_while() - - saywhat("d5; press any key to continue") - del p5 - pflush() - wait_a_while() - if nap_msec == 1: - break - nap_msec = 100 - -# -# one fine day there'll be the menu at this place -# -curses.wrapper(demo_panels) diff --git a/Demo/curses/rain.py b/Demo/curses/rain.py deleted file mode 100644 index 7cabb4f..0000000 --- a/Demo/curses/rain.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/env python3 -# -# $Id$ -# -# somebody should probably check the randrange()s... - -import curses -from random import randrange - -def next_j(j): - if j == 0: - j = 4 - else: - j -= 1 - - if curses.has_colors(): - z = randrange(0, 3) - color = curses.color_pair(z) - if z: - color = color | curses.A_BOLD - stdscr.attrset(color) - - return j - -def main(win): - # we know that the first argument from curses.wrapper() is stdscr. - # Initialize it globally for convenience. - global stdscr - stdscr = win - - if curses.has_colors(): - bg = curses.COLOR_BLACK - curses.init_pair(1, curses.COLOR_BLUE, bg) - curses.init_pair(2, curses.COLOR_CYAN, bg) - - curses.nl() - curses.noecho() - # XXX curs_set() always returns ERR - # curses.curs_set(0) - stdscr.timeout(0) - - c = curses.COLS - 4 - r = curses.LINES - 4 - xpos = [0] * c - ypos = [0] * r - for j in range(4, -1, -1): - xpos[j] = randrange(0, c) + 2 - ypos[j] = randrange(0, r) + 2 - - j = 0 - while True: - x = randrange(0, c) + 2 - y = randrange(0, r) + 2 - - stdscr.addch(y, x, ord('.')) - - stdscr.addch(ypos[j], xpos[j], ord('o')) - - j = next_j(j) - stdscr.addch(ypos[j], xpos[j], ord('O')) - - j = next_j(j) - stdscr.addch( ypos[j] - 1, xpos[j], ord('-')) - stdscr.addstr(ypos[j], xpos[j] - 1, "|.|") - stdscr.addch( ypos[j] + 1, xpos[j], ord('-')) - - j = next_j(j) - stdscr.addch( ypos[j] - 2, xpos[j], ord('-')) - stdscr.addstr(ypos[j] - 1, xpos[j] - 1, "/ \\") - stdscr.addstr(ypos[j], xpos[j] - 2, "| O |") - stdscr.addstr(ypos[j] + 1, xpos[j] - 1, "\\ /") - stdscr.addch( ypos[j] + 2, xpos[j], ord('-')) - - j = next_j(j) - stdscr.addch( ypos[j] - 2, xpos[j], ord(' ')) - stdscr.addstr(ypos[j] - 1, xpos[j] - 1, " ") - stdscr.addstr(ypos[j], xpos[j] - 2, " ") - stdscr.addstr(ypos[j] + 1, xpos[j] - 1, " ") - stdscr.addch( ypos[j] + 2, xpos[j], ord(' ')) - - xpos[j] = x - ypos[j] = y - - ch = stdscr.getch() - if ch == ord('q') or ch == ord('Q'): - return - elif ch == ord('s'): - stdscr.nodelay(0) - elif ch == ord(' '): - stdscr.nodelay(1) - - curses.napms(50) - -curses.wrapper(main) diff --git a/Demo/curses/tclock.py b/Demo/curses/tclock.py deleted file mode 100644 index cde0a93..0000000 --- a/Demo/curses/tclock.py +++ /dev/null @@ -1,147 +0,0 @@ -#!/usr/bin/env python3 -# -# $Id$ -# -# From tclock.c, Copyright Howard Jones , September 1994. - -from math import * -import curses, time - -ASPECT = 2.2 - -def sign(_x): - if _x < 0: return -1 - return 1 - -def A2XY(angle, radius): - return (int(round(ASPECT * radius * sin(angle))), - int(round(radius * cos(angle)))) - -def plot(x, y, col): - stdscr.addch(y, x, col) - -# draw a diagonal line using Bresenham's algorithm -def dline(pair, from_x, from_y, x2, y2, ch): - if curses.has_colors(): - stdscr.attrset(curses.color_pair(pair)) - - dx = x2 - from_x - dy = y2 - from_y - - ax = abs(dx * 2) - ay = abs(dy * 2) - - sx = sign(dx) - sy = sign(dy) - - x = from_x - y = from_y - - if ax > ay: - d = ay - ax // 2 - - while True: - plot(x, y, ch) - if x == x2: - return - - if d >= 0: - y += sy - d -= ax - x += sx - d += ay - else: - d = ax - ay // 2 - - while True: - plot(x, y, ch) - if y == y2: - return - - if d >= 0: - x += sx - d -= ay - y += sy - d += ax - -def main(win): - global stdscr - stdscr = win - - lastbeep = -1 - my_bg = curses.COLOR_BLACK - - stdscr.nodelay(1) - stdscr.timeout(0) -# curses.curs_set(0) - if curses.has_colors(): - curses.init_pair(1, curses.COLOR_RED, my_bg) - curses.init_pair(2, curses.COLOR_MAGENTA, my_bg) - curses.init_pair(3, curses.COLOR_GREEN, my_bg) - - cx = (curses.COLS - 1) // 2 - cy = curses.LINES // 2 - ch = min( cy-1, int(cx // ASPECT) - 1) - mradius = (3 * ch) // 4 - hradius = ch // 2 - sradius = 5 * ch // 6 - - for i in range(0, 12): - sangle = (i + 1) * 2.0 * pi / 12.0 - sdx, sdy = A2XY(sangle, sradius) - - stdscr.addstr(cy - sdy, cx + sdx, "%d" % (i + 1)) - - stdscr.addstr(0, 0, - "ASCII Clock by Howard Jones , 1994") - - sradius = max(sradius-4, 8) - - while True: - curses.napms(1000) - - tim = time.time() - t = time.localtime(tim) - - hours = t[3] + t[4] / 60.0 - if hours > 12.0: - hours -= 12.0 - - mangle = t[4] * 2 * pi / 60.0 - mdx, mdy = A2XY(mangle, mradius) - - hangle = hours * 2 * pi / 12.0 - hdx, hdy = A2XY(hangle, hradius) - - sangle = t[5] * 2 * pi / 60.0 - sdx, sdy = A2XY(sangle, sradius) - - dline(3, cx, cy, cx + mdx, cy - mdy, ord('#')) - - stdscr.attrset(curses.A_REVERSE) - dline(2, cx, cy, cx + hdx, cy - hdy, ord('.')) - stdscr.attroff(curses.A_REVERSE) - - if curses.has_colors(): - stdscr.attrset(curses.color_pair(1)) - - plot(cx + sdx, cy - sdy, ord('O')) - - if curses.has_colors(): - stdscr.attrset(curses.color_pair(0)) - - stdscr.addstr(curses.LINES - 2, 0, time.ctime(tim)) - stdscr.refresh() - if (t[5] % 5) == 0 and t[5] != lastbeep: - lastbeep = t[5] - curses.beep() - - ch = stdscr.getch() - if ch == ord('q'): - return 0 - - plot(cx + sdx, cy - sdy, ord(' ')) - dline(0, cx, cy, cx + hdx, cy - hdy, ord(' ')) - dline(0, cx, cy, cx + mdx, cy - mdy, ord(' ')) - -curses.wrapper(main) diff --git a/Demo/curses/xmas.py b/Demo/curses/xmas.py deleted file mode 100644 index 349b3a8..0000000 --- a/Demo/curses/xmas.py +++ /dev/null @@ -1,906 +0,0 @@ -# asciixmas -# December 1989 Larry Bartz Indianapolis, IN -# -# $Id$ -# -# I'm dreaming of an ascii character-based monochrome Christmas, -# Just like the ones I used to know! -# Via a full duplex communications channel, -# At 9600 bits per second, -# Even though it's kinda slow. -# -# I'm dreaming of an ascii character-based monochrome Christmas, -# With ev'ry C program I write! -# May your screen be merry and bright! -# And may all your Christmases be amber or green, -# (for reduced eyestrain and improved visibility)! -# -# -# Notes on the Python version: -# I used a couple of `try...except curses.error' to get around some functions -# returning ERR. The errors come from using wrapping functions to fill -# windows to the last character cell. The C version doesn't have this problem, -# it simply ignores any return values. -# - -import curses -import sys - -FROMWHO = "Thomas Gellekum " - -def set_color(win, color): - if curses.has_colors(): - n = color + 1 - curses.init_pair(n, color, my_bg) - win.attroff(curses.A_COLOR) - win.attron(curses.color_pair(n)) - -def unset_color(win): - if curses.has_colors(): - win.attrset(curses.color_pair(0)) - -def look_out(msecs): - curses.napms(msecs) - if stdscr.getch() != -1: - curses.beep() - sys.exit(0) - -def boxit(): - for y in range(0, 20): - stdscr.addch(y, 7, ord('|')) - - for x in range(8, 80): - stdscr.addch(19, x, ord('_')) - - for x in range(0, 80): - stdscr.addch(22, x, ord('_')) - - return - -def seas(): - stdscr.addch(4, 1, ord('S')) - stdscr.addch(6, 1, ord('E')) - stdscr.addch(8, 1, ord('A')) - stdscr.addch(10, 1, ord('S')) - stdscr.addch(12, 1, ord('O')) - stdscr.addch(14, 1, ord('N')) - stdscr.addch(16, 1, ord("'")) - stdscr.addch(18, 1, ord('S')) - - return - -def greet(): - stdscr.addch(3, 5, ord('G')) - stdscr.addch(5, 5, ord('R')) - stdscr.addch(7, 5, ord('E')) - stdscr.addch(9, 5, ord('E')) - stdscr.addch(11, 5, ord('T')) - stdscr.addch(13, 5, ord('I')) - stdscr.addch(15, 5, ord('N')) - stdscr.addch(17, 5, ord('G')) - stdscr.addch(19, 5, ord('S')) - - return - -def fromwho(): - stdscr.addstr(21, 13, FROMWHO) - return - -def tree(): - set_color(treescrn, curses.COLOR_GREEN) - treescrn.addch(1, 11, ord('/')) - treescrn.addch(2, 11, ord('/')) - treescrn.addch(3, 10, ord('/')) - treescrn.addch(4, 9, ord('/')) - treescrn.addch(5, 9, ord('/')) - treescrn.addch(6, 8, ord('/')) - treescrn.addch(7, 7, ord('/')) - treescrn.addch(8, 6, ord('/')) - treescrn.addch(9, 6, ord('/')) - treescrn.addch(10, 5, ord('/')) - treescrn.addch(11, 3, ord('/')) - treescrn.addch(12, 2, ord('/')) - - treescrn.addch(1, 13, ord('\\')) - treescrn.addch(2, 13, ord('\\')) - treescrn.addch(3, 14, ord('\\')) - treescrn.addch(4, 15, ord('\\')) - treescrn.addch(5, 15, ord('\\')) - treescrn.addch(6, 16, ord('\\')) - treescrn.addch(7, 17, ord('\\')) - treescrn.addch(8, 18, ord('\\')) - treescrn.addch(9, 18, ord('\\')) - treescrn.addch(10, 19, ord('\\')) - treescrn.addch(11, 21, ord('\\')) - treescrn.addch(12, 22, ord('\\')) - - treescrn.addch(4, 10, ord('_')) - treescrn.addch(4, 14, ord('_')) - treescrn.addch(8, 7, ord('_')) - treescrn.addch(8, 17, ord('_')) - - treescrn.addstr(13, 0, "//////////// \\\\\\\\\\\\\\\\\\\\\\\\") - - treescrn.addstr(14, 11, "| |") - treescrn.addstr(15, 11, "|_|") - - unset_color(treescrn) - treescrn.refresh() - w_del_msg.refresh() - - return - -def balls(): - treescrn.overlay(treescrn2) - - set_color(treescrn2, curses.COLOR_BLUE) - treescrn2.addch(3, 9, ord('@')) - treescrn2.addch(3, 15, ord('@')) - treescrn2.addch(4, 8, ord('@')) - treescrn2.addch(4, 16, ord('@')) - treescrn2.addch(5, 7, ord('@')) - treescrn2.addch(5, 17, ord('@')) - treescrn2.addch(7, 6, ord('@')) - treescrn2.addch(7, 18, ord('@')) - treescrn2.addch(8, 5, ord('@')) - treescrn2.addch(8, 19, ord('@')) - treescrn2.addch(10, 4, ord('@')) - treescrn2.addch(10, 20, ord('@')) - treescrn2.addch(11, 2, ord('@')) - treescrn2.addch(11, 22, ord('@')) - treescrn2.addch(12, 1, ord('@')) - treescrn2.addch(12, 23, ord('@')) - - unset_color(treescrn2) - treescrn2.refresh() - w_del_msg.refresh() - return - -def star(): - treescrn2.attrset(curses.A_BOLD | curses.A_BLINK) - set_color(treescrn2, curses.COLOR_YELLOW) - - treescrn2.addch(0, 12, ord('*')) - treescrn2.standend() - - unset_color(treescrn2) - treescrn2.refresh() - w_del_msg.refresh() - return - -def strng1(): - treescrn2.attrset(curses.A_BOLD | curses.A_BLINK) - set_color(treescrn2, curses.COLOR_WHITE) - - treescrn2.addch(3, 13, ord('\'')) - treescrn2.addch(3, 12, ord(':')) - treescrn2.addch(3, 11, ord('.')) - - treescrn2.attroff(curses.A_BOLD | curses.A_BLINK) - unset_color(treescrn2) - - treescrn2.refresh() - w_del_msg.refresh() - return - -def strng2(): - treescrn2.attrset(curses.A_BOLD | curses.A_BLINK) - set_color(treescrn2, curses.COLOR_WHITE) - - treescrn2.addch(5, 14, ord('\'')) - treescrn2.addch(5, 13, ord(':')) - treescrn2.addch(5, 12, ord('.')) - treescrn2.addch(5, 11, ord(',')) - treescrn2.addch(6, 10, ord('\'')) - treescrn2.addch(6, 9, ord(':')) - - treescrn2.attroff(curses.A_BOLD | curses.A_BLINK) - unset_color(treescrn2) - - treescrn2.refresh() - w_del_msg.refresh() - return - -def strng3(): - treescrn2.attrset(curses.A_BOLD | curses.A_BLINK) - set_color(treescrn2, curses.COLOR_WHITE) - - treescrn2.addch(7, 16, ord('\'')) - treescrn2.addch(7, 15, ord(':')) - treescrn2.addch(7, 14, ord('.')) - treescrn2.addch(7, 13, ord(',')) - treescrn2.addch(8, 12, ord('\'')) - treescrn2.addch(8, 11, ord(':')) - treescrn2.addch(8, 10, ord('.')) - treescrn2.addch(8, 9, ord(',')) - - treescrn2.attroff(curses.A_BOLD | curses.A_BLINK) - unset_color(treescrn2) - - treescrn2.refresh() - w_del_msg.refresh() - return - -def strng4(): - treescrn2.attrset(curses.A_BOLD | curses.A_BLINK) - set_color(treescrn2, curses.COLOR_WHITE) - - treescrn2.addch(9, 17, ord('\'')) - treescrn2.addch(9, 16, ord(':')) - treescrn2.addch(9, 15, ord('.')) - treescrn2.addch(9, 14, ord(',')) - treescrn2.addch(10, 13, ord('\'')) - treescrn2.addch(10, 12, ord(':')) - treescrn2.addch(10, 11, ord('.')) - treescrn2.addch(10, 10, ord(',')) - treescrn2.addch(11, 9, ord('\'')) - treescrn2.addch(11, 8, ord(':')) - treescrn2.addch(11, 7, ord('.')) - treescrn2.addch(11, 6, ord(',')) - treescrn2.addch(12, 5, ord('\'')) - - treescrn2.attroff(curses.A_BOLD | curses.A_BLINK) - unset_color(treescrn2) - - treescrn2.refresh() - w_del_msg.refresh() - return - -def strng5(): - treescrn2.attrset(curses.A_BOLD | curses.A_BLINK) - set_color(treescrn2, curses.COLOR_WHITE) - - treescrn2.addch(11, 19, ord('\'')) - treescrn2.addch(11, 18, ord(':')) - treescrn2.addch(11, 17, ord('.')) - treescrn2.addch(11, 16, ord(',')) - treescrn2.addch(12, 15, ord('\'')) - treescrn2.addch(12, 14, ord(':')) - treescrn2.addch(12, 13, ord('.')) - treescrn2.addch(12, 12, ord(',')) - - treescrn2.attroff(curses.A_BOLD | curses.A_BLINK) - unset_color(treescrn2) - - # save a fully lit tree - treescrn2.overlay(treescrn) - - treescrn2.refresh() - w_del_msg.refresh() - return - -def blinkit(): - treescrn8.touchwin() - - for cycle in range(5): - if cycle == 0: - treescrn3.overlay(treescrn8) - treescrn8.refresh() - w_del_msg.refresh() - break - elif cycle == 1: - treescrn4.overlay(treescrn8) - treescrn8.refresh() - w_del_msg.refresh() - break - elif cycle == 2: - treescrn5.overlay(treescrn8) - treescrn8.refresh() - w_del_msg.refresh() - break - elif cycle == 3: - treescrn6.overlay(treescrn8) - treescrn8.refresh() - w_del_msg.refresh() - break - elif cycle == 4: - treescrn7.overlay(treescrn8) - treescrn8.refresh() - w_del_msg.refresh() - break - - treescrn8.touchwin() - - # ALL ON - treescrn.overlay(treescrn8) - treescrn8.refresh() - w_del_msg.refresh() - - return - -def deer_step(win, y, x): - win.mvwin(y, x) - win.refresh() - w_del_msg.refresh() - look_out(5) - -def reindeer(): - y_pos = 0 - - for x_pos in range(70, 62, -1): - if x_pos < 66: y_pos = 1 - for looper in range(0, 4): - dotdeer0.addch(y_pos, x_pos, ord('.')) - dotdeer0.refresh() - w_del_msg.refresh() - dotdeer0.erase() - dotdeer0.refresh() - w_del_msg.refresh() - look_out(50) - - y_pos = 2 - - for x_pos in range(x_pos - 1, 50, -1): - for looper in range(0, 4): - if x_pos < 56: - y_pos = 3 - - try: - stardeer0.addch(y_pos, x_pos, ord('*')) - except curses.error: - pass - stardeer0.refresh() - w_del_msg.refresh() - stardeer0.erase() - stardeer0.refresh() - w_del_msg.refresh() - else: - dotdeer0.addch(y_pos, x_pos, ord('*')) - dotdeer0.refresh() - w_del_msg.refresh() - dotdeer0.erase() - dotdeer0.refresh() - w_del_msg.refresh() - - x_pos = 58 - - for y_pos in range(2, 5): - lildeer0.touchwin() - lildeer0.refresh() - w_del_msg.refresh() - - for looper in range(0, 4): - deer_step(lildeer3, y_pos, x_pos) - deer_step(lildeer2, y_pos, x_pos) - deer_step(lildeer1, y_pos, x_pos) - deer_step(lildeer2, y_pos, x_pos) - deer_step(lildeer3, y_pos, x_pos) - - lildeer0.touchwin() - lildeer0.refresh() - w_del_msg.refresh() - - x_pos -= 2 - - x_pos = 35 - - for y_pos in range(5, 10): - - middeer0.touchwin() - middeer0.refresh() - w_del_msg.refresh() - - for looper in range(2): - deer_step(middeer3, y_pos, x_pos) - deer_step(middeer2, y_pos, x_pos) - deer_step(middeer1, y_pos, x_pos) - deer_step(middeer2, y_pos, x_pos) - deer_step(middeer3, y_pos, x_pos) - - middeer0.touchwin() - middeer0.refresh() - w_del_msg.refresh() - - x_pos -= 3 - - look_out(300) - - y_pos = 1 - - for x_pos in range(8, 16): - deer_step(bigdeer4, y_pos, x_pos) - deer_step(bigdeer3, y_pos, x_pos) - deer_step(bigdeer2, y_pos, x_pos) - deer_step(bigdeer1, y_pos, x_pos) - deer_step(bigdeer2, y_pos, x_pos) - deer_step(bigdeer3, y_pos, x_pos) - deer_step(bigdeer4, y_pos, x_pos) - deer_step(bigdeer0, y_pos, x_pos) - - x_pos -= 1 - - for looper in range(0, 6): - deer_step(lookdeer4, y_pos, x_pos) - deer_step(lookdeer3, y_pos, x_pos) - deer_step(lookdeer2, y_pos, x_pos) - deer_step(lookdeer1, y_pos, x_pos) - deer_step(lookdeer2, y_pos, x_pos) - deer_step(lookdeer3, y_pos, x_pos) - deer_step(lookdeer4, y_pos, x_pos) - - deer_step(lookdeer0, y_pos, x_pos) - - for y_pos in range(y_pos, 10): - for looper in range(0, 2): - deer_step(bigdeer4, y_pos, x_pos) - deer_step(bigdeer3, y_pos, x_pos) - deer_step(bigdeer2, y_pos, x_pos) - deer_step(bigdeer1, y_pos, x_pos) - deer_step(bigdeer2, y_pos, x_pos) - deer_step(bigdeer3, y_pos, x_pos) - deer_step(bigdeer4, y_pos, x_pos) - deer_step(bigdeer0, y_pos, x_pos) - - y_pos -= 1 - - deer_step(lookdeer3, y_pos, x_pos) - return - -def main(win): - global stdscr - stdscr = win - - global my_bg, y_pos, x_pos - global treescrn, treescrn2, treescrn3, treescrn4 - global treescrn5, treescrn6, treescrn7, treescrn8 - global dotdeer0, stardeer0 - global lildeer0, lildeer1, lildeer2, lildeer3 - global middeer0, middeer1, middeer2, middeer3 - global bigdeer0, bigdeer1, bigdeer2, bigdeer3, bigdeer4 - global lookdeer0, lookdeer1, lookdeer2, lookdeer3, lookdeer4 - global w_holiday, w_del_msg - - my_bg = curses.COLOR_BLACK - # curses.curs_set(0) - - treescrn = curses.newwin(16, 27, 3, 53) - treescrn2 = curses.newwin(16, 27, 3, 53) - treescrn3 = curses.newwin(16, 27, 3, 53) - treescrn4 = curses.newwin(16, 27, 3, 53) - treescrn5 = curses.newwin(16, 27, 3, 53) - treescrn6 = curses.newwin(16, 27, 3, 53) - treescrn7 = curses.newwin(16, 27, 3, 53) - treescrn8 = curses.newwin(16, 27, 3, 53) - - dotdeer0 = curses.newwin(3, 71, 0, 8) - - stardeer0 = curses.newwin(4, 56, 0, 8) - - lildeer0 = curses.newwin(7, 53, 0, 8) - lildeer1 = curses.newwin(2, 4, 0, 0) - lildeer2 = curses.newwin(2, 4, 0, 0) - lildeer3 = curses.newwin(2, 4, 0, 0) - - middeer0 = curses.newwin(15, 42, 0, 8) - middeer1 = curses.newwin(3, 7, 0, 0) - middeer2 = curses.newwin(3, 7, 0, 0) - middeer3 = curses.newwin(3, 7, 0, 0) - - bigdeer0 = curses.newwin(10, 23, 0, 0) - bigdeer1 = curses.newwin(10, 23, 0, 0) - bigdeer2 = curses.newwin(10, 23, 0, 0) - bigdeer3 = curses.newwin(10, 23, 0, 0) - bigdeer4 = curses.newwin(10, 23, 0, 0) - - lookdeer0 = curses.newwin(10, 25, 0, 0) - lookdeer1 = curses.newwin(10, 25, 0, 0) - lookdeer2 = curses.newwin(10, 25, 0, 0) - lookdeer3 = curses.newwin(10, 25, 0, 0) - lookdeer4 = curses.newwin(10, 25, 0, 0) - - w_holiday = curses.newwin(1, 27, 3, 27) - - w_del_msg = curses.newwin(1, 20, 23, 60) - - try: - w_del_msg.addstr(0, 0, "Hit any key to quit") - except curses.error: - pass - - try: - w_holiday.addstr(0, 0, "H A P P Y H O L I D A Y S") - except curses.error: - pass - - # set up the windows for our various reindeer - lildeer1.addch(0, 0, ord('V')) - lildeer1.addch(1, 0, ord('@')) - lildeer1.addch(1, 1, ord('<')) - lildeer1.addch(1, 2, ord('>')) - try: - lildeer1.addch(1, 3, ord('~')) - except curses.error: - pass - - lildeer2.addch(0, 0, ord('V')) - lildeer2.addch(1, 0, ord('@')) - lildeer2.addch(1, 1, ord('|')) - lildeer2.addch(1, 2, ord('|')) - try: - lildeer2.addch(1, 3, ord('~')) - except curses.error: - pass - - lildeer3.addch(0, 0, ord('V')) - lildeer3.addch(1, 0, ord('@')) - lildeer3.addch(1, 1, ord('>')) - lildeer3.addch(1, 2, ord('<')) - try: - lildeer2.addch(1, 3, ord('~')) # XXX - except curses.error: - pass - - middeer1.addch(0, 2, ord('y')) - middeer1.addch(0, 3, ord('y')) - middeer1.addch(1, 2, ord('0')) - middeer1.addch(1, 3, ord('(')) - middeer1.addch(1, 4, ord('=')) - middeer1.addch(1, 5, ord(')')) - middeer1.addch(1, 6, ord('~')) - middeer1.addch(2, 3, ord('\\')) - middeer1.addch(2, 5, ord('/')) - - middeer2.addch(0, 2, ord('y')) - middeer2.addch(0, 3, ord('y')) - middeer2.addch(1, 2, ord('0')) - middeer2.addch(1, 3, ord('(')) - middeer2.addch(1, 4, ord('=')) - middeer2.addch(1, 5, ord(')')) - middeer2.addch(1, 6, ord('~')) - middeer2.addch(2, 3, ord('|')) - middeer2.addch(2, 5, ord('|')) - - middeer3.addch(0, 2, ord('y')) - middeer3.addch(0, 3, ord('y')) - middeer3.addch(1, 2, ord('0')) - middeer3.addch(1, 3, ord('(')) - middeer3.addch(1, 4, ord('=')) - middeer3.addch(1, 5, ord(')')) - middeer3.addch(1, 6, ord('~')) - middeer3.addch(2, 3, ord('/')) - middeer3.addch(2, 5, ord('\\')) - - bigdeer1.addch(0, 17, ord('\\')) - bigdeer1.addch(0, 18, ord('/')) - bigdeer1.addch(0, 19, ord('\\')) - bigdeer1.addch(0, 20, ord('/')) - bigdeer1.addch(1, 18, ord('\\')) - bigdeer1.addch(1, 20, ord('/')) - bigdeer1.addch(2, 19, ord('|')) - bigdeer1.addch(2, 20, ord('_')) - bigdeer1.addch(3, 18, ord('/')) - bigdeer1.addch(3, 19, ord('^')) - bigdeer1.addch(3, 20, ord('0')) - bigdeer1.addch(3, 21, ord('\\')) - bigdeer1.addch(4, 17, ord('/')) - bigdeer1.addch(4, 18, ord('/')) - bigdeer1.addch(4, 19, ord('\\')) - bigdeer1.addch(4, 22, ord('\\')) - bigdeer1.addstr(5, 7, "^~~~~~~~~// ~~U") - bigdeer1.addstr(6, 7, "( \\_____( /") # )) - bigdeer1.addstr(7, 8, "( ) /") - bigdeer1.addstr(8, 9, "\\\\ /") - bigdeer1.addstr(9, 11, "\\>/>") - - bigdeer2.addch(0, 17, ord('\\')) - bigdeer2.addch(0, 18, ord('/')) - bigdeer2.addch(0, 19, ord('\\')) - bigdeer2.addch(0, 20, ord('/')) - bigdeer2.addch(1, 18, ord('\\')) - bigdeer2.addch(1, 20, ord('/')) - bigdeer2.addch(2, 19, ord('|')) - bigdeer2.addch(2, 20, ord('_')) - bigdeer2.addch(3, 18, ord('/')) - bigdeer2.addch(3, 19, ord('^')) - bigdeer2.addch(3, 20, ord('0')) - bigdeer2.addch(3, 21, ord('\\')) - bigdeer2.addch(4, 17, ord('/')) - bigdeer2.addch(4, 18, ord('/')) - bigdeer2.addch(4, 19, ord('\\')) - bigdeer2.addch(4, 22, ord('\\')) - bigdeer2.addstr(5, 7, "^~~~~~~~~// ~~U") - bigdeer2.addstr(6, 7, "(( )____( /") # )) - bigdeer2.addstr(7, 7, "( / |") - bigdeer2.addstr(8, 8, "\\/ |") - bigdeer2.addstr(9, 9, "|> |>") - - bigdeer3.addch(0, 17, ord('\\')) - bigdeer3.addch(0, 18, ord('/')) - bigdeer3.addch(0, 19, ord('\\')) - bigdeer3.addch(0, 20, ord('/')) - bigdeer3.addch(1, 18, ord('\\')) - bigdeer3.addch(1, 20, ord('/')) - bigdeer3.addch(2, 19, ord('|')) - bigdeer3.addch(2, 20, ord('_')) - bigdeer3.addch(3, 18, ord('/')) - bigdeer3.addch(3, 19, ord('^')) - bigdeer3.addch(3, 20, ord('0')) - bigdeer3.addch(3, 21, ord('\\')) - bigdeer3.addch(4, 17, ord('/')) - bigdeer3.addch(4, 18, ord('/')) - bigdeer3.addch(4, 19, ord('\\')) - bigdeer3.addch(4, 22, ord('\\')) - bigdeer3.addstr(5, 7, "^~~~~~~~~// ~~U") - bigdeer3.addstr(6, 6, "( ()_____( /") # )) - bigdeer3.addstr(7, 6, "/ / /") - bigdeer3.addstr(8, 5, "|/ \\") - bigdeer3.addstr(9, 5, "/> \\>") - - bigdeer4.addch(0, 17, ord('\\')) - bigdeer4.addch(0, 18, ord('/')) - bigdeer4.addch(0, 19, ord('\\')) - bigdeer4.addch(0, 20, ord('/')) - bigdeer4.addch(1, 18, ord('\\')) - bigdeer4.addch(1, 20, ord('/')) - bigdeer4.addch(2, 19, ord('|')) - bigdeer4.addch(2, 20, ord('_')) - bigdeer4.addch(3, 18, ord('/')) - bigdeer4.addch(3, 19, ord('^')) - bigdeer4.addch(3, 20, ord('0')) - bigdeer4.addch(3, 21, ord('\\')) - bigdeer4.addch(4, 17, ord('/')) - bigdeer4.addch(4, 18, ord('/')) - bigdeer4.addch(4, 19, ord('\\')) - bigdeer4.addch(4, 22, ord('\\')) - bigdeer4.addstr(5, 7, "^~~~~~~~~// ~~U") - bigdeer4.addstr(6, 6, "( )______( /") # ) - bigdeer4.addstr(7, 5, "(/ \\") # ) - bigdeer4.addstr(8, 0, "v___= ----^") - - lookdeer1.addstr(0, 16, "\\/ \\/") - lookdeer1.addstr(1, 17, "\\Y/ \\Y/") - lookdeer1.addstr(2, 19, "\\=/") - lookdeer1.addstr(3, 17, "^\\o o/^") - lookdeer1.addstr(4, 17, "//( )") - lookdeer1.addstr(5, 7, "^~~~~~~~~// \\O/") - lookdeer1.addstr(6, 7, "( \\_____( /") # )) - lookdeer1.addstr(7, 8, "( ) /") - lookdeer1.addstr(8, 9, "\\\\ /") - lookdeer1.addstr(9, 11, "\\>/>") - - lookdeer2.addstr(0, 16, "\\/ \\/") - lookdeer2.addstr(1, 17, "\\Y/ \\Y/") - lookdeer2.addstr(2, 19, "\\=/") - lookdeer2.addstr(3, 17, "^\\o o/^") - lookdeer2.addstr(4, 17, "//( )") - lookdeer2.addstr(5, 7, "^~~~~~~~~// \\O/") - lookdeer2.addstr(6, 7, "(( )____( /") # )) - lookdeer2.addstr(7, 7, "( / |") - lookdeer2.addstr(8, 8, "\\/ |") - lookdeer2.addstr(9, 9, "|> |>") - - lookdeer3.addstr(0, 16, "\\/ \\/") - lookdeer3.addstr(1, 17, "\\Y/ \\Y/") - lookdeer3.addstr(2, 19, "\\=/") - lookdeer3.addstr(3, 17, "^\\o o/^") - lookdeer3.addstr(4, 17, "//( )") - lookdeer3.addstr(5, 7, "^~~~~~~~~// \\O/") - lookdeer3.addstr(6, 6, "( ()_____( /") # )) - lookdeer3.addstr(7, 6, "/ / /") - lookdeer3.addstr(8, 5, "|/ \\") - lookdeer3.addstr(9, 5, "/> \\>") - - lookdeer4.addstr(0, 16, "\\/ \\/") - lookdeer4.addstr(1, 17, "\\Y/ \\Y/") - lookdeer4.addstr(2, 19, "\\=/") - lookdeer4.addstr(3, 17, "^\\o o/^") - lookdeer4.addstr(4, 17, "//( )") - lookdeer4.addstr(5, 7, "^~~~~~~~~// \\O/") - lookdeer4.addstr(6, 6, "( )______( /") # ) - lookdeer4.addstr(7, 5, "(/ \\") # ) - lookdeer4.addstr(8, 0, "v___= ----^") - - ############################################### - curses.cbreak() - stdscr.nodelay(1) - - while 1: - stdscr.clear() - treescrn.erase() - w_del_msg.touchwin() - treescrn.touchwin() - treescrn2.erase() - treescrn2.touchwin() - treescrn8.erase() - treescrn8.touchwin() - stdscr.refresh() - look_out(150) - boxit() - stdscr.refresh() - look_out(150) - seas() - stdscr.refresh() - greet() - stdscr.refresh() - look_out(150) - fromwho() - stdscr.refresh() - look_out(150) - tree() - look_out(150) - balls() - look_out(150) - star() - look_out(150) - strng1() - strng2() - strng3() - strng4() - strng5() - - # set up the windows for our blinking trees - # - # treescrn3 - treescrn.overlay(treescrn3) - - # balls - treescrn3.addch(4, 18, ord(' ')) - treescrn3.addch(7, 6, ord(' ')) - treescrn3.addch(8, 19, ord(' ')) - treescrn3.addch(11, 22, ord(' ')) - - # star - treescrn3.addch(0, 12, ord('*')) - - # strng1 - treescrn3.addch(3, 11, ord(' ')) - - # strng2 - treescrn3.addch(5, 13, ord(' ')) - treescrn3.addch(6, 10, ord(' ')) - - # strng3 - treescrn3.addch(7, 16, ord(' ')) - treescrn3.addch(7, 14, ord(' ')) - - # strng4 - treescrn3.addch(10, 13, ord(' ')) - treescrn3.addch(10, 10, ord(' ')) - treescrn3.addch(11, 8, ord(' ')) - - # strng5 - treescrn3.addch(11, 18, ord(' ')) - treescrn3.addch(12, 13, ord(' ')) - - # treescrn4 - treescrn.overlay(treescrn4) - - # balls - treescrn4.addch(3, 9, ord(' ')) - treescrn4.addch(4, 16, ord(' ')) - treescrn4.addch(7, 6, ord(' ')) - treescrn4.addch(8, 19, ord(' ')) - treescrn4.addch(11, 2, ord(' ')) - treescrn4.addch(12, 23, ord(' ')) - - # star - treescrn4.standout() - treescrn4.addch(0, 12, ord('*')) - treescrn4.standend() - - # strng1 - treescrn4.addch(3, 13, ord(' ')) - - # strng2 - - # strng3 - treescrn4.addch(7, 15, ord(' ')) - treescrn4.addch(8, 11, ord(' ')) - - # strng4 - treescrn4.addch(9, 16, ord(' ')) - treescrn4.addch(10, 12, ord(' ')) - treescrn4.addch(11, 8, ord(' ')) - - # strng5 - treescrn4.addch(11, 18, ord(' ')) - treescrn4.addch(12, 14, ord(' ')) - - # treescrn5 - treescrn.overlay(treescrn5) - - # balls - treescrn5.addch(3, 15, ord(' ')) - treescrn5.addch(10, 20, ord(' ')) - treescrn5.addch(12, 1, ord(' ')) - - # star - treescrn5.addch(0, 12, ord(' ')) - - # strng1 - treescrn5.addch(3, 11, ord(' ')) - - # strng2 - treescrn5.addch(5, 12, ord(' ')) - - # strng3 - treescrn5.addch(7, 14, ord(' ')) - treescrn5.addch(8, 10, ord(' ')) - - # strng4 - treescrn5.addch(9, 15, ord(' ')) - treescrn5.addch(10, 11, ord(' ')) - treescrn5.addch(11, 7, ord(' ')) - - # strng5 - treescrn5.addch(11, 17, ord(' ')) - treescrn5.addch(12, 13, ord(' ')) - - # treescrn6 - treescrn.overlay(treescrn6) - - # balls - treescrn6.addch(6, 7, ord(' ')) - treescrn6.addch(7, 18, ord(' ')) - treescrn6.addch(10, 4, ord(' ')) - treescrn6.addch(11, 23, ord(' ')) - - # star - treescrn6.standout() - treescrn6.addch(0, 12, ord('*')) - treescrn6.standend() - - # strng1 - - # strng2 - treescrn6.addch(5, 11, ord(' ')) - - # strng3 - treescrn6.addch(7, 13, ord(' ')) - treescrn6.addch(8, 9, ord(' ')) - - # strng4 - treescrn6.addch(9, 14, ord(' ')) - treescrn6.addch(10, 10, ord(' ')) - treescrn6.addch(11, 6, ord(' ')) - - # strng5 - treescrn6.addch(11, 16, ord(' ')) - treescrn6.addch(12, 12, ord(' ')) - - # treescrn7 - - treescrn.overlay(treescrn7) - - # balls - treescrn7.addch(3, 15, ord(' ')) - treescrn7.addch(6, 7, ord(' ')) - treescrn7.addch(7, 18, ord(' ')) - treescrn7.addch(10, 4, ord(' ')) - treescrn7.addch(11, 22, ord(' ')) - - # star - treescrn7.addch(0, 12, ord('*')) - - # strng1 - treescrn7.addch(3, 12, ord(' ')) - - # strng2 - treescrn7.addch(5, 13, ord(' ')) - treescrn7.addch(6, 9, ord(' ')) - - # strng3 - treescrn7.addch(7, 15, ord(' ')) - treescrn7.addch(8, 11, ord(' ')) - - # strng4 - treescrn7.addch(9, 16, ord(' ')) - treescrn7.addch(10, 12, ord(' ')) - treescrn7.addch(11, 8, ord(' ')) - - # strng5 - treescrn7.addch(11, 18, ord(' ')) - treescrn7.addch(12, 14, ord(' ')) - - look_out(150) - reindeer() - - w_holiday.touchwin() - w_holiday.refresh() - w_del_msg.refresh() - - look_out(500) - for i in range(0, 20): - blinkit() - -curses.wrapper(main) diff --git a/Demo/md5test/README b/Demo/md5test/README deleted file mode 100644 index be7621e..0000000 --- a/Demo/md5test/README +++ /dev/null @@ -1,10 +0,0 @@ -This is the Python version of the MD5 test program from the MD5 -Internet Draft (Rivest and Dusse, The MD5 Message-Digest Algorithm, 10 -July 1991). The file "foo" contains the string "abc" with no trailing -newline. - -When called without arguments, it acts as a filter. When called with -"-x", it executes a self-test, and the output should literally match -the output given in the RFC. - -Code by Jan-Hein B\"uhrman after the original in C. diff --git a/Demo/md5test/foo b/Demo/md5test/foo deleted file mode 100755 index f2ba8f8..0000000 --- a/Demo/md5test/foo +++ /dev/null @@ -1 +0,0 @@ -abc \ No newline at end of file diff --git a/Demo/md5test/md5driver.py b/Demo/md5test/md5driver.py deleted file mode 100644 index 7f561ab..0000000 --- a/Demo/md5test/md5driver.py +++ /dev/null @@ -1,122 +0,0 @@ -from hashlib import md5 -import string -from sys import argv - -def MDPrint(str): - outstr = '' - for o in str: - outstr = (outstr - + string.hexdigits[(o >> 4) & 0xF] - + string.hexdigits[o & 0xF]) - print(outstr, end=' ') - - -from time import time - -def makestr(start, end): - result = '' - for i in range(start, end + 1): - result = result + chr(i) - - return result - - -def MDTimeTrial(): - TEST_BLOCK_SIZE = 1000 - TEST_BLOCKS = 10000 - - TEST_BYTES = TEST_BLOCK_SIZE * TEST_BLOCKS - - # initialize test data, need temporary string filler - - filsiz = 1 << 8 - filler = makestr(0, filsiz-1) - data = filler * (TEST_BLOCK_SIZE // filsiz) - data = data + filler[:(TEST_BLOCK_SIZE % filsiz)] - - del filsiz, filler - - - # start timer - print('MD5 time trial. Processing', TEST_BYTES, 'characters...') - t1 = time() - - mdContext = md5() - - for i in range(TEST_BLOCKS): - mdContext.update(data) - - str = mdContext.digest() - t2 = time() - - MDPrint(str) - print('is digest of test input.') - print('Seconds to process test input:', t2 - t1) - print('Characters processed per second:', TEST_BYTES / (t2 - t1)) - - -def MDString(str): - MDPrint(md5(str.encode("utf-8")).digest()) - print('"' + str + '"') - - -def MDFile(filename): - f = open(filename, 'rb') - mdContext = md5() - - while 1: - data = f.read(1024) - if not data: - break - mdContext.update(data) - - MDPrint(mdContext.digest()) - print(filename) - - -import sys - -def MDFilter(): - mdContext = md5() - - while 1: - data = sys.stdin.read(16).encode() - if not data: - break - mdContext.update(data) - - MDPrint(mdContext.digest()) - print() - - -def MDTestSuite(): - print('MD5 test suite results:') - MDString('') - MDString('a') - MDString('abc') - MDString('message digest') - MDString(makestr(ord('a'), ord('z'))) - MDString(makestr(ord('A'), ord('Z')) - + makestr(ord('a'), ord('z')) - + makestr(ord('0'), ord('9'))) - MDString((makestr(ord('1'), ord('9')) + '0') * 8) - - # Contents of file foo are "abc" - MDFile('foo') - - -# I don't wanna use getopt(), since I want to use the same i/f... -def main(): - if len(argv) == 1: - MDFilter() - for arg in argv[1:]: - if arg[:2] == '-s': - MDString(arg[2:]) - elif arg == '-t': - MDTimeTrial() - elif arg == '-x': - MDTestSuite() - else: - MDFile(arg) - -main() diff --git a/Demo/parser/FILES b/Demo/parser/FILES deleted file mode 100644 index 1ff59a3..0000000 --- a/Demo/parser/FILES +++ /dev/null @@ -1,6 +0,0 @@ -Demo/parser -Doc/libparser.tex -Lib/AST.py -Lib/symbol.py -Lib/token.py -Modules/parsermodule.c diff --git a/Demo/parser/README b/Demo/parser/README deleted file mode 100644 index a576d33..0000000 --- a/Demo/parser/README +++ /dev/null @@ -1,31 +0,0 @@ -These files are from the large example of using the `parser' module. Refer -to the Python Library Reference for more information. - -It also contains examples for the AST parser. - -Files: ------- - - FILES -- list of files associated with the parser module. - - README -- this file. - - example.py -- module that uses the `parser' module to extract - information from the parse tree of Python source - code. - - docstring.py -- sample source file containing only a module docstring. - - simple.py -- sample source containing a "short form" definition. - - source.py -- sample source code used to demonstrate ability to - handle nested constructs easily using the functions - and classes in example.py. - - test_parser.py program to put the parser module through its paces. - - unparse.py AST (2.5) based example to recreate source code - from an AST. This is incomplete; contributions - are welcome. - -Enjoy! diff --git a/Demo/parser/docstring.py b/Demo/parser/docstring.py deleted file mode 100644 index 45a261b..0000000 --- a/Demo/parser/docstring.py +++ /dev/null @@ -1,2 +0,0 @@ -"""Some documentation. -""" diff --git a/Demo/parser/example.py b/Demo/parser/example.py deleted file mode 100644 index c2f0883..0000000 --- a/Demo/parser/example.py +++ /dev/null @@ -1,190 +0,0 @@ -"""Simple code to extract class & function docstrings from a module. - -This code is used as an example in the library reference manual in the -section on using the parser module. Refer to the manual for a thorough -discussion of the operation of this code. -""" - -import os -import parser -import symbol -import token -import types - -from types import ListType, TupleType - - -def get_docs(fileName): - """Retrieve information from the parse tree of a source file. - - fileName - Name of the file to read Python source code from. - """ - source = open(fileName).read() - basename = os.path.basename(os.path.splitext(fileName)[0]) - ast = parser.suite(source) - return ModuleInfo(ast.totuple(), basename) - - -class SuiteInfoBase: - _docstring = '' - _name = '' - - def __init__(self, tree = None): - self._class_info = {} - self._function_info = {} - if tree: - self._extract_info(tree) - - def _extract_info(self, tree): - # extract docstring - if len(tree) == 2: - found, vars = match(DOCSTRING_STMT_PATTERN[1], tree[1]) - else: - found, vars = match(DOCSTRING_STMT_PATTERN, tree[3]) - if found: - self._docstring = eval(vars['docstring']) - # discover inner definitions - for node in tree[1:]: - found, vars = match(COMPOUND_STMT_PATTERN, node) - if found: - cstmt = vars['compound'] - if cstmt[0] == symbol.funcdef: - name = cstmt[2][1] - self._function_info[name] = FunctionInfo(cstmt) - elif cstmt[0] == symbol.classdef: - name = cstmt[2][1] - self._class_info[name] = ClassInfo(cstmt) - - def get_docstring(self): - return self._docstring - - def get_name(self): - return self._name - - def get_class_names(self): - return list(self._class_info.keys()) - - def get_class_info(self, name): - return self._class_info[name] - - def __getitem__(self, name): - try: - return self._class_info[name] - except KeyError: - return self._function_info[name] - - -class SuiteFuncInfo: - # Mixin class providing access to function names and info. - - def get_function_names(self): - return list(self._function_info.keys()) - - def get_function_info(self, name): - return self._function_info[name] - - -class FunctionInfo(SuiteInfoBase, SuiteFuncInfo): - def __init__(self, tree = None): - self._name = tree[2][1] - SuiteInfoBase.__init__(self, tree and tree[-1] or None) - - -class ClassInfo(SuiteInfoBase): - def __init__(self, tree = None): - self._name = tree[2][1] - SuiteInfoBase.__init__(self, tree and tree[-1] or None) - - def get_method_names(self): - return list(self._function_info.keys()) - - def get_method_info(self, name): - return self._function_info[name] - - -class ModuleInfo(SuiteInfoBase, SuiteFuncInfo): - def __init__(self, tree = None, name = ""): - self._name = name - SuiteInfoBase.__init__(self, tree) - if tree: - found, vars = match(DOCSTRING_STMT_PATTERN, tree[1]) - if found: - self._docstring = vars["docstring"] - - -def match(pattern, data, vars=None): - """Match `data' to `pattern', with variable extraction. - - pattern - Pattern to match against, possibly containing variables. - - data - Data to be checked and against which variables are extracted. - - vars - Dictionary of variables which have already been found. If not - provided, an empty dictionary is created. - - The `pattern' value may contain variables of the form ['varname'] which - are allowed to match anything. The value that is matched is returned as - part of a dictionary which maps 'varname' to the matched value. 'varname' - is not required to be a string object, but using strings makes patterns - and the code which uses them more readable. - - This function returns two values: a boolean indicating whether a match - was found and a dictionary mapping variable names to their associated - values. - """ - if vars is None: - vars = {} - if type(pattern) is ListType: # 'variables' are ['varname'] - vars[pattern[0]] = data - return 1, vars - if type(pattern) is not TupleType: - return (pattern == data), vars - if len(data) != len(pattern): - return 0, vars - for pattern, data in map(None, pattern, data): - same, vars = match(pattern, data, vars) - if not same: - break - return same, vars - - -# This pattern identifies compound statements, allowing them to be readily -# differentiated from simple statements. -# -COMPOUND_STMT_PATTERN = ( - symbol.stmt, - (symbol.compound_stmt, ['compound']) - ) - - -# This pattern will match a 'stmt' node which *might* represent a docstring; -# docstrings require that the statement which provides the docstring be the -# first statement in the class or function, which this pattern does not check. -# -DOCSTRING_STMT_PATTERN = ( - symbol.stmt, - (symbol.simple_stmt, - (symbol.small_stmt, - (symbol.expr_stmt, - (symbol.testlist, - (symbol.test, - (symbol.and_test, - (symbol.not_test, - (symbol.comparison, - (symbol.expr, - (symbol.xor_expr, - (symbol.and_expr, - (symbol.shift_expr, - (symbol.arith_expr, - (symbol.term, - (symbol.factor, - (symbol.power, - (symbol.atom, - (token.STRING, ['docstring']) - )))))))))))))))), - (token.NEWLINE, '') - )) diff --git a/Demo/parser/simple.py b/Demo/parser/simple.py deleted file mode 100644 index 184e2fe..0000000 --- a/Demo/parser/simple.py +++ /dev/null @@ -1 +0,0 @@ -def f(): "maybe a docstring" diff --git a/Demo/parser/source.py b/Demo/parser/source.py deleted file mode 100644 index b900628..0000000 --- a/Demo/parser/source.py +++ /dev/null @@ -1,27 +0,0 @@ -"""Exmaple file to be parsed for the parsermodule example. - -The classes and functions in this module exist only to exhibit the ability -of the handling information extraction from nested definitions using parse -trees. They shouldn't interest you otherwise! -""" - -class Simple: - "This class does very little." - - def method(self): - "This method does almost nothing." - return 1 - - class Nested: - "This is a nested class." - - def nested_method(self): - "Method of Nested class." - def nested_function(): - "Function in method of Nested class." - pass - return nested_function - -def function(): - "This function lives at the module level." - return 0 diff --git a/Demo/parser/test_parser.py b/Demo/parser/test_parser.py deleted file mode 100755 index ffa6630..0000000 --- a/Demo/parser/test_parser.py +++ /dev/null @@ -1,48 +0,0 @@ -#! /usr/bin/env python3 -# (Force the script to use the latest build.) -# -# test_parser.py - -import parser, traceback - -_numFailed = 0 - -def testChunk(t, fileName): - global _numFailed - print('----', fileName, end=' ') - try: - st = parser.suite(t) - tup = parser.st2tuple(st) - # this discards the first ST; a huge memory savings when running - # against a large source file like Tkinter.py. - st = None - new = parser.tuple2st(tup) - except parser.ParserError as err: - print() - print('parser module raised exception on input file', fileName + ':') - traceback.print_exc() - _numFailed = _numFailed + 1 - else: - if tup != parser.st2tuple(new): - print() - print('parser module failed on input file', fileName) - _numFailed = _numFailed + 1 - else: - print('o.k.') - -def testFile(fileName): - t = open(fileName).read() - testChunk(t, fileName) - -def test(): - import sys - args = sys.argv[1:] - if not args: - import glob - args = glob.glob("*.py") - args.sort() - list(map(testFile, args)) - sys.exit(_numFailed != 0) - -if __name__ == '__main__': - test() diff --git a/Demo/parser/test_unparse.py b/Demo/parser/test_unparse.py deleted file mode 100644 index d457523..0000000 --- a/Demo/parser/test_unparse.py +++ /dev/null @@ -1,240 +0,0 @@ -import unittest -import test.support -import io -import os -import tokenize -import ast -import unparse - -def read_pyfile(filename): - """Read and return the contents of a Python source file (as a - string), taking into account the file encoding.""" - with open(filename, "rb") as pyfile: - encoding = tokenize.detect_encoding(pyfile.readline)[0] - with open(filename, "r", encoding=encoding) as pyfile: - source = pyfile.read() - return source - -for_else = """\ -def f(): - for x in range(10): - break - else: - y = 2 - z = 3 -""" - -while_else = """\ -def g(): - while True: - break - else: - y = 2 - z = 3 -""" - -relative_import = """\ -from . import fred -from .. import barney -from .australia import shrimp as prawns -""" - -nonlocal_ex = """\ -def f(): - x = 1 - def g(): - nonlocal x - x = 2 - y = 7 - def h(): - nonlocal x, y -""" - -# also acts as test for 'except ... as ...' -raise_from = """\ -try: - 1 / 0 -except ZeroDivisionError as e: - raise ArithmeticError from e -""" - -class_decorator = """\ -@f1(arg) -@f2 -class Foo: pass -""" - -elif1 = """\ -if cond1: - suite1 -elif cond2: - suite2 -else: - suite3 -""" - -elif2 = """\ -if cond1: - suite1 -elif cond2: - suite2 -""" - -try_except_finally = """\ -try: - suite1 -except ex1: - suite2 -except ex2: - suite3 -else: - suite4 -finally: - suite5 -""" - -class ASTTestCase(unittest.TestCase): - def assertASTEqual(self, ast1, ast2): - self.assertEqual(ast.dump(ast1), ast.dump(ast2)) - - def check_roundtrip(self, code1, filename="internal"): - ast1 = compile(code1, filename, "exec", ast.PyCF_ONLY_AST) - unparse_buffer = io.StringIO() - unparse.Unparser(ast1, unparse_buffer) - code2 = unparse_buffer.getvalue() - ast2 = compile(code2, filename, "exec", ast.PyCF_ONLY_AST) - self.assertASTEqual(ast1, ast2) - -class UnparseTestCase(ASTTestCase): - # Tests for specific bugs found in earlier versions of unparse - - def test_del_statement(self): - self.check_roundtrip("del x, y, z") - - def test_shifts(self): - self.check_roundtrip("45 << 2") - self.check_roundtrip("13 >> 7") - - def test_for_else(self): - self.check_roundtrip(for_else) - - def test_while_else(self): - self.check_roundtrip(while_else) - - def test_unary_parens(self): - self.check_roundtrip("(-1)**7") - self.check_roundtrip("(-1.)**8") - self.check_roundtrip("(-1j)**6") - self.check_roundtrip("not True or False") - self.check_roundtrip("True or not False") - - def test_integer_parens(self): - self.check_roundtrip("3 .__abs__()") - - def test_huge_float(self): - self.check_roundtrip("1e1000") - self.check_roundtrip("-1e1000") - self.check_roundtrip("1e1000j") - self.check_roundtrip("-1e1000j") - - def test_min_int(self): - self.check_roundtrip(str(-2**31)) - self.check_roundtrip(str(-2**63)) - - def test_imaginary_literals(self): - self.check_roundtrip("7j") - self.check_roundtrip("-7j") - self.check_roundtrip("0j") - self.check_roundtrip("-0j") - - def test_lambda_parentheses(self): - self.check_roundtrip("(lambda: int)()") - - def test_chained_comparisons(self): - self.check_roundtrip("1 < 4 <= 5") - self.check_roundtrip("a is b is c is not d") - - def test_function_arguments(self): - self.check_roundtrip("def f(): pass") - self.check_roundtrip("def f(a): pass") - self.check_roundtrip("def f(b = 2): pass") - self.check_roundtrip("def f(a, b): pass") - self.check_roundtrip("def f(a, b = 2): pass") - self.check_roundtrip("def f(a = 5, b = 2): pass") - self.check_roundtrip("def f(*, a = 1, b = 2): pass") - self.check_roundtrip("def f(*, a = 1, b): pass") - self.check_roundtrip("def f(*, a, b = 2): pass") - self.check_roundtrip("def f(a, b = None, *, c, **kwds): pass") - self.check_roundtrip("def f(a=2, *args, c=5, d, **kwds): pass") - self.check_roundtrip("def f(*args, **kwargs): pass") - - def test_relative_import(self): - self.check_roundtrip(relative_import) - - def test_nonlocal(self): - self.check_roundtrip(nonlocal_ex) - - def test_raise_from(self): - self.check_roundtrip(raise_from) - - def test_bytes(self): - self.check_roundtrip("b'123'") - - def test_annotations(self): - self.check_roundtrip("def f(a : int): pass") - self.check_roundtrip("def f(a: int = 5): pass") - self.check_roundtrip("def f(*args: [int]): pass") - self.check_roundtrip("def f(**kwargs: dict): pass") - self.check_roundtrip("def f() -> None: pass") - - def test_set_literal(self): - self.check_roundtrip("{'a', 'b', 'c'}") - - def test_set_comprehension(self): - self.check_roundtrip("{x for x in range(5)}") - - def test_dict_comprehension(self): - self.check_roundtrip("{x: x*x for x in range(10)}") - - def test_class_decorators(self): - self.check_roundtrip(class_decorator) - - def test_class_definition(self): - self.check_roundtrip("class A(metaclass=type, *[], **{}): pass") - - def test_elifs(self): - self.check_roundtrip(elif1) - self.check_roundtrip(elif2) - - def test_try_except_finally(self): - self.check_roundtrip(try_except_finally) - -class DirectoryTestCase(ASTTestCase): - """Test roundtrip behaviour on all files in Lib and Lib/test.""" - - # test directories, relative to the root of the distribution - test_directories = 'Lib', os.path.join('Lib', 'test') - - def test_files(self): - # get names of files to test - dist_dir = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir) - - names = [] - for d in self.test_directories: - test_dir = os.path.join(dist_dir, d) - for n in os.listdir(test_dir): - if n.endswith('.py') and not n.startswith('bad'): - names.append(os.path.join(test_dir, n)) - - for filename in names: - if test.support.verbose: - print('Testing %s' % filename) - source = read_pyfile(filename) - self.check_roundtrip(source) - - -def test_main(): - test.support.run_unittest(UnparseTestCase, DirectoryTestCase) - -if __name__ == '__main__': - test_main() diff --git a/Demo/parser/texipre.dat b/Demo/parser/texipre.dat deleted file mode 100644 index 8ad03a6..0000000 --- a/Demo/parser/texipre.dat +++ /dev/null @@ -1,100 +0,0 @@ -\input texinfo @c -*-texinfo-*- -@c %**start of header -@setfilename parser.info -@settitle Python Parser Module Reference -@setchapternewpage odd -@footnotestyle end -@c %**end of header - -@ifinfo -This file describes the interfaces -published by the optional @code{parser} module and gives examples of -how they may be used. It contains the same text as the chapter on the -@code{parser} module in the @cite{Python Library Reference}, but is -presented as a separate document. - -Copyright 1995-1996 by Fred L. Drake, Jr., Reston, Virginia, USA, and -Virginia Polytechnic Institute and State University, Blacksburg, -Virginia, USA. Portions of the software copyright 1991-1995 by -Stichting Mathematisch Centrum, Amsterdam, The Netherlands. Copying is -permitted under the terms associated with the main Python distribution, -with the additional restriction that this additional notice be included -and maintained on all distributed copies. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, -provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in -supporting documentation, and that the names of Fred L. Drake, Jr. and -Virginia Polytechnic Institute and State University not be used in -advertising or publicity pertaining to distribution of the software -without specific, written prior permission. - -FRED L. DRAKE, JR. AND VIRGINIA POLYTECHNIC INSTITUTE AND STATE -UNIVERSITY DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, -INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO -EVENT SHALL FRED L. DRAKE, JR. OR VIRGINIA POLYTECHNIC INSTITUTE AND -STATE UNIVERSITY BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL -DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR -PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER -TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -@end ifinfo - -@titlepage -@title Python Parser Module Reference -@author Fred L. Drake, Jr. - -@c The following two commands start the copyright page. -@page -@vskip 0pt plus 1filll -Copyright 1995-1996 by Fred L. Drake, Jr., Reston, Virginia, USA, and -Virginia Polytechnic Institute and State University, Blacksburg, -Virginia, USA. Portions of the software copyright 1991-1995 by -Stichting Mathematisch Centrum, Amsterdam, The Netherlands. Copying is -permitted under the terms associated with the main Python distribution, -with the additional restriction that this additional notice be included -and maintained on all distributed copies. - -@center All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, -provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in -supporting documentation, and that the names of Fred L. Drake, Jr. and -Virginia Polytechnic Institute and State University not be used in -advertising or publicity pertaining to distribution of the software -without specific, written prior permission. - -FRED L. DRAKE, JR. AND VIRGINIA POLYTECHNIC INSTITUTE AND STATE -UNIVERSITY DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, -INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO -EVENT SHALL FRED L. DRAKE, JR. OR VIRGINIA POLYTECHNIC INSTITUTE AND -STATE UNIVERSITY BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL -DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR -PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER -TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -@end titlepage - - -@node Top, Overview, (dir), (dir) -@top The Python Parser Module - -@ifinfo -This file describes the interfaces -published by the optional @code{parser} module and gives examples of -how they may be used. It contains the same text as the chapter on the -@code{parser} module in the @cite{Python Library Reference}, but is -presented as a separate document. - -This version corresponds to Python version 1.4 (1 Sept. 1996). - -@end ifinfo - -@c placeholder for the master menu -- patched by texinfo-all-menus-update -@menu -@end menu diff --git a/Demo/parser/unparse.py b/Demo/parser/unparse.py deleted file mode 100644 index e96ef54..0000000 --- a/Demo/parser/unparse.py +++ /dev/null @@ -1,600 +0,0 @@ -"Usage: unparse.py " -import sys -import math -import ast -import tokenize -import io -import os - -# Large float and imaginary literals get turned into infinities in the AST. -# We unparse those infinities to INFSTR. -INFSTR = "1e" + repr(sys.float_info.max_10_exp + 1) - -def interleave(inter, f, seq): - """Call f on each item in seq, calling inter() in between. - """ - seq = iter(seq) - try: - f(next(seq)) - except StopIteration: - pass - else: - for x in seq: - inter() - f(x) - -class Unparser: - """Methods in this class recursively traverse an AST and - output source code for the abstract syntax; original formatting - is disregarded. """ - - def __init__(self, tree, file = sys.stdout): - """Unparser(tree, file=sys.stdout) -> None. - Print the source for tree to file.""" - self.f = file - self._indent = 0 - self.dispatch(tree) - print("", file=self.f) - self.f.flush() - - def fill(self, text = ""): - "Indent a piece of text, according to the current indentation level" - self.f.write("\n"+" "*self._indent + text) - - def write(self, text): - "Append a piece of text to the current line." - self.f.write(text) - - def enter(self): - "Print ':', and increase the indentation." - self.write(":") - self._indent += 1 - - def leave(self): - "Decrease the indentation level." - self._indent -= 1 - - def dispatch(self, tree): - "Dispatcher function, dispatching tree type T to method _T." - if isinstance(tree, list): - for t in tree: - self.dispatch(t) - return - meth = getattr(self, "_"+tree.__class__.__name__) - meth(tree) - - - ############### Unparsing methods ###################### - # There should be one method per concrete grammar type # - # Constructors should be grouped by sum type. Ideally, # - # this would follow the order in the grammar, but # - # currently doesn't. # - ######################################################## - - def _Module(self, tree): - for stmt in tree.body: - self.dispatch(stmt) - - # stmt - def _Expr(self, tree): - self.fill() - self.dispatch(tree.value) - - def _Import(self, t): - self.fill("import ") - interleave(lambda: self.write(", "), self.dispatch, t.names) - - def _ImportFrom(self, t): - self.fill("from ") - self.write("." * t.level) - if t.module: - self.write(t.module) - self.write(" import ") - interleave(lambda: self.write(", "), self.dispatch, t.names) - - def _Assign(self, t): - self.fill() - for target in t.targets: - self.dispatch(target) - self.write(" = ") - self.dispatch(t.value) - - def _AugAssign(self, t): - self.fill() - self.dispatch(t.target) - self.write(" "+self.binop[t.op.__class__.__name__]+"= ") - self.dispatch(t.value) - - def _Return(self, t): - self.fill("return") - if t.value: - self.write(" ") - self.dispatch(t.value) - - def _Pass(self, t): - self.fill("pass") - - def _Break(self, t): - self.fill("break") - - def _Continue(self, t): - self.fill("continue") - - def _Delete(self, t): - self.fill("del ") - interleave(lambda: self.write(", "), self.dispatch, t.targets) - - def _Assert(self, t): - self.fill("assert ") - self.dispatch(t.test) - if t.msg: - self.write(", ") - self.dispatch(t.msg) - - def _Global(self, t): - self.fill("global ") - interleave(lambda: self.write(", "), self.write, t.names) - - def _Nonlocal(self, t): - self.fill("nonlocal ") - interleave(lambda: self.write(", "), self.write, t.names) - - def _Yield(self, t): - self.write("(") - self.write("yield") - if t.value: - self.write(" ") - self.dispatch(t.value) - self.write(")") - - def _Raise(self, t): - self.fill("raise") - if not t.exc: - assert not t.cause - return - self.write(" ") - self.dispatch(t.exc) - if t.cause: - self.write(" from ") - self.dispatch(t.cause) - - def _TryExcept(self, t): - self.fill("try") - self.enter() - self.dispatch(t.body) - self.leave() - - for ex in t.handlers: - self.dispatch(ex) - if t.orelse: - self.fill("else") - self.enter() - self.dispatch(t.orelse) - self.leave() - - def _TryFinally(self, t): - if len(t.body) == 1 and isinstance(t.body[0], ast.TryExcept): - # try-except-finally - self.dispatch(t.body) - else: - self.fill("try") - self.enter() - self.dispatch(t.body) - self.leave() - - self.fill("finally") - self.enter() - self.dispatch(t.finalbody) - self.leave() - - def _ExceptHandler(self, t): - self.fill("except") - if t.type: - self.write(" ") - self.dispatch(t.type) - if t.name: - self.write(" as ") - self.write(t.name) - self.enter() - self.dispatch(t.body) - self.leave() - - def _ClassDef(self, t): - self.write("\n") - for deco in t.decorator_list: - self.fill("@") - self.dispatch(deco) - self.fill("class "+t.name) - self.write("(") - comma = False - for e in t.bases: - if comma: self.write(", ") - else: comma = True - self.dispatch(e) - for e in t.keywords: - if comma: self.write(", ") - else: comma = True - self.dispatch(e) - if t.starargs: - if comma: self.write(", ") - else: comma = True - self.write("*") - self.dispatch(t.starargs) - if t.kwargs: - if comma: self.write(", ") - else: comma = True - self.write("**") - self.dispatch(t.kwargs) - self.write(")") - - self.enter() - self.dispatch(t.body) - self.leave() - - def _FunctionDef(self, t): - self.write("\n") - for deco in t.decorator_list: - self.fill("@") - self.dispatch(deco) - self.fill("def "+t.name + "(") - self.dispatch(t.args) - self.write(")") - if t.returns: - self.write(" -> ") - self.dispatch(t.returns) - self.enter() - self.dispatch(t.body) - self.leave() - - def _For(self, t): - self.fill("for ") - self.dispatch(t.target) - self.write(" in ") - self.dispatch(t.iter) - self.enter() - self.dispatch(t.body) - self.leave() - if t.orelse: - self.fill("else") - self.enter() - self.dispatch(t.orelse) - self.leave() - - def _If(self, t): - self.fill("if ") - self.dispatch(t.test) - self.enter() - self.dispatch(t.body) - self.leave() - # collapse nested ifs into equivalent elifs. - while (t.orelse and len(t.orelse) == 1 and - isinstance(t.orelse[0], ast.If)): - t = t.orelse[0] - self.fill("elif ") - self.dispatch(t.test) - self.enter() - self.dispatch(t.body) - self.leave() - # final else - if t.orelse: - self.fill("else") - self.enter() - self.dispatch(t.orelse) - self.leave() - - def _While(self, t): - self.fill("while ") - self.dispatch(t.test) - self.enter() - self.dispatch(t.body) - self.leave() - if t.orelse: - self.fill("else") - self.enter() - self.dispatch(t.orelse) - self.leave() - - def _With(self, t): - self.fill("with ") - self.dispatch(t.context_expr) - if t.optional_vars: - self.write(" as ") - self.dispatch(t.optional_vars) - self.enter() - self.dispatch(t.body) - self.leave() - - # expr - def _Bytes(self, t): - self.write(repr(t.s)) - - def _Str(self, tree): - self.write(repr(tree.s)) - - def _Name(self, t): - self.write(t.id) - - def _Num(self, t): - # Substitute overflowing decimal literal for AST infinities. - self.write(repr(t.n).replace("inf", INFSTR)) - - def _List(self, t): - self.write("[") - interleave(lambda: self.write(", "), self.dispatch, t.elts) - self.write("]") - - def _ListComp(self, t): - self.write("[") - self.dispatch(t.elt) - for gen in t.generators: - self.dispatch(gen) - self.write("]") - - def _GeneratorExp(self, t): - self.write("(") - self.dispatch(t.elt) - for gen in t.generators: - self.dispatch(gen) - self.write(")") - - def _SetComp(self, t): - self.write("{") - self.dispatch(t.elt) - for gen in t.generators: - self.dispatch(gen) - self.write("}") - - def _DictComp(self, t): - self.write("{") - self.dispatch(t.key) - self.write(": ") - self.dispatch(t.value) - for gen in t.generators: - self.dispatch(gen) - self.write("}") - - def _comprehension(self, t): - self.write(" for ") - self.dispatch(t.target) - self.write(" in ") - self.dispatch(t.iter) - for if_clause in t.ifs: - self.write(" if ") - self.dispatch(if_clause) - - def _IfExp(self, t): - self.write("(") - self.dispatch(t.body) - self.write(" if ") - self.dispatch(t.test) - self.write(" else ") - self.dispatch(t.orelse) - self.write(")") - - def _Set(self, t): - assert(t.elts) # should be at least one element - self.write("{") - interleave(lambda: self.write(", "), self.dispatch, t.elts) - self.write("}") - - def _Dict(self, t): - self.write("{") - def write_pair(pair): - (k, v) = pair - self.dispatch(k) - self.write(": ") - self.dispatch(v) - interleave(lambda: self.write(", "), write_pair, zip(t.keys, t.values)) - self.write("}") - - def _Tuple(self, t): - self.write("(") - if len(t.elts) == 1: - (elt,) = t.elts - self.dispatch(elt) - self.write(",") - else: - interleave(lambda: self.write(", "), self.dispatch, t.elts) - self.write(")") - - unop = {"Invert":"~", "Not": "not", "UAdd":"+", "USub":"-"} - def _UnaryOp(self, t): - self.write("(") - self.write(self.unop[t.op.__class__.__name__]) - self.write(" ") - self.dispatch(t.operand) - self.write(")") - - binop = { "Add":"+", "Sub":"-", "Mult":"*", "Div":"/", "Mod":"%", - "LShift":"<<", "RShift":">>", "BitOr":"|", "BitXor":"^", "BitAnd":"&", - "FloorDiv":"//", "Pow": "**"} - def _BinOp(self, t): - self.write("(") - self.dispatch(t.left) - self.write(" " + self.binop[t.op.__class__.__name__] + " ") - self.dispatch(t.right) - self.write(")") - - cmpops = {"Eq":"==", "NotEq":"!=", "Lt":"<", "LtE":"<=", "Gt":">", "GtE":">=", - "Is":"is", "IsNot":"is not", "In":"in", "NotIn":"not in"} - def _Compare(self, t): - self.write("(") - self.dispatch(t.left) - for o, e in zip(t.ops, t.comparators): - self.write(" " + self.cmpops[o.__class__.__name__] + " ") - self.dispatch(e) - self.write(")") - - boolops = {ast.And: 'and', ast.Or: 'or'} - def _BoolOp(self, t): - self.write("(") - s = " %s " % self.boolops[t.op.__class__] - interleave(lambda: self.write(s), self.dispatch, t.values) - self.write(")") - - def _Attribute(self,t): - self.dispatch(t.value) - # Special case: 3.__abs__() is a syntax error, so if t.value - # is an integer literal then we need to either parenthesize - # it or add an extra space to get 3 .__abs__(). - if isinstance(t.value, ast.Num) and isinstance(t.value.n, int): - self.write(" ") - self.write(".") - self.write(t.attr) - - def _Call(self, t): - self.dispatch(t.func) - self.write("(") - comma = False - for e in t.args: - if comma: self.write(", ") - else: comma = True - self.dispatch(e) - for e in t.keywords: - if comma: self.write(", ") - else: comma = True - self.dispatch(e) - if t.starargs: - if comma: self.write(", ") - else: comma = True - self.write("*") - self.dispatch(t.starargs) - if t.kwargs: - if comma: self.write(", ") - else: comma = True - self.write("**") - self.dispatch(t.kwargs) - self.write(")") - - def _Subscript(self, t): - self.dispatch(t.value) - self.write("[") - self.dispatch(t.slice) - self.write("]") - - # slice - def _Ellipsis(self, t): - self.write("...") - - def _Index(self, t): - self.dispatch(t.value) - - def _Slice(self, t): - if t.lower: - self.dispatch(t.lower) - self.write(":") - if t.upper: - self.dispatch(t.upper) - if t.step: - self.write(":") - self.dispatch(t.step) - - def _ExtSlice(self, t): - interleave(lambda: self.write(', '), self.dispatch, t.dims) - - # argument - def _arg(self, t): - self.write(t.arg) - if t.annotation: - self.write(": ") - self.dispatch(t.annotation) - - # others - def _arguments(self, t): - first = True - # normal arguments - defaults = [None] * (len(t.args) - len(t.defaults)) + t.defaults - for a, d in zip(t.args, defaults): - if first:first = False - else: self.write(", ") - self.dispatch(a) - if d: - self.write("=") - self.dispatch(d) - - # varargs, or bare '*' if no varargs but keyword-only arguments present - if t.vararg or t.kwonlyargs: - if first:first = False - else: self.write(", ") - self.write("*") - if t.vararg: - self.write(t.vararg) - if t.varargannotation: - self.write(": ") - self.dispatch(t.varargannotation) - - # keyword-only arguments - if t.kwonlyargs: - for a, d in zip(t.kwonlyargs, t.kw_defaults): - if first:first = False - else: self.write(", ") - self.dispatch(a), - if d: - self.write("=") - self.dispatch(d) - - # kwargs - if t.kwarg: - if first:first = False - else: self.write(", ") - self.write("**"+t.kwarg) - if t.kwargannotation: - self.write(": ") - self.dispatch(t.kwargannotation) - - def _keyword(self, t): - self.write(t.arg) - self.write("=") - self.dispatch(t.value) - - def _Lambda(self, t): - self.write("(") - self.write("lambda ") - self.dispatch(t.args) - self.write(": ") - self.dispatch(t.body) - self.write(")") - - def _alias(self, t): - self.write(t.name) - if t.asname: - self.write(" as "+t.asname) - -def roundtrip(filename, output=sys.stdout): - with open(filename, "rb") as pyfile: - encoding = tokenize.detect_encoding(pyfile.readline)[0] - with open(filename, "r", encoding=encoding) as pyfile: - source = pyfile.read() - tree = compile(source, filename, "exec", ast.PyCF_ONLY_AST) - Unparser(tree, output) - - - -def testdir(a): - try: - names = [n for n in os.listdir(a) if n.endswith('.py')] - except OSError: - print("Directory not readable: %s" % a, file=sys.stderr) - else: - for n in names: - fullname = os.path.join(a, n) - if os.path.isfile(fullname): - output = io.StringIO() - print('Testing %s' % fullname) - try: - roundtrip(fullname, output) - except Exception as e: - print(' Failed to compile, exception is %s' % repr(e)) - elif os.path.isdir(fullname): - testdir(fullname) - -def main(args): - if args[0] == '--testdir': - for a in args[1:]: - testdir(a) - else: - for a in args: - roundtrip(a) - -if __name__=='__main__': - main(sys.argv[1:]) diff --git a/Demo/pysvr/Makefile b/Demo/pysvr/Makefile deleted file mode 100644 index b4b9f3e..0000000 --- a/Demo/pysvr/Makefile +++ /dev/null @@ -1,57 +0,0 @@ -# Makefile for 'pysvr' application embedding Python. -# Tailored for Python 1.5a3 or later. -# Some details are specific for Solaris or CNRI. -# Also see ## comments for tailoring. - -# Which C compiler -CC=gcc -##PURIFY=/usr/local/pure/purify -LINKCC=$(PURIFY) $(CC) - -# Optimization preferences -OPT=-g - -# Which Python version we're using -VER=2.2 - -# Expressions using the above definitions -PYVER=python$(VER) - -# Use these defs when compiling against installed Python -##INST=/usr/local -##PYC=$(INST)/lib/$(PYVER)/config -##PYINCL=-I$(INST)/include/$(PYVER) -I$(PYC) -##PYLIBS=$(PYC)/lib$(PYVER).a - -# Use these defs when compiling against built Python -PLAT=linux -PYINCL=-I../../Include -I../../$(PLAT) -PYLIBS=../../$(PLAT)/lib$(PYVER).a - -# Libraries to link with -- very installation dependent -# (See LIBS= in Modules/Makefile in build tree) -RLLIBS=-lreadline -ltermcap -OTHERLIBS=-lnsl -lpthread -ldl -lm -ldb -lutil - -# Compilation and link flags -- no need to change normally -CFLAGS=$(OPT) -CPPFLAGS=$(PYINCL) -LIBS=$(PYLIBS) $(RLLIBS) $(OTHERLIBS) - -# Default port for the pysvr application -PORT=4000 - -# Default target -all: pysvr - -# Target to build pysvr -pysvr: pysvr.o $(PYOBJS) $(PYLIBS) - $(LINKCC) pysvr.o $(LIBS) -o pysvr - -# Target to build and run pysvr -run: pysvr - pysvr $(PORT) - -# Target to clean up the directory -clean: - -rm -f pysvr *.o *~ core diff --git a/Demo/pysvr/README b/Demo/pysvr/README deleted file mode 100644 index 5e64e38..0000000 --- a/Demo/pysvr/README +++ /dev/null @@ -1,9 +0,0 @@ -This is an example of a multi-threaded C application embedding a -Python interpreter. - -The particular application is a multi-threaded telnet-like server that -provides you with a Python prompt (instead of a shell prompt). - -The file pysvr.py is a prototype in Python. - -THIS APPLICATION IS NOT SECURE -- ONLY USE IT FOR TESTING! diff --git a/Demo/pysvr/pysvr.c b/Demo/pysvr/pysvr.c deleted file mode 100644 index 706cd2a..0000000 --- a/Demo/pysvr/pysvr.c +++ /dev/null @@ -1,370 +0,0 @@ -/* A multi-threaded telnet-like server that gives a Python prompt. - -Usage: pysvr [port] - -For security reasons, it only accepts requests from the current host. -This can still be insecure, but restricts violations from people who -can log in on your machine. Use with caution! - -*/ - -#include -#include -#include -#include -#include - -#include -#include -#include - -#include -#include - -/* XXX Umpfh. - Python.h defines a typedef destructor, which conflicts with pthread.h. - So Python.h must be included after pthread.h. */ - -#include "Python.h" - -extern int Py_VerboseFlag; - -#ifndef PORT -#define PORT 4000 -#endif - -struct workorder { - int conn; - struct sockaddr_in addr; -}; - -/* Forward */ -static void init_python(void); -static void usage(void); -static void oprogname(void); -static void main_thread(int); -static void create_thread(int, struct sockaddr_in *); -static void *service_thread(struct workorder *); -static void run_interpreter(FILE *, FILE *); -static int run_command(char *, PyObject *); -static void ps(void); - -static char *progname = "pysvr"; - -static PyThreadState *gtstate; - -main(int argc, char **argv) -{ - int port = PORT; - int c; - - if (argc > 0 && argv[0] != NULL && argv[0][0] != '\0') - progname = argv[0]; - - while ((c = getopt(argc, argv, "v")) != EOF) { - switch (c) { - case 'v': - Py_VerboseFlag++; - break; - default: - usage(); - } - } - - if (optind < argc) { - if (optind+1 < argc) { - oprogname(); - fprintf(stderr, "too many arguments\n"); - usage(); - } - port = atoi(argv[optind]); - if (port <= 0) { - fprintf(stderr, "bad port (%s)\n", argv[optind]); - usage(); - } - } - - main_thread(port); - - fprintf(stderr, "Bye.\n"); - - exit(0); -} - -static char usage_line[] = "usage: %s [port]\n"; - -static void -usage(void) -{ - fprintf(stderr, usage_line, progname); - exit(2); -} - -static void -main_thread(int port) -{ - int sock, conn, size, i; - struct sockaddr_in addr, clientaddr; - - sock = socket(PF_INET, SOCK_STREAM, 0); - if (sock < 0) { - oprogname(); - perror("can't create socket"); - exit(1); - } - -#ifdef SO_REUSEADDR - i = 1; - setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &i, sizeof i); -#endif - - memset((char *)&addr, '\0', sizeof addr); - addr.sin_family = AF_INET; - addr.sin_port = htons(port); - addr.sin_addr.s_addr = 0L; - if (bind(sock, (struct sockaddr *)&addr, sizeof addr) < 0) { - oprogname(); - perror("can't bind socket to address"); - exit(1); - } - - if (listen(sock, 5) < 0) { - oprogname(); - perror("can't listen on socket"); - exit(1); - } - - fprintf(stderr, "Listening on port %d...\n", port); - - for (i = 0; ; i++) { - size = sizeof clientaddr; - memset((char *) &clientaddr, '\0', size); - conn = accept(sock, (struct sockaddr *) &clientaddr, &size); - if (conn < 0) { - oprogname(); - perror("can't accept connection from socket"); - exit(1); - } - - size = sizeof addr; - memset((char *) &addr, '\0', size); - if (getsockname(conn, (struct sockaddr *)&addr, &size) < 0) { - oprogname(); - perror("can't get socket name of connection"); - exit(1); - } - if (clientaddr.sin_addr.s_addr != addr.sin_addr.s_addr) { - oprogname(); - perror("connection from non-local host refused"); - fprintf(stderr, "(addr=%lx, clientaddr=%lx)\n", - ntohl(addr.sin_addr.s_addr), - ntohl(clientaddr.sin_addr.s_addr)); - close(conn); - continue; - } - if (i == 4) { - close(conn); - break; - } - create_thread(conn, &clientaddr); - } - - close(sock); - - if (gtstate) { - PyEval_AcquireThread(gtstate); - gtstate = NULL; - Py_Finalize(); - /* And a second time, just because we can. */ - Py_Finalize(); /* This should be harmless. */ - } - exit(0); -} - -static void -create_thread(int conn, struct sockaddr_in *addr) -{ - struct workorder *work; - pthread_t tdata; - - work = malloc(sizeof(struct workorder)); - if (work == NULL) { - oprogname(); - fprintf(stderr, "out of memory for thread.\n"); - close(conn); - return; - } - work->conn = conn; - work->addr = *addr; - - init_python(); - - if (pthread_create(&tdata, NULL, (void *)service_thread, work) < 0) { - oprogname(); - perror("can't create new thread"); - close(conn); - return; - } - - if (pthread_detach(tdata) < 0) { - oprogname(); - perror("can't detach from thread"); - } -} - -static PyThreadState *the_tstate; -static PyInterpreterState *the_interp; -static PyObject *the_builtins; - -static void -init_python(void) -{ - if (gtstate) - return; - Py_Initialize(); /* Initialize the interpreter */ - PyEval_InitThreads(); /* Create (and acquire) the interpreter lock */ - gtstate = PyEval_SaveThread(); /* Release the thread state */ -} - -static void * -service_thread(struct workorder *work) -{ - FILE *input, *output; - - fprintf(stderr, "Start thread for connection %d.\n", work->conn); - - ps(); - - input = fdopen(work->conn, "r"); - if (input == NULL) { - oprogname(); - perror("can't create input stream"); - goto done; - } - - output = fdopen(work->conn, "w"); - if (output == NULL) { - oprogname(); - perror("can't create output stream"); - fclose(input); - goto done; - } - - setvbuf(input, NULL, _IONBF, 0); - setvbuf(output, NULL, _IONBF, 0); - - run_interpreter(input, output); - - fclose(input); - fclose(output); - - done: - fprintf(stderr, "End thread for connection %d.\n", work->conn); - close(work->conn); - free(work); -} - -static void -oprogname(void) -{ - int save = errno; - fprintf(stderr, "%s: ", progname); - errno = save; -} - -static void -run_interpreter(FILE *input, FILE *output) -{ - PyThreadState *tstate; - PyObject *new_stdin, *new_stdout; - PyObject *mainmod, *globals; - char buffer[1000]; - char *p, *q; - int n, end; - - PyEval_AcquireLock(); - tstate = Py_NewInterpreter(); - if (tstate == NULL) { - fprintf(output, "Sorry -- can't create an interpreter\n"); - return; - } - - mainmod = PyImport_AddModule("__main__"); - globals = PyModule_GetDict(mainmod); - Py_INCREF(globals); - - new_stdin = PyFile_FromFile(input, "", "r", NULL); - new_stdout = PyFile_FromFile(output, "", "w", NULL); - - PySys_SetObject("stdin", new_stdin); - PySys_SetObject("stdout", new_stdout); - PySys_SetObject("stderr", new_stdout); - - for (n = 1; !PyErr_Occurred(); n++) { - Py_BEGIN_ALLOW_THREADS - fprintf(output, "%d> ", n); - p = fgets(buffer, sizeof buffer, input); - Py_END_ALLOW_THREADS - - if (p == NULL) - break; - if (p[0] == '\377' && p[1] == '\354') - break; - - q = strrchr(p, '\r'); - if (q && q[1] == '\n' && q[2] == '\0') { - *q++ = '\n'; - *q++ = '\0'; - } - - while (*p && isspace(*p)) - p++; - if (p[0] == '#' || p[0] == '\0') - continue; - - end = run_command(buffer, globals); - if (end < 0) - PyErr_Print(); - - if (end) - break; - } - - Py_XDECREF(globals); - Py_XDECREF(new_stdin); - Py_XDECREF(new_stdout); - - Py_EndInterpreter(tstate); - PyEval_ReleaseLock(); - - fprintf(output, "Goodbye!\n"); -} - -static int -run_command(char *buffer, PyObject *globals) -{ - PyObject *m, *d, *v; - fprintf(stderr, "run_command: %s", buffer); - if (strchr(buffer, '\n') == NULL) - fprintf(stderr, "\n"); - v = PyRun_String(buffer, Py_single_input, globals, globals); - if (v == NULL) { - if (PyErr_Occurred() == PyExc_SystemExit) { - PyErr_Clear(); - return 1; - } - PyErr_Print(); - return 0; - } - Py_DECREF(v); - return 0; -} - -static void -ps(void) -{ - char buffer[100]; - PyOS_snprintf(buffer, sizeof(buffer), - "ps -l -p %d 1: - raise getopt.error("Too many arguments.") - except getopt.error as msg: - usage(msg) - for o, a in opts: - pass - if args: - try: - port = string.atoi(args[0]) - except ValueError as msg: - usage(msg) - else: - port = PORT - main_thread(port) - -def usage(msg=None): - sys.stdout = sys.stderr - if msg: - print(msg) - print("\n", __doc__, end=' ') - sys.exit(2) - -def main_thread(port): - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - sock.bind(("", port)) - sock.listen(5) - print("Listening on port", port, "...") - while 1: - (conn, addr) = sock.accept() - if addr[0] != conn.getsockname()[0]: - conn.close() - print("Refusing connection from non-local host", addr[0], ".") - continue - _thread.start_new_thread(service_thread, (conn, addr)) - del conn, addr - -def service_thread(conn, addr): - (caddr, cport) = addr - print("Thread %s has connection from %s.\n" % (str(_thread.get_ident()), - caddr), end=' ') - stdin = conn.makefile("r") - stdout = conn.makefile("w", 0) - run_interpreter(stdin, stdout) - print("Thread %s is done.\n" % str(_thread.get_ident()), end=' ') - -def run_interpreter(stdin, stdout): - globals = {} - try: - str(sys.ps1) - except: - sys.ps1 = ">>> " - source = "" - while 1: - stdout.write(sys.ps1) - line = stdin.readline() - if line[:2] == '\377\354': - line = "" - if not line and not source: - break - if line[-2:] == '\r\n': - line = line[:-2] + '\n' - source = source + line - try: - code = compile_command(source) - except SyntaxError as err: - source = "" - traceback.print_exception(SyntaxError, err, None, file=stdout) - continue - if not code: - continue - source = "" - try: - run_command(code, stdin, stdout, globals) - except SystemExit as how: - if how: - try: - how = str(how) - except: - how = "" - stdout.write("Exit %s\n" % how) - break - stdout.write("\nGoodbye.\n") - -def run_command(code, stdin, stdout, globals): - save = sys.stdin, sys.stdout, sys.stderr - try: - sys.stdout = sys.stderr = stdout - sys.stdin = stdin - try: - exec(code, globals) - except SystemExit as how: - raise SystemExit(how).with_traceback(sys.exc_info()[2]) - except: - type, value, tb = sys.exc_info() - if tb: tb = tb.tb_next - traceback.print_exception(type, value, tb) - del tb - finally: - sys.stdin, sys.stdout, sys.stderr = save - -from code import compile_command - -main() diff --git a/Demo/rpc/MANIFEST b/Demo/rpc/MANIFEST deleted file mode 100644 index e65f3eb..0000000 --- a/Demo/rpc/MANIFEST +++ /dev/null @@ -1,10 +0,0 @@ - File Name Archive # Description ------------------------------------------------------------ - MANIFEST 1 This shipping list - README 1 - T.py 1 - mountclient.py 1 - nfsclient.py 1 - rpc.py 1 - test 1 - xdr.py 1 diff --git a/Demo/rpc/README b/Demo/rpc/README deleted file mode 100644 index 97948a3..0000000 --- a/Demo/rpc/README +++ /dev/null @@ -1,31 +0,0 @@ -This is a Python interface to Sun RPC, designed and implemented mostly -by reading the Internet RFCs about the subject. - -*** NOTE: xdr.py has evolved into the standard module xdrlib.py *** - -There are two library modules, xdr.py and rpc.py, and several example -clients: mountclient.py, nfsclient.py, and rnusersclient.py, -implementing the NFS Mount protocol, (part of) the NFS protocol, and -the "rnusers" protocol (used by rusers(1)), respectively. The latter -demonstrates the use of broadcast via the Port mapper's CALLIT -procedure. - -There is also a way to create servers in Python. - -To test the nfs client, run it from the shell with something like this: - - python -c 'import nfsclient; nfsclient.test()' [hostname [filesystemname]] - -When called without a filesystemname, it lists the filesystems at the -host; default host is the local machine. - -Other clients are tested similarly. - -For hostname, use e.g. wuarchive.wustl.edu or gatekeeper.dec.com (two -hosts that are known to export NFS filesystems with little restrictions). - -There are now two different RPC compilers: - -1) Wim Lewis rpcgen.py found on http://www.omnigroup.com/~wiml/soft/stale-index.html#python. - -2) Peter Åstrands rpcgen.py, which is part of "pynfs" (http://www.cendio.se/~peter/pynfs/). diff --git a/Demo/rpc/T.py b/Demo/rpc/T.py deleted file mode 100644 index 3325507..0000000 --- a/Demo/rpc/T.py +++ /dev/null @@ -1,22 +0,0 @@ -# Simple interface to report execution times of program fragments. -# Call TSTART() to reset the timer, TSTOP(...) to report times. - -import sys, os, time - -def TSTART(): - global t0, t1 - u, s, cu, cs = os.times() - t0 = u+cu, s+cs, time.time() - -def TSTOP(*label): - global t0, t1 - u, s, cu, cs = os.times() - t1 = u+cu, s+cs, time.time() - tt = [] - for i in range(3): - tt.append(t1[i] - t0[i]) - [u, s, r] = tt - msg = '' - for x in label: msg = msg + (x + ' ') - msg = msg + '%r user, %r sys, %r real\n' % (u, s, r) - sys.stderr.write(msg) diff --git a/Demo/rpc/mountclient.py b/Demo/rpc/mountclient.py deleted file mode 100644 index 81797df..0000000 --- a/Demo/rpc/mountclient.py +++ /dev/null @@ -1,202 +0,0 @@ -# Mount RPC client -- RFC 1094 (NFS), Appendix A - -# This module demonstrates how to write your own RPC client in Python. -# When this example was written, there was no RPC compiler for -# Python. Without such a compiler, you must first create classes -# derived from Packer and Unpacker to handle the data types for the -# server you want to interface to. You then write the client class. -# If you want to support both the TCP and the UDP version of a -# protocol, use multiple inheritance as shown below. - - -import rpc -from rpc import Packer, Unpacker, TCPClient, UDPClient - - -# Program number and version for the mount protocol -MOUNTPROG = 100005 -MOUNTVERS = 1 - -# Size of the 'fhandle' opaque structure -FHSIZE = 32 - - -# Packer derived class for Mount protocol clients. -# The only thing we need to pack beyond basic types is an 'fhandle' - -class MountPacker(Packer): - - def pack_fhandle(self, fhandle): - self.pack_fopaque(FHSIZE, fhandle) - - -# Unpacker derived class for Mount protocol clients. -# The important types we need to unpack are fhandle, fhstatus, -# mountlist and exportlist; mountstruct, exportstruct and groups are -# used to unpack components of mountlist and exportlist and the -# corresponding functions are passed as function argument to the -# generic unpack_list function. - -class MountUnpacker(Unpacker): - - def unpack_fhandle(self): - return self.unpack_fopaque(FHSIZE) - - def unpack_fhstatus(self): - status = self.unpack_uint() - if status == 0: - fh = self.unpack_fhandle() - else: - fh = None - return status, fh - - def unpack_mountlist(self): - return self.unpack_list(self.unpack_mountstruct) - - def unpack_mountstruct(self): - hostname = self.unpack_string() - directory = self.unpack_string() - return (hostname, directory) - - def unpack_exportlist(self): - return self.unpack_list(self.unpack_exportstruct) - - def unpack_exportstruct(self): - filesys = self.unpack_string() - groups = self.unpack_groups() - return (filesys, groups) - - def unpack_groups(self): - return self.unpack_list(self.unpack_string) - - -# These are the procedures specific to the Mount client class. -# Think of this as a derived class of either TCPClient or UDPClient. - -class PartialMountClient: - - # This method is called by Client.__init__ to initialize - # self.packer and self.unpacker - def addpackers(self): - self.packer = MountPacker() - self.unpacker = MountUnpacker('') - - # This method is called by Client.__init__ to bind the socket - # to a particular network interface and port. We use the - # default network interface, but if we're running as root, - # we want to bind to a reserved port - def bindsocket(self): - import os - try: - uid = os.getuid() - except AttributeError: - uid = 1 - if uid == 0: - port = rpc.bindresvport(self.sock, '') - # 'port' is not used - else: - self.sock.bind(('', 0)) - - # This function is called to cough up a suitable - # authentication object for a call to procedure 'proc'. - def mkcred(self): - if self.cred is None: - self.cred = rpc.AUTH_UNIX, rpc.make_auth_unix_default() - return self.cred - - # The methods Mnt, Dump etc. each implement one Remote - # Procedure Call. This is done by calling self.make_call() - # with as arguments: - # - # - the procedure number - # - the arguments (or None) - # - the "packer" function for the arguments (or None) - # - the "unpacker" function for the return value (or None) - # - # The packer and unpacker function, if not None, *must* be - # methods of self.packer and self.unpacker, respectively. - # A value of None means that there are no arguments or is no - # return value, respectively. - # - # The return value from make_call() is the return value from - # the remote procedure call, as unpacked by the "unpacker" - # function, or None if the unpacker function is None. - # - # (Even if you expect a result of None, you should still - # return the return value from make_call(), since this may be - # needed by a broadcasting version of the class.) - # - # If the call fails, make_call() raises an exception - # (this includes time-outs and invalid results). - # - # Note that (at least with the UDP protocol) there is no - # guarantee that a call is executed at most once. When you do - # get a reply, you know it has been executed at least once; - # when you don't get a reply, you know nothing. - - def Mnt(self, directory): - return self.make_call(1, directory, \ - self.packer.pack_string, \ - self.unpacker.unpack_fhstatus) - - def Dump(self): - return self.make_call(2, None, \ - None, self.unpacker.unpack_mountlist) - - def Umnt(self, directory): - return self.make_call(3, directory, \ - self.packer.pack_string, None) - - def Umntall(self): - return self.make_call(4, None, None, None) - - def Export(self): - return self.make_call(5, None, \ - None, self.unpacker.unpack_exportlist) - - -# We turn the partial Mount client into a full one for either protocol -# by use of multiple inheritance. (In general, when class C has base -# classes B1...Bn, if x is an instance of class C, methods of x are -# searched first in C, then in B1, then in B2, ..., finally in Bn.) - -class TCPMountClient(PartialMountClient, TCPClient): - - def __init__(self, host): - TCPClient.__init__(self, host, MOUNTPROG, MOUNTVERS) - - -class UDPMountClient(PartialMountClient, UDPClient): - - def __init__(self, host): - UDPClient.__init__(self, host, MOUNTPROG, MOUNTVERS) - - -# A little test program for the Mount client. This takes a host as -# command line argument (default the local machine), prints its export -# list, and attempts to mount and unmount each exported files system. -# An optional first argument of -t or -u specifies the protocol to use -# (TCP or UDP), default is UDP. - -def test(): - import sys - if sys.argv[1:] and sys.argv[1] == '-t': - C = TCPMountClient - del sys.argv[1] - elif sys.argv[1:] and sys.argv[1] == '-u': - C = UDPMountClient - del sys.argv[1] - else: - C = UDPMountClient - if sys.argv[1:]: host = sys.argv[1] - else: host = '' - mcl = C(host) - list = mcl.Export() - for item in list: - print(item) - try: - mcl.Mnt(item[0]) - except: - print('Sorry') - continue - mcl.Umnt(item[0]) diff --git a/Demo/rpc/nfsclient.py b/Demo/rpc/nfsclient.py deleted file mode 100644 index a291ce0..0000000 --- a/Demo/rpc/nfsclient.py +++ /dev/null @@ -1,201 +0,0 @@ -# NFS RPC client -- RFC 1094 - -# XXX This is not yet complete. -# XXX Only GETATTR, SETTTR, LOOKUP and READDIR are supported. - -# (See mountclient.py for some hints on how to write RPC clients in -# Python in general) - -import rpc -from rpc import UDPClient, TCPClient -from mountclient import FHSIZE, MountPacker, MountUnpacker - -NFS_PROGRAM = 100003 -NFS_VERSION = 2 - -# enum stat -NFS_OK = 0 -# (...many error values...) - -# enum ftype -NFNON = 0 -NFREG = 1 -NFDIR = 2 -NFBLK = 3 -NFCHR = 4 -NFLNK = 5 - - -class NFSPacker(MountPacker): - - def pack_sattrargs(self, sa): - file, attributes = sa - self.pack_fhandle(file) - self.pack_sattr(attributes) - - def pack_sattr(self, sa): - mode, uid, gid, size, atime, mtime = sa - self.pack_uint(mode) - self.pack_uint(uid) - self.pack_uint(gid) - self.pack_uint(size) - self.pack_timeval(atime) - self.pack_timeval(mtime) - - def pack_diropargs(self, da): - dir, name = da - self.pack_fhandle(dir) - self.pack_string(name) - - def pack_readdirargs(self, ra): - dir, cookie, count = ra - self.pack_fhandle(dir) - self.pack_uint(cookie) - self.pack_uint(count) - - def pack_timeval(self, tv): - secs, usecs = tv - self.pack_uint(secs) - self.pack_uint(usecs) - - -class NFSUnpacker(MountUnpacker): - - def unpack_readdirres(self): - status = self.unpack_enum() - if status == NFS_OK: - entries = self.unpack_list(self.unpack_entry) - eof = self.unpack_bool() - rest = (entries, eof) - else: - rest = None - return (status, rest) - - def unpack_entry(self): - fileid = self.unpack_uint() - name = self.unpack_string() - cookie = self.unpack_uint() - return (fileid, name, cookie) - - def unpack_diropres(self): - status = self.unpack_enum() - if status == NFS_OK: - fh = self.unpack_fhandle() - fa = self.unpack_fattr() - rest = (fh, fa) - else: - rest = None - return (status, rest) - - def unpack_attrstat(self): - status = self.unpack_enum() - if status == NFS_OK: - attributes = self.unpack_fattr() - else: - attributes = None - return status, attributes - - def unpack_fattr(self): - type = self.unpack_enum() - mode = self.unpack_uint() - nlink = self.unpack_uint() - uid = self.unpack_uint() - gid = self.unpack_uint() - size = self.unpack_uint() - blocksize = self.unpack_uint() - rdev = self.unpack_uint() - blocks = self.unpack_uint() - fsid = self.unpack_uint() - fileid = self.unpack_uint() - atime = self.unpack_timeval() - mtime = self.unpack_timeval() - ctime = self.unpack_timeval() - return (type, mode, nlink, uid, gid, size, blocksize, \ - rdev, blocks, fsid, fileid, atime, mtime, ctime) - - def unpack_timeval(self): - secs = self.unpack_uint() - usecs = self.unpack_uint() - return (secs, usecs) - - -class NFSClient(UDPClient): - - def __init__(self, host): - UDPClient.__init__(self, host, NFS_PROGRAM, NFS_VERSION) - - def addpackers(self): - self.packer = NFSPacker() - self.unpacker = NFSUnpacker('') - - def mkcred(self): - if self.cred is None: - self.cred = rpc.AUTH_UNIX, rpc.make_auth_unix_default() - return self.cred - - def Getattr(self, fh): - return self.make_call(1, fh, \ - self.packer.pack_fhandle, \ - self.unpacker.unpack_attrstat) - - def Setattr(self, sa): - return self.make_call(2, sa, \ - self.packer.pack_sattrargs, \ - self.unpacker.unpack_attrstat) - - # Root() is obsolete - - def Lookup(self, da): - return self.make_call(4, da, \ - self.packer.pack_diropargs, \ - self.unpacker.unpack_diropres) - - # ... - - def Readdir(self, ra): - return self.make_call(16, ra, \ - self.packer.pack_readdirargs, \ - self.unpacker.unpack_readdirres) - - # Shorthand to get the entire contents of a directory - def Listdir(self, dir): - list = [] - ra = (dir, 0, 2000) - while 1: - (status, rest) = self.Readdir(ra) - if status != NFS_OK: - break - entries, eof = rest - last_cookie = None - for fileid, name, cookie in entries: - list.append((fileid, name)) - last_cookie = cookie - if eof or last_cookie is None: - break - ra = (ra[0], last_cookie, ra[2]) - return list - - -def test(): - import sys - if sys.argv[1:]: host = sys.argv[1] - else: host = '' - if sys.argv[2:]: filesys = sys.argv[2] - else: filesys = None - from mountclient import UDPMountClient, TCPMountClient - mcl = TCPMountClient(host) - if filesys is None: - list = mcl.Export() - for item in list: - print(item) - return - sf = mcl.Mnt(filesys) - print(sf) - fh = sf[1] - if fh: - ncl = NFSClient(host) - attrstat = ncl.Getattr(fh) - print(attrstat) - list = ncl.Listdir(fh) - for item in list: print(item) - mcl.Umnt(filesys) diff --git a/Demo/rpc/rnusersclient.py b/Demo/rpc/rnusersclient.py deleted file mode 100644 index eaabefe..0000000 --- a/Demo/rpc/rnusersclient.py +++ /dev/null @@ -1,98 +0,0 @@ -# Remote nusers client interface - -import rpc -from rpc import Packer, Unpacker, UDPClient, BroadcastUDPClient - - -class RnusersPacker(Packer): - def pack_utmp(self, ui): - ut_line, ut_name, ut_host, ut_time = utmp - self.pack_string(ut_line) - self.pack_string(ut_name) - self.pack_string(ut_host) - self.pack_int(ut_time) - def pack_utmpidle(self, ui): - ui_itmp, ui_idle = ui - self.pack_utmp(ui_utmp) - self.pack_uint(ui_idle) - def pack_utmpidlearr(self, list): - self.pack_array(list, self.pack_itmpidle) - - -class RnusersUnpacker(Unpacker): - def unpack_utmp(self): - ut_line = self.unpack_string() - ut_name = self.unpack_string() - ut_host = self.unpack_string() - ut_time = self.unpack_int() - return ut_line, ut_name, ut_host, ut_time - def unpack_utmpidle(self): - ui_utmp = self.unpack_utmp() - ui_idle = self.unpack_uint() - return ui_utmp, ui_idle - def unpack_utmpidlearr(self): - return self.unpack_array(self.unpack_utmpidle) - - -class PartialRnusersClient: - - def addpackers(self): - self.packer = RnusersPacker() - self.unpacker = RnusersUnpacker('') - - def Num(self): - return self.make_call(1, None, None, self.unpacker.unpack_int) - - def Names(self): - return self.make_call(2, None, \ - None, self.unpacker.unpack_utmpidlearr) - - def Allnames(self): - return self.make_call(3, None, \ - None, self.unpacker.unpack_utmpidlearr) - - -class RnusersClient(PartialRnusersClient, UDPClient): - - def __init__(self, host): - UDPClient.__init__(self, host, 100002, 2) - - -class BroadcastRnusersClient(PartialRnusersClient, BroadcastUDPClient): - - def __init__(self, bcastaddr): - BroadcastUDPClient.__init__(self, bcastaddr, 100002, 2) - - -def test(): - import sys - if not sys.argv[1:]: - testbcast() - return - else: - host = sys.argv[1] - c = RnusersClient(host) - list = c.Names() - for (line, name, host, time), idle in list: - line = strip0(line) - name = strip0(name) - host = strip0(host) - print("%r %r %r %s %s" % (name, host, line, time, idle)) - -def testbcast(): - c = BroadcastRnusersClient('') - def listit(list, fromaddr): - host, port = fromaddr - print(host + '\t:', end=' ') - for (line, name, host, time), idle in list: - print(strip0(name), end=' ') - print() - c.set_reply_handler(listit) - all = c.Names() - print('Total Count:', len(all)) - -def strip0(s): - while s and s[-1] == '\0': s = s[:-1] - return s - -test() diff --git a/Demo/rpc/rpc.py b/Demo/rpc/rpc.py deleted file mode 100644 index 30b3017..0000000 --- a/Demo/rpc/rpc.py +++ /dev/null @@ -1,890 +0,0 @@ -# Sun RPC version 2 -- RFC1057. - -# XXX There should be separate exceptions for the various reasons why -# XXX an RPC can fail, rather than using RuntimeError for everything - -# XXX Need to use class based exceptions rather than string exceptions - -# XXX The UDP version of the protocol resends requests when it does -# XXX not receive a timely reply -- use only for idempotent calls! - -# XXX There is no provision for call timeout on TCP connections - -import xdr -import socket -import os - -RPCVERSION = 2 - -CALL = 0 -REPLY = 1 - -AUTH_NULL = 0 -AUTH_UNIX = 1 -AUTH_SHORT = 2 -AUTH_DES = 3 - -MSG_ACCEPTED = 0 -MSG_DENIED = 1 - -SUCCESS = 0 # RPC executed successfully -PROG_UNAVAIL = 1 # remote hasn't exported program -PROG_MISMATCH = 2 # remote can't support version # -PROC_UNAVAIL = 3 # program can't support procedure -GARBAGE_ARGS = 4 # procedure can't decode params - -RPC_MISMATCH = 0 # RPC version number != 2 -AUTH_ERROR = 1 # remote can't authenticate caller - -AUTH_BADCRED = 1 # bad credentials (seal broken) -AUTH_REJECTEDCRED = 2 # client must begin new session -AUTH_BADVERF = 3 # bad verifier (seal broken) -AUTH_REJECTEDVERF = 4 # verifier expired or replayed -AUTH_TOOWEAK = 5 # rejected for security reasons - - -class Packer(xdr.Packer): - - def pack_auth(self, auth): - flavor, stuff = auth - self.pack_enum(flavor) - self.pack_opaque(stuff) - - def pack_auth_unix(self, stamp, machinename, uid, gid, gids): - self.pack_uint(stamp) - self.pack_string(machinename) - self.pack_uint(uid) - self.pack_uint(gid) - self.pack_uint(len(gids)) - for i in gids: - self.pack_uint(i) - - def pack_callheader(self, xid, prog, vers, proc, cred, verf): - self.pack_uint(xid) - self.pack_enum(CALL) - self.pack_uint(RPCVERSION) - self.pack_uint(prog) - self.pack_uint(vers) - self.pack_uint(proc) - self.pack_auth(cred) - self.pack_auth(verf) - # Caller must add procedure-specific part of call - - def pack_replyheader(self, xid, verf): - self.pack_uint(xid) - self.pack_enum(REPLY) - self.pack_uint(MSG_ACCEPTED) - self.pack_auth(verf) - self.pack_enum(SUCCESS) - # Caller must add procedure-specific part of reply - - -# Exceptions -class BadRPCFormat(Exception): pass -class BadRPCVersion(Exception): pass -class GarbageArgs(Exception): pass - -class Unpacker(xdr.Unpacker): - - def unpack_auth(self): - flavor = self.unpack_enum() - stuff = self.unpack_opaque() - return (flavor, stuff) - - def unpack_callheader(self): - xid = self.unpack_uint() - temp = self.unpack_enum() - if temp != CALL: - raise BadRPCFormat('no CALL but %r' % (temp,)) - temp = self.unpack_uint() - if temp != RPCVERSION: - raise BadRPCVersion('bad RPC version %r' % (temp,)) - prog = self.unpack_uint() - vers = self.unpack_uint() - proc = self.unpack_uint() - cred = self.unpack_auth() - verf = self.unpack_auth() - return xid, prog, vers, proc, cred, verf - # Caller must add procedure-specific part of call - - def unpack_replyheader(self): - xid = self.unpack_uint() - mtype = self.unpack_enum() - if mtype != REPLY: - raise RuntimeError('no REPLY but %r' % (mtype,)) - stat = self.unpack_enum() - if stat == MSG_DENIED: - stat = self.unpack_enum() - if stat == RPC_MISMATCH: - low = self.unpack_uint() - high = self.unpack_uint() - raise RuntimeError('MSG_DENIED: RPC_MISMATCH: %r' % ((low, high),)) - if stat == AUTH_ERROR: - stat = self.unpack_uint() - raise RuntimeError('MSG_DENIED: AUTH_ERROR: %r' % (stat,)) - raise RuntimeError('MSG_DENIED: %r' % (stat,)) - if stat != MSG_ACCEPTED: - raise RuntimeError('Neither MSG_DENIED nor MSG_ACCEPTED: %r' % (stat,)) - verf = self.unpack_auth() - stat = self.unpack_enum() - if stat == PROG_UNAVAIL: - raise RuntimeError('call failed: PROG_UNAVAIL') - if stat == PROG_MISMATCH: - low = self.unpack_uint() - high = self.unpack_uint() - raise RuntimeError('call failed: PROG_MISMATCH: %r' % ((low, high),)) - if stat == PROC_UNAVAIL: - raise RuntimeError('call failed: PROC_UNAVAIL') - if stat == GARBAGE_ARGS: - raise RuntimeError('call failed: GARBAGE_ARGS') - if stat != SUCCESS: - raise RuntimeError('call failed: %r' % (stat,)) - return xid, verf - # Caller must get procedure-specific part of reply - - -# Subroutines to create opaque authentication objects - -def make_auth_null(): - return '' - -def make_auth_unix(seed, host, uid, gid, groups): - p = Packer() - p.pack_auth_unix(seed, host, uid, gid, groups) - return p.get_buf() - -def make_auth_unix_default(): - try: - from os import getuid, getgid - uid = getuid() - gid = getgid() - except ImportError: - uid = gid = 0 - import time - return make_auth_unix(int(time.time()-unix_epoch()), \ - socket.gethostname(), uid, gid, []) - -_unix_epoch = -1 -def unix_epoch(): - """Very painful calculation of when the Unix Epoch is. - - This is defined as the return value of time.time() on Jan 1st, - 1970, 00:00:00 GMT. - - On a Unix system, this should always return 0.0. On a Mac, the - calculations are needed -- and hard because of integer overflow - and other limitations. - - """ - global _unix_epoch - if _unix_epoch >= 0: return _unix_epoch - import time - now = time.time() - localt = time.localtime(now) # (y, m, d, hh, mm, ss, ..., ..., ...) - gmt = time.gmtime(now) - offset = time.mktime(localt) - time.mktime(gmt) - y, m, d, hh, mm, ss = 1970, 1, 1, 0, 0, 0 - offset, ss = divmod(ss + offset, 60) - offset, mm = divmod(mm + offset, 60) - offset, hh = divmod(hh + offset, 24) - d = d + offset - _unix_epoch = time.mktime((y, m, d, hh, mm, ss, 0, 0, 0)) - print("Unix epoch:", time.ctime(_unix_epoch)) - return _unix_epoch - - -# Common base class for clients - -class Client: - - def __init__(self, host, prog, vers, port): - self.host = host - self.prog = prog - self.vers = vers - self.port = port - self.makesocket() # Assigns to self.sock - self.bindsocket() - self.connsocket() - self.lastxid = 0 # XXX should be more random? - self.addpackers() - self.cred = None - self.verf = None - - def close(self): - self.sock.close() - - def makesocket(self): - # This MUST be overridden - raise RuntimeError('makesocket not defined') - - def connsocket(self): - # Override this if you don't want/need a connection - self.sock.connect((self.host, self.port)) - - def bindsocket(self): - # Override this to bind to a different port (e.g. reserved) - self.sock.bind(('', 0)) - - def addpackers(self): - # Override this to use derived classes from Packer/Unpacker - self.packer = Packer() - self.unpacker = Unpacker('') - - def make_call(self, proc, args, pack_func, unpack_func): - # Don't normally override this (but see Broadcast) - if pack_func is None and args is not None: - raise TypeError('non-null args with null pack_func') - self.start_call(proc) - if pack_func: - pack_func(args) - self.do_call() - if unpack_func: - result = unpack_func() - else: - result = None - self.unpacker.done() - return result - - def start_call(self, proc): - # Don't override this - self.lastxid = xid = self.lastxid + 1 - cred = self.mkcred() - verf = self.mkverf() - p = self.packer - p.reset() - p.pack_callheader(xid, self.prog, self.vers, proc, cred, verf) - - def do_call(self): - # This MUST be overridden - raise RuntimeError('do_call not defined') - - def mkcred(self): - # Override this to use more powerful credentials - if self.cred is None: - self.cred = (AUTH_NULL, make_auth_null()) - return self.cred - - def mkverf(self): - # Override this to use a more powerful verifier - if self.verf is None: - self.verf = (AUTH_NULL, make_auth_null()) - return self.verf - - def call_0(self): # Procedure 0 is always like this - return self.make_call(0, None, None, None) - - -# Record-Marking standard support - -def sendfrag(sock, last, frag): - x = len(frag) - if last: x = x | 0x80000000 - header = (chr(int(x>>24 & 0xff)) + chr(int(x>>16 & 0xff)) + \ - chr(int(x>>8 & 0xff)) + chr(int(x & 0xff))) - sock.send(header + frag) - -def sendrecord(sock, record): - sendfrag(sock, 1, record) - -def recvfrag(sock): - header = sock.recv(4) - if len(header) < 4: - raise EOFError - x = int(ord(header[0]))<<24 | ord(header[1])<<16 | \ - ord(header[2])<<8 | ord(header[3]) - last = ((x & 0x80000000) != 0) - n = int(x & 0x7fffffff) - frag = '' - while n > 0: - buf = sock.recv(n) - if not buf: raise EOFError - n = n - len(buf) - frag = frag + buf - return last, frag - -def recvrecord(sock): - record = '' - last = 0 - while not last: - last, frag = recvfrag(sock) - record = record + frag - return record - - -# Try to bind to a reserved port (must be root) - -last_resv_port_tried = None -def bindresvport(sock, host): - global last_resv_port_tried - FIRST, LAST = 600, 1024 # Range of ports to try - if last_resv_port_tried is None: - import os - last_resv_port_tried = FIRST + os.getpid() % (LAST-FIRST) - for i in range(last_resv_port_tried, LAST) + \ - range(FIRST, last_resv_port_tried): - last_resv_port_tried = i - try: - sock.bind((host, i)) - return last_resv_port_tried - except socket.error as e: - (errno, msg) = e - if errno != 114: - raise socket.error(errno, msg) - raise RuntimeError('can\'t assign reserved port') - - -# Client using TCP to a specific port - -class RawTCPClient(Client): - - def makesocket(self): - self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - - def do_call(self): - call = self.packer.get_buf() - sendrecord(self.sock, call) - reply = recvrecord(self.sock) - u = self.unpacker - u.reset(reply) - xid, verf = u.unpack_replyheader() - if xid != self.lastxid: - # Can't really happen since this is TCP... - raise RuntimeError('wrong xid in reply %r instead of %r' % ( - xid, self.lastxid)) - - -# Client using UDP to a specific port - -class RawUDPClient(Client): - - def makesocket(self): - self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - - def do_call(self): - call = self.packer.get_buf() - self.sock.send(call) - try: - from select import select - except ImportError: - print('WARNING: select not found, RPC may hang') - select = None - BUFSIZE = 8192 # Max UDP buffer size - timeout = 1 - count = 5 - while 1: - r, w, x = [self.sock], [], [] - if select: - r, w, x = select(r, w, x, timeout) - if self.sock not in r: - count = count - 1 - if count < 0: raise RuntimeError('timeout') - if timeout < 25: timeout = timeout *2 -## print 'RESEND', timeout, count - self.sock.send(call) - continue - reply = self.sock.recv(BUFSIZE) - u = self.unpacker - u.reset(reply) - xid, verf = u.unpack_replyheader() - if xid != self.lastxid: -## print 'BAD xid' - continue - break - - -# Client using UDP broadcast to a specific port - -class RawBroadcastUDPClient(RawUDPClient): - - def __init__(self, bcastaddr, prog, vers, port): - RawUDPClient.__init__(self, bcastaddr, prog, vers, port) - self.reply_handler = None - self.timeout = 30 - - def connsocket(self): - # Don't connect -- use sendto - self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) - - def set_reply_handler(self, reply_handler): - self.reply_handler = reply_handler - - def set_timeout(self, timeout): - self.timeout = timeout # Use None for infinite timeout - - def make_call(self, proc, args, pack_func, unpack_func): - if pack_func is None and args is not None: - raise TypeError('non-null args with null pack_func') - self.start_call(proc) - if pack_func: - pack_func(args) - call = self.packer.get_buf() - self.sock.sendto(call, (self.host, self.port)) - try: - from select import select - except ImportError: - print('WARNING: select not found, broadcast will hang') - select = None - BUFSIZE = 8192 # Max UDP buffer size (for reply) - replies = [] - if unpack_func is None: - def dummy(): pass - unpack_func = dummy - while 1: - r, w, x = [self.sock], [], [] - if select: - if self.timeout is None: - r, w, x = select(r, w, x) - else: - r, w, x = select(r, w, x, self.timeout) - if self.sock not in r: - break - reply, fromaddr = self.sock.recvfrom(BUFSIZE) - u = self.unpacker - u.reset(reply) - xid, verf = u.unpack_replyheader() - if xid != self.lastxid: -## print 'BAD xid' - continue - reply = unpack_func() - self.unpacker.done() - replies.append((reply, fromaddr)) - if self.reply_handler: - self.reply_handler(reply, fromaddr) - return replies - - -# Port mapper interface - -# Program number, version and (fixed!) port number -PMAP_PROG = 100000 -PMAP_VERS = 2 -PMAP_PORT = 111 - -# Procedure numbers -PMAPPROC_NULL = 0 # (void) -> void -PMAPPROC_SET = 1 # (mapping) -> bool -PMAPPROC_UNSET = 2 # (mapping) -> bool -PMAPPROC_GETPORT = 3 # (mapping) -> unsigned int -PMAPPROC_DUMP = 4 # (void) -> pmaplist -PMAPPROC_CALLIT = 5 # (call_args) -> call_result - -# A mapping is (prog, vers, prot, port) and prot is one of: - -IPPROTO_TCP = 6 -IPPROTO_UDP = 17 - -# A pmaplist is a variable-length list of mappings, as follows: -# either (1, mapping, pmaplist) or (0). - -# A call_args is (prog, vers, proc, args) where args is opaque; -# a call_result is (port, res) where res is opaque. - - -class PortMapperPacker(Packer): - - def pack_mapping(self, mapping): - prog, vers, prot, port = mapping - self.pack_uint(prog) - self.pack_uint(vers) - self.pack_uint(prot) - self.pack_uint(port) - - def pack_pmaplist(self, list): - self.pack_list(list, self.pack_mapping) - - def pack_call_args(self, ca): - prog, vers, proc, args = ca - self.pack_uint(prog) - self.pack_uint(vers) - self.pack_uint(proc) - self.pack_opaque(args) - - -class PortMapperUnpacker(Unpacker): - - def unpack_mapping(self): - prog = self.unpack_uint() - vers = self.unpack_uint() - prot = self.unpack_uint() - port = self.unpack_uint() - return prog, vers, prot, port - - def unpack_pmaplist(self): - return self.unpack_list(self.unpack_mapping) - - def unpack_call_result(self): - port = self.unpack_uint() - res = self.unpack_opaque() - return port, res - - -class PartialPortMapperClient: - - def addpackers(self): - self.packer = PortMapperPacker() - self.unpacker = PortMapperUnpacker('') - - def Set(self, mapping): - return self.make_call(PMAPPROC_SET, mapping, \ - self.packer.pack_mapping, \ - self.unpacker.unpack_uint) - - def Unset(self, mapping): - return self.make_call(PMAPPROC_UNSET, mapping, \ - self.packer.pack_mapping, \ - self.unpacker.unpack_uint) - - def Getport(self, mapping): - return self.make_call(PMAPPROC_GETPORT, mapping, \ - self.packer.pack_mapping, \ - self.unpacker.unpack_uint) - - def Dump(self): - return self.make_call(PMAPPROC_DUMP, None, \ - None, \ - self.unpacker.unpack_pmaplist) - - def Callit(self, ca): - return self.make_call(PMAPPROC_CALLIT, ca, \ - self.packer.pack_call_args, \ - self.unpacker.unpack_call_result) - - -class TCPPortMapperClient(PartialPortMapperClient, RawTCPClient): - - def __init__(self, host): - RawTCPClient.__init__(self, \ - host, PMAP_PROG, PMAP_VERS, PMAP_PORT) - - -class UDPPortMapperClient(PartialPortMapperClient, RawUDPClient): - - def __init__(self, host): - RawUDPClient.__init__(self, \ - host, PMAP_PROG, PMAP_VERS, PMAP_PORT) - - -class BroadcastUDPPortMapperClient(PartialPortMapperClient, \ - RawBroadcastUDPClient): - - def __init__(self, bcastaddr): - RawBroadcastUDPClient.__init__(self, \ - bcastaddr, PMAP_PROG, PMAP_VERS, PMAP_PORT) - - -# Generic clients that find their server through the Port mapper - -class TCPClient(RawTCPClient): - - def __init__(self, host, prog, vers): - pmap = TCPPortMapperClient(host) - port = pmap.Getport((prog, vers, IPPROTO_TCP, 0)) - pmap.close() - if port == 0: - raise RuntimeError('program not registered') - RawTCPClient.__init__(self, host, prog, vers, port) - - -class UDPClient(RawUDPClient): - - def __init__(self, host, prog, vers): - pmap = UDPPortMapperClient(host) - port = pmap.Getport((prog, vers, IPPROTO_UDP, 0)) - pmap.close() - if port == 0: - raise RuntimeError('program not registered') - RawUDPClient.__init__(self, host, prog, vers, port) - - -class BroadcastUDPClient(Client): - - def __init__(self, bcastaddr, prog, vers): - self.pmap = BroadcastUDPPortMapperClient(bcastaddr) - self.pmap.set_reply_handler(self.my_reply_handler) - self.prog = prog - self.vers = vers - self.user_reply_handler = None - self.addpackers() - - def close(self): - self.pmap.close() - - def set_reply_handler(self, reply_handler): - self.user_reply_handler = reply_handler - - def set_timeout(self, timeout): - self.pmap.set_timeout(timeout) - - def my_reply_handler(self, reply, fromaddr): - port, res = reply - self.unpacker.reset(res) - result = self.unpack_func() - self.unpacker.done() - self.replies.append((result, fromaddr)) - if self.user_reply_handler is not None: - self.user_reply_handler(result, fromaddr) - - def make_call(self, proc, args, pack_func, unpack_func): - self.packer.reset() - if pack_func: - pack_func(args) - if unpack_func is None: - def dummy(): pass - self.unpack_func = dummy - else: - self.unpack_func = unpack_func - self.replies = [] - packed_args = self.packer.get_buf() - dummy_replies = self.pmap.Callit( \ - (self.prog, self.vers, proc, packed_args)) - return self.replies - - -# Server classes - -# These are not symmetric to the Client classes -# XXX No attempt is made to provide authorization hooks yet - -class Server: - - def __init__(self, host, prog, vers, port): - self.host = host # Should normally be '' for default interface - self.prog = prog - self.vers = vers - self.port = port # Should normally be 0 for random port - self.makesocket() # Assigns to self.sock and self.prot - self.bindsocket() - self.host, self.port = self.sock.getsockname() - self.addpackers() - - def register(self): - mapping = self.prog, self.vers, self.prot, self.port - p = TCPPortMapperClient(self.host) - if not p.Set(mapping): - raise RuntimeError('register failed') - - def unregister(self): - mapping = self.prog, self.vers, self.prot, self.port - p = TCPPortMapperClient(self.host) - if not p.Unset(mapping): - raise RuntimeError('unregister failed') - - def handle(self, call): - # Don't use unpack_header but parse the header piecewise - # XXX I have no idea if I am using the right error responses! - self.unpacker.reset(call) - self.packer.reset() - xid = self.unpacker.unpack_uint() - self.packer.pack_uint(xid) - temp = self.unpacker.unpack_enum() - if temp != CALL: - return None # Not worthy of a reply - self.packer.pack_uint(REPLY) - temp = self.unpacker.unpack_uint() - if temp != RPCVERSION: - self.packer.pack_uint(MSG_DENIED) - self.packer.pack_uint(RPC_MISMATCH) - self.packer.pack_uint(RPCVERSION) - self.packer.pack_uint(RPCVERSION) - return self.packer.get_buf() - self.packer.pack_uint(MSG_ACCEPTED) - self.packer.pack_auth((AUTH_NULL, make_auth_null())) - prog = self.unpacker.unpack_uint() - if prog != self.prog: - self.packer.pack_uint(PROG_UNAVAIL) - return self.packer.get_buf() - vers = self.unpacker.unpack_uint() - if vers != self.vers: - self.packer.pack_uint(PROG_MISMATCH) - self.packer.pack_uint(self.vers) - self.packer.pack_uint(self.vers) - return self.packer.get_buf() - proc = self.unpacker.unpack_uint() - methname = 'handle_' + repr(proc) - try: - meth = getattr(self, methname) - except AttributeError: - self.packer.pack_uint(PROC_UNAVAIL) - return self.packer.get_buf() - cred = self.unpacker.unpack_auth() - verf = self.unpacker.unpack_auth() - try: - meth() # Unpack args, call turn_around(), pack reply - except (EOFError, GarbageArgs): - # Too few or too many arguments - self.packer.reset() - self.packer.pack_uint(xid) - self.packer.pack_uint(REPLY) - self.packer.pack_uint(MSG_ACCEPTED) - self.packer.pack_auth((AUTH_NULL, make_auth_null())) - self.packer.pack_uint(GARBAGE_ARGS) - return self.packer.get_buf() - - def turn_around(self): - try: - self.unpacker.done() - except RuntimeError: - raise GarbageArgs - self.packer.pack_uint(SUCCESS) - - def handle_0(self): # Handle NULL message - self.turn_around() - - def makesocket(self): - # This MUST be overridden - raise RuntimeError('makesocket not defined') - - def bindsocket(self): - # Override this to bind to a different port (e.g. reserved) - self.sock.bind((self.host, self.port)) - - def addpackers(self): - # Override this to use derived classes from Packer/Unpacker - self.packer = Packer() - self.unpacker = Unpacker('') - - -class TCPServer(Server): - - def makesocket(self): - self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self.prot = IPPROTO_TCP - - def loop(self): - self.sock.listen(0) - while 1: - self.session(self.sock.accept()) - - def session(self, connection): - sock, (host, port) = connection - while 1: - try: - call = recvrecord(sock) - except EOFError: - break - except socket.error as msg: - print('socket error:', msg) - break - reply = self.handle(call) - if reply is not None: - sendrecord(sock, reply) - - def forkingloop(self): - # Like loop but uses forksession() - self.sock.listen(0) - while 1: - self.forksession(self.sock.accept()) - - def forksession(self, connection): - # Like session but forks off a subprocess - import os - # Wait for deceased children - try: - while 1: - pid, sts = os.waitpid(0, 1) - except os.error: - pass - pid = None - try: - pid = os.fork() - if pid: # Parent - connection[0].close() - return - # Child - self.session(connection) - finally: - # Make sure we don't fall through in the parent - if pid == 0: - os._exit(0) - - -class UDPServer(Server): - - def makesocket(self): - self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - self.prot = IPPROTO_UDP - - def loop(self): - while 1: - self.session() - - def session(self): - call, host_port = self.sock.recvfrom(8192) - reply = self.handle(call) - if reply is not None: - self.sock.sendto(reply, host_port) - - -# Simple test program -- dump local portmapper status - -def test(): - pmap = UDPPortMapperClient('') - list = pmap.Dump() - list.sort() - for prog, vers, prot, port in list: - print(prog, vers, end=' ') - if prot == IPPROTO_TCP: print('tcp', end=' ') - elif prot == IPPROTO_UDP: print('udp', end=' ') - else: print(prot, end=' ') - print(port) - - -# Test program for broadcast operation -- dump everybody's portmapper status - -def testbcast(): - import sys - if sys.argv[1:]: - bcastaddr = sys.argv[1] - else: - bcastaddr = '' - def rh(reply, fromaddr): - host, port = fromaddr - print(host + '\t' + repr(reply)) - pmap = BroadcastUDPPortMapperClient(bcastaddr) - pmap.set_reply_handler(rh) - pmap.set_timeout(5) - replies = pmap.Getport((100002, 1, IPPROTO_UDP, 0)) - - -# Test program for server, with corresponding client -# On machine A: python -c 'import rpc; rpc.testsvr()' -# On machine B: python -c 'import rpc; rpc.testclt()' A -# (A may be == B) - -def testsvr(): - # Simple test class -- proc 1 doubles its string argument as reply - class S(UDPServer): - def handle_1(self): - arg = self.unpacker.unpack_string() - self.turn_around() - print('RPC function 1 called, arg', repr(arg)) - self.packer.pack_string(arg + arg) - # - s = S('', 0x20000000, 1, 0) - try: - s.unregister() - except RuntimeError as msg: - print('RuntimeError:', msg, '(ignored)') - s.register() - print('Service started...') - try: - s.loop() - finally: - s.unregister() - print('Service interrupted.') - - -def testclt(): - import sys - if sys.argv[1:]: host = sys.argv[1] - else: host = '' - # Client for above server - class C(UDPClient): - def call_1(self, arg): - return self.make_call(1, arg, \ - self.packer.pack_string, \ - self.unpacker.unpack_string) - c = C(host, 0x20000000, 1) - print('making call...') - reply = c.call_1('hello, world, ') - print('call returned', repr(reply)) diff --git a/Demo/rpc/test b/Demo/rpc/test deleted file mode 100755 index ba220f2..0000000 --- a/Demo/rpc/test +++ /dev/null @@ -1,24 +0,0 @@ -: ${PYTHON=python} -: ${SERVER=charon.cwi.nl} - -set -xe - -$PYTHON -c 'from rpc import test; test()' -$PYTHON -c 'from rpc import test; test()' ${SERVER} - -$PYTHON -c 'from rpc import testsvr; testsvr()' & -PID=$! -sleep 2 -$PYTHON -c 'from rpc import testclt; testclt()' -kill -2 $PID - -$PYTHON -c 'from mountclient import test; test()' -$PYTHON -c 'from mountclient import test; test()' gatekeeper.dec.com - -$PYTHON -c 'from nfsclient import test; test()' -$PYTHON -c 'from nfsclient import test; test()' gatekeeper.dec.com -$PYTHON -c 'from nfsclient import test; test()' gatekeeper.dec.com /archive - -$PYTHON -c 'from rnusersclient import test; test()' '' - -$PYTHON -c 'from rpc import testbcast; testbcast()' diff --git a/Demo/rpc/xdr.py b/Demo/rpc/xdr.py deleted file mode 100644 index 2d5f9c3..0000000 --- a/Demo/rpc/xdr.py +++ /dev/null @@ -1,200 +0,0 @@ -# Implement (a subset of) Sun XDR -- RFC1014. - - -try: - import struct -except ImportError: - struct = None - - -Long = type(0) - - -class Packer: - - def __init__(self): - self.reset() - - def reset(self): - self.buf = '' - - def get_buf(self): - return self.buf - - def pack_uint(self, x): - self.buf = self.buf + \ - (chr(int(x>>24 & 0xff)) + chr(int(x>>16 & 0xff)) + \ - chr(int(x>>8 & 0xff)) + chr(int(x & 0xff))) - if struct and struct.pack('l', 1) == '\0\0\0\1': - def pack_uint(self, x): - if type(x) == Long: - x = int((x + 0x80000000) % 0x100000000 \ - - 0x80000000) - self.buf = self.buf + struct.pack('l', x) - - pack_int = pack_uint - - pack_enum = pack_int - - def pack_bool(self, x): - if x: self.buf = self.buf + '\0\0\0\1' - else: self.buf = self.buf + '\0\0\0\0' - - def pack_uhyper(self, x): - self.pack_uint(int(x>>32 & 0xffffffff)) - self.pack_uint(int(x & 0xffffffff)) - - pack_hyper = pack_uhyper - - def pack_float(self, x): - # XXX - self.buf = self.buf + struct.pack('f', x) - - def pack_double(self, x): - # XXX - self.buf = self.buf + struct.pack('d', x) - - def pack_fstring(self, n, s): - if n < 0: - raise ValueError('fstring size must be nonnegative') - n = ((n + 3)//4)*4 - data = s[:n] - data = data + (n - len(data)) * '\0' - self.buf = self.buf + data - - pack_fopaque = pack_fstring - - def pack_string(self, s): - n = len(s) - self.pack_uint(n) - self.pack_fstring(n, s) - - pack_opaque = pack_string - - def pack_list(self, list, pack_item): - for item in list: - self.pack_uint(1) - pack_item(item) - self.pack_uint(0) - - def pack_farray(self, n, list, pack_item): - if len(list) != n: - raise ValueError('wrong array size') - for item in list: - pack_item(item) - - def pack_array(self, list, pack_item): - n = len(list) - self.pack_uint(n) - self.pack_farray(n, list, pack_item) - - -class Unpacker: - - def __init__(self, data): - self.reset(data) - - def reset(self, data): - self.buf = data - self.pos = 0 - - def done(self): - if self.pos < len(self.buf): - raise RuntimeError('unextracted data remains') - - def unpack_uint(self): - i = self.pos - self.pos = j = i+4 - data = self.buf[i:j] - if len(data) < 4: - raise EOFError - x = int(ord(data[0]))<<24 | ord(data[1])<<16 | \ - ord(data[2])<<8 | ord(data[3]) - # Return a Python long only if the value is not representable - # as a nonnegative Python int - if x < 0x80000000: x = int(x) - return x - if struct and struct.unpack('l', '\0\0\0\1') == 1: - def unpack_uint(self): - i = self.pos - self.pos = j = i+4 - data = self.buf[i:j] - if len(data) < 4: - raise EOFError - return struct.unpack('l', data) - - def unpack_int(self): - x = self.unpack_uint() - if x >= 0x80000000: x = x - 0x100000000 - return int(x) - - unpack_enum = unpack_int - - unpack_bool = unpack_int - - def unpack_uhyper(self): - hi = self.unpack_uint() - lo = self.unpack_uint() - return int(hi)<<32 | lo - - def unpack_hyper(self): - x = self.unpack_uhyper() - if x >= 0x8000000000000000: x = x - 0x10000000000000000 - return x - - def unpack_float(self): - # XXX - i = self.pos - self.pos = j = i+4 - data = self.buf[i:j] - if len(data) < 4: - raise EOFError - return struct.unpack('f', data)[0] - - def unpack_double(self): - # XXX - i = self.pos - self.pos = j = i+8 - data = self.buf[i:j] - if len(data) < 8: - raise EOFError - return struct.unpack('d', data)[0] - - def unpack_fstring(self, n): - if n < 0: - raise ValueError('fstring size must be nonnegative') - i = self.pos - j = i + (n+3)//4*4 - if j > len(self.buf): - raise EOFError - self.pos = j - return self.buf[i:i+n] - - unpack_fopaque = unpack_fstring - - def unpack_string(self): - n = self.unpack_uint() - return self.unpack_fstring(n) - - unpack_opaque = unpack_string - - def unpack_list(self, unpack_item): - list = [] - while 1: - x = self.unpack_uint() - if x == 0: break - if x != 1: - raise RuntimeError('0 or 1 expected, got %r' % (x, )) - item = unpack_item() - list.append(item) - return list - - def unpack_farray(self, n, unpack_item): - list = [] - for i in range(n): - list.append(unpack_item()) - return list - - def unpack_array(self, unpack_item): - n = self.unpack_uint() - return self.unpack_farray(n, unpack_item) diff --git a/Demo/scripts/eqfix.py b/Demo/scripts/eqfix.py deleted file mode 100755 index 8d0c8df..0000000 --- a/Demo/scripts/eqfix.py +++ /dev/null @@ -1,198 +0,0 @@ -#! /usr/bin/env python3 - -# Fix Python source files to use the new equality test operator, i.e., -# if x = y: ... -# is changed to -# if x == y: ... -# The script correctly tokenizes the Python program to reliably -# distinguish between assignments and equality tests. -# -# Command line arguments are files or directories to be processed. -# Directories are searched recursively for files whose name looks -# like a python module. -# Symbolic links are always ignored (except as explicit directory -# arguments). Of course, the original file is kept as a back-up -# (with a "~" attached to its name). -# It complains about binaries (files containing null bytes) -# and about files that are ostensibly not Python files: if the first -# line starts with '#!' and does not contain the string 'python'. -# -# Changes made are reported to stdout in a diff-like format. -# -# Undoubtedly you can do this using find and sed or perl, but this is -# a nice example of Python code that recurses down a directory tree -# and uses regular expressions. Also note several subtleties like -# preserving the file's mode and avoiding to even write a temp file -# when no changes are needed for a file. -# -# NB: by changing only the function fixline() you can turn this -# into a program for a different change to Python programs... - -import sys -import re -import os -from stat import * -import string - -err = sys.stderr.write -dbg = err -rep = sys.stdout.write - -def main(): - bad = 0 - if not sys.argv[1:]: # No arguments - err('usage: ' + sys.argv[0] + ' file-or-directory ...\n') - sys.exit(2) - for arg in sys.argv[1:]: - if os.path.isdir(arg): - if recursedown(arg): bad = 1 - elif os.path.islink(arg): - err(arg + ': will not process symbolic links\n') - bad = 1 - else: - if fix(arg): bad = 1 - sys.exit(bad) - -ispythonprog = re.compile('^[a-zA-Z0-9_]+\.py$') -def ispython(name): - return ispythonprog.match(name) >= 0 - -def recursedown(dirname): - dbg('recursedown(%r)\n' % (dirname,)) - bad = 0 - try: - names = os.listdir(dirname) - except os.error as msg: - err('%s: cannot list directory: %r\n' % (dirname, msg)) - return 1 - names.sort() - subdirs = [] - for name in names: - if name in (os.curdir, os.pardir): continue - fullname = os.path.join(dirname, name) - if os.path.islink(fullname): pass - elif os.path.isdir(fullname): - subdirs.append(fullname) - elif ispython(name): - if fix(fullname): bad = 1 - for fullname in subdirs: - if recursedown(fullname): bad = 1 - return bad - -def fix(filename): -## dbg('fix(%r)\n' % (dirname,)) - try: - f = open(filename, 'r') - except IOError as msg: - err('%s: cannot open: %r\n' % (filename, msg)) - return 1 - head, tail = os.path.split(filename) - tempname = os.path.join(head, '@' + tail) - g = None - # If we find a match, we rewind the file and start over but - # now copy everything to a temp file. - lineno = 0 - while 1: - line = f.readline() - if not line: break - lineno = lineno + 1 - if g is None and '\0' in line: - # Check for binary files - err(filename + ': contains null bytes; not fixed\n') - f.close() - return 1 - if lineno == 1 and g is None and line[:2] == '#!': - # Check for non-Python scripts - words = string.split(line[2:]) - if words and re.search('[pP]ython', words[0]) < 0: - msg = filename + ': ' + words[0] - msg = msg + ' script; not fixed\n' - err(msg) - f.close() - return 1 - while line[-2:] == '\\\n': - nextline = f.readline() - if not nextline: break - line = line + nextline - lineno = lineno + 1 - newline = fixline(line) - if newline != line: - if g is None: - try: - g = open(tempname, 'w') - except IOError as msg: - f.close() - err('%s: cannot create: %r\n' % (tempname, msg)) - return 1 - f.seek(0) - lineno = 0 - rep(filename + ':\n') - continue # restart from the beginning - rep(repr(lineno) + '\n') - rep('< ' + line) - rep('> ' + newline) - if g is not None: - g.write(newline) - - # End of file - f.close() - if not g: return 0 # No changes - - # Finishing touch -- move files - - # First copy the file's mode to the temp file - try: - statbuf = os.stat(filename) - os.chmod(tempname, statbuf[ST_MODE] & 0o7777) - except os.error as msg: - err('%s: warning: chmod failed (%r)\n' % (tempname, msg)) - # Then make a backup of the original file as filename~ - try: - os.rename(filename, filename + '~') - except os.error as msg: - err('%s: warning: backup failed (%r)\n' % (filename, msg)) - # Now move the temp file to the original file - try: - os.rename(tempname, filename) - except os.error as msg: - err('%s: rename failed (%r)\n' % (filename, msg)) - return 1 - # Return succes - return 0 - - -from tokenize import tokenprog - -match = {'if':':', 'elif':':', 'while':':', 'return':'\n', \ - '(':')', '[':']', '{':'}', '`':'`'} - -def fixline(line): - # Quick check for easy case - if '=' not in line: return line - - i, n = 0, len(line) - stack = [] - while i < n: - j = tokenprog.match(line, i) - if j < 0: - # A bad token; forget about the rest of this line - print('(Syntax error:)') - print(line, end=' ') - return line - a, b = tokenprog.regs[3] # Location of the token proper - token = line[a:b] - i = i+j - if stack and token == stack[-1]: - del stack[-1] - elif token in match: - stack.append(match[token]) - elif token == '=' and stack: - line = line[:a] + '==' + line[b:] - i, n = a + len('=='), len(line) - elif token == '==' and not stack: - print('(Warning: \'==\' at top level:)') - print(line, end=' ') - return line - -if __name__ == "__main__": - main() diff --git a/Demo/scripts/find-uname.py b/Demo/scripts/find-uname.py deleted file mode 100755 index b6ec1b6..0000000 --- a/Demo/scripts/find-uname.py +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env python3 - -""" -For each argument on the command line, look for it in the set of all Unicode -names. Arguments are treated as case-insensitive regular expressions, e.g.: - - % find-uname 'small letter a$' 'horizontal line' - *** small letter a$ matches *** - LATIN SMALL LETTER A (97) - COMBINING LATIN SMALL LETTER A (867) - CYRILLIC SMALL LETTER A (1072) - PARENTHESIZED LATIN SMALL LETTER A (9372) - CIRCLED LATIN SMALL LETTER A (9424) - FULLWIDTH LATIN SMALL LETTER A (65345) - *** horizontal line matches *** - HORIZONTAL LINE EXTENSION (9135) -""" - -import unicodedata -import sys -import re - -def main(args): - unicode_names = [] - for ix in range(sys.maxunicode+1): - try: - unicode_names.append((ix, unicodedata.name(chr(ix)))) - except ValueError: # no name for the character - pass - for arg in args: - pat = re.compile(arg, re.I) - matches = [(y,x) for (x,y) in unicode_names - if pat.search(y) is not None] - if matches: - print("***", arg, "matches", "***") - for match in matches: - print("%s (%d)" % match) - -if __name__ == "__main__": - main(sys.argv[1:]) diff --git a/Demo/scripts/from.py b/Demo/scripts/from.py deleted file mode 100755 index c8a9346..0000000 --- a/Demo/scripts/from.py +++ /dev/null @@ -1,35 +0,0 @@ -#! /usr/bin/env python3 - -# Print From and Subject of messages in $MAIL. -# Extension to multiple mailboxes and other bells & whistles are left -# as exercises for the reader. - -import sys, os - -# Open mailbox file. Exits with exception when this fails. - -try: - mailbox = os.environ['MAIL'] -except (AttributeError, KeyError): - sys.stderr.write('No environment variable $MAIL\n') - sys.exit(2) - -try: - mail = open(mailbox) -except IOError: - sys.exit('Cannot open mailbox file: ' + mailbox) - -while 1: - line = mail.readline() - if not line: - break # EOF - if line.startswith('From '): - # Start of message found - print(line[:-1], end=' ') - while 1: - line = mail.readline() - if not line or line == '\n': - break - if line.startswith('Subject: '): - print(repr(line[9:-1]), end=' ') - print() diff --git a/Demo/scripts/lpwatch.py b/Demo/scripts/lpwatch.py deleted file mode 100755 index 01d9fea..0000000 --- a/Demo/scripts/lpwatch.py +++ /dev/null @@ -1,102 +0,0 @@ -#! /usr/bin/env python3 - -# Watch line printer queue(s). -# Intended for BSD 4.3 lpq. - -import os -import sys -import time - -DEF_PRINTER = 'psc' -DEF_DELAY = 10 - -def main(): - delay = DEF_DELAY # XXX Use getopt() later - try: - thisuser = os.environ['LOGNAME'] - except: - thisuser = os.environ['USER'] - printers = sys.argv[1:] - if printers: - # Strip '-P' from printer names just in case - # the user specified it... - for i, name in enumerate(printers): - if name[:2] == '-P': - printers[i] = name[2:] - else: - if 'PRINTER' in os.environ: - printers = [os.environ['PRINTER']] - else: - printers = [DEF_PRINTER] - - clearhome = os.popen('clear', 'r').read() - - while True: - text = clearhome - for name in printers: - text += makestatus(name, thisuser) + '\n' - print(text) - time.sleep(delay) - -def makestatus(name, thisuser): - pipe = os.popen('lpq -P' + name + ' 2>&1', 'r') - lines = [] - users = {} - aheadbytes = 0 - aheadjobs = 0 - userseen = False - totalbytes = 0 - totaljobs = 0 - for line in pipe: - fields = line.split() - n = len(fields) - if len(fields) >= 6 and fields[n-1] == 'bytes': - rank, user, job = fields[0:3] - files = fields[3:-2] - bytes = int(fields[n-2]) - if user == thisuser: - userseen = True - elif not userseen: - aheadbytes += bytes - aheadjobs += 1 - totalbytes += bytes - totaljobs += 1 - ujobs, ubytes = users.get(user, (0, 0)) - ujobs += 1 - ubytes += bytes - users[user] = ujobs, ubytes - else: - if fields and fields[0] != 'Rank': - line = line.strip() - if line == 'no entries': - line = name + ': idle' - elif line[-22:] == ' is ready and printing': - line = name - lines.append(line) - - if totaljobs: - line = '%d K' % ((totalbytes+1023) // 1024) - if totaljobs != len(users): - line += ' (%d jobs)' % totaljobs - if len(users) == 1: - line += ' for %s' % next(iter(users)) - else: - line += ' for %d users' % len(users) - if userseen: - if aheadjobs == 0: - line += ' (%s first)' % thisuser - else: - line += ' (%d K before %s)' % ( - (aheadbytes+1023) // 1024, thisuser) - lines.append(line) - - sts = pipe.close() - if sts: - lines.append('lpq exit status %r' % (sts,)) - return ': '.join(lines) - -if __name__ == "__main__": - try: - main() - except KeyboardInterrupt: - pass diff --git a/Demo/scripts/makedir.py b/Demo/scripts/makedir.py deleted file mode 100755 index a14e848..0000000 --- a/Demo/scripts/makedir.py +++ /dev/null @@ -1,21 +0,0 @@ -#! /usr/bin/env python3 - -# Like mkdir, but also make intermediate directories if necessary. -# It is not an error if the given directory already exists (as long -# as it is a directory). -# Errors are not treated specially -- you just get a Python exception. - -import sys, os - -def main(): - for p in sys.argv[1:]: - makedirs(p) - -def makedirs(p): - if p and not os.path.isdir(p): - head, tail = os.path.split(p) - makedirs(head) - os.mkdir(p, 0o777) - -if __name__ == "__main__": - main() diff --git a/Demo/scripts/mboxconvert.py b/Demo/scripts/mboxconvert.py deleted file mode 100755 index cb3ed89..0000000 --- a/Demo/scripts/mboxconvert.py +++ /dev/null @@ -1,124 +0,0 @@ -#! /usr/bin/env python3 - -# Convert MH directories (1 message per file) or MMDF mailboxes (4x^A -# delimited) to unix mailbox (From ... delimited) on stdout. -# If -f is given, files contain one message per file (e.g. MH messages) - -import rfc822 -import sys -import time -import os -import stat -import getopt -import re - -def main(): - dofile = mmdf - try: - opts, args = getopt.getopt(sys.argv[1:], 'f') - except getopt.error as msg: - sys.stderr.write('%s\n' % msg) - sys.exit(2) - for o, a in opts: - if o == '-f': - dofile = message - if not args: - args = ['-'] - sts = 0 - for arg in args: - if arg == '-' or arg == '': - sts = dofile(sys.stdin) or sts - elif os.path.isdir(arg): - sts = mh(arg) or sts - elif os.path.isfile(arg): - try: - f = open(arg) - except IOError as msg: - sys.stderr.write('%s: %s\n' % (arg, msg)) - sts = 1 - continue - sts = dofile(f) or sts - f.close() - else: - sys.stderr.write('%s: not found\n' % arg) - sts = 1 - if sts: - sys.exit(sts) - -numeric = re.compile('[1-9][0-9]*') - -def mh(dir): - sts = 0 - msgs = os.listdir(dir) - for msg in msgs: - if numeric.match(msg) != len(msg): - continue - fn = os.path.join(dir, msg) - try: - f = open(fn) - except IOError as msg: - sys.stderr.write('%s: %s\n' % (fn, msg)) - sts = 1 - continue - sts = message(f) or sts - return sts - -def mmdf(f): - sts = 0 - while 1: - line = f.readline() - if not line: - break - if line == '\1\1\1\1\n': - sts = message(f, line) or sts - else: - sys.stderr.write( - 'Bad line in MMFD mailbox: %r\n' % (line,)) - return sts - -counter = 0 # for generating unique Message-ID headers - -def message(f, delimiter = ''): - sts = 0 - # Parse RFC822 header - m = rfc822.Message(f) - # Write unix header line - fullname, email = m.getaddr('From') - tt = m.getdate('Date') - if tt: - t = time.mktime(tt) - else: - sys.stderr.write( - 'Unparseable date: %r\n' % (m.get('Date'),)) - t = os.fstat(f.fileno())[stat.ST_MTIME] - print('From', email, time.ctime(t)) - # Copy RFC822 header - for line in m.headers: - print(line, end=' ') - # Invent Message-ID header if none is present - if 'message-id' not in m: - global counter - counter = counter + 1 - msgid = "<%s.%d>" % (hex(t), counter) - sys.stderr.write("Adding Message-ID %s (From %s)\n" % - (msgid, email)) - print("Message-ID:", msgid) - print() - # Copy body - while 1: - line = f.readline() - if line == delimiter: - break - if not line: - sys.stderr.write('Unexpected EOF in message\n') - sts = 1 - break - if line[:5] == 'From ': - line = '>' + line - print(line, end=' ') - # Print trailing newline - print() - return sts - -if __name__ == "__main__": - main() diff --git a/Demo/scripts/morse.py b/Demo/scripts/morse.py deleted file mode 100755 index c2f408f..0000000 --- a/Demo/scripts/morse.py +++ /dev/null @@ -1,128 +0,0 @@ -#! /usr/bin/env python3 - -# DAH should be three DOTs. -# Space between DOTs and DAHs should be one DOT. -# Space between two letters should be one DAH. -# Space between two words should be DOT DAH DAH. - -import sys, math, aifc -from contextlib import closing - -DOT = 30 -DAH = 3 * DOT -OCTAVE = 2 # 1 == 441 Hz, 2 == 882 Hz, ... - -morsetab = { - 'A': '.-', 'a': '.-', - 'B': '-...', 'b': '-...', - 'C': '-.-.', 'c': '-.-.', - 'D': '-..', 'd': '-..', - 'E': '.', 'e': '.', - 'F': '..-.', 'f': '..-.', - 'G': '--.', 'g': '--.', - 'H': '....', 'h': '....', - 'I': '..', 'i': '..', - 'J': '.---', 'j': '.---', - 'K': '-.-', 'k': '-.-', - 'L': '.-..', 'l': '.-..', - 'M': '--', 'm': '--', - 'N': '-.', 'n': '-.', - 'O': '---', 'o': '---', - 'P': '.--.', 'p': '.--.', - 'Q': '--.-', 'q': '--.-', - 'R': '.-.', 'r': '.-.', - 'S': '...', 's': '...', - 'T': '-', 't': '-', - 'U': '..-', 'u': '..-', - 'V': '...-', 'v': '...-', - 'W': '.--', 'w': '.--', - 'X': '-..-', 'x': '-..-', - 'Y': '-.--', 'y': '-.--', - 'Z': '--..', 'z': '--..', - '0': '-----', ',': '--..--', - '1': '.----', '.': '.-.-.-', - '2': '..---', '?': '..--..', - '3': '...--', ';': '-.-.-.', - '4': '....-', ':': '---...', - '5': '.....', "'": '.----.', - '6': '-....', '-': '-....-', - '7': '--...', '/': '-..-.', - '8': '---..', '(': '-.--.-', - '9': '----.', ')': '-.--.-', - ' ': ' ', '_': '..--.-', -} - -nowave = b'\0' * 200 - -# If we play at 44.1 kHz (which we do), then if we produce one sine -# wave in 100 samples, we get a tone of 441 Hz. If we produce two -# sine waves in these 100 samples, we get a tone of 882 Hz. 882 Hz -# appears to be a nice one for playing morse code. -def mkwave(octave): - sinewave = bytearray() - for i in range(100): - val = int(math.sin(math.pi * i * octave / 50.0) * 30000) - sinewave.extend([(val >> 8) & 255, val & 255]) - return bytes(sinewave) - -defaultwave = mkwave(OCTAVE) - -def main(): - import getopt - try: - opts, args = getopt.getopt(sys.argv[1:], 'o:p:') - except getopt.error: - sys.stderr.write('Usage ' + sys.argv[0] + - ' [ -o outfile ] [ -p octave ] [ words ] ...\n') - sys.exit(1) - wave = defaultwave - outfile = 'morse.aifc' - for o, a in opts: - if o == '-o': - outfile = a - if o == '-p': - wave = mkwave(int(a)) - with closing(aifc.open(outfile, 'w')) as fp: - fp.setframerate(44100) - fp.setsampwidth(2) - fp.setnchannels(1) - if args: - source = [' '.join(args)] - else: - source = iter(sys.stdin.readline, '') - for line in source: - mline = morse(line) - play(mline, fp, wave) - -# Convert a string to morse code with \001 between the characters in -# the string. -def morse(line): - res = '' - for c in line: - try: - res += morsetab[c] + '\001' - except KeyError: - pass - return res - -# Play a line of morse code. -def play(line, fp, wave): - for c in line: - if c == '.': - sine(fp, DOT, wave) - elif c == '-': - sine(fp, DAH, wave) - else: # space - pause(fp, DAH + DOT) - pause(fp, DOT) - -def sine(fp, length, wave): - for i in range(length): - fp.writeframesraw(wave) - -def pause(fp, length): - for i in range(length): - fp.writeframesraw(nowave) - -if __name__ == '__main__': - main() diff --git a/Demo/scripts/newslist.doc b/Demo/scripts/newslist.doc deleted file mode 100755 index 87fd9ba..0000000 --- a/Demo/scripts/newslist.doc +++ /dev/null @@ -1,59 +0,0 @@ - NEWSLIST - ======== - A program to assist HTTP browsing of newsgroups - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -WWW browsers such as NCSA Mosaic allow the user to read newsgroup -articles by specifying the group name in a URL eg 'news:comp.answers'. - -To browse through many groups, though, (and there are several thousand -of them) you really need a page or pages containing links to all the -groups. There are some good ones out there, for example, - - http://info.cern.ch/hypertext/DataSources/News/Groups/Overview.html - -is the standard one at CERN, but it only shows the groups available there, -which may be rather different from those available on your machine. - -Newslist is a program which creates a hierarchy of pages for you based -on the groups available from YOUR server. It is written in python - a -splendid interpreted object-oriented language which I suggest you get -right now from the directory /pub/python at ftp.cwi.nl, if you haven't -already got it. - -You should be able to see some sample output by looking at: - http://pelican.cl.cam.ac.uk/newspage/root.html - -Descriptions of newsgroups can be added from a file with one group -per line. eg: - - alt.foo Articles about foo - comp.bar Programming in 'bar' and related languages - -A suitable list detailing most groups can be found at ftp.uu.net in -/uunet-info/newsgroups.gz. - -Make sure you read the information at the beginning of the program source and -configure the variables before running. - -In addition to python, you need: - - An NNTP-based news feed. - A directory in which to put the pages. - -The programming is not very beautiful, but it works! It comes with no -warranty, express or implied, but with the hope that some others may -find it useful. - -Comments, improvements & suggestions welcomed. -Quentin Stafford-Fraser - - ---------------------------------------------------------------------- - Quentin Stafford-Fraser - http://pelican.cl.cam.ac.uk/people/qs101/me.html - - Cambridge University Computer Lab Rank Xerox Cambridge EuroPARC - qs101@cl.cam.ac.uk fraser@europarc.xerox.com - Tel: +44 223 334411 Tel: +44 223 341521 - Fax: +44 223 334679 Fax: +44 223 341510 - ---------------------------------------------------------------------- diff --git a/Demo/scripts/newslist.py b/Demo/scripts/newslist.py deleted file mode 100755 index b345f2ef..0000000 --- a/Demo/scripts/newslist.py +++ /dev/null @@ -1,361 +0,0 @@ -#! /usr/bin/env python3 -####################################################################### -# Newslist $Revision$ -# -# Syntax: -# newslist [ -a ] -# -# This is a program to create a directory full of HTML pages -# which between them contain links to all the newsgroups available -# on your server. -# -# The -a option causes a complete list of all groups to be read from -# the server rather than just the ones which have appeared since last -# execution. This recreates the local list from scratch. Use this on -# the first invocation of the program, and from time to time thereafter. -# When new groups are first created they may appear on your server as -# empty groups. By default, empty groups are ignored by the -a option. -# However, these new groups will not be created again, and so will not -# appear in the server's list of 'new groups' at a later date. Hence it -# won't appear until you do a '-a' after some articles have appeared. -# -# I should really keep a list of ignored empty groups and re-check them -# for articles on every run, but I haven't got around to it yet. -# -# This assumes an NNTP news feed. -# -# Feel free to copy, distribute and modify this code for -# non-commercial use. If you make any useful modifications, let me -# know! -# -# (c) Quentin Stafford-Fraser 1994 -# fraser@europarc.xerox.com qs101@cl.cam.ac.uk -# # -####################################################################### -import sys, nntplib, marshal, time, os - -####################################################################### -# Check these variables before running! # - -# Top directory. -# Filenames which don't start with / are taken as being relative to this. -topdir = os.path.expanduser('~/newspage') - -# The name of your NNTP host -# eg. -# newshost = 'nntp-serv.cl.cam.ac.uk' -# or use following to get the name from the NNTPSERVER environment -# variable: -# newshost = os.environ['NNTPSERVER'] -newshost = 'news.example.com' - -# The filename for a local cache of the newsgroup list -treefile = 'grouptree' - -# The filename for descriptions of newsgroups -# I found a suitable one at ftp.uu.net in /uunet-info/newgroups.gz -# You can set this to '' if you don't wish to use one. -descfile = 'newsgroups' - -# The directory in which HTML pages should be created -# eg. -# pagedir = '/usr/local/lib/html/newspage' -# pagedir = 'pages' -pagedir = topdir - -# The html prefix which will refer to this directory -# eg. -# httppref = '/newspage/', -# or leave blank for relative links between pages: (Recommended) -# httppref = '' -httppref = '' - -# The name of the 'root' news page in this directory. -# A .html suffix will be added. -rootpage = 'root' - -# Set skipempty to 0 if you wish to see links to empty groups as well. -# Only affects the -a option. -skipempty = 1 - -# pagelinkicon can contain html to put an icon after links to -# further pages. This helps to make important links stand out. -# Set to '' if not wanted, or '...' is quite a good one. -pagelinkicon = '... ' - -# --------------------------------------------------------------------- -# Less important personal preferences: - -# Sublistsize controls the maximum number of items the will appear as -# an indented sub-list before the whole thing is moved onto a different -# page. The smaller this is, the more pages you will have, but the -# shorter each will be. -sublistsize = 4 - -# That should be all. # -####################################################################### - -for dir in os.curdir, os.environ['HOME']: - rcfile = os.path.join(dir, '.newslistrc.py') - if os.path.exists(rcfile): - print(rcfile) - exec(open(rcfile).read()) - break - -from nntplib import NNTP -from stat import * - -rcsrev = '$Revision$' -rcsrev = ' '.join([s for s in rcsrev.split() if '$' not in s]) -desc = {} - -# Make (possibly) relative filenames into absolute ones -treefile = os.path.join(topdir,treefile) -descfile = os.path.join(topdir,descfile) -page = os.path.join(topdir,pagedir) - -# First the bits for creating trees --------------------------- - -# Addtotree creates/augments a tree from a list of group names -def addtotree(tree, groups): - print('Updating tree...') - for i in groups: - parts = i.split('.') - makeleaf(tree, parts) - -# Makeleaf makes a leaf and the branch leading to it if necessary -def makeleaf(tree,path): - j = path[0] - l = len(path) - - if j not in tree: - tree[j] = {} - if l == 1: - tree[j]['.'] = '.' - if l > 1: - makeleaf(tree[j],path[1:]) - -# Then the bits for outputting trees as pages ---------------- - -# Createpage creates an HTML file named .html containing links -# to those groups beginning with . - -def createpage(root, tree, p): - filename = os.path.join(pagedir, root+'.html') - if root == rootpage: - detail = '' - else: - detail = ' under ' + root - with open(filename, 'w') as f: - # f.write('Content-Type: text/html\n') - f.write('\n\n') - f.write('Newsgroups available%s\n' % detail) - f.write('\n\n') - f.write('

Newsgroups available%s

\n' % detail) - f.write('Back to top level

\n' % - (httppref, rootpage)) - printtree(f, tree, 0, p) - f.write('\n

') - f.write("This page automatically created by 'newslist' v. %s." % - rcsrev) - f.write(time.ctime(time.time()) + '\n') - f.write('\n\n') - -# Printtree prints the groups as a bulleted list. Groups with -# more than subgroups will be put on a separate page. -# Other sets of subgroups are just indented. - -def printtree(f, tree, indent, p): - l = len(tree) - - if l > sublistsize and indent > 0: - # Create a new page and a link to it - f.write('

  • ' % (httppref, p[1:])) - f.write(p[1:] + '.*') - f.write('%s\n' % pagelinkicon) - createpage(p[1:], tree, p) - return - - kl = sorted(tree.keys()) - - if l > 1: - if indent > 0: - # Create a sub-list - f.write('
  • %s\n - -
    -
    -Converted to HTML by rss2html.py. -
    - - - -""" - -# --- The ContentHandler - -class RSSHandler(handler.ContentHandler): - - def __init__(self, out=sys.stdout): - handler.ContentHandler.__init__(self) - self._out = out - - self._text = "" - self._parent = None - self._list_started = False - self._title = None - self._link = None - self._descr = "" - - # ContentHandler methods - - def startElement(self, name, attrs): - if name == "channel" or name == "image" or name == "item": - self._parent = name - - self._text = "" - - def endElement(self, name): - if self._parent == "channel": - if name == "title": - self._out.write(top % (self._text, self._text)) - elif name == "description": - self._out.write("

    %s

    \n" % self._text) - - elif self._parent == "item": - if name == "title": - self._title = self._text - elif name == "link": - self._link = self._text - elif name == "description": - self._descr = self._text - elif name == "item": - if not self._list_started: - self._out.write("