Ignore:
Timestamp:
Mar 19, 2014, 11:11:30 AM (11 years ago)
Author:
dmik
Message:

python: Update vendor to 2.7.6.

Location:
python/vendor/current/Demo
Files:
18 added
5 deleted
69 edited

Legend:

Unmodified
Added
Removed
  • python/vendor/current/Demo/cgi/cgi1.py

    r2 r388  
    1 #!/usr/local/bin/python
     1#!/usr/bin/env python
    22
    33"""CGI test 1 - check server setup."""
  • python/vendor/current/Demo/cgi/cgi2.py

    r2 r388  
    1 #!/usr/local/bin/python
     1#!/usr/bin/env python
    22
    33"""CGI test 2 - basic use of cgi module."""
  • python/vendor/current/Demo/cgi/cgi3.py

    r2 r388  
    1 #!/usr/local/bin/python
     1#!/usr/bin/env python
    22
    33"""CGI test 3 (persistent data)."""
  • python/vendor/current/Demo/classes/Vec.py

    r2 r388  
    1 # A simple vector class
     1class Vec:
     2    """ A simple vector class
    23
     4    Instances of the Vec class  can be constructed from numbers
    35
    4 def vec(*v):
    5     return Vec(*v)
     6    >>> a = Vec(1, 2, 3)
     7    >>> b = Vec(3, 2, 1)
    68
     9    added
     10    >>> a + b
     11    Vec(4, 4, 4)
    712
    8 class Vec:
     13    subtracted
     14    >>> a - b
     15    Vec(-2, 0, 2)
    916
     17    and multiplied by a scalar on the left
     18    >>> 3.0 * a
     19    Vec(3.0, 6.0, 9.0)
     20
     21    or on the right
     22    >>> a * 3.0
     23    Vec(3.0, 6.0, 9.0)
     24    """
    1025    def __init__(self, *v):
    1126        self.v = list(v)
    1227
    13     def fromlist(self, v):
     28    @classmethod
     29    def fromlist(cls, v):
    1430        if not isinstance(v, list):
    1531            raise TypeError
    16         self.v = v[:]
    17         return self
     32        inst = cls()
     33        inst.v = v
     34        return inst
    1835
    1936    def __repr__(self):
    20         return 'vec(' + repr(self.v)[1:-1] + ')'
     37        args = ', '.join(repr(x) for x in self.v)
     38        return 'Vec({0})'.format(args)
    2139
    2240    def __len__(self):
     
    2846    def __add__(self, other):
    2947        # Element-wise addition
    30         v = map(lambda x, y: x+y, self, other)
    31         return Vec().fromlist(v)
     48        v = [x + y for x, y in zip(self.v, other.v)]
     49        return Vec.fromlist(v)
    3250
    3351    def __sub__(self, other):
    3452        # Element-wise subtraction
    35         v = map(lambda x, y: x-y, self, other)
    36         return Vec().fromlist(v)
     53        v = [x - y for x, y in zip(self.v, other.v)]
     54        return Vec.fromlist(v)
    3755
    3856    def __mul__(self, scalar):
    3957        # Multiply by scalar
    40         v = map(lambda x: x*scalar, self.v)
    41         return Vec().fromlist(v)
     58        v = [x * scalar for x in self.v]
     59        return Vec.fromlist(v)
    4260
     61    __rmul__ = __mul__
    4362
    4463
    4564def test():
    46     a = vec(1, 2, 3)
    47     b = vec(3, 2, 1)
    48     print a
    49     print b
    50     print a+b
    51     print a-b
    52     print a*3.0
     65    import doctest
     66    doctest.testmod()
    5367
    5468test()
  • python/vendor/current/Demo/curses/ncurses.py

    r2 r388  
    11#!/usr/bin/env python
    22#
    3 # $Id: ncurses.py 66424 2008-09-13 01:22:08Z andrew.kuchling $
     3# $Id$
    44#
    55# (n)curses exerciser in Python, an interactive test for the curses
  • python/vendor/current/Demo/curses/rain.py

    r2 r388  
    11#!/usr/bin/env python
    22#
    3 # $Id: rain.py 46625 2006-06-03 23:02:15Z andrew.kuchling $
     3# $Id$
    44#
    55# somebody should probably check the randrange()s...
  • python/vendor/current/Demo/curses/tclock.py

    r2 r388  
    11#!/usr/bin/env python
    22#
    3 # $Id: tclock.py 46626 2006-06-03 23:07:21Z andrew.kuchling $
     3# $Id$
    44#
    55# From tclock.c, Copyright Howard Jones <ha.jones@ic.ac.uk>, September 1994.
  • python/vendor/current/Demo/curses/xmas.py

    r2 r388  
    22# December 1989             Larry Bartz           Indianapolis, IN
    33#
    4 # $Id: xmas.py 46623 2006-06-03 22:59:23Z andrew.kuchling $
     4# $Id$
    55#
    66# I'm dreaming of an ascii character-based monochrome Christmas,
  • python/vendor/current/Demo/embed/Makefile

    r2 r388  
    11# Makefile for embedded Python use demo.
    2 # (This version tailored for my Red Hat Linux 6.1 setup;
     2# (This version originally written on Red Hat Linux 6.1;
    33# edit lines marked with XXX.)
    44
     
    1111
    1212# Python version
    13 VERSION=        2.6
     13VERSION=        2.7
    1414
    1515# Compiler flags
     
    2222LIBPYTHON=      $(blddir)/libpython$(VERSION).a
    2323
    24 # XXX edit LIBS (in particular) to match $(blddir)/Modules/Makefile
     24# XXX edit LIBS (in particular) to match $(blddir)/Makefile
    2525LIBS=           -lnsl -ldl -lreadline -ltermcap -lieee -lpthread -lutil
    2626LDFLAGS=        -Xlinker -export-dynamic
  • python/vendor/current/Demo/embed/demo.c

    r2 r388  
    77main(int argc, char **argv)
    88{
    9         /* Pass argv[0] to the Python interpreter */
    10         Py_SetProgramName(argv[0]);
     9    /* Pass argv[0] to the Python interpreter */
     10    Py_SetProgramName(argv[0]);
    1111
    12         /* Initialize the Python interpreter.  Required. */
    13         Py_Initialize();
     12    /* Initialize the Python interpreter.  Required. */
     13    Py_Initialize();
    1414
    15         /* Add a static module */
    16         initxyzzy();
     15    /* Add a static module */
     16    initxyzzy();
    1717
    18         /* Define sys.argv.  It is up to the application if you
    19            want this; you can also let it undefined (since the Python
    20            code is generally not a main program it has no business
    21            touching sys.argv...) */
    22         PySys_SetArgv(argc, argv);
     18    /* Define sys.argv.  It is up to the application if you
     19       want this; you can also leave it undefined (since the Python
     20       code is generally not a main program it has no business
     21       touching sys.argv...)
    2322
    24         /* Do some application specific code */
    25         printf("Hello, brave new world\n\n");
     23       If the third argument is true, sys.path is modified to include
     24       either the directory containing the script named by argv[0], or
     25       the current working directory.  This can be risky; if you run
     26       an application embedding Python in a directory controlled by
     27       someone else, attackers could put a Trojan-horse module in the
     28       directory (say, a file named os.py) that your application would
     29       then import and run.
     30    */
     31    PySys_SetArgvEx(argc, argv, 0);
    2632
    27         /* Execute some Python statements (in module __main__) */
    28         PyRun_SimpleString("import sys\n");
    29         PyRun_SimpleString("print sys.builtin_module_names\n");
    30         PyRun_SimpleString("print sys.modules.keys()\n");
    31         PyRun_SimpleString("print sys.executable\n");
    32         PyRun_SimpleString("print sys.argv\n");
     33    /* Do some application specific code */
     34    printf("Hello, brave new world\n\n");
    3335
    34         /* Note that you can call any public function of the Python
    35            interpreter here, e.g. call_object(). */
     36    /* Execute some Python statements (in module __main__) */
     37    PyRun_SimpleString("import sys\n");
     38    PyRun_SimpleString("print sys.builtin_module_names\n");
     39    PyRun_SimpleString("print sys.modules.keys()\n");
     40    PyRun_SimpleString("print sys.executable\n");
     41    PyRun_SimpleString("print sys.argv\n");
    3642
    37         /* Some more application specific code */
    38         printf("\nGoodbye, cruel world\n");
     43    /* Note that you can call any public function of the Python
     44       interpreter here, e.g. call_object(). */
    3945
    40         /* Exit, cleaning up the interpreter */
    41         Py_Exit(0);
    42         /*NOTREACHED*/
     46    /* Some more application specific code */
     47    printf("\nGoodbye, cruel world\n");
     48
     49    /* Exit, cleaning up the interpreter */
     50    Py_Exit(0);
     51    /*NOTREACHED*/
    4352}
    4453
     
    4958xyzzy_foo(PyObject *self, PyObject* args)
    5059{
    51         return PyInt_FromLong(42L);
     60    return PyInt_FromLong(42L);
    5261}
    5362
    5463static PyMethodDef xyzzy_methods[] = {
    55         {"foo",         xyzzy_foo,      METH_NOARGS,
    56         "Return the meaning of everything."},
    57         {NULL,          NULL}           /* sentinel */
     64    {"foo",             xyzzy_foo,      METH_NOARGS,
     65    "Return the meaning of everything."},
     66    {NULL,              NULL}           /* sentinel */
    5867};
    5968
     
    6170initxyzzy(void)
    6271{
    63         PyImport_AddModule("xyzzy");
    64         Py_InitModule("xyzzy", xyzzy_methods);
     72    PyImport_AddModule("xyzzy");
     73    Py_InitModule("xyzzy", xyzzy_methods);
    6574}
  • python/vendor/current/Demo/embed/loop.c

    r2 r388  
    77main(int argc, char **argv)
    88{
    9         int count = -1;
    10         char *command;
     9    int count = -1;
     10    char *command;
    1111
    12         if (argc < 2 || argc > 3) {
    13                 fprintf(stderr, "usage: loop <python-command> [count]\n");
    14                 exit(2);
    15         }
    16         command = argv[1];
     12    if (argc < 2 || argc > 3) {
     13        fprintf(stderr, "usage: loop <python-command> [count]\n");
     14        exit(2);
     15    }
     16    command = argv[1];
    1717
    18         if (argc == 3) {
    19                 count = atoi(argv[2]);
    20         }
     18    if (argc == 3) {
     19        count = atoi(argv[2]);
     20    }
    2121
    22         Py_SetProgramName(argv[0]);
     22    Py_SetProgramName(argv[0]);
    2323
    24         /* uncomment this if you don't want to load site.py */
    25         /* Py_NoSiteFlag = 1; */
     24    /* uncomment this if you don't want to load site.py */
     25    /* Py_NoSiteFlag = 1; */
    2626
    27         while (count == -1 || --count >= 0 ) {
    28                 Py_Initialize();
    29                 PyRun_SimpleString(command);
    30                 Py_Finalize();
    31         }
    32         return 0;
     27    while (count == -1 || --count >= 0 ) {
     28        Py_Initialize();
     29        PyRun_SimpleString(command);
     30        Py_Finalize();
     31    }
     32    return 0;
    3333}
  • python/vendor/current/Demo/newmetaclasses/Eiffel.py

    r2 r388  
    3030            post = dict.get("%s_post" % m)
    3131            if pre or post:
    32                 dict[k] = cls.make_eiffel_method(dict[m], pre, post)
     32                dict[m] = cls.make_eiffel_method(dict[m], pre, post)
    3333
    3434class EiffelMetaClass1(EiffelBaseMetaClass):
  • python/vendor/current/Demo/parser/README

    r2 r388  
    77------
    88
    9         FILES        -- list of files associated with the parser module.
     9    FILES        -- list of files associated with the parser module.
    1010
    11         README       -- this file.
     11    README       -- this file.
    1212
    13         example.py   -- module that uses the `parser' module to extract
    14                         information from the parse tree of Python source
    15                         code.
     13    docstring.py -- sample source file containing only a module docstring.
    1614
    17         docstring.py -- sample source file containing only a module docstring.
     15    example.py   -- module that uses the `parser' module to extract
     16                    information from the parse tree of Python source
     17                    code.
    1818
    19         simple.py    -- sample source containing a "short form" definition.
     19    simple.py    -- sample source containing a "short form" definition.
    2020
    21         source.py    -- sample source code used to demonstrate ability to
    22                         handle nested constructs easily using the functions
    23                         and classes in example.py.
     21    source.py    -- sample source code used to demonstrate ability to
     22                    handle nested constructs easily using the functions
     23                    and classes in example.py.
    2424
    25         test_parser.py  program to put the parser module through its paces.
     25    test_parser.py  program to put the parser module through its paces.
    2626
    27         unparse.py      AST (2.5) based example to recreate source code
    28                         from an AST. This is incomplete; contributions
    29                         are welcome.
     27    test_unparse.py tests for the unparse module
     28
     29    unparse.py      AST (2.7) based example to recreate source code
     30                    from an AST.
    3031
    3132Enjoy!
  • python/vendor/current/Demo/parser/test_parser.py

    r2 r388  
    1212    print '----', fileName,
    1313    try:
    14         ast = parser.suite(t)
    15         tup = parser.ast2tuple(ast)
    16         # this discards the first AST; a huge memory savings when running
     14        st = parser.suite(t)
     15        tup = parser.st2tuple(st)
     16        # this discards the first ST; a huge memory savings when running
    1717        # against a large source file like Tkinter.py.
    18         ast = None
    19         new = parser.tuple2ast(tup)
     18        st = None
     19        new = parser.tuple2st(tup)
    2020    except parser.ParserError, err:
    2121        print
     
    2424        _numFailed = _numFailed + 1
    2525    else:
    26         if tup != parser.ast2tuple(new):
     26        if tup != parser.st2tuple(new):
    2727            print
    2828            print 'parser module failed on input file', fileName
  • python/vendor/current/Demo/parser/unparse.py

    r2 r388  
    11"Usage: unparse.py <path to source file>"
    22import sys
    3 import _ast
     3import ast
    44import cStringIO
    55import os
     6
     7# Large float and imaginary literals get turned into infinities in the AST.
     8# We unparse those infinities to INFSTR.
     9INFSTR = "1e" + repr(sys.float_info.max_10_exp + 1)
    610
    711def interleave(inter, f, seq):
     
    1014    seq = iter(seq)
    1115    try:
    12         f(seq.next())
     16        f(next(seq))
    1317    except StopIteration:
    1418        pass
     
    2125    """Methods in this class recursively traverse an AST and
    2226    output source code for the abstract syntax; original formatting
    23     is disregarged. """
     27    is disregarded. """
    2428
    2529    def __init__(self, tree, file = sys.stdout):
     
    2731         Print the source for tree to file."""
    2832        self.f = file
     33        self.future_imports = []
    2934        self._indent = 0
    3035        self.dispatch(tree)
    31         print >>self.f,""
     36        self.f.write("")
    3237        self.f.flush()
    3338
     
    8085
    8186    def _ImportFrom(self, t):
     87        # A from __future__ import may affect unparsing, so record it.
     88        if t.module and t.module == '__future__':
     89            self.future_imports.extend(n.name for n in t.names)
     90
    8291        self.fill("from ")
    83         self.write(t.module)
     92        self.write("." * t.level)
     93        if t.module:
     94            self.write(t.module)
    8495        self.write(" import ")
    8596        interleave(lambda: self.write(", "), self.dispatch, t.names)
    86         # XXX(jpe) what is level for?
    8797
    8898    def _Assign(self, t):
     
    116126    def _Delete(self, t):
    117127        self.fill("del ")
    118         self.dispatch(t.targets)
     128        interleave(lambda: self.write(", "), self.dispatch, t.targets)
    119129
    120130    def _Assert(self, t):
     
    187197
    188198    def _TryFinally(self, t):
    189         self.fill("try")
    190         self.enter()
    191         self.dispatch(t.body)
    192         self.leave()
     199        if len(t.body) == 1 and isinstance(t.body[0], ast.TryExcept):
     200            # try-except-finally
     201            self.dispatch(t.body)
     202        else:
     203            self.fill("try")
     204            self.enter()
     205            self.dispatch(t.body)
     206            self.leave()
    193207
    194208        self.fill("finally")
     
    203217            self.dispatch(t.type)
    204218        if t.name:
    205             self.write(", ")
     219            self.write(" as ")
    206220            self.dispatch(t.name)
    207221        self.enter()
     
    211225    def _ClassDef(self, t):
    212226        self.write("\n")
     227        for deco in t.decorator_list:
     228            self.fill("@")
     229            self.dispatch(deco)
    213230        self.fill("class "+t.name)
    214231        if t.bases:
     
    246263            self.enter()
    247264            self.dispatch(t.orelse)
    248             self.leave
     265            self.leave()
    249266
    250267    def _If(self, t):
     
    252269        self.dispatch(t.test)
    253270        self.enter()
    254         # XXX elif?
    255         self.dispatch(t.body)
    256         self.leave()
     271        self.dispatch(t.body)
     272        self.leave()
     273        # collapse nested ifs into equivalent elifs.
     274        while (t.orelse and len(t.orelse) == 1 and
     275               isinstance(t.orelse[0], ast.If)):
     276            t = t.orelse[0]
     277            self.fill("elif ")
     278            self.dispatch(t.test)
     279            self.enter()
     280            self.dispatch(t.body)
     281            self.leave()
     282        # final else
    257283        if t.orelse:
    258284            self.fill("else")
     
    271297            self.enter()
    272298            self.dispatch(t.orelse)
    273             self.leave
     299            self.leave()
    274300
    275301    def _With(self, t):
     
    285311    # expr
    286312    def _Str(self, tree):
    287         self.write(repr(tree.s))
     313        # if from __future__ import unicode_literals is in effect,
     314        # then we want to output string literals using a 'b' prefix
     315        # and unicode literals with no prefix.
     316        if "unicode_literals" not in self.future_imports:
     317            self.write(repr(tree.s))
     318        elif isinstance(tree.s, str):
     319            self.write("b" + repr(tree.s))
     320        elif isinstance(tree.s, unicode):
     321            self.write(repr(tree.s).lstrip("u"))
     322        else:
     323            assert False, "shouldn't get here"
    288324
    289325    def _Name(self, t):
     
    296332
    297333    def _Num(self, t):
    298         self.write(repr(t.n))
     334        repr_n = repr(t.n)
     335        # Parenthesize negative numbers, to avoid turning (-1)**2 into -1**2.
     336        if repr_n.startswith("-"):
     337            self.write("(")
     338        # Substitute overflowing decimal literal for AST infinities.
     339        self.write(repr_n.replace("inf", INFSTR))
     340        if repr_n.startswith("-"):
     341            self.write(")")
    299342
    300343    def _List(self, t):
     
    316359            self.dispatch(gen)
    317360        self.write(")")
     361
     362    def _SetComp(self, t):
     363        self.write("{")
     364        self.dispatch(t.elt)
     365        for gen in t.generators:
     366            self.dispatch(gen)
     367        self.write("}")
     368
     369    def _DictComp(self, t):
     370        self.write("{")
     371        self.dispatch(t.key)
     372        self.write(": ")
     373        self.dispatch(t.value)
     374        for gen in t.generators:
     375            self.dispatch(gen)
     376        self.write("}")
    318377
    319378    def _comprehension(self, t):
     
    335394        self.write(")")
    336395
     396    def _Set(self, t):
     397        assert(t.elts) # should be at least one element
     398        self.write("{")
     399        interleave(lambda: self.write(", "), self.dispatch, t.elts)
     400        self.write("}")
     401
    337402    def _Dict(self, t):
    338403        self.write("{")
    339         def writem((k, v)):
     404        def write_pair(pair):
     405            (k, v) = pair
    340406            self.dispatch(k)
    341407            self.write(": ")
    342408            self.dispatch(v)
    343         interleave(lambda: self.write(", "), writem, zip(t.keys, t.values))
     409        interleave(lambda: self.write(", "), write_pair, zip(t.keys, t.values))
    344410        self.write("}")
    345411
     
    356422    unop = {"Invert":"~", "Not": "not", "UAdd":"+", "USub":"-"}
    357423    def _UnaryOp(self, t):
     424        self.write("(")
    358425        self.write(self.unop[t.op.__class__.__name__])
    359         self.write("(")
    360         self.dispatch(t.operand)
     426        self.write(" ")
     427        # If we're applying unary minus to a number, parenthesize the number.
     428        # This is necessary: -2147483648 is different from -(2147483648) on
     429        # a 32-bit machine (the first is an int, the second a long), and
     430        # -7j is different from -(7j).  (The first has real part 0.0, the second
     431        # has real part -0.0.)
     432        if isinstance(t.op, ast.USub) and isinstance(t.operand, ast.Num):
     433            self.write("(")
     434            self.dispatch(t.operand)
     435            self.write(")")
     436        else:
     437            self.dispatch(t.operand)
    361438        self.write(")")
    362439
    363440    binop = { "Add":"+", "Sub":"-", "Mult":"*", "Div":"/", "Mod":"%",
    364                     "LShift":">>", "RShift":"<<", "BitOr":"|", "BitXor":"^", "BitAnd":"&",
     441                    "LShift":"<<", "RShift":">>", "BitOr":"|", "BitXor":"^", "BitAnd":"&",
    365442                    "FloorDiv":"//", "Pow": "**"}
    366443    def _BinOp(self, t):
     
    379456            self.write(" " + self.cmpops[o.__class__.__name__] + " ")
    380457            self.dispatch(e)
    381             self.write(")")
    382 
    383     boolops = {_ast.And: 'and', _ast.Or: 'or'}
     458        self.write(")")
     459
     460    boolops = {ast.And: 'and', ast.Or: 'or'}
    384461    def _BoolOp(self, t):
    385462        self.write("(")
     
    390467    def _Attribute(self,t):
    391468        self.dispatch(t.value)
     469        # Special case: 3.__abs__() is a syntax error, so if t.value
     470        # is an integer literal then we need to either parenthesize
     471        # it or add an extra space to get 3 .__abs__().
     472        if isinstance(t.value, ast.Num) and isinstance(t.value.n, int):
     473            self.write(" ")
    392474        self.write(".")
    393475        self.write(t.attr)
     
    446528    def _arguments(self, t):
    447529        first = True
    448         nonDef = len(t.args)-len(t.defaults)
    449         for a in t.args[0:nonDef]:
    450             if first:first = False
    451             else: self.write(", ")
    452             self.dispatch(a)
    453         for a,d in zip(t.args[nonDef:], t.defaults):
     530        # normal arguments
     531        defaults = [None] * (len(t.args) - len(t.defaults)) + t.defaults
     532        for a,d in zip(t.args, defaults):
    454533            if first:first = False
    455534            else: self.write(", ")
    456535            self.dispatch(a),
    457             self.write("=")
    458             self.dispatch(d)
     536            if d:
     537                self.write("=")
     538                self.dispatch(d)
     539
     540        # varargs
    459541        if t.vararg:
    460542            if first:first = False
    461543            else: self.write(", ")
    462             self.write("*"+t.vararg)
     544            self.write("*")
     545            self.write(t.vararg)
     546
     547        # kwargs
    463548        if t.kwarg:
    464549            if first:first = False
     
    472557
    473558    def _Lambda(self, t):
     559        self.write("(")
    474560        self.write("lambda ")
    475561        self.dispatch(t.args)
    476562        self.write(": ")
    477563        self.dispatch(t.body)
     564        self.write(")")
    478565
    479566    def _alias(self, t):
     
    483570
    484571def roundtrip(filename, output=sys.stdout):
    485     source = open(filename).read()
    486     tree = compile(source, filename, "exec", _ast.PyCF_ONLY_AST)
     572    with open(filename, "r") as pyfile:
     573        source = pyfile.read()
     574    tree = compile(source, filename, "exec", ast.PyCF_ONLY_AST)
    487575    Unparser(tree, output)
    488576
     
    493581        names = [n for n in os.listdir(a) if n.endswith('.py')]
    494582    except OSError:
    495         print >> sys.stderr, "Directory not readable: %s" % a
     583        sys.stderr.write("Directory not readable: %s" % a)
    496584    else:
    497585        for n in names:
     
    502590                try:
    503591                    roundtrip(fullname, output)
    504                 except Exception, e:
     592                except Exception as e:
    505593                    print '  Failed to compile, exception is %s' % repr(e)
    506594            elif os.path.isdir(fullname):
  • python/vendor/current/Demo/pdist/FSProxy.py

    r2 r388  
    2424import fnmatch
    2525
    26 if os.name == 'mac':
    27     import macfs
    28     maxnamelen = 31
    29 else:
    30     macfs = None
    31     maxnamelen = 255
     26maxnamelen = 255
    3227
    3328skipnames = (os.curdir, os.pardir)
     
    6459
    6560    def _hidden(self, name):
    66         if os.name == 'mac':
    67             return name[0] == '(' and name[-1] == ')'
    68         else:
    69             return name[0] == '.'
     61        return name[0] == '.'
    7062
    7163    def _hide(self, name):
    72         if os.name == 'mac':
    73             return '(%s)' % name
    74         else:
    75             return '.%s' % name
     64        return '.%s' % name
    7665
    7766    def visible(self, name):
     
    8271        head, tail = os.path.split(name)
    8372        if head or not tail: return 0
    84         if macfs:
    85             if os.path.exists(name) and not os.path.isdir(name):
    86                 try:
    87                     fs = macfs.FSSpec(name)
    88                     c, t = fs.GetCreatorType()
    89                     if t != 'TEXT': return 0
    90                 except macfs.error, msg:
    91                     print "***", name, msg
    92                     return 0
    93         else:
    94             if os.path.islink(name): return 0
    95             if '\0' in open(name, 'rb').read(512): return 0
     73        if os.path.islink(name): return 0
     74        if '\0' in open(name, 'rb').read(512): return 0
    9675        for ign in self._ignore:
    9776            if fnmatch.fnmatch(name, ign): return 0
  • python/vendor/current/Demo/pysvr/pysvr.c

    r2 r388  
    3535
    3636struct workorder {
    37         int conn;
    38         struct sockaddr_in addr;
     37    int conn;
     38    struct sockaddr_in addr;
    3939};
    4040
     
    5656main(int argc, char **argv)
    5757{
    58         int port = PORT;
    59         int c;
    60 
    61         if (argc > 0 && argv[0] != NULL && argv[0][0] != '\0')
    62                 progname = argv[0];
    63 
    64         while ((c = getopt(argc, argv, "v")) != EOF) {
    65                 switch (c) {
    66                 case 'v':
    67                         Py_VerboseFlag++;
    68                         break;
    69                 default:
    70                         usage();
    71                 }
    72         }
    73 
    74         if (optind < argc) {
    75                 if (optind+1 < argc) {
    76                         oprogname();
    77                         fprintf(stderr, "too many arguments\n");
    78                         usage();
    79                 }
    80                 port = atoi(argv[optind]);
    81                 if (port <= 0) {
    82                         fprintf(stderr, "bad port (%s)\n", argv[optind]);
    83                         usage();
    84                 }
    85         }
    86 
    87         main_thread(port);
    88 
    89         fprintf(stderr, "Bye.\n");
    90 
    91         exit(0);
     58    int port = PORT;
     59    int c;
     60
     61    if (argc > 0 && argv[0] != NULL && argv[0][0] != '\0')
     62        progname = argv[0];
     63
     64    while ((c = getopt(argc, argv, "v")) != EOF) {
     65        switch (c) {
     66        case 'v':
     67            Py_VerboseFlag++;
     68            break;
     69        default:
     70            usage();
     71        }
     72    }
     73
     74    if (optind < argc) {
     75        if (optind+1 < argc) {
     76            oprogname();
     77            fprintf(stderr, "too many arguments\n");
     78            usage();
     79        }
     80        port = atoi(argv[optind]);
     81        if (port <= 0) {
     82            fprintf(stderr, "bad port (%s)\n", argv[optind]);
     83            usage();
     84        }
     85    }
     86
     87    main_thread(port);
     88
     89    fprintf(stderr, "Bye.\n");
     90
     91    exit(0);
    9292}
    9393
     
    9797usage(void)
    9898{
    99         fprintf(stderr, usage_line, progname);
    100         exit(2);
     99    fprintf(stderr, usage_line, progname);
     100    exit(2);
    101101}
    102102
     
    104104main_thread(int port)
    105105{
    106         int sock, conn, size, i;
    107         struct sockaddr_in addr, clientaddr;
    108 
    109         sock = socket(PF_INET, SOCK_STREAM, 0);
    110         if (sock < 0) {
    111                 oprogname();
    112                 perror("can't create socket");
    113                 exit(1);
    114         }
     106    int sock, conn, size, i;
     107    struct sockaddr_in addr, clientaddr;
     108
     109    sock = socket(PF_INET, SOCK_STREAM, 0);
     110    if (sock < 0) {
     111        oprogname();
     112        perror("can't create socket");
     113        exit(1);
     114    }
    115115
    116116#ifdef SO_REUSEADDR
    117         i = 1;
    118         setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &i, sizeof i);
     117    i = 1;
     118    setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &i, sizeof i);
    119119#endif
    120120
    121         memset((char *)&addr, '\0', sizeof addr);
    122         addr.sin_family = AF_INET;
    123         addr.sin_port = htons(port);
    124         addr.sin_addr.s_addr = 0L;
    125         if (bind(sock, (struct sockaddr *)&addr, sizeof addr) < 0) {
    126                 oprogname();
    127                 perror("can't bind socket to address");
    128                 exit(1);
    129         }
    130 
    131         if (listen(sock, 5) < 0) {
    132                 oprogname();
    133                 perror("can't listen on socket");
    134                 exit(1);
    135         }
    136 
    137         fprintf(stderr, "Listening on port %d...\n", port);
    138 
    139         for (i = 0; ; i++) {
    140                 size = sizeof clientaddr;
    141                 memset((char *) &clientaddr, '\0', size);
    142                 conn = accept(sock, (struct sockaddr *) &clientaddr, &size);
    143                 if (conn < 0) {
    144                         oprogname();
    145                         perror("can't accept connection from socket");
    146                         exit(1);
    147                 }
    148 
    149                 size = sizeof addr;
    150                 memset((char *) &addr, '\0', size);
    151                 if (getsockname(conn, (struct sockaddr *)&addr, &size) < 0) {
    152                         oprogname();
    153                         perror("can't get socket name of connection");
    154                         exit(1);
    155                 }
    156                 if (clientaddr.sin_addr.s_addr != addr.sin_addr.s_addr) {
    157                         oprogname();
    158                         perror("connection from non-local host refused");
    159                         fprintf(stderr, "(addr=%lx, clientaddr=%lx)\n",
    160                                 ntohl(addr.sin_addr.s_addr),
    161                                 ntohl(clientaddr.sin_addr.s_addr));
    162                         close(conn);
    163                         continue;
    164                 }
    165                 if (i == 4) {
    166                         close(conn);
    167                         break;
    168                 }
    169                 create_thread(conn, &clientaddr);
    170         }
    171 
    172         close(sock);
    173 
    174         if (gtstate) {
    175                 PyEval_AcquireThread(gtstate);
    176                 gtstate = NULL;
    177                 Py_Finalize();
    178                 /* And a second time, just because we can. */
    179                 Py_Finalize(); /* This should be harmless. */
    180         }
    181         exit(0);
     121    memset((char *)&addr, '\0', sizeof addr);
     122    addr.sin_family = AF_INET;
     123    addr.sin_port = htons(port);
     124    addr.sin_addr.s_addr = 0L;
     125    if (bind(sock, (struct sockaddr *)&addr, sizeof addr) < 0) {
     126        oprogname();
     127        perror("can't bind socket to address");
     128        exit(1);
     129    }
     130
     131    if (listen(sock, 5) < 0) {
     132        oprogname();
     133        perror("can't listen on socket");
     134        exit(1);
     135    }
     136
     137    fprintf(stderr, "Listening on port %d...\n", port);
     138
     139    for (i = 0; ; i++) {
     140        size = sizeof clientaddr;
     141        memset((char *) &clientaddr, '\0', size);
     142        conn = accept(sock, (struct sockaddr *) &clientaddr, &size);
     143        if (conn < 0) {
     144            oprogname();
     145            perror("can't accept connection from socket");
     146            exit(1);
     147        }
     148
     149        size = sizeof addr;
     150        memset((char *) &addr, '\0', size);
     151        if (getsockname(conn, (struct sockaddr *)&addr, &size) < 0) {
     152            oprogname();
     153            perror("can't get socket name of connection");
     154            exit(1);
     155        }
     156        if (clientaddr.sin_addr.s_addr != addr.sin_addr.s_addr) {
     157            oprogname();
     158            perror("connection from non-local host refused");
     159            fprintf(stderr, "(addr=%lx, clientaddr=%lx)\n",
     160                ntohl(addr.sin_addr.s_addr),
     161                ntohl(clientaddr.sin_addr.s_addr));
     162            close(conn);
     163            continue;
     164        }
     165        if (i == 4) {
     166            close(conn);
     167            break;
     168        }
     169        create_thread(conn, &clientaddr);
     170    }
     171
     172    close(sock);
     173
     174    if (gtstate) {
     175        PyEval_AcquireThread(gtstate);
     176        gtstate = NULL;
     177        Py_Finalize();
     178        /* And a second time, just because we can. */
     179        Py_Finalize(); /* This should be harmless. */
     180    }
     181    exit(0);
    182182}
    183183
     
    185185create_thread(int conn, struct sockaddr_in *addr)
    186186{
    187         struct workorder *work;
    188         pthread_t tdata;
    189 
    190         work = malloc(sizeof(struct workorder));
    191         if (work == NULL) {
    192                 oprogname();
    193                 fprintf(stderr, "out of memory for thread.\n");
    194                 close(conn);
    195                 return;
    196         }
    197         work->conn = conn;
    198         work->addr = *addr;
    199 
    200         init_python();
    201 
    202         if (pthread_create(&tdata, NULL, (void *)service_thread, work) < 0) {
    203                 oprogname();
    204                 perror("can't create new thread");
    205                 close(conn);
    206                 return;
    207         }
    208 
    209         if (pthread_detach(tdata) < 0) {
    210                 oprogname();
    211                 perror("can't detach from thread");
    212         }
     187    struct workorder *work;
     188    pthread_t tdata;
     189
     190    work = malloc(sizeof(struct workorder));
     191    if (work == NULL) {
     192        oprogname();
     193        fprintf(stderr, "out of memory for thread.\n");
     194        close(conn);
     195        return;
     196    }
     197    work->conn = conn;
     198    work->addr = *addr;
     199
     200    init_python();
     201
     202    if (pthread_create(&tdata, NULL, (void *)service_thread, work) < 0) {
     203        oprogname();
     204        perror("can't create new thread");
     205        close(conn);
     206        return;
     207    }
     208
     209    if (pthread_detach(tdata) < 0) {
     210        oprogname();
     211        perror("can't detach from thread");
     212    }
    213213}
    214214
     
    220220init_python(void)
    221221{
    222         if (gtstate)
    223                 return;
    224         Py_Initialize(); /* Initialize the interpreter */
    225         PyEval_InitThreads(); /* Create (and acquire) the interpreter lock */
    226         gtstate = PyEval_SaveThread(); /* Release the thread state */
     222    if (gtstate)
     223        return;
     224    Py_Initialize(); /* Initialize the interpreter */
     225    PyEval_InitThreads(); /* Create (and acquire) the interpreter lock */
     226    gtstate = PyEval_SaveThread(); /* Release the thread state */
    227227}
    228228
     
    230230service_thread(struct workorder *work)
    231231{
    232         FILE *input, *output;
    233 
    234         fprintf(stderr, "Start thread for connection %d.\n", work->conn);
    235 
    236         ps();
    237 
    238         input = fdopen(work->conn, "r");
    239         if (input == NULL) {
    240                 oprogname();
    241                 perror("can't create input stream");
    242                 goto done;
    243         }
    244 
    245         output = fdopen(work->conn, "w");
    246         if (output == NULL) {
    247                 oprogname();
    248                 perror("can't create output stream");
    249                 fclose(input);
    250                 goto done;
    251         }
    252 
    253         setvbuf(input, NULL, _IONBF, 0);
    254         setvbuf(output, NULL, _IONBF, 0);
    255 
    256         run_interpreter(input, output);
    257 
    258         fclose(input);
    259         fclose(output);
     232    FILE *input, *output;
     233
     234    fprintf(stderr, "Start thread for connection %d.\n", work->conn);
     235
     236    ps();
     237
     238    input = fdopen(work->conn, "r");
     239    if (input == NULL) {
     240        oprogname();
     241        perror("can't create input stream");
     242        goto done;
     243    }
     244
     245    output = fdopen(work->conn, "w");
     246    if (output == NULL) {
     247        oprogname();
     248        perror("can't create output stream");
     249        fclose(input);
     250        goto done;
     251    }
     252
     253    setvbuf(input, NULL, _IONBF, 0);
     254    setvbuf(output, NULL, _IONBF, 0);
     255
     256    run_interpreter(input, output);
     257
     258    fclose(input);
     259    fclose(output);
    260260
    261261  done:
    262         fprintf(stderr, "End thread for connection %d.\n", work->conn);
    263         close(work->conn);
    264         free(work);
     262    fprintf(stderr, "End thread for connection %d.\n", work->conn);
     263    close(work->conn);
     264    free(work);
    265265}
    266266
     
    268268oprogname(void)
    269269{
    270         int save = errno;
    271         fprintf(stderr, "%s: ", progname);
    272         errno = save;
     270    int save = errno;
     271    fprintf(stderr, "%s: ", progname);
     272    errno = save;
    273273}
    274274
     
    276276run_interpreter(FILE *input, FILE *output)
    277277{
    278         PyThreadState *tstate;
    279         PyObject *new_stdin, *new_stdout;
    280         PyObject *mainmod, *globals;
    281         char buffer[1000];
    282         char *p, *q;
    283         int n, end;
    284 
    285         PyEval_AcquireLock();
    286         tstate = Py_NewInterpreter();
    287         if (tstate == NULL) {
    288                 fprintf(output, "Sorry -- can't create an interpreter\n");
    289                 return;
    290         }
    291 
    292         mainmod = PyImport_AddModule("__main__");
    293         globals = PyModule_GetDict(mainmod);
    294         Py_INCREF(globals);
    295 
    296         new_stdin = PyFile_FromFile(input, "<socket-in>", "r", NULL);
    297         new_stdout = PyFile_FromFile(output, "<socket-out>", "w", NULL);
    298 
    299         PySys_SetObject("stdin", new_stdin);
    300         PySys_SetObject("stdout", new_stdout);
    301         PySys_SetObject("stderr", new_stdout);
    302 
    303         for (n = 1; !PyErr_Occurred(); n++) {
    304                 Py_BEGIN_ALLOW_THREADS
    305                 fprintf(output, "%d> ", n);
    306                 p = fgets(buffer, sizeof buffer, input);
    307                 Py_END_ALLOW_THREADS
    308 
    309                 if (p == NULL)
    310                         break;
    311                 if (p[0] == '\377' && p[1] == '\354')
    312                         break;
    313 
    314                 q = strrchr(p, '\r');
    315                 if (q && q[1] == '\n' && q[2] == '\0') {
    316                         *q++ = '\n';
    317                         *q++ = '\0';
    318                 }
    319 
    320                 while (*p && isspace(*p))
    321                         p++;
    322                 if (p[0] == '#' || p[0] == '\0')
    323                         continue;
    324 
    325                 end = run_command(buffer, globals);
    326                 if (end < 0)
    327                         PyErr_Print();
    328 
    329                 if (end)
    330                         break;
    331         }
    332 
    333         Py_XDECREF(globals);
    334         Py_XDECREF(new_stdin);
    335         Py_XDECREF(new_stdout);
    336 
    337         Py_EndInterpreter(tstate);
    338         PyEval_ReleaseLock();
    339 
    340         fprintf(output, "Goodbye!\n");
     278    PyThreadState *tstate;
     279    PyObject *new_stdin, *new_stdout;
     280    PyObject *mainmod, *globals;
     281    char buffer[1000];
     282    char *p, *q;
     283    int n, end;
     284
     285    PyEval_AcquireLock();
     286    tstate = Py_NewInterpreter();
     287    if (tstate == NULL) {
     288        fprintf(output, "Sorry -- can't create an interpreter\n");
     289        return;
     290    }
     291
     292    mainmod = PyImport_AddModule("__main__");
     293    globals = PyModule_GetDict(mainmod);
     294    Py_INCREF(globals);
     295
     296    new_stdin = PyFile_FromFile(input, "<socket-in>", "r", NULL);
     297    new_stdout = PyFile_FromFile(output, "<socket-out>", "w", NULL);
     298
     299    PySys_SetObject("stdin", new_stdin);
     300    PySys_SetObject("stdout", new_stdout);
     301    PySys_SetObject("stderr", new_stdout);
     302
     303    for (n = 1; !PyErr_Occurred(); n++) {
     304        Py_BEGIN_ALLOW_THREADS
     305        fprintf(output, "%d> ", n);
     306        p = fgets(buffer, sizeof buffer, input);
     307        Py_END_ALLOW_THREADS
     308
     309        if (p == NULL)
     310            break;
     311        if (p[0] == '\377' && p[1] == '\354')
     312            break;
     313
     314        q = strrchr(p, '\r');
     315        if (q && q[1] == '\n' && q[2] == '\0') {
     316            *q++ = '\n';
     317            *q++ = '\0';
     318        }
     319
     320        while (*p && isspace(*p))
     321            p++;
     322        if (p[0] == '#' || p[0] == '\0')
     323            continue;
     324
     325        end = run_command(buffer, globals);
     326        if (end < 0)
     327            PyErr_Print();
     328
     329        if (end)
     330            break;
     331    }
     332
     333    Py_XDECREF(globals);
     334    Py_XDECREF(new_stdin);
     335    Py_XDECREF(new_stdout);
     336
     337    Py_EndInterpreter(tstate);
     338    PyEval_ReleaseLock();
     339
     340    fprintf(output, "Goodbye!\n");
    341341}
    342342
     
    344344run_command(char *buffer, PyObject *globals)
    345345{
    346         PyObject *m, *d, *v;
    347         fprintf(stderr, "run_command: %s", buffer);
    348         if (strchr(buffer, '\n') == NULL)
    349                 fprintf(stderr, "\n");
    350         v = PyRun_String(buffer, Py_single_input, globals, globals);
    351         if (v == NULL) {
    352                 if (PyErr_Occurred() == PyExc_SystemExit) {
    353                         PyErr_Clear();
    354                         return 1;
    355                 }
    356                 PyErr_Print();
    357                 return 0;
    358         }
    359         Py_DECREF(v);
    360         return 0;
     346    PyObject *m, *d, *v;
     347    fprintf(stderr, "run_command: %s", buffer);
     348    if (strchr(buffer, '\n') == NULL)
     349        fprintf(stderr, "\n");
     350    v = PyRun_String(buffer, Py_single_input, globals, globals);
     351    if (v == NULL) {
     352        if (PyErr_Occurred() == PyExc_SystemExit) {
     353            PyErr_Clear();
     354            return 1;
     355        }
     356        PyErr_Print();
     357        return 0;
     358    }
     359    Py_DECREF(v);
     360    return 0;
    361361}
    362362
     
    364364ps(void)
    365365{
    366         char buffer[100];
    367         PyOS_snprintf(buffer, sizeof(buffer),
    368                       "ps -l -p %d </dev/null | sed 1d\n", getpid());
    369         system(buffer);
    370 }
     366    char buffer[100];
     367    PyOS_snprintf(buffer, sizeof(buffer),
     368                  "ps -l -p %d </dev/null | sed 1d\n", getpid());
     369    system(buffer);
     370}
  • python/vendor/current/Demo/scripts/README

    r2 r388  
    33See also the Tools/scripts directory!
    44
    5 beer.py                 Print the classic 'bottles of beer' list.
     5beer.py                 Print the classic 'bottles of beer' list
    66eqfix.py                Fix .py files to use the correct equality test operator
    77fact.py                 Factorize numbers
    8 find-uname.py           Search for Unicode characters using regexps.
     8find-uname.py           Search for Unicode characters using regexps
    99from.py                 Summarize mailbox
    10 ftpstats.py             Summarize ftp daemon log file
    1110lpwatch.py              Watch BSD line printer queues
    1211makedir.py              Like mkdir -p
    1312markov.py               Markov chain simulation of words or characters
    14 mboxconvvert.py         Convert MH or MMDF mailboxes to unix mailbox format
    15 mkrcs.py                Fix symlinks named RCS into parallel tree
     13mboxconvert.py          Convert MH or MMDF mailboxes to unix mailbox format
    1614morse.py                Produce morse code (audible or on AIFF file)
     15newslist.py             List all newsgroups on a NNTP server as HTML pages
    1716pi.py                   Print all digits of pi -- given enough time and memory
    1817pp.py                   Emulate some Perl command line options
  • python/vendor/current/Demo/scripts/beer.py

    r2 r388  
    11#! /usr/bin/env python
     2
    23# By GvR, demystified after a version by Fredrik Lundh.
     4
    35import sys
     6
    47n = 100
    5 if sys.argv[1:]: n = int(sys.argv[1])
     8if sys.argv[1:]:
     9    n = int(sys.argv[1])
     10
    611def bottle(n):
    712    if n == 0: return "no more bottles of beer"
    813    if n == 1: return "one bottle of beer"
    914    return str(n) + " bottles of beer"
    10 for i in range(n):
    11     print bottle(n-i), "on the wall,"
    12     print bottle(n-i) + "."
     15
     16for i in range(n, 0, -1):
     17    print bottle(i), "on the wall,"
     18    print bottle(i) + "."
    1319    print "Take one down, pass it around,"
    14     print bottle(n-i-1), "on the wall."
     20    print bottle(i-1), "on the wall."
  • python/vendor/current/Demo/scripts/fact.py

    r2 r388  
    1010
    1111def fact(n):
    12     if n < 1: raise ValueError # fact() argument should be >= 1
    13     if n == 1: return []    # special case
     12    if n < 1:
     13        raise ValueError('fact() argument should be >= 1')
     14    if n == 1:
     15        return []  # special case
    1416    res = []
    15     # Treat even factors special, so we can use i = i+2 later
    16     while n%2 == 0:
     17    # Treat even factors special, so we can use i += 2 later
     18    while n % 2 == 0:
    1719        res.append(2)
    18         n = n//2
     20        n //= 2
    1921    # Try odd numbers up to sqrt(n)
    20     limit = sqrt(float(n+1))
     22    limit = sqrt(n+1)
    2123    i = 3
    2224    while i <= limit:
    23         if n%i == 0:
     25        if n % i == 0:
    2426            res.append(i)
    25             n = n//i
     27            n //= i
    2628            limit = sqrt(n+1)
    2729        else:
    28             i = i+2
     30            i += 2
    2931    if n != 1:
    3032        res.append(n)
     
    3335def main():
    3436    if len(sys.argv) > 1:
    35         for arg in sys.argv[1:]:
    36             n = eval(arg)
     37        source = sys.argv[1:]
     38    else:
     39        source = iter(raw_input, '')
     40    for arg in source:
     41        try:
     42            n = int(arg)
     43        except ValueError:
     44            print arg, 'is not an integer'
     45        else:
    3746            print n, fact(n)
    38     else:
    39         try:
    40             while 1:
    41                 n = input()
    42                 print n, fact(n)
    43         except EOFError:
    44             pass
    4547
    4648if __name__ == "__main__":
  • python/vendor/current/Demo/scripts/find-uname.py

    r2 r388  
    2222
    2323def main(args):
    24     unicode_names= []
     24    unicode_names = []
    2525    for ix in range(sys.maxunicode+1):
    2626        try:
    27             unicode_names.append( (ix, unicodedata.name(unichr(ix))) )
     27            unicode_names.append((ix, unicodedata.name(unichr(ix))))
    2828        except ValueError: # no name for the character
    2929            pass
    3030    for arg in args:
    3131        pat = re.compile(arg, re.I)
    32         matches = [(x,y) for (x,y) in unicode_names
    33                        if pat.search(y) is not None]
     32        matches = [(y,x) for (x,y) in unicode_names
     33                   if pat.search(y) is not None]
    3434        if matches:
    3535            print "***", arg, "matches", "***"
    36             for (x,y) in matches:
    37                 print "%s (%d)" % (y,x)
     36            for match in matches:
     37                print "%s (%d)" % match
    3838
    3939if __name__ == "__main__":
  • python/vendor/current/Demo/scripts/lpwatch.py

    r2 r388  
    44# Intended for BSD 4.3 lpq.
    55
    6 import posix
     6import os
    77import sys
    88import time
    9 import string
    109
    1110DEF_PRINTER = 'psc'
     
    1514    delay = DEF_DELAY # XXX Use getopt() later
    1615    try:
    17         thisuser = posix.environ['LOGNAME']
     16        thisuser = os.environ['LOGNAME']
    1817    except:
    19         thisuser = posix.environ['USER']
     18        thisuser = os.environ['USER']
    2019    printers = sys.argv[1:]
    2120    if printers:
    2221        # Strip '-P' from printer names just in case
    2322        # the user specified it...
    24         for i in range(len(printers)):
    25             if printers[i][:2] == '-P':
    26                 printers[i] = printers[i][2:]
     23        for i, name in enumerate(printers):
     24            if name[:2] == '-P':
     25                printers[i] = name[2:]
    2726    else:
    28         if posix.environ.has_key('PRINTER'):
    29             printers = [posix.environ['PRINTER']]
     27        if os.environ.has_key('PRINTER'):
     28            printers = [os.environ['PRINTER']]
    3029        else:
    3130            printers = [DEF_PRINTER]
    32     #
    33     clearhome = posix.popen('clear', 'r').read()
    34     #
    35     while 1:
     31
     32    clearhome = os.popen('clear', 'r').read()
     33
     34    while True:
    3635        text = clearhome
    3736        for name in printers:
    38             text = text + makestatus(name, thisuser) + '\n'
     37            text += makestatus(name, thisuser) + '\n'
    3938        print text
    4039        time.sleep(delay)
    4140
    4241def makestatus(name, thisuser):
    43     pipe = posix.popen('lpq -P' + name + ' 2>&1', 'r')
     42    pipe = os.popen('lpq -P' + name + ' 2>&1', 'r')
    4443    lines = []
    4544    users = {}
    4645    aheadbytes = 0
    4746    aheadjobs = 0
    48     userseen = 0
     47    userseen = False
    4948    totalbytes = 0
    5049    totaljobs = 0
    51     while 1:
    52         line = pipe.readline()
    53         if not line: break
    54         fields = string.split(line)
     50    for line in pipe:
     51        fields = line.split()
    5552        n = len(fields)
    5653        if len(fields) >= 6 and fields[n-1] == 'bytes':
    57             rank = fields[0]
    58             user = fields[1]
    59             job = fields[2]
     54            rank, user, job = fields[0:3]
    6055            files = fields[3:-2]
    61             bytes = eval(fields[n-2])
     56            bytes = int(fields[n-2])
    6257            if user == thisuser:
    63                 userseen = 1
     58                userseen = True
    6459            elif not userseen:
    65                 aheadbytes = aheadbytes + bytes
    66                 aheadjobs = aheadjobs + 1
    67             totalbytes = totalbytes + bytes
    68             totaljobs = totaljobs + 1
    69             if users.has_key(user):
    70                 ujobs, ubytes = users[user]
    71             else:
    72                 ujobs, ubytes = 0, 0
    73             ujobs = ujobs + 1
    74             ubytes = ubytes + bytes
     60                aheadbytes += bytes
     61                aheadjobs += 1
     62            totalbytes += bytes
     63            totaljobs += 1
     64            ujobs, ubytes = users.get(user, (0, 0))
     65            ujobs += 1
     66            ubytes += bytes
    7567            users[user] = ujobs, ubytes
    7668        else:
    77             if fields and fields[0] <> 'Rank':
    78                 line = string.strip(line)
     69            if fields and fields[0] != 'Rank':
     70                line = line.strip()
    7971                if line == 'no entries':
    8072                    line = name + ': idle'
     
    8274                    line = name
    8375                lines.append(line)
    84     #
     76
    8577    if totaljobs:
    86         line = '%d K' % ((totalbytes+1023)//1024)
    87         if totaljobs <> len(users):
    88             line = line + ' (%d jobs)' % totaljobs
     78        line = '%d K' % ((totalbytes+1023) // 1024)
     79        if totaljobs != len(users):
     80            line += ' (%d jobs)' % totaljobs
    8981        if len(users) == 1:
    90             line = line + ' for %s' % (users.keys()[0],)
     82            line += ' for %s' % (users.keys()[0],)
    9183        else:
    92             line = line + ' for %d users' % len(users)
     84            line += ' for %d users' % len(users)
    9385            if userseen:
    9486                if aheadjobs == 0:
    95                     line =  line + ' (%s first)' % thisuser
     87                    line += ' (%s first)' % thisuser
    9688                else:
    97                     line = line + ' (%d K before %s)' % (
    98                                    (aheadbytes+1023)//1024, thisuser)
     89                    line += ' (%d K before %s)' % (
     90                        (aheadbytes+1023) // 1024, thisuser)
    9991        lines.append(line)
    100     #
     92
    10193    sts = pipe.close()
    10294    if sts:
    10395        lines.append('lpq exit status %r' % (sts,))
    104     return string.joinfields(lines, ': ')
     96    return ': '.join(lines)
    10597
    10698if __name__ == "__main__":
  • python/vendor/current/Demo/scripts/markov.py

    r2 r388  
    66        self.choice = choice
    77        self.trans = {}
     8
    89    def add(self, state, next):
    9         if not self.trans.has_key(state):
    10             self.trans[state] = [next]
    11         else:
    12             self.trans[state].append(next)
     10        self.trans.setdefault(state, []).append(next)
     11
    1312    def put(self, seq):
    1413        n = self.histsize
     
    1817            add(seq[max(0, i-n):i], seq[i:i+1])
    1918        add(seq[len(seq)-n:], None)
     19
    2020    def get(self):
    2121        choice = self.choice
     
    2323        n = self.histsize
    2424        seq = choice(trans[None])
    25         while 1:
     25        while True:
    2626            subseq = seq[max(0, len(seq)-n):]
    2727            options = trans[subseq]
    2828            next = choice(options)
    29             if not next: break
    30             seq = seq + next
     29            if not next:
     30                break
     31            seq += next
    3132        return seq
    3233
     34
    3335def test():
    34     import sys, string, random, getopt
     36    import sys, random, getopt
    3537    args = sys.argv[1:]
    3638    try:
    37         opts, args = getopt.getopt(args, '0123456789cdw')
     39        opts, args = getopt.getopt(args, '0123456789cdwq')
    3840    except getopt.error:
    39         print 'Usage: markov [-#] [-cddqw] [file] ...'
     41        print 'Usage: %s [-#] [-cddqw] [file] ...' % sys.argv[0]
    4042        print 'Options:'
    4143        print '-#: 1-digit history size (default 2)'
     
    5052        print 'Output consists of paragraphs separated by blank'
    5153        print 'lines, where lines are no longer than 72 characters.'
     54        sys.exit(2)
    5255    histsize = 2
    53     do_words = 0
     56    do_words = False
    5457    debug = 1
    5558    for o, a in opts:
    56         if '-0' <= o <= '-9': histsize = eval(o[1:])
    57         if o == '-c': do_words = 0
    58         if o == '-d': debug = debug + 1
     59        if '-0' <= o <= '-9': histsize = int(o[1:])
     60        if o == '-c': do_words = False
     61        if o == '-d': debug += 1
    5962        if o == '-q': debug = 0
    60         if o == '-w': do_words = 1
    61     if not args: args = ['-']
     63        if o == '-w': do_words = True
     64    if not args:
     65        args = ['-']
     66
    6267    m = Markov(histsize, random.choice)
    6368    try:
     
    7378            text = f.read()
    7479            f.close()
    75             paralist = string.splitfields(text, '\n\n')
     80            paralist = text.split('\n\n')
    7681            for para in paralist:
    7782                if debug > 1: print 'feeding ...'
    78                 words = string.split(para)
     83                words = para.split()
    7984                if words:
    80                     if do_words: data = tuple(words)
    81                     else: data = string.joinfields(words, ' ')
     85                    if do_words:
     86                        data = tuple(words)
     87                    else:
     88                        data = ' '.join(words)
    8289                    m.put(data)
    8390    except KeyboardInterrupt:
     
    8794        return
    8895    if debug: print 'done.'
     96
    8997    if debug > 1:
    9098        for key in m.trans.keys():
     
    93101        if histsize == 0: print repr(''), m.trans['']
    94102        print
    95     while 1:
     103    while True:
    96104        data = m.get()
    97         if do_words: words = data
    98         else: words = string.split(data)
     105        if do_words:
     106            words = data
     107        else:
     108            words = data.split()
    99109        n = 0
    100110        limit = 72
     
    104114                n = 0
    105115            print w,
    106             n = n + len(w) + 1
     116            n += len(w) + 1
    107117        print
    108118        print
    109119
    110 def tuple(list):
    111     if len(list) == 0: return ()
    112     if len(list) == 1: return (list[0],)
    113     i = len(list)//2
    114     return tuple(list[:i]) + tuple(list[i:])
    115 
    116120if __name__ == "__main__":
    117121    test()
  • python/vendor/current/Demo/scripts/morse.py

    r2 r388  
     1#! /usr/bin/env python
     2
    13# DAH should be three DOTs.
    24# Space between DOTs and DAHs should be one DOT.
     
    3739        'Y': '-.--',            'y': '-.--',
    3840        'Z': '--..',            'z': '--..',
    39         '0': '-----',
    40         '1': '.----',
    41         '2': '..---',
    42         '3': '...--',
    43         '4': '....-',
    44         '5': '.....',
    45         '6': '-....',
    46         '7': '--...',
    47         '8': '---..',
    48         '9': '----.',
    49         ',': '--..--',
    50         '.': '.-.-.-',
    51         '?': '..--..',
    52         ';': '-.-.-.',
    53         ':': '---...',
    54         "'": '.----.',
    55         '-': '-....-',
    56         '/': '-..-.',
    57         '(': '-.--.-',
    58         ')': '-.--.-',
    59         '_': '..--.-',
    60         ' ': ' '
     41        '0': '-----',           ',': '--..--',
     42        '1': '.----',           '.': '.-.-.-',
     43        '2': '..---',           '?': '..--..',
     44        '3': '...--',           ';': '-.-.-.',
     45        '4': '....-',           ':': '---...',
     46        '5': '.....',           "'": '.----.',
     47        '6': '-....',           '-': '-....-',
     48        '7': '--...',           '/': '-..-.',
     49        '8': '---..',           '(': '-.--.-',
     50        '9': '----.',           ')': '-.--.-',
     51        ' ': ' ',               '_': '..--.-',
    6152}
     53
     54nowave = '\0' * 200
    6255
    6356# If we play at 44.1 kHz (which we do), then if we produce one sine
     
    6659# appears to be a nice one for playing morse code.
    6760def mkwave(octave):
    68     global sinewave, nowave
    6961    sinewave = ''
    7062    for i in range(100):
    71         val = int(math.sin(math.pi * float(i) * octave / 50.0) * 30000)
    72         sinewave = sinewave + chr((val >> 8) & 255) + chr(val & 255)
    73     nowave = '\0' * 200
     63        val = int(math.sin(math.pi * i * octave / 50.0) * 30000)
     64        sinewave += chr((val >> 8) & 255) + chr(val & 255)
     65    return sinewave
    7466
    75 mkwave(OCTAVE)
     67defaultwave = mkwave(OCTAVE)
    7668
    7769def main():
    78     import getopt, string
     70    import getopt
    7971    try:
    8072        opts, args = getopt.getopt(sys.argv[1:], 'o:p:')
    8173    except getopt.error:
    8274        sys.stderr.write('Usage ' + sys.argv[0] +
    83                          ' [ -o outfile ] [ args ] ...\n')
     75                         ' [ -o outfile ] [ -p octave ] [ words ] ...\n')
    8476        sys.exit(1)
    8577    dev = None
     78    wave = defaultwave
    8679    for o, a in opts:
    8780        if o == '-o':
     
    9285            dev.setnchannels(1)
    9386        if o == '-p':
    94             mkwave(string.atoi(a))
     87            wave = mkwave(int(a))
    9588    if not dev:
    9689        import audiodev
     
    10295        dev.writeframesraw = dev.writeframes
    10396    if args:
    104         line = string.join(args)
     97        source = [' '.join(args)]
    10598    else:
    106         line = sys.stdin.readline()
    107     while line:
     99        source = iter(sys.stdin.readline, '')
     100    for line in source:
    108101        mline = morse(line)
    109         play(mline, dev)
     102        play(mline, dev, wave)
    110103        if hasattr(dev, 'wait'):
    111104            dev.wait()
    112         if not args:
    113             line = sys.stdin.readline()
    114         else:
    115             line = ''
    116105    dev.close()
    117106
     
    122111    for c in line:
    123112        try:
    124             res = res + morsetab[c] + '\001'
     113            res += morsetab[c] + '\001'
    125114        except KeyError:
    126115            pass
     
    128117
    129118# Play a line of morse code.
    130 def play(line, dev):
     119def play(line, dev, wave):
    131120    for c in line:
    132121        if c == '.':
    133             sine(dev, DOT)
     122            sine(dev, DOT, wave)
    134123        elif c == '-':
    135             sine(dev, DAH)
     124            sine(dev, DAH, wave)
    136125        else:                   # space
    137126            pause(dev, DAH + DOT)
    138127        pause(dev, DOT)
    139128
    140 def sine(dev, length):
     129def sine(dev, length, wave):
    141130    for i in range(length):
    142         dev.writeframesraw(sinewave)
     131        dev.writeframesraw(wave)
    143132
    144133def pause(dev, length):
     
    146135        dev.writeframesraw(nowave)
    147136
    148 if __name__ == '__main__' or sys.argv[0] == __name__:
     137if __name__ == '__main__':
    149138    main()
  • python/vendor/current/Demo/scripts/newslist.py

    r2 r388  
    11#! /usr/bin/env python
    22#######################################################################
    3 # Newslist  $Revision: 66429 $
     3# Newslist  $Revision$
    44#
    55# Syntax:
     
    3333#                                                                     #
    3434#######################################################################
    35 import sys,nntplib, string, marshal, time, os, posix, string
     35import sys, nntplib, marshal, time, os
    3636
    3737#######################################################################
     
    4040# Top directory.
    4141# Filenames which don't start with / are taken as being relative to this.
    42 topdir='/anfs/qsbigdisc/web/html/newspage'
     42topdir = os.path.expanduser('~/newspage')
    4343
    4444# The name of your NNTP host
     
    4747# or use following to get the name from the NNTPSERVER environment
    4848# variable:
    49 #    newshost = posix.environ['NNTPSERVER']
    50 newshost = 'nntp-serv.cl.cam.ac.uk'
     49#    newshost = os.environ['NNTPSERVER']
     50newshost = 'news.example.com'
    5151
    5252# The filename for a local cache of the newsgroup list
     
    8282# further pages. This helps to make important links stand out.
    8383# Set to '' if not wanted, or '...' is quite a good one.
    84 pagelinkicon='... <img src="http://pelican.cl.cam.ac.uk/icons/page.xbm"> '
     84pagelinkicon = '... <img src="http://pelican.cl.cam.ac.uk/icons/page.xbm"> '
    8585
    8686# ---------------------------------------------------------------------
     
    106106from stat import *
    107107
    108 rcsrev = '$Revision: 66429 $'
    109 rcsrev = string.join(filter(lambda s: '$' not in s, string.split(rcsrev)))
     108rcsrev = '$Revision$'
     109rcsrev = ' '.join(filter(lambda s: '$' not in s, rcsrev.split()))
    110110desc = {}
    111111
     
    121121    print 'Updating tree...'
    122122    for i in groups:
    123         parts = string.splitfields(i,'.')
     123        parts = i.split('.')
    124124        makeleaf(tree, parts)
    125125
     
    129129    l = len(path)
    130130
    131     if not tree.has_key(j):
     131    if j not in tree:
    132132        tree[j] = {}
    133133    if l == 1:
     
    142142
    143143def createpage(root, tree, p):
    144     filename = os.path.join(pagedir,root+'.html')
     144    filename = os.path.join(pagedir, root+'.html')
    145145    if root == rootpage:
    146146        detail = ''
    147147    else:
    148148        detail = ' under ' + root
    149     f = open(filename,'w')
    150     # f.write('Content-Type: text/html\n')
    151     f.write('<TITLE>Newsgroups available' + detail + '</TITLE>\n')
    152     f.write('<H1>Newsgroups available' + detail +'</H1>\n')
    153     f.write('<A HREF="'+httppref+rootpage+'.html">Back to top level</A><P>\n')
    154     printtree(f,tree,0,p)
    155     f.write('<I>This page automatically created by \'newslist\' v. '+rcsrev+'.')
    156     f.write(time.ctime(time.time()) + '</I><P>')
    157     f.close()
     149    with open(filename, 'w') as f:
     150        # f.write('Content-Type: text/html\n')
     151        f.write('<html>\n<head>\n')
     152        f.write('<title>Newsgroups available%s</title>\n' % detail)
     153        f.write('</head>\n<body>\n')
     154        f.write('<h1>Newsgroups available%s</h1>\n' % detail)
     155        f.write('<a href="%s%s.html">Back to top level</a><p>\n' %
     156                (httppref, rootpage))
     157        printtree(f, tree, 0, p)
     158        f.write('\n<p>')
     159        f.write("<i>This page automatically created by 'newslist' v. %s." %
     160                rcsrev)
     161        f.write(time.ctime(time.time()) + '</i>\n')
     162        f.write('</body>\n</html>\n')
    158163
    159164# Printtree prints the groups as a bulleted list.  Groups with
     
    162167
    163168def printtree(f, tree, indent, p):
    164     global desc
    165169    l = len(tree)
    166170
    167     if l > sublistsize and indent>0:
     171    if l > sublistsize and indent > 0:
    168172        # Create a new page and a link to it
    169         f.write('<LI><B><A HREF="'+httppref+p[1:]+'.html">')
    170         f.write(p[1:]+'.*')
    171         f.write('</A></B>'+pagelinkicon+'\n')
     173        f.write('<li><b><a href="%s%s.html">' % (httppref, p[1:]))
     174        f.write(p[1:] + '.*')
     175        f.write('</a></b>%s\n' % pagelinkicon)
    172176        createpage(p[1:], tree, p)
    173177        return
     
    179183        if indent > 0:
    180184            # Create a sub-list
    181             f.write('<LI>'+p[1:]+'\n<UL>')
     185            f.write('<li>%s\n<ul>' % p[1:])
    182186        else:
    183187            # Create a main list
    184             f.write('<UL>')
     188            f.write('<ul>')
    185189        indent = indent + 1
    186190
     
    188192        if i == '.':
    189193            # Output a newsgroup
    190             f.write('<LI><A HREF="news:' + p[1:] + '">'+ p[1:] + '</A> ')
    191             if desc.has_key(p[1:]):
    192                 f.write('     <I>'+desc[p[1:]]+'</I>\n')
     194            f.write('<li><a href="news:%s">%s</a> ' % (p[1:], p[1:]))
     195            if p[1:] in desc:
     196                f.write('     <i>%s</i>\n' % desc[p[1:]])
    193197            else:
    194198                f.write('\n')
    195199        else:
    196200            # Output a hierarchy
    197             printtree(f,tree[i], indent, p+'.'+i)
     201            printtree(f, tree[i], indent, p+'.'+i)
    198202
    199203    if l > 1:
    200         f.write('\n</UL>')
     204        f.write('\n</ul>')
    201205
    202206# Reading descriptions file ---------------------------------------
    203207
    204 # This returns an array mapping group name to its description
     208# This returns a dict mapping group name to its description
    205209
    206210def readdesc(descfile):
    207211    global desc
    208 
    209212    desc = {}
    210213
     
    213216
    214217    try:
    215         d = open(descfile, 'r')
    216         print 'Reading descriptions...'
    217     except (IOError):
     218        with open(descfile, 'r') as d:
     219            print 'Reading descriptions...'
     220            for l in d:
     221                bits = l.split()
     222                try:
     223                    grp = bits[0]
     224                    dsc = ' '.join(bits[1:])
     225                    if len(dsc) > 1:
     226                        desc[grp] = dsc
     227                except IndexError:
     228                    pass
     229    except IOError:
    218230        print 'Failed to open description file ' + descfile
    219231        return
    220     l = d.readline()
    221     while l != '':
    222         bits = string.split(l)
    223         try:
    224             grp = bits[0]
    225             dsc = string.join(bits[1:])
    226             if len(dsc)>1:
    227                 desc[grp] = dsc
    228         except (IndexError):
    229             pass
    230         l = d.readline()
    231232
    232233# Check that ouput directory exists, ------------------------------
     
    235236def checkopdir(pagedir):
    236237    if not os.path.isdir(pagedir):
    237         print 'Directory '+pagedir+' does not exist.'
     238        print 'Directory %s does not exist.' % pagedir
    238239        print 'Shall I create it for you? (y/n)'
    239240        if sys.stdin.readline()[0] == 'y':
    240241            try:
    241                 os.mkdir(pagedir,0777)
     242                os.mkdir(pagedir, 0777)
    242243            except:
    243244                print 'Sorry - failed!'
     
    259260        print 'use the -a option to create it.'
    260261        sys.exit(1)
    261     treedate = '%02d%02d%02d' % (treetime[0] % 100 ,treetime[1], treetime[2])
    262     try:
    263         dump = open(treefile,'r')
    264         tree = marshal.load(dump)
    265         dump.close()
    266     except (IOError):
     262    treedate = '%02d%02d%02d' % (treetime[0] % 100, treetime[1], treetime[2])
     263    try:
     264        with open(treefile, 'rb') as dump:
     265            tree = marshal.load(dump)
     266    except IOError:
    267267        print 'Cannot open local group list ' + treefile
    268268    return (tree, treedate)
     
    270270def writelocallist(treefile, tree):
    271271    try:
    272         dump = open(treefile,'w')
    273         groups = marshal.dump(tree,dump)
    274         dump.close()
    275         print 'Saved list to '+treefile+'\n'
     272        with open(treefile, 'wb') as dump:
     273            groups = marshal.dump(tree, dump)
     274        print 'Saved list to %s\n' % treefile
    276275    except:
    277         print 'Sorry - failed to write to local group cache '+treefile
     276        print 'Sorry - failed to write to local group cache', treefile
    278277        print 'Does it (or its directory) have the correct permissions?'
    279278        sys.exit(1)
     
    283282def getallgroups(server):
    284283    print 'Getting list of all groups...'
    285     treedate='010101'
     284    treedate = '010101'
    286285    info = server.list()[1]
    287286    groups = []
     
    290289        print '\nIgnoring following empty groups:'
    291290    for i in info:
    292         grpname = string.split(i[0])[0]
    293         if skipempty and string.atoi(i[1]) < string.atoi(i[2]):
    294             print grpname+' ',
     291        grpname = i[0].split()[0]
     292        if skipempty and int(i[1]) < int(i[2]):
     293            print grpname + ' ',
    295294        else:
    296295            groups.append(grpname)
     
    303302
    304303def getnewgroups(server, treedate):
    305     print 'Getting list of new groups since start of '+treedate+'...',
    306     info = server.newgroups(treedate,'000001')[1]
     304    print 'Getting list of new groups since start of %s...' % treedate,
     305    info = server.newgroups(treedate, '000001')[1]
    307306    print 'got %d.' % len(info)
    308307    print 'Processing...',
    309308    groups = []
    310309    for i in info:
    311         grpname = string.split(i)[0]
     310        grpname = i.split()[0]
    312311        groups.append(grpname)
    313312    print 'Done'
     
    317316
    318317def main():
    319     global desc
    320 
    321     tree={}
     318    tree = {}
    322319
    323320    # Check that the output directory exists
     
    325322
    326323    try:
    327         print 'Connecting to '+newshost+'...'
     324        print 'Connecting to %s...' % newshost
    328325        if sys.version[0] == '0':
    329326            s = NNTP.init(newshost)
    330327        else:
    331328            s = NNTP(newshost)
    332         connected = 1
     329        connected = True
    333330    except (nntplib.error_temp, nntplib.error_perm), x:
    334331        print 'Error connecting to host:', x
    335332        print 'I\'ll try to use just the local list.'
    336         connected = 0
     333        connected = False
    337334
    338335    # If -a is specified, read the full list of groups from server
    339336    if connected and len(sys.argv) > 1 and sys.argv[1] == '-a':
    340 
    341337        groups = getallgroups(s)
    342338
  • python/vendor/current/Demo/scripts/pi.py

    r2 r388  
    1212
    1313def main():
    14     k, a, b, a1, b1 = 2L, 4L, 1L, 12L, 4L
    15     while 1:
     14    k, a, b, a1, b1 = 2, 4, 1, 12, 4
     15    while True:
    1616        # Next approximation
    17         p, q, k = k*k, 2L*k+1L, k+1L
     17        p, q, k = k*k, 2*k+1, k+1
    1818        a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
    1919        # Print common digits
     
    2121        while d == d1:
    2222            output(d)
    23             a, a1 = 10L*(a%b), 10L*(a1%b1)
     23            a, a1 = 10*(a%b), 10*(a1%b1)
    2424            d, d1 = a//b, a1//b1
    2525
    2626def output(d):
    2727    # Use write() to avoid spaces between the digits
    28     # Use str() to avoid the 'L'
    2928    sys.stdout.write(str(d))
    3029    # Flush so the output is seen immediately
  • python/vendor/current/Demo/scripts/pp.py

    r2 r388  
    2323
    2424import sys
    25 import string
    2625import getopt
    2726
     
    3736    optlist, ARGS = getopt.getopt(sys.argv[1:], 'acde:F:np')
    3837except getopt.error, msg:
    39     sys.stderr.write(sys.argv[0] + ': ' + msg + '\n')
     38    sys.stderr.write('%s: %s\n' % (sys.argv[0], msg))
    4039    sys.exit(2)
    4140
     
    4847        DFLAG = 1
    4948    elif option == '-e':
    50         for line in string.splitfields(optarg, '\n'):
     49        for line in optarg.split('\n'):
    5150            SCRIPT.append(line)
    5251    elif option == '-F':
     
    8281    # Note that it is on purpose that AFLAG and PFLAG are
    8382    # tested dynamically each time through the loop
    84     prologue = [ \
    85             'LINECOUNT = 0', \
    86             'for FILE in ARGS:', \
    87             '   \tif FILE == \'-\':', \
    88             '   \t   \tFP = sys.stdin', \
    89             '   \telse:', \
    90             '   \t   \tFP = open(FILE, \'r\')', \
    91             '   \tLINENO = 0', \
    92             '   \twhile 1:', \
    93             '   \t   \tLINE = FP.readline()', \
    94             '   \t   \tif not LINE: break', \
    95             '   \t   \tLINENO = LINENO + 1', \
    96             '   \t   \tLINECOUNT = LINECOUNT + 1', \
    97             '   \t   \tL = LINE[:-1]', \
    98             '   \t   \taflag = AFLAG', \
    99             '   \t   \tif aflag:', \
    100             '   \t   \t   \tif FS: F = string.splitfields(L, FS)', \
    101             '   \t   \t   \telse: F = string.split(L)' \
     83    prologue = [
     84            'LINECOUNT = 0',
     85            'for FILE in ARGS:',
     86            '   \tif FILE == \'-\':',
     87            '   \t   \tFP = sys.stdin',
     88            '   \telse:',
     89            '   \t   \tFP = open(FILE, \'r\')',
     90            '   \tLINENO = 0',
     91            '   \twhile 1:',
     92            '   \t   \tLINE = FP.readline()',
     93            '   \t   \tif not LINE: break',
     94            '   \t   \tLINENO = LINENO + 1',
     95            '   \t   \tLINECOUNT = LINECOUNT + 1',
     96            '   \t   \tL = LINE[:-1]',
     97            '   \t   \taflag = AFLAG',
     98            '   \t   \tif aflag:',
     99            '   \t   \t   \tif FS: F = L.split(FS)',
     100            '   \t   \t   \telse: F = L.split()'
    102101            ]
    103     epilogue = [ \
    104             '   \t   \tif not PFLAG: continue', \
    105             '   \t   \tif aflag:', \
    106             '   \t   \t   \tif FS: print string.joinfields(F, FS)', \
    107             '   \t   \t   \telse: print string.join(F)', \
    108             '   \t   \telse: print L', \
     102    epilogue = [
     103            '   \t   \tif not PFLAG: continue',
     104            '   \t   \tif aflag:',
     105            '   \t   \t   \tif FS: print FS.join(F)',
     106            '   \t   \t   \telse: print \' \'.join(F)',
     107            '   \t   \telse: print L',
    109108            ]
    110109else:
     
    115114# used in 'command' will come out right after re-indentation.
    116115
    117 program = string.joinfields(prologue, '\n') + '\n'
     116program = '\n'.join(prologue) + '\n'
    118117for line in SCRIPT:
    119     program = program + ('   \t   \t' + line + '\n')
    120 program = program + (string.joinfields(epilogue, '\n') + '\n')
     118    program += '   \t   \t' + line + '\n'
     119program += '\n'.join(epilogue) + '\n'
    121120
    122121import tempfile
     
    126125if DFLAG:
    127126    import pdb
    128     pdb.run('execfile(%r)' % (tfn,))
     127    pdb.run('execfile(%r)' % (fp.name,))
    129128else:
    130     execfile(tfn)
     129    execfile(fp.name)
  • python/vendor/current/Demo/scripts/primes.py

    r2 r388  
    22
    33# Print prime numbers in a given range
     4
     5def primes(min, max):
     6    if max >= 2 >= min:
     7        print 2
     8    primes = [2]
     9    i = 3
     10    while i <= max:
     11        for p in primes:
     12            if i % p == 0 or p*p > i:
     13                break
     14        if i % p != 0:
     15            primes.append(i)
     16            if i >= min:
     17                print i
     18        i += 2
    419
    520def main():
     
    722    min, max = 2, 0x7fffffff
    823    if sys.argv[1:]:
    9         min = int(eval(sys.argv[1]))
     24        min = int(sys.argv[1])
    1025        if sys.argv[2:]:
    11             max = int(eval(sys.argv[2]))
     26            max = int(sys.argv[2])
    1227    primes(min, max)
    13 
    14 def primes(min, max):
    15     if 2 >= min: print 2
    16     primes = [2]
    17     i = 3
    18     while i <= max:
    19         for p in primes:
    20             if i%p == 0 or p*p > i: break
    21         if i%p <> 0:
    22             primes.append(i)
    23             if i >= min: print i
    24         i = i+2
    2528
    2629if __name__ == "__main__":
  • python/vendor/current/Demo/scripts/queens.py

    r2 r388  
    2020    def reset(self):
    2121        n = self.n
    22         self.y = [None]*n               # Where is the queen in column x
    23         self.row = [0]*n                # Is row[y] safe?
     22        self.y = [None] * n             # Where is the queen in column x
     23        self.row = [0] * n              # Is row[y] safe?
    2424        self.up = [0] * (2*n-1)         # Is upward diagonal[x-y] safe?
    2525        self.down = [0] * (2*n-1)       # Is downward diagonal[x+y] safe?
     
    5151        self.down[x+y] = 0
    5252
    53     silent = 0                          # If set, count solutions only
     53    silent = 0                          # If true, count solutions only
    5454
    5555    def display(self):
  • python/vendor/current/Demo/scripts/script.py

    r2 r388  
    11#! /usr/bin/env python
     2
    23# script.py -- Make typescript of terminal session.
    34# Usage:
     
    78
    89
    9 import os, time, sys
     10import os, time, sys, getopt
    1011import pty
    1112
    1213def read(fd):
    1314    data = os.read(fd, 1024)
    14     file.write(data)
     15    script.write(data)
    1516    return data
    1617
     
    2021if os.environ.has_key('SHELL'):
    2122    shell = os.environ['SHELL']
    22 if '-a' in sys.argv:
    23     mode = 'a'
    24 if '-p' in sys.argv:
    25     shell = 'python'
    2623
    27 file = open(filename, mode)
     24try:
     25    opts, args = getopt.getopt(sys.argv[1:], 'ap')
     26except getopt.error, msg:
     27    print '%s: %s' % (sys.argv[0], msg)
     28    sys.exit(2)
     29
     30for o, a in opts:
     31    if o == '-a':
     32        mode = 'a'
     33    elif o == '-p':
     34        shell = 'python'
     35
     36script = open(filename, mode)
    2837
    2938sys.stdout.write('Script started, file is %s\n' % filename)
    30 file.write('Script started on %s\n' % time.ctime(time.time()))
     39script.write('Script started on %s\n' % time.ctime(time.time()))
    3140pty.spawn(shell, read)
    32 file.write('Script done on %s\n' % time.ctime(time.time()))
     41script.write('Script done on %s\n' % time.ctime(time.time()))
    3342sys.stdout.write('Script done, file is %s\n' % filename)
  • python/vendor/current/Demo/scripts/unbirthday.py

    r2 r388  
    1111
    1212def main():
    13     # Note that the range checks below also check for bad types,
    14     # e.g. 3.14 or ().  However syntactically invalid replies
    15     # will raise an exception.
    1613    if sys.argv[1:]:
    1714        year = int(sys.argv[1])
    1815    else:
    1916        year = int(raw_input('In which year were you born? '))
    20     if 0<=year<100:
     17    if 0 <= year < 100:
    2118        print "I'll assume that by", year,
    2219        year = year + 1900
    2320        print 'you mean', year, 'and not the early Christian era'
    24     elif not (1850<=year<=2002):
     21    elif not (1850 <= year <= time.localtime()[0]):
    2522        print "It's hard to believe you were born in", year
    2623        return
    27     #
     24
    2825    if sys.argv[2:]:
    2926        month = int(sys.argv[2])
    3027    else:
    3128        month = int(raw_input('And in which month? (1-12) '))
    32     if not (1<=month<=12):
     29    if not (1 <= month <= 12):
    3330        print 'There is no month numbered', month
    3431        return
    35     #
     32
    3633    if sys.argv[3:]:
    3734        day = int(sys.argv[3])
     
    4239    else:
    4340        maxday = calendar.mdays[month]
    44     if not (1<=day<=maxday):
     41    if not (1 <= day <= maxday):
    4542        print 'There are no', day, 'days in that month!'
    4643        return
    47     #
     44
    4845    bdaytuple = (year, month, day)
    4946    bdaydate = mkdate(bdaytuple)
    5047    print 'You were born on', format(bdaytuple)
    51     #
     48
    5249    todaytuple = time.localtime()[:3]
    5350    todaydate = mkdate(todaytuple)
    5451    print 'Today is', format(todaytuple)
    55     #
     52
    5653    if bdaytuple > todaytuple:
    5754        print 'You are a time traveler.  Go back to the future!'
    5855        return
    59     #
     56
    6057    if bdaytuple == todaytuple:
    6158        print 'You were born today.  Have a nice life!'
    6259        return
    63     #
     60
    6461    days = todaydate - bdaydate
    6562    print 'You have lived', days, 'days'
    66     #
     63
    6764    age = 0
    6865    for y in range(year, todaytuple[0] + 1):
    6966        if bdaytuple < (y, month, day) <= todaytuple:
    7067            age = age + 1
    71     #
     68
    7269    print 'You are', age, 'years old'
    73     #
     70
    7471    if todaytuple[1:] == bdaytuple[1:]:
    7572        print 'Congratulations!  Today is your', nth(age), 'birthday'
     
    8986
    9087def mkdate((year, month, day)):
    91     # Januari 1st, in 0 A.D. is arbitrarily defined to be day 1,
     88    # January 1st, in 0 A.D. is arbitrarily defined to be day 1,
    9289    # even though that day never actually existed and the calendar
    9390    # was different then...
    94     days = year*365                 # years, roughly
     91    days = year*365                  # years, roughly
    9592    days = days + (year+3)//4        # plus leap years, roughly
    9693    days = days - (year+99)//100     # minus non-leap years every century
  • python/vendor/current/Demo/sockets/README

    r2 r388  
    66ftp.py                  A very simple ftp client.
    77gopher.py               A simple gopher client.
     8mcast.py                IPv4/v6 multicast example
    89radio.py                Receive time broadcasts from broadcast.py.
    910telnet.py               Client for the 'telnet' protocol.
     
    1213unixserver.py           Unix socket example, server side
    1314udpecho.py              Client and server for the UDP echo protocol.
    14 
    15 The following file is only relevant on SGI machines (or other systems
    16 that support multicast):
    17 
    18 mcast.py                A Python translation of
    19                         /usr/people/4Dgifts/examples/network/mcast.c
    20                         (Note that IN.py is in ../../lib/sgi.)
    21 
  • python/vendor/current/Demo/sockets/mcast.py

    r2 r388  
     1#!/usr/bin/env python
     2#
    13# Send/receive UDP multicast packets.
    24# Requires that your OS kernel supports IP multicast.
    3 # This is built-in on SGI, still optional for most other vendors.
    45#
    56# Usage:
    6 #   mcast -s (sender)
    7 #   mcast -b (sender, using broadcast instead multicast)
    8 #   mcast    (receivers)
     7#   mcast -s (sender, IPv4)
     8#   mcast -s -6 (sender, IPv6)
     9#   mcast    (receivers, IPv4)
     10#   mcast  -6  (receivers, IPv6)
    911
    1012MYPORT = 8123
    11 MYGROUP = '225.0.0.250'
     13MYGROUP_4 = '225.0.0.250'
     14MYGROUP_6 = 'ff15:7079:7468:6f6e:6465:6d6f:6d63:6173'
     15MYTTL = 1 # Increase to reach other networks
    1216
    13 import sys
    1417import time
    1518import struct
    16 from socket import *
     19import socket
     20import sys
     21
     22def main():
     23    group = MYGROUP_6 if "-6" in sys.argv[1:] else MYGROUP_4
     24
     25    if "-s" in sys.argv[1:]:
     26        sender(group)
     27    else:
     28        receiver(group)
    1729
    1830
    19 # Main program
    20 def main():
    21     flags = sys.argv[1:]
    22     #
    23     if flags:
    24         sender(flags[0])
     31def sender(group):
     32    addrinfo = socket.getaddrinfo(group, None)[0]
     33
     34    s = socket.socket(addrinfo[0], socket.SOCK_DGRAM)
     35
     36    # Set Time-to-live (optional)
     37    ttl_bin = struct.pack('@i', MYTTL)
     38    if addrinfo[0] == socket.AF_INET: # IPv4
     39        s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl_bin)
    2540    else:
    26         receiver()
     41        s.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_HOPS, ttl_bin)
    2742
    28 
    29 # Sender subroutine (only one per local area network)
    30 def sender(flag):
    31     s = socket(AF_INET, SOCK_DGRAM)
    32     if flag == '-b':
    33         s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
    34         mygroup = '<broadcast>'
    35     else:
    36         mygroup = MYGROUP
    37         ttl = struct.pack('b', 1)               # Time-to-live
    38         s.setsockopt(IPPROTO_IP, IP_MULTICAST_TTL, ttl)
    39     while 1:
     43    while True:
    4044        data = repr(time.time())
    41 ##              data = data + (1400 - len(data)) * '\0'
    42         s.sendto(data, (mygroup, MYPORT))
     45        s.sendto(data + '\0', (addrinfo[4][0], MYPORT))
    4346        time.sleep(1)
    4447
    4548
    46 # Receiver subroutine (as many as you like)
    47 def receiver():
    48     # Open and initialize the socket
    49     s = openmcastsock(MYGROUP, MYPORT)
    50     #
     49def receiver(group):
     50    # Look up multicast group address in name server and find out IP version
     51    addrinfo = socket.getaddrinfo(group, None)[0]
     52
     53    # Create a socket
     54    s = socket.socket(addrinfo[0], socket.SOCK_DGRAM)
     55
     56    # Allow multiple copies of this program on one machine
     57    # (not strictly needed)
     58    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     59
     60    # Bind it to the port
     61    s.bind(('', MYPORT))
     62
     63    group_bin = socket.inet_pton(addrinfo[0], addrinfo[4][0])
     64    # Join group
     65    if addrinfo[0] == socket.AF_INET: # IPv4
     66        mreq = group_bin + struct.pack('=I', socket.INADDR_ANY)
     67        s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
     68    else:
     69        mreq = group_bin + struct.pack('@I', 0)
     70        s.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, mreq)
     71
    5172    # Loop, printing any data we receive
    52     while 1:
     73    while True:
    5374        data, sender = s.recvfrom(1500)
    5475        while data[-1:] == '\0': data = data[:-1] # Strip trailing \0's
    55         print sender, ':', repr(data)
     76        print (str(sender) + '  ' + repr(data))
    5677
    5778
    58 # Open a UDP socket, bind it to a port and select a multicast group
    59 def openmcastsock(group, port):
    60     # Import modules used only here
    61     import string
    62     import struct
    63     #
    64     # Create a socket
    65     s = socket(AF_INET, SOCK_DGRAM)
    66     #
    67     # Allow multiple copies of this program on one machine
    68     # (not strictly needed)
    69     s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    70     #
    71     # Bind it to the port
    72     s.bind(('', port))
    73     #
    74     # Look up multicast group address in name server
    75     # (doesn't hurt if it is already in ddd.ddd.ddd.ddd format)
    76     group = gethostbyname(group)
    77     #
    78     # Construct binary group address
    79     bytes = map(int, string.split(group, "."))
    80     grpaddr = 0
    81     for byte in bytes: grpaddr = (grpaddr << 8) | byte
    82     #
    83     # Construct struct mreq from grpaddr and ifaddr
    84     ifaddr = INADDR_ANY
    85     mreq = struct.pack('ll', htonl(grpaddr), htonl(ifaddr))
    86     #
    87     # Add group membership
    88     s.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq)
    89     #
    90     return s
    91 
    92 
    93 main()
     79if __name__ == '__main__':
     80    main()
  • python/vendor/current/Demo/threads/sync.py

    r2 r388  
    266266#      are allowed to proceed only if the current thread calls
    267267#      .read_out; threads waiting to read are only allowed to proceed
    268 #      if there are are no threads waiting to write.  (This is a
     268#      if there are no threads waiting to write.  (This is a
    269269#      weakness of the interface!)
    270270
  • python/vendor/current/Demo/tix/INSTALL.txt

    r2 r388  
    1 $Id: INSTALL.txt 24230 2001-11-11 14:07:37Z loewis $
     1$Id$
    22
    33Installing Tix.py
  • python/vendor/current/Demo/tix/samples/Balloon.py

    r2 r388  
    11# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
    22#
    3 # $Id: Balloon.py 36560 2004-07-18 06:16:08Z tim_one $
     3# $Id$
    44#
    55# Tix Demostration Program
  • python/vendor/current/Demo/tix/samples/BtnBox.py

    r2 r388  
    11# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
    22#
    3 # $Id: BtnBox.py 36560 2004-07-18 06:16:08Z tim_one $
     3# $Id$
    44#
    55# Tix Demostration Program
  • python/vendor/current/Demo/tix/samples/CmpImg.py

    r2 r388  
    11# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
    22#
    3 # $Id: CmpImg.py 36560 2004-07-18 06:16:08Z tim_one $
     3# $Id$
    44#
    55# Tix Demostration Program
  • python/vendor/current/Demo/tix/samples/ComboBox.py

    r2 r388  
    11# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
    22#
    3 # $Id: ComboBox.py 36560 2004-07-18 06:16:08Z tim_one $
     3# $Id$
    44#
    55# Tix Demostration Program
  • python/vendor/current/Demo/tix/samples/Control.py

    r2 r388  
    11# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
    22#
    3 # $Id: Control.py 36560 2004-07-18 06:16:08Z tim_one $
     3# $Id$
    44#
    55# Tix Demostration Program
  • python/vendor/current/Demo/tix/samples/DirList.py

    r2 r388  
    11# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
    22#
    3 #       $Id: DirList.py 36560 2004-07-18 06:16:08Z tim_one $
     3#       $Id$
    44#
    55# Tix Demostration Program
  • python/vendor/current/Demo/tix/samples/DirTree.py

    r2 r388  
    11# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
    22#
    3 #       $Id: DirTree.py 36560 2004-07-18 06:16:08Z tim_one $
     3#       $Id$
    44#
    55# Tix Demostration Program
  • python/vendor/current/Demo/tix/samples/NoteBook.py

    r2 r388  
    11# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
    22#
    3 # $Id: NoteBook.py 36560 2004-07-18 06:16:08Z tim_one $
     3# $Id$
    44#
    55# Tix Demostration Program
  • python/vendor/current/Demo/tix/samples/OptMenu.py

    r2 r388  
    11# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
    22#
    3 # $Id: OptMenu.py 36560 2004-07-18 06:16:08Z tim_one $
     3# $Id$
    44#
    55# Tix Demostration Program
  • python/vendor/current/Demo/tix/samples/PanedWin.py

    r2 r388  
    11# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
    22#
    3 # $Id: PanedWin.py 36560 2004-07-18 06:16:08Z tim_one $
     3# $Id$
    44#
    55# Tix Demostration Program
  • python/vendor/current/Demo/tix/samples/PopMenu.py

    r2 r388  
    11# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
    22#
    3 #       $Id: PopMenu.py 36560 2004-07-18 06:16:08Z tim_one $
     3#       $Id$
    44#
    55# Tix Demostration Program
  • python/vendor/current/Demo/tix/samples/SHList1.py

    r2 r388  
    11# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
    22#
    3 # $Id: SHList1.py 36560 2004-07-18 06:16:08Z tim_one $
     3# $Id$
    44#
    55# Tix Demostration Program
  • python/vendor/current/Demo/tix/samples/SHList2.py

    r2 r388  
    11# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
    22#
    3 # $Id: SHList2.py 36560 2004-07-18 06:16:08Z tim_one $
     3# $Id$
    44#
    55# Tix Demostration Program
  • python/vendor/current/Demo/tix/samples/Tree.py

    r2 r388  
    11# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
    22#
    3 # $Id: Tree.py 36560 2004-07-18 06:16:08Z tim_one $
     3# $Id$
    44#
    55# Tix Demostration Program
  • python/vendor/current/Demo/tix/tixwidgets.py

    r2 r388  
    11# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
    22#
    3 # $Id: tixwidgets.py 36560 2004-07-18 06:16:08Z tim_one $
     3# $Id$
    44#
    55# tixwidgets.py --
     
    660660to glue together a bunch of bitmaps, images and text strings together
    661661to form a bigger image. Then you can use this image with widgets that
    662 support the -image option. For example, you can display a text string string
     662support the -image option. For example, you can display a text string
    663663together with a bitmap, at the same time, inside a TK button widget.
    664664""")
  • python/vendor/current/Demo/tkinter/README

    r2 r388  
    99guido           my original example set (fairly random collection)
    1010matt            Matt Conway's examples, to go with his lifesaver document
     11ttk         Examples using the ttk module
  • python/vendor/current/Demo/turtle/about_turtle.txt

    r2 r388  
    88by Wally Feurzig and Seymour Papert in 1966.
    99
    10 Imagine a robotic turtle starting at (0, 0) in the x-y plane. Give it
     10Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an ``import turtle``, give it
    1111the command turtle.forward(15), and it moves (on-screen!) 15 pixels in
    1212the direction it is facing, drawing a line as it moves. Give it the
    13 command turtle.left(25), and it rotates in-place 25 degrees clockwise.
     13command turtle.right(25), and it rotates in-place 25 degrees clockwise.
    1414
    1515By combining together these and similar commands, intricate shapes and
  • python/vendor/current/Demo/turtle/tdemo_I_dontlike_tiltdemo.py

    r2 r388  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22"""       turtle-example-suite:
    33
  • python/vendor/current/Demo/turtle/tdemo_bytedesign.py

    r2 r388  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22"""      turtle-example-suite:
    33
  • python/vendor/current/Demo/turtle/tdemo_clock.py

    r2 r388  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22# -*- coding: cp1252 -*-
    33"""       turtle-example-suite:
  • python/vendor/current/Demo/turtle/tdemo_fractalcurves.py

    r2 r388  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22"""      turtle-example-suite:
    33
  • python/vendor/current/Demo/turtle/tdemo_lindenmayer_indian.py

    r2 r388  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22"""       turtle-example-suite:
    33
  • python/vendor/current/Demo/turtle/tdemo_minimal_hanoi.py

    r2 r388  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22"""       turtle-example-suite:
    33
  • python/vendor/current/Demo/turtle/tdemo_paint.py

    r2 r388  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22"""       turtle-example-suite:
    33
  • python/vendor/current/Demo/turtle/tdemo_peace.py

    r2 r388  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22"""       turtle-example-suite:
    33
  • python/vendor/current/Demo/turtle/tdemo_penrose.py

    r2 r388  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22"""       xturtle-example-suite:
    33
  • python/vendor/current/Demo/turtle/tdemo_planet_and_moon.py

    r2 r388  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22"""       turtle-example-suite:
    33
  • python/vendor/current/Demo/turtle/tdemo_tree.py

    r2 r388  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22"""      turtle-example-suite:
    33
  • python/vendor/current/Demo/turtle/tdemo_yinyang.py

    r2 r388  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22"""       turtle-example-suite:
    33
  • python/vendor/current/Demo/turtle/turtleDemo.py

    r2 r388  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22import sys
    33import os
     
    213213            self.text.insert("1.0",chars)
    214214            direc, fname = os.path.split(filename)
    215             self.root.title(fname[6:-3]+" - an xturtle example")
     215            self.root.title(fname[6:-3]+" - a Python turtle graphics example")
    216216            self.module = __import__(fname[:-3])
    217217            reload(self.module)
  • python/vendor/current/Demo/turtle/turtledemo_two_canvases.py

    r2 r388  
    1 #!/usr/bin/python
     1#!/usr/bin/env python
    22## DEMONSTRATES USE OF 2 CANVASES, SO CANNOT BE RUN IN DEMOVIEWER!
    33"""turtle example: Using TurtleScreen and RawTurtle
  • python/vendor/current/Demo/xml/elem_count.py

    r2 r388  
     1"""
     2A simple demo that reads in an XML document and displays the number of
     3elements and attributes as well as a tally of elements and attributes by name.
     4"""
     5
    16import sys
     7from collections import defaultdict
    28
    39from xml.sax import make_parser, handler
     
    814        self._elems = 0
    915        self._attrs = 0
    10         self._elem_types = {}
    11         self._attr_types = {}
     16        self._elem_types = defaultdict(int)
     17        self._attr_types = defaultdict(int)
    1218
    1319    def startElement(self, name, attrs):
    14         self._elems = self._elems + 1
    15         self._attrs = self._attrs + len(attrs)
    16         self._elem_types[name] = self._elem_types.get(name, 0) + 1
     20        self._elems += 1
     21        self._attrs += len(attrs)
     22        self._elem_types[name] += 1
    1723
    1824        for name in attrs.keys():
    19             self._attr_types[name] = self._attr_types.get(name, 0) + 1
     25            self._attr_types[name] += 1
    2026
    2127    def endDocument(self):
     
    3137            print "%20s %d" % pair
    3238
    33 
    34 parser = make_parser()
    35 parser.setContentHandler(FancyCounter())
    36 parser.parse(sys.argv[1])
     39if __name__ == '__main__':
     40    parser = make_parser()
     41    parser.setContentHandler(FancyCounter())
     42    parser.parse(sys.argv[1])
  • python/vendor/current/Demo/xml/roundtrip.py

    r2 r388  
    44"""
    55
    6 import sys, string
     6import sys
    77
    88from xml.sax import saxutils, handler, make_parser
     
    1212class ContentGenerator(handler.ContentHandler):
    1313
    14     def __init__(self, out = sys.stdout):
     14    def __init__(self, out=sys.stdout):
    1515        handler.ContentHandler.__init__(self)
    1616        self._out = out
     
    4141# --- The main program
    4242
    43 parser = make_parser()
    44 parser.setContentHandler(ContentGenerator())
    45 parser.parse(sys.argv[1])
     43if __name__ == '__main__':
     44    parser = make_parser()
     45    parser.setContentHandler(ContentGenerator())
     46    parser.parse(sys.argv[1])
  • python/vendor/current/Demo/xml/rss2html.py

    r2 r388  
     1"""
     2A demo that reads in an RSS XML document and emits an HTML file containing
     3a list of the individual items in the feed.
     4"""
     5
    16import sys
     7import codecs
    28
    39from xml.sax import make_parser, handler
     
    511# --- Templates
    612
    7 top = \
    8 """
     13top = """\
    914<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    10 <HTML>
    11 <HEAD>
    12   <TITLE>%s</TITLE>
    13 </HEAD>
     15<html>
     16<head>
     17  <title>%s</title>
     18  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
     19</head>
    1420
    15 <BODY>
    16 <H1>%s</H1>
     21<body>
     22<h1>%s</h1>
    1723"""
    1824
    19 bottom = \
    20 """
     25bottom = """
    2126</ul>
    2227
    23 <HR>
    24 <ADDRESS>
    25 Converted to HTML by sax_rss2html.py.
    26 </ADDRESS>
     28<hr>
     29<address>
     30Converted to HTML by rss2html.py.
     31</address>
    2732
    28 </BODY>
    29 </HTML>
     33</body>
     34</html>
    3035"""
    3136
     
    3439class RSSHandler(handler.ContentHandler):
    3540
    36     def __init__(self, out = sys.stdout):
     41    def __init__(self, out=sys.stdout):
    3742        handler.ContentHandler.__init__(self)
    38         self._out = out
     43        self._out = codecs.getwriter('utf-8')(out)
    3944
    4045        self._text = ""
    4146        self._parent = None
    42         self._list_started = 0
     47        self._list_started = False
    4348        self._title = None
    4449        self._link = None
     
    7075                if not self._list_started:
    7176                    self._out.write("<ul>\n")
    72                     self._list_started = 1
     77                    self._list_started = True
    7378
    7479                self._out.write('  <li><a href="%s">%s</a> %s\n' %
     
    8792# --- Main program
    8893
    89 parser = make_parser()
    90 parser.setContentHandler(RSSHandler())
    91 parser.parse(sys.argv[1])
     94if __name__ == '__main__':
     95    parser = make_parser()
     96    parser.setContentHandler(RSSHandler())
     97    parser.parse(sys.argv[1])
Note: See TracChangeset for help on using the changeset viewer.