Kaydet (Commit) 4acc25bd authored tarafından Guido van Rossum's avatar Guido van Rossum

Mass patch by Ka-Ping Yee:

    1. Comments at the beginning of the module, before
       functions, and before classes have been turned
       into docstrings.

    2. Tabs are normalized to four spaces.

Also, removed the "remove" function from dircmp.py, which reimplements
list.remove() (it must have been very old).
üst 113e70ef
# A multi-producer, multi-consumer queue. """A multi-producer, multi-consumer queue."""
# define this exception to be compatible with Python 1.5's class # define this exception to be compatible with Python 1.5's class
# exceptions, but also when -X option is used. # exceptions, but also when -X option is used.
......
# class StringIO implements file-like objects that read/write a """File-like objects that read from or write to a string buffer.
# string buffer (a.k.a. "memory files").
# This implements (nearly) all stdio methods.
# This implements (nearly) all stdio methods.
# f = StringIO() # ready for writing
# f = StringIO() # ready for writing f = StringIO(buf) # ready for reading
# f = StringIO(buf) # ready for reading f.close() # explicitly release resources held
# f.close() # explicitly release resources held flag = f.isatty() # always false
# flag = f.isatty() # always false pos = f.tell() # get current position
# pos = f.tell() # get current position f.seek(pos) # set current position
# f.seek(pos) # set current position f.seek(pos, mode) # mode 0: absolute; 1: relative; 2: relative to EOF
# f.seek(pos, mode) # mode 0: absolute; 1: relative; 2: relative to EOF buf = f.read() # read until EOF
# buf = f.read() # read until EOF buf = f.read(n) # read up to n bytes
# buf = f.read(n) # read up to n bytes buf = f.readline() # read until end of line ('\n') or EOF
# buf = f.readline() # read until end of line ('\n') or EOF list = f.readlines()# list of f.readline() results until EOF
# list = f.readlines()# list of f.readline() results until EOF f.write(buf) # write at current position
# f.write(buf) # write at current position f.writelines(list) # for line in list: f.write(line)
# f.writelines(list) # for line in list: f.write(line) f.getvalue() # return whole file's contents as a string
# f.getvalue() # return whole file's contents as a string
# Notes:
# Notes: - Using a real file is often faster (but less convenient).
# - Using a real file is often faster (but less convenient). - fileno() is left unimplemented so that code which uses it triggers
# - fileno() is left unimplemented so that code which uses it triggers an exception early.
# an exception early. - Seeking far beyond EOF and then writing will insert real null
# - Seeking far beyond EOF and then writing will insert real null bytes that occupy space in the buffer.
# bytes that occupy space in the buffer. - There's a simple test set (see end of this file).
# - There's a simple test set (see end of this file). """
import string import string
......
# A more or less complete user-defined wrapper around dictionary objects """A more or less complete user-defined wrapper around dictionary objects."""
class UserDict: class UserDict:
def __init__(self, dict=None): def __init__(self, dict=None):
......
# A more or less complete user-defined wrapper around list objects """A more or less complete user-defined wrapper around list objects."""
class UserList: class UserList:
def __init__(self, list=None): def __init__(self, list=None):
......
This diff is collapsed.
"""Classes for manipulating audio devices (currently only for Sun and SGI)"""
error = 'audiodev.error' error = 'audiodev.error'
class Play_Audio_sgi: class Play_Audio_sgi:
......
#! /usr/bin/env python #! /usr/bin/env python
# Conversions to/from base64 transport encoding as per RFC-1521. """Conversions to/from base64 transport encoding as per RFC-1521."""
#
# Modified 04-Oct-95 by Jack to use binascii module # Modified 04-Oct-95 by Jack to use binascii module
import binascii import binascii
...@@ -9,69 +9,71 @@ import binascii ...@@ -9,69 +9,71 @@ import binascii
MAXLINESIZE = 76 # Excluding the CRLF MAXLINESIZE = 76 # Excluding the CRLF
MAXBINSIZE = (MAXLINESIZE/4)*3 MAXBINSIZE = (MAXLINESIZE/4)*3
# Encode a file.
def encode(input, output): def encode(input, output):
while 1: """Encode a file."""
s = input.read(MAXBINSIZE) while 1:
if not s: break s = input.read(MAXBINSIZE)
while len(s) < MAXBINSIZE: if not s: break
ns = input.read(MAXBINSIZE-len(s)) while len(s) < MAXBINSIZE:
if not ns: break ns = input.read(MAXBINSIZE-len(s))
s = s + ns if not ns: break
line = binascii.b2a_base64(s) s = s + ns
output.write(line) line = binascii.b2a_base64(s)
output.write(line)
# Decode a file.
def decode(input, output): def decode(input, output):
while 1: """Decode a file."""
line = input.readline() while 1:
if not line: break line = input.readline()
s = binascii.a2b_base64(line) if not line: break
output.write(s) s = binascii.a2b_base64(line)
output.write(s)
def encodestring(s): def encodestring(s):
import StringIO """Encode a string."""
f = StringIO.StringIO(s) import StringIO
g = StringIO.StringIO() f = StringIO.StringIO(s)
encode(f, g) g = StringIO.StringIO()
return g.getvalue() encode(f, g)
return g.getvalue()
def decodestring(s): def decodestring(s):
import StringIO """Decode a string."""
f = StringIO.StringIO(s) import StringIO
g = StringIO.StringIO() f = StringIO.StringIO(s)
decode(f, g) g = StringIO.StringIO()
return g.getvalue() decode(f, g)
return g.getvalue()
# Small test program
def test(): def test():
import sys, getopt """Small test program"""
try: import sys, getopt
opts, args = getopt.getopt(sys.argv[1:], 'deut') try:
except getopt.error, msg: opts, args = getopt.getopt(sys.argv[1:], 'deut')
sys.stdout = sys.stderr except getopt.error, msg:
print msg sys.stdout = sys.stderr
print """usage: basd64 [-d] [-e] [-u] [-t] [file|-] print msg
-d, -u: decode print """usage: basd64 [-d] [-e] [-u] [-t] [file|-]
-e: encode (default) -d, -u: decode
-t: decode string 'Aladdin:open sesame'""" -e: encode (default)
sys.exit(2) -t: decode string 'Aladdin:open sesame'"""
func = encode sys.exit(2)
for o, a in opts: func = encode
if o == '-e': func = encode for o, a in opts:
if o == '-d': func = decode if o == '-e': func = encode
if o == '-u': func = decode if o == '-d': func = decode
if o == '-t': test1(); return if o == '-u': func = decode
if args and args[0] != '-': if o == '-t': test1(); return
func(open(args[0], 'rb'), sys.stdout) if args and args[0] != '-':
else: func(open(args[0], 'rb'), sys.stdout)
func(sys.stdin, sys.stdout) else:
func(sys.stdin, sys.stdout)
def test1(): def test1():
s0 = "Aladdin:open sesame" s0 = "Aladdin:open sesame"
s1 = encodestring(s0) s1 = encodestring(s0)
s2 = decodestring(s1) s2 = decodestring(s1)
print s0, `s1`, s2 print s0, `s1`, s2
if __name__ == '__main__': if __name__ == '__main__':
test() test()
This diff is collapsed.
This diff is collapsed.
# Bisection algorithms """Bisection algorithms."""
# Insert item x in list a, and keep it sorted assuming a is sorted
def insort(a, x, lo=0, hi=None): def insort(a, x, lo=0, hi=None):
if hi is None: """Insert item x in list a, and keep it sorted assuming a is sorted."""
hi = len(a) if hi is None:
while lo < hi: hi = len(a)
mid = (lo+hi)/2 while lo < hi:
if x < a[mid]: hi = mid mid = (lo+hi)/2
else: lo = mid+1 if x < a[mid]: hi = mid
a.insert(lo, x) else: lo = mid+1
a.insert(lo, x)
# Find the index where to insert item x in list a, assuming a is sorted
def bisect(a, x, lo=0, hi=None): def bisect(a, x, lo=0, hi=None):
if hi is None: """Find the index where to insert item x in list a, assuming a is sorted."""
hi = len(a) if hi is None:
while lo < hi: hi = len(a)
mid = (lo+hi)/2 while lo < hi:
if x < a[mid]: hi = mid mid = (lo+hi)/2
else: lo = mid+1 if x < a[mid]: hi = mid
return lo else: lo = mid+1
return lo
############################### """Calendar printing functions"""
# Calendar printing functions #
###############################
# Revision 2: uses funtions from built-in time module # Revision 2: uses funtions from built-in time module
...@@ -22,149 +20,149 @@ February = 2 ...@@ -22,149 +20,149 @@ February = 2
mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
# Full and abbreviated names of weekdays # Full and abbreviated names of weekdays
day_name = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', \ day_name = ['Monday', 'Tuesday', 'Wednesday', 'Thursday',
'Friday', 'Saturday', 'Sunday'] 'Friday', 'Saturday', 'Sunday']
day_abbr = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] day_abbr = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
# Full and abbreviated names of months (1-based arrays!!!) # Full and abbreviated names of months (1-based arrays!!!)
month_name = ['', 'January', 'February', 'March', 'April', \ month_name = ['', 'January', 'February', 'March', 'April',
'May', 'June', 'July', 'August', \ 'May', 'June', 'July', 'August',
'September', 'October', 'November', 'December'] 'September', 'October', 'November', 'December']
month_abbr = [' ', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', \ month_abbr = [' ', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
# Return 1 for leap years, 0 for non-leap years
def isleap(year): def isleap(year):
return year % 4 == 0 and (year % 100 <> 0 or year % 400 == 0) """Return 1 for leap years, 0 for non-leap years."""
return year % 4 == 0 and (year % 100 <> 0 or year % 400 == 0)
# Return number of leap years in range [y1, y2)
# Assume y1 <= y2 and no funny (non-leap century) years
def leapdays(y1, y2): def leapdays(y1, y2):
return (y2+3)/4 - (y1+3)/4 """Return number of leap years in range [y1, y2).
Assume y1 <= y2 and no funny (non-leap century) years."""
return (y2+3)/4 - (y1+3)/4
# Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12), day (1-31)
def weekday(year, month, day): def weekday(year, month, day):
secs = mktime((year, month, day, 0, 0, 0, 0, 0, 0)) """Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12), day (1-31)."""
tuple = localtime(secs) secs = mktime((year, month, day, 0, 0, 0, 0, 0, 0))
return tuple[6] tuple = localtime(secs)
return tuple[6]
# Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for year, month
def monthrange(year, month): def monthrange(year, month):
if not 1 <= month <= 12: raise ValueError, 'bad month number' """Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for year, month."""
day1 = weekday(year, month, 1) if not 1 <= month <= 12: raise ValueError, 'bad month number'
ndays = mdays[month] + (month == February and isleap(year)) day1 = weekday(year, month, 1)
return day1, ndays ndays = mdays[month] + (month == February and isleap(year))
return day1, ndays
# Return a matrix representing a month's calendar
# Each row represents a week; days outside this month are zero
def _monthcalendar(year, month): def _monthcalendar(year, month):
day1, ndays = monthrange(year, month) """Return a matrix representing a month's calendar.
rows = [] Each row represents a week; days outside this month are zero."""
r7 = range(7) day1, ndays = monthrange(year, month)
day = 1 - day1 rows = []
while day <= ndays: r7 = range(7)
row = [0, 0, 0, 0, 0, 0, 0] day = 1 - day1
for i in r7: while day <= ndays:
if 1 <= day <= ndays: row[i] = day row = [0, 0, 0, 0, 0, 0, 0]
day = day + 1 for i in r7:
rows.append(row) if 1 <= day <= ndays: row[i] = day
return rows day = day + 1
rows.append(row)
# Caching interface to _monthcalendar return rows
_mc_cache = {} _mc_cache = {}
def monthcalendar(year, month): def monthcalendar(year, month):
key = (year, month) """Caching interface to _monthcalendar."""
if _mc_cache.has_key(key): key = (year, month)
return _mc_cache[key] if _mc_cache.has_key(key):
else: return _mc_cache[key]
_mc_cache[key] = ret = _monthcalendar(year, month) else:
return ret _mc_cache[key] = ret = _monthcalendar(year, month)
return ret
# Center a string in a field
def _center(str, width): def _center(str, width):
n = width - len(str) """Center a string in a field."""
if n <= 0: return str n = width - len(str)
return ' '*((n+1)/2) + str + ' '*((n)/2) if n <= 0: return str
return ' '*((n+1)/2) + str + ' '*((n)/2)
# XXX The following code knows that print separates items with space! # XXX The following code knows that print separates items with space!
# Print a single week (no newline)
def prweek(week, width): def prweek(week, width):
for day in week: """Print a single week (no newline)."""
if day == 0: s = '' for day in week:
else: s = `day` if day == 0: s = ''
print _center(s, width), else: s = `day`
print _center(s, width),
# Return a header for a week
def weekheader(width): def weekheader(width):
str = '' """Return a header for a week."""
if width >= 9: names = day_name str = ''
else: names = day_abbr if width >= 9: names = day_name
for i in range(7): else: names = day_abbr
if str: str = str + ' ' for i in range(7):
str = str + _center(names[i%7][:width], width) if str: str = str + ' '
return str str = str + _center(names[i%7][:width], width)
return str
# Print a month's calendar
def prmonth(year, month, w = 0, l = 0): def prmonth(year, month, w = 0, l = 0):
w = max(2, w) """Print a month's calendar."""
l = max(1, l) w = max(2, w)
print _center(month_name[month] + ' ' + `year`, 7*(w+1) - 1), l = max(1, l)
print '\n'*l, print _center(month_name[month] + ' ' + `year`, 7*(w+1) - 1),
print weekheader(w), print '\n'*l,
print '\n'*l, print weekheader(w),
for week in monthcalendar(year, month): print '\n'*l,
prweek(week, w) for week in monthcalendar(year, month):
print '\n'*l, prweek(week, w)
print '\n'*l,
# Spacing of month columns # Spacing of month columns
_colwidth = 7*3 - 1 # Amount printed by prweek() _colwidth = 7*3 - 1 # Amount printed by prweek()
_spacing = ' '*4 # Spaces between columns _spacing = ' '*4 # Spaces between columns
# 3-column formatting for year calendars
def format3c(a, b, c): def format3c(a, b, c):
print _center(a, _colwidth), """3-column formatting for year calendars"""
print _spacing, print _center(a, _colwidth),
print _center(b, _colwidth), print _spacing,
print _spacing, print _center(b, _colwidth),
print _center(c, _colwidth) print _spacing,
print _center(c, _colwidth)
# Print a year's calendar
def prcal(year): def prcal(year):
header = weekheader(2) """Print a year's calendar."""
format3c('', `year`, '') header = weekheader(2)
for q in range(January, January+12, 3): format3c('', `year`, '')
print for q in range(January, January+12, 3):
format3c(month_name[q], month_name[q+1], month_name[q+2]) print
format3c(header, header, header) format3c(month_name[q], month_name[q+1], month_name[q+2])
data = [] format3c(header, header, header)
height = 0 data = []
for month in range(q, q+3): height = 0
cal = monthcalendar(year, month) for month in range(q, q+3):
if len(cal) > height: height = len(cal) cal = monthcalendar(year, month)
data.append(cal) if len(cal) > height: height = len(cal)
for i in range(height): data.append(cal)
for cal in data: for i in range(height):
if i >= len(cal): for cal in data:
print ' '*_colwidth, if i >= len(cal):
else: print ' '*_colwidth,
prweek(cal[i], 2) else:
print _spacing, prweek(cal[i], 2)
print print _spacing,
print
# Unrelated but handy function to calculate Unix timestamp from GMT
EPOCH = 1970 EPOCH = 1970
def timegm(tuple): def timegm(tuple):
year, month, day, hour, minute, second = tuple[:6] """Unrelated but handy function to calculate Unix timestamp from GMT."""
assert year >= EPOCH year, month, day, hour, minute, second = tuple[:6]
assert 1 <= month <= 12 assert year >= EPOCH
days = 365*(year-EPOCH) + leapdays(EPOCH, year) assert 1 <= month <= 12
for i in range(1, month): days = 365*(year-EPOCH) + leapdays(EPOCH, year)
days = days + mdays[i] for i in range(1, month):
if month > 2 and isleap(year): days = days + mdays[i]
days = days + 1 if month > 2 and isleap(year):
days = days + day - 1 days = days + 1
hours = days*24 + hour days = days + day - 1
minutes = hours*60 + minute hours = days*24 + hour
seconds = minutes*60 + second minutes = hours*60 + minute
return seconds seconds = minutes*60 + second
return seconds
This diff is collapsed.
# Module 'cmp' """Efficiently compare files, boolean outcome only (equal / not equal).
# Efficiently compare files, boolean outcome only (equal / not equal). Tricks (used in this order):
- Files with identical type, size & mtime are assumed to be clones
# Tricks (used in this order): - Files with different type or size cannot be identical
# - Files with identical type, size & mtime are assumed to be clones - We keep a cache of outcomes of earlier comparisons
# - Files with different type or size cannot be identical - We don't fork a process to run 'cmp' but read the files ourselves
# - We keep a cache of outcomes of earlier comparisons """
# - We don't fork a process to run 'cmp' but read the files ourselves
import os import os
cache = {} cache = {}
def cmp(f1, f2, shallow=1): # Compare two files, use the cache if possible. def cmp(f1, f2, shallow=1):
# Return 1 for identical files, 0 for different. """Compare two files, use the cache if possible.
# Raise exceptions if either file could not be statted, read, etc. Return 1 for identical files, 0 for different.
s1, s2 = sig(os.stat(f1)), sig(os.stat(f2)) Raise exceptions if either file could not be statted, read, etc."""
if s1[0] <> 8 or s2[0] <> 8: s1, s2 = sig(os.stat(f1)), sig(os.stat(f2))
# Either is a not a plain file -- always report as different if s1[0] <> 8 or s2[0] <> 8:
return 0 # Either is a not a plain file -- always report as different
if shallow and s1 == s2: return 0
# type, size & mtime match -- report same if shallow and s1 == s2:
return 1 # type, size & mtime match -- report same
if s1[:2] <> s2[:2]: # Types or sizes differ, don't bother return 1
# types or sizes differ -- report different if s1[:2] <> s2[:2]: # Types or sizes differ, don't bother
return 0 # types or sizes differ -- report different
# same type and size -- look in the cache return 0
key = (f1, f2) # same type and size -- look in the cache
try: key = (f1, f2)
cs1, cs2, outcome = cache[key] try:
# cache hit cs1, cs2, outcome = cache[key]
if s1 == cs1 and s2 == cs2: # cache hit
# cached signatures match if s1 == cs1 and s2 == cs2:
return outcome # cached signatures match
# stale cached signature(s) return outcome
except KeyError: # stale cached signature(s)
# cache miss except KeyError:
pass # cache miss
# really compare pass
outcome = do_cmp(f1, f2) # really compare
cache[key] = s1, s2, outcome outcome = do_cmp(f1, f2)
return outcome cache[key] = s1, s2, outcome
return outcome
def sig(st): # Return signature (i.e., type, size, mtime) from raw stat data def sig(st):
# 0-5: st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid """Return signature (i.e., type, size, mtime) from raw stat data
# 6-9: st_size, st_atime, st_mtime, st_ctime 0-5: st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid
type = st[0] / 4096 6-9: st_size, st_atime, st_mtime, st_ctime"""
size = st[6] type = st[0] / 4096
mtime = st[8] size = st[6]
return type, size, mtime mtime = st[8]
return type, size, mtime
def do_cmp(f1, f2): # Compare two files, really def do_cmp(f1, f2):
bufsize = 8*1024 # Could be tuned """Compare two files, really."""
fp1 = open(f1, 'rb') bufsize = 8*1024 # Could be tuned
fp2 = open(f2, 'rb') fp1 = open(f1, 'rb')
while 1: fp2 = open(f2, 'rb')
b1 = fp1.read(bufsize) while 1:
b2 = fp2.read(bufsize) b1 = fp1.read(bufsize)
if b1 <> b2: return 0 b2 = fp2.read(bufsize)
if not b1: return 1 if b1 <> b2: return 0
if not b1: return 1
This diff is collapsed.
# Helper to provide extensibility for pickle/cPickle. """Helper to provide extensibility for pickle/cPickle."""
dispatch_table = {} dispatch_table = {}
safe_constructors = {} safe_constructors = {}
......
This diff is collapsed.
This diff is collapsed.
# General floating point formatting functions. """General floating point formatting functions.
# Functions: Functions:
# fix(x, digits_behind) fix(x, digits_behind)
# sci(x, digits_behind) sci(x, digits_behind)
# Each takes a number or a string and a number of digits as arguments. Each takes a number or a string and a number of digits as arguments.
# Parameters:
# x: number to be formatted; or a string resembling a number
# digits_behind: number of digits behind the decimal point
Parameters:
x: number to be formatted; or a string resembling a number
digits_behind: number of digits behind the decimal point
"""
import re import re
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment