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/scripts
Files:
3 deleted
14 edited

Legend:

Unmodified
Added
Removed
  • 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
Note: See TracChangeset for help on using the changeset viewer.