rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
For method docs, see each method's docstrings. In general, there is a method of the same name to perform each SMTP command, and there is a method called 'sendmail' that will do an entire mail transaction. """ | See each method's docstrings for details. In general, there is a method of the same name to perform each SMTP command. There is also a method called 'sendmail' that will do an entire mail transaction. """ | def quotedata(data): """Quote data for email. Double leading '.', and change Unix newline '\n', or Mac '\r' into Internet CRLF end-of-line. """ return re.sub(r'(?m)^\.', '..', re.sub(r'(?:\r\n|\n|\r(?!\n))', CRLF, data)) |
SMTPRecipientsRefused The server rejected for ALL recipients | SMTPRecipientsRefused The server rejected ALL recipients | def sendmail(self, from_addr, to_addrs, msg, mail_options=[], rcpt_options=[]): """This command performs an entire mail transaction. |
text = text.translate(self.whitespace_trans) | if isinstance(text, str): text = text.translate(self.whitespace_trans) elif isinstance(text, unicode): text = text.translate(self.unicode_whitespace_trans) | def _munge_whitespace(self, text): """_munge_whitespace(text : string) -> string |
entriesbygid = {} | def test_values(self): entries = grp.getgrall() entriesbyname = {} entriesbygid = {} |
|
self.assertEqual(len(e), 4) self.assertEqual(e[0], e.gr_name) self.assert_(isinstance(e.gr_name, basestring)) self.assertEqual(e[1], e.gr_passwd) self.assert_(isinstance(e.gr_passwd, basestring)) self.assertEqual(e[2], e.gr_gid) self.assert_(isinstance(e.gr_gid, int)) self.assertEqual(e[3], e.gr_mem) self.assert_(isinstance(e.gr_mem, list)) | self.check_value(e) entriesbygid.setdefault(e.gr_gid, []).append(e) entriesbyname.setdefault(e.gr_name, []).append(e) | def test_values(self): entries = grp.getgrall() entriesbyname = {} entriesbygid = {} |
entriesbyname.setdefault(e.gr_name, []).append(e) entriesbygid.setdefault(e.gr_gid, []).append(e) | def test_values(self): entries = grp.getgrall() entriesbyname = {} entriesbygid = {} |
|
self.assert_(grp.getgrgid(e.gr_gid) in entriesbygid[e.gr_gid]) self.assert_(grp.getgrnam(e.gr_name) in entriesbyname[e.gr_name]) | e2 = grp.getgrgid(e.gr_gid) self.check_value(e2) self.assert_(max([self.valueseq(e2, x) \ for x in entriesbygid[e.gr_gid]])) e2 = grp.getgrnam(e.gr_name) self.check_value(e2) self.assert_(max([self.valueseq(e2, x) \ for x in entriesbyname[e.gr_name]])) | def test_values(self): entries = grp.getgrall() entriesbyname = {} entriesbygid = {} |
'initial value %r' % (maxcount,)) | 'initial value %r' % self.maxcount | def v(self): self.nonzero.acquire() if self.count == self.maxcount: raise ValueError, '.v() tried to raise semaphore count above ' \ 'initial value %r' % (maxcount,)) self.count = self.count + 1 self.nonzero.signal() self.nonzero.release() |
input = text_file.TextFile('Modules/Setup', join_lines=1) | def build_extensions(self): |
|
while 1: line = input.readline() if not line: break line = line.split() remove_modules.append( line[0] ) input.close() | for filename in ('Modules/Setup', 'Modules/Setup.local'): input = text_file.TextFile(filename, join_lines=1) while 1: line = input.readline() if not line: break line = line.split() remove_modules.append(line[0]) input.close() | def build_extensions(self): |
'.mid': 'audio/midi', '.midi': 'audio/midi', | def read_mime_types(file): try: f = open(file) except IOError: return None db = MimeTypes() db.readfp(f) return db.types_map |
|
'.rtf': 'application/rtf', | def read_mime_types(file): try: f = open(file) except IOError: return None db = MimeTypes() db.readfp(f) return db.types_map |
|
for dirname in sys.path: fullname = os.path.join(dirname, 'profile.doc') if os.path.exists(fullname): sts = os.system('${PAGER-more} ' + fullname) if sts: print '*** Pager exit status:', sts break else: print 'Sorry, can\'t find the help file "profile.doc"', print 'along the Python search path.' | print "Documentation for the profile module can be found " print "in the Python Library Reference, section 'The Python Profiler'." | def help(): for dirname in sys.path: fullname = os.path.join(dirname, 'profile.doc') if os.path.exists(fullname): sts = os.system('${PAGER-more} ' + fullname) if sts: print '*** Pager exit status:', sts break else: print 'Sorry, can\'t find the help file "profile.doc"', print 'along the Python search path.' |
if platform in ('darwin', 'mac'): | if platform in ('darwin', 'mac') and ("--disable-toolbox-glue" not in sysconfig.get_config_var("CONFIG_ARGS")): | def build_extensions(self): |
if platform == 'darwin': | if platform == 'darwin' and ("--disable-toolbox-glue" not in sysconfig.get_config_var("CONFIG_ARGS")): | def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include') |
elif o[-6:] == '.lproj': files = os.listdir(o) for f in files: if f[-4:] == '.nib': nibname = os.path.split(f)[1][:-4] cocoainfo = """ <key>NSMainNibFile</key> <string>%s</string> <key>NSPrincipalClass</key> <string>NSApplication</string>""" % nibname | def process_common_macho(template, progress, code, rsrcname, destname, is_update, raw=0, others=[]): # First make sure the name ends in ".app" if destname[-4:] != '.app': destname = destname + '.app' # Now deduce the short name shortname = os.path.split(destname)[1] if shortname[-4:] == '.app': # Strip the .app suffix shortname = shortname[:-4] # And deduce the .plist and .icns names plistname = None icnsname = None if rsrcname and rsrcname[-5:] == '.rsrc': tmp = rsrcname[:-5] plistname = tmp + '.plist' if os.path.exists(plistname): icnsname = tmp + '.icns' if not os.path.exists(icnsname): icnsname = None else: plistname = None # Start with copying the .app framework if not is_update: exceptlist = ["Contents/Info.plist", "Contents/Resources/English.lproj/InfoPlist.strings", "Contents/Resources/python.rsrc", ] copyapptree(template, destname, exceptlist, progress) # Now either use the .plist file or the default if progress: progress.label('Create info.plist') progress.inc(0) if plistname: shutil.copy2(plistname, os.path.join(destname, 'Contents', 'Info.plist')) if icnsname: icnsdest = os.path.split(icnsname)[1] icnsdest = os.path.join(destname, os.path.join('Contents', 'Resources', icnsdest)) shutil.copy2(icnsname, icnsdest) # XXXX Wrong. This should be parsed from plist file. Also a big hack:-) if shortname == 'PythonIDE': ownertype = 'Pide' else: ownertype = 'PytA' # XXXX Should copy .icns file else: cocoainfo = '' for o in others: if o[-4:] == '.nib': nibname = os.path.split(o)[1][:-4] cocoainfo = """ <key>NSMainNibFile</key> <string>%s</string> <key>NSPrincipalClass</key> <string>NSApplication</string>""" % nibname plistname = os.path.join(template, 'Contents', 'Resources', 'Applet-Info.plist') plistdata = open(plistname).read() plistdata = plistdata % {'appletname':shortname, 'cocoainfo':cocoainfo} ofp = open(os.path.join(destname, 'Contents', 'Info.plist'), 'w') ofp.write(plistdata) ofp.close() ownertype = 'PytA' # Create the PkgInfo file if progress: progress.label('Create PkgInfo') progress.inc(0) ofp = open(os.path.join(destname, 'Contents', 'PkgInfo'), 'wb') ofp.write('APPL' + ownertype) ofp.close() if progress: progress.label("Copy resources...") progress.set(20) resfilename = 'python.rsrc' # XXXX later: '%s.rsrc' % shortname try: output = Res.FSOpenResourceFile( os.path.join(destname, 'Contents', 'Resources', resfilename), u'', WRITE) except MacOS.Error: fsr, dummy = Res.FSCreateResourceFile( os.path.join(destname, 'Contents', 'Resources'), unicode(resfilename), '') output = Res.FSOpenResourceFile(fsr, u'', WRITE) # Copy the resources from the target specific resource template, if any typesfound, ownertype = [], None try: input = macresource.open_pathname(rsrcname) except (MacOS.Error, ValueError): pass if progress: progress.inc(50) else: typesfound, ownertype = copyres(input, output, [], 0, progress) Res.CloseResFile(input) # Check which resource-types we should not copy from the template skiptypes = [] |
|
stat_function = (os.stat, statcache.stat)[use_statcache] s1, s2 = _sig(stat_function(f1)), _sig(stat_function(f2)) if s1[0]!=stat.S_IFREG or s2[0]!=stat.S_IFREG: return 0 if shallow and s1 == s2: return 1 if s1[1]!=s2[1]: return 0 | if use_statcache: stat_function = statcache.stat else: stat_function = os.stat s1 = _sig(stat_function(f1)) s2 = _sig(stat_function(f2)) if s1[0] != stat.S_IFREG or s2[0] != stat.S_IFREG: return 0 if shallow and s1 == s2: return 1 if s1[1] != s2[1]: return 0 | def cmp(f1, f2, shallow=1,use_statcache=0): """Compare two files. Arguments: f1 -- First file name f2 -- Second file name shallow -- Just check stat signature (do not read the files). defaults to 1. use_statcache -- Do not stat() each file directly: go through the statcache module for more efficiency. Return value: integer -- 1 if the files are the same, 0 otherwise. This function uses a cache for past comparisons and the results, with a cache invalidation mechanism relying on stale signatures. Of course, if 'use_statcache' is true, this mechanism is defeated, and the cache will never grow stale. """ stat_function = (os.stat, statcache.stat)[use_statcache] s1, s2 = _sig(stat_function(f1)), _sig(stat_function(f2)) if s1[0]!=stat.S_IFREG or s2[0]!=stat.S_IFREG: return 0 if shallow and s1 == s2: return 1 if s1[1]!=s2[1]: return 0 result = _cache.get((f1, f2)) if result and (s1, s2)==result[:2]: return result[2] outcome = _do_cmp(f1, f2) _cache[f1, f2] = s1, s2, outcome return outcome |
print "path =", `path` if "/arse" in path: import pdb; pdb.set_trace() | def write_results_file(self, path, lines, lnotab, lines_hit): """Return a coverage results file in path.""" |
|
raise IOError(errno.EBADF, "write() on read-only GzipFile object") | raise IOError(errno.EBADF, "read() on write-only GzipFile object") | def read(self, size=-1): if self.mode != READ: import errno raise IOError(errno.EBADF, "write() on read-only GzipFile object") |
elif type(arg) == type(""): | elif isinstance(arg, basestring): | def load_stats(self, arg): if not arg: self.stats = {} elif type(arg) == type(""): f = open(arg, 'rb') self.stats = marshal.load(f) f.close() try: file_stats = os.stat(arg) arg = time.ctime(file_stats.st_mtime) + " " + arg except: # in case this is not unix pass self.files = [ arg ] elif hasattr(arg, 'create_stats'): arg.create_stats() self.stats = arg.stats arg.stats = {} if not self.stats: raise TypeError, "Cannot create or construct a %r object from '%r''" % ( self.__class__, arg) return |
'lambda': ('ref/lambda', 'FUNCTIONS'), | 'lambda': ('ref/lambdas', 'FUNCTIONS'), | def writedocs(dir, pkgpath='', done=None): """Write out HTML documentation for all modules in a directory tree.""" if done is None: done = {} for file in os.listdir(dir): path = os.path.join(dir, file) if ispackage(path): writedocs(path, pkgpath + file + '.', done) elif os.path.isfile(path): modname = inspect.getmodulename(path) if modname: if modname == '__init__': modname = pkgpath[:-1] # remove trailing period else: modname = pkgpath + modname if modname not in done: done[modname] = 1 writedoc(modname) |
'pass': 'PASS', | 'pass': ('ref/pass', ''), | def writedocs(dir, pkgpath='', done=None): """Write out HTML documentation for all modules in a directory tree.""" if done is None: done = {} for file in os.listdir(dir): path = os.path.join(dir, file) if ispackage(path): writedocs(path, pkgpath + file + '.', done) elif os.path.isfile(path): modname = inspect.getmodulename(path) if modname: if modname == '__init__': modname = pkgpath[:-1] # remove trailing period else: modname = pkgpath + modname if modname not in done: done[modname] = 1 writedoc(modname) |
'EXECUTION': ('ref/execframes', ''), 'NAMESPACES': ('ref/execframes', 'global ASSIGNMENT DELETION'), | 'EXECUTION': ('ref/naming', ''), 'NAMESPACES': ('ref/naming', 'global ASSIGNMENT DELETION'), | 'METHODS': ('lib/typesmethods', 'class def CLASSES TYPES'), |
x = property(getx, setx, delx) | x = property(getx, setx, delx, doc="I'm the x property.") | def delx(self): del self.__x |
if not modname: | if not modname or '.' in modname: | def search_function(encoding): # Cache lookup entry = _cache.get(encoding, _unknown) if entry is not _unknown: return entry # Import the module: # # First try to find an alias for the normalized encoding # name and lookup the module using the aliased name, then try to # lookup the module using the standard import scheme, i.e. first # try in the encodings package, then at top-level. # norm_encoding = normalize_encoding(encoding) aliased_encoding = _aliases.get(norm_encoding) or \ _aliases.get(norm_encoding.replace('.', '_')) if aliased_encoding is not None: modnames = [aliased_encoding, norm_encoding] else: modnames = [norm_encoding] for modname in modnames: if not modname: continue try: mod = __import__('encodings.' + modname, globals(), locals(), _import_tail) except ImportError: pass else: break else: mod = None try: getregentry = mod.getregentry except AttributeError: # Not a codec module mod = None if mod is None: # Cache misses _cache[encoding] = None return None # Now ask the module for the registry entry entry = getregentry() if not isinstance(entry, codecs.CodecInfo): if not 4 <= len(entry) <= 7: raise CodecRegistryError,\ 'module "%s" (%s) failed to register' % \ (mod.__name__, mod.__file__) if not callable(entry[0]) or \ not callable(entry[1]) or \ (entry[2] is not None and not callable(entry[2])) or \ (entry[3] is not None and not callable(entry[3])) or \ (len(entry) > 4 and entry[4] is not None and not callable(entry[4])) or \ (len(entry) > 5 and entry[5] is not None and not callable(entry[5])): raise CodecRegistryError,\ 'incompatible codecs in module "%s" (%s)' % \ (mod.__name__, mod.__file__) if len(entry)<7 or entry[6] is None: entry += (None,)*(6-len(entry)) + (mod.__name__.split(".", 1)[1],) entry = codecs.CodecInfo(*entry) # Cache the codec registry entry _cache[encoding] = entry # Register its aliases (without overwriting previously registered # aliases) try: codecaliases = mod.getaliases() except AttributeError: pass else: for alias in codecaliases: if not _aliases.has_key(alias): _aliases[alias] = modname # Return the registry entry return entry |
np = lambda *f: norm(self.tempdir, *f) | def test_glob_literal(self): eq = self.assertSequencesEqual_noorder np = lambda *f: norm(self.tempdir, *f) eq(self.glob('a'), [self.norm('a')]) eq(self.glob('a', 'D'), [self.norm('a', 'D')]) eq(self.glob('aab'), [self.norm('aab')]) eq(self.glob('zymurgy'), []) |
|
np = lambda *f: norm(self.tempdir, *f) | def test_glob_one_directory(self): eq = self.assertSequencesEqual_noorder np = lambda *f: norm(self.tempdir, *f) eq(self.glob('a*'), map(self.norm, ['a', 'aab', 'aaa'])) eq(self.glob('*a'), map(self.norm, ['a', 'aaa'])) eq(self.glob('aa?'), map(self.norm, ['aaa', 'aab'])) eq(self.glob('aa[ab]'), map(self.norm, ['aaa', 'aab'])) eq(self.glob('*q'), []) |
|
np = lambda *f: norm(self.tempdir, *f) | def test_glob_nested_directory(self): eq = self.assertSequencesEqual_noorder np = lambda *f: norm(self.tempdir, *f) if os.path.normcase("abCD") == "abCD": # case-sensitive filesystem eq(self.glob('a', 'bcd', 'E*'), [self.norm('a', 'bcd', 'EF')]) else: # case insensitive filesystem eq(self.glob('a', 'bcd', 'E*'), [self.norm('a', 'bcd', 'EF'), self.norm('a', 'bcd', 'efg')]) eq(self.glob('a', 'bcd', '*g'), [self.norm('a', 'bcd', 'efg')]) |
|
np = lambda *f: norm(self.tempdir, *f) | def test_glob_directory_names(self): eq = self.assertSequencesEqual_noorder np = lambda *f: norm(self.tempdir, *f) eq(self.glob('*', 'D'), [self.norm('a', 'D')]) eq(self.glob('*', '*a'), []) eq(self.glob('a', '*', '*', '*a'), [self.norm('a', 'bcd', 'efg', 'ha')]) eq(self.glob('?a?', '*F'), map(self.norm, [os.path.join('aaa', 'zzzF'), os.path.join('aab', 'F')])) |
|
class Bottom: """A "card-like" object to serve as the bottom for some stacks. Specifically, this is used by the deck and the suit stacks. """ def __init__(self, stack): """Constructor, taking the stack as an argument. We displays ourselves as a gray rectangle the size of a playing card, positioned at the stack's x and y location. We register the stack's bottomhandler to handle clicks. No other behavior. """ self.rect = Rectangle(stack.game.canvas, stack.x, stack.y, stack.x+CARDWIDTH, stack.y+CARDHEIGHT, outline='black', fill='gray') self.rect.bind('<ButtonRelease-1>', stack.bottomhandler) | def bind(self, sequence=None, command=None): |
|
turnover() -- turn the card (face up or down) & raise it onclick(handler), ondouble(handler), onmove(handler), onrelease(handler) -- set various mount event handlers reset() -- move the card out of sight, face down, and reset all event handlers Public instance variables: color, suit, value -- the card's color, suit and value | Public read-only instance variables: suit, value, color -- the card's suit, value and color | def __init__(self, stack): |
Semi-public instance variables (XXX should be made private): | Semi-public read-only instance variables (XXX should be made private): | def __init__(self, stack): |
is reversed.) | is reversed. The card is created face down.) | def __init__(self, stack): |
def __init__(self, game, suit, value): | def __init__(self, suit, value, canvas): """Card constructor. Arguments are the card's suit and value, and the canvas widget. The card is created at position (0, 0), with its face down (adding it to a stack will position it according to that stack's rules). """ | def __init__(self, game, suit, value): |
self.value = value canvas = game.canvas | self.face_shown = 0 | def __init__(self, game, suit, value): |
self.__rect = Rectangle(canvas, 0, 0, CARDWIDTH, CARDHEIGHT, outline='black', fill='white') text = "%s %s" % (VALNAMES[value], suit) self.__text = CanvasText(canvas, CARDWIDTH/2, 0, anchor=N, fill=self.color, text=text) self.group = Group(canvas) | def __init__(self, game, suit, value): |
|
self.group.addtag_withtag(self.__rect) self.group.addtag_withtag(self.__text) self.reset() | def __init__(self, game, suit, value): |
|
return "Card(game, %s, %s)" % (`self.suit`, `self.value`) | return "Card(%s, %s)" % (`self.suit`, `self.value`) | def __repr__(self): |
dx = x - self.x dy = y - self.y | self.moveby(x - self.x, y - self.y) def moveby(self, dx, dy): """Move the card by (dx, dy).""" self.x = self.x + dx self.y = self.y + dy | def moveto(self, x, y): |
self.x = x self.y = y def moveby(self, dx, dy): self.moveto(self.x + dx, self.y + dy) | def moveto(self, x, y): |
|
def turnover(self): if self.face_shown: self.showback() | class Stack: """A generic stack of cards. This is used as a base class for all other stacks (e.g. the deck, the suit stacks, and the row stacks). Public methods: add(card) -- add a card to the stack delete(card) -- delete a card from the stack showtop() -- show the top card (if any) face up deal() -- delete and return the top card, or None if empty Method that subclasses may override: position(card) -- move the card to its proper (x, y) position The default position() method places all cards at the stack's own (x, y) position. userclickhandler(), userdoubleclickhandler() -- called to do subclass specific things on single and double clicks The default user (single) click handler shows the top card face up. The default user double click handler calls the user single click handler. usermovehandler(cards) -- called to complete a subpile move The default user move handler moves all moved cards back to their original position (by calling the position() method). Private methods: clickhandler(event), doubleclickhandler(event), motionhandler(event), releasehandler(event) -- event handlers The default event handlers turn the top card of the stack with its face up on a (single or double) click, and also support moving a subpile around. startmoving(event) -- begin a move operation finishmoving() -- finish a move operation """ def __init__(self, x, y, game=None): """Stack constructor. Arguments are the stack's nominal x and y position (the top left corner of the first card placed in the stack), and the game object (which is used to get the canvas; subclasses use the game object to find other stacks). """ self.x = x self.y = y self.game = game self.cards = [] self.group = Group(self.game.canvas) self.group.bind('<1>', self.clickhandler) self.group.bind('<Double-1>', self.doubleclickhandler) self.group.bind('<B1-Motion>', self.motionhandler) self.group.bind('<ButtonRelease-1>', self.releasehandler) self.makebottom() def makebottom(self): pass def __repr__(self): """Return a string for debug print statements.""" return "%s(%d, %d)" % (self.__class__.__name__, self.x, self.y) def add(self, card): self.cards.append(card) card.tkraise() self.position(card) self.group.addtag_withtag(card.group) def delete(self, card): self.cards.remove(card) card.group.dtag(self.group) def showtop(self): if self.cards: self.cards[-1].showface() def deal(self): if not self.cards: return None card = self.cards[-1] self.delete(card) return card def position(self, card): card.moveto(self.x, self.y) def userclickhandler(self): self.showtop() def userdoubleclickhandler(self): self.userclickhandler() def usermovehandler(self, cards): for card in cards: self.position(card) def clickhandler(self, event): self.finishmoving() self.userclickhandler() self.startmoving(event) def motionhandler(self, event): self.keepmoving(event) def releasehandler(self, event): self.keepmoving(event) self.finishmoving() def doubleclickhandler(self, event): self.finishmoving() self.userdoubleclickhandler() self.startmoving(event) moving = None def startmoving(self, event): self.moving = None tags = self.game.canvas.gettags('current') for i in range(len(self.cards)): card = self.cards[i] if card.group.tag in tags: break | def turnover(self): |
self.showface() def onclick(self, handler): self.group.bind('<1>', handler) def ondouble(self, handler): self.group.bind('<Double-1>', handler) def onmove(self, handler): self.group.bind('<B1-Motion>', handler) def onrelease(self, handler): self.group.bind('<ButtonRelease-1>', handler) def reset(self): self.moveto(-1000, -1000) self.onclick('') self.ondouble('') self.onmove('') self.onrelease('') self.showback() class Deck: def __init__(self, game): self.game = game self.allcards = [] | return if not card.face_shown: return self.moving = self.cards[i:] self.lastx = event.x self.lasty = event.y for card in self.moving: card.tkraise() def keepmoving(self, event): if not self.moving: return dx = event.x - self.lastx dy = event.y - self.lasty self.lastx = event.x self.lasty = event.y if dx or dy: for card in self.moving: card.moveby(dx, dy) def finishmoving(self): cards = self.moving self.moving = None if cards: self.usermovehandler(cards) class Deck(Stack): """The deck is a stack with support for shuffling. New methods: fill() -- create the playing cards shuffle() -- shuffle the playing cards A single click moves the top card to the game's open deck and moves it face up; if we're out of cards, it moves the open deck back to the deck. """ def makebottom(self): bottom = Rectangle(self.game.canvas, self.x, self.y, self.x+CARDWIDTH, self.y+CARDHEIGHT, outline='black', fill=BACKGROUND) self.group.addtag_withtag(bottom) def fill(self): | def turnover(self): |
self.allcards.append(Card(self.game, suit, value)) self.reset() | self.add(Card(suit, value, self.game.canvas)) | def __init__(self, game): |
def deal(self): card = self.cards[-1] del self.cards[-1] return card def accept(self, card): if card not in self.cards: self.cards.append(card) def reset(self): self.cards = self.allcards[:] for card in self.cards: card.reset() | def userclickhandler(self): opendeck = self.game.opendeck card = self.deal() if not card: while 1: card = opendeck.deal() if not card: break self.add(card) card.showback() else: self.game.opendeck.add(card) card.showface() | def deal(self): |
class Stack: x = MARGIN y = MARGIN def __init__(self, game): self.game = game self.cards = [] def __repr__(self): return "<Stack at (%d, %d)>" % (self.x, self.y) def reset(self): self.cards = [] def acceptable(self, cards): return 1 def accept(self, card): self.cards.append(card) card.onclick(self.clickhandler) card.onmove(self.movehandler) card.onrelease(self.releasehandler) card.ondouble(self.doublehandler) card.tkraise() self.placecard(card) def placecard(self, card): card.moveto(self.x, self.y) def showtop(self): if self.cards: self.cards[-1].showface() def clickhandler(self, event): pass def movehandler(self, event): pass def releasehandler(self, event): pass def doublehandler(self, event): pass class PoolStack(Stack): def __init__(self, game): Stack.__init__(self, game) self.bottom = Bottom(self) def releasehandler(self, event): | class OpenStack(Stack): def usermovehandler(self, cards): card = cards[0] stack = self.game.closeststack(card) if not stack or stack is self or not stack.acceptable(cards): Stack.usermovehandler(self, cards) else: for card in cards: self.delete(card) stack.add(card) self.game.wincheck() def userdoubleclickhandler(self): | def randperm(n): r = range(n) x = [] while r: i = random.choice(r) x.append(i) r.remove(i) return x |
self.game.turned.accept(card) del self.cards[-1] card.showface() def bottomhandler(self, event): cards = self.game.turned.cards cards.reverse() for card in cards: card.showback() self.accept(card) self.game.turned.reset() class MovingStack(Stack): thecards = None theindex = None def clickhandler(self, event): self.thecards = self.theindex = None tags = self.game.canvas.gettags('current') if not tags: | if not card.face_shown: self.userclickhandler() | def releasehandler(self, event): |
tag = tags[0] for i in range(len(self.cards)): card = self.cards[i] if tag == str(card.group): | for s in self.game.suits: if s.acceptable([card]): self.delete(card) s.add(card) self.game.wincheck() | def clickhandler(self, event): |
else: return self.theindex = i self.thecards = Group(self.game.canvas) for card in self.cards[i:]: self.thecards.addtag_withtag(card.group) self.thecards.tkraise() self.lastx = self.firstx = event.x self.lasty = self.firsty = event.y def movehandler(self, event): if not self.thecards: return card = self.cards[self.theindex] if not card.face_shown: return dx = event.x - self.lastx dy = event.y - self.lasty self.thecards.move(dx, dy) self.lastx = event.x self.lasty = event.y def releasehandler(self, event): cards = self._endmove() if not cards: return card = cards[0] if not card.face_shown: if len(cards) == 1: card.showface() self.thecards = self.theindex = None return stack = self.game.closeststack(cards[0]) if stack and stack is not self and stack.acceptable(cards): for card in cards: stack.accept(card) self.cards.remove(card) else: for card in cards: self.placecard(card) def doublehandler(self, event): cards = self._endmove() if not cards: return for stack in self.game.suits: if stack.acceptable(cards): break else: return for card in cards: stack.accept(card) del self.cards[self.theindex:] self.thecards = self.theindex = None def _endmove(self): if not self.thecards: return [] self.thecards.move(self.firstx - self.lastx, self.firsty - self.lasty) self.thecards.dtag() cards = self.cards[self.theindex:] if not cards: return [] card = cards[0] card.moveby(self.lastx - self.firstx, self.lasty - self.firsty) self.lastx = self.firstx self.lasty = self.firsty return cards class TurnedStack(MovingStack): x = XSPACING + MARGIN y = MARGIN class SuitStack(MovingStack): y = MARGIN def __init__(self, game, i): self.index = i self.x = MARGIN + XSPACING * (i+3) Stack.__init__(self, game) self.bottom = Bottom(self) bottomhandler = "" def __repr__(self): return "SuitStack(game, %d)" % self.index | class SuitStack(OpenStack): def makebottom(self): bottom = Rectangle(self.game.canvas, self.x, self.y, self.x+CARDWIDTH, self.y+CARDHEIGHT, outline='black', fill='') def userclickhandler(self): pass def userdoubleclickhandler(self): pass | def clickhandler(self, event): |
if not card.face_shown: return 0 | def acceptable(self, cards): |
|
if not topcard.face_shown: return 0 | def acceptable(self, cards): |
|
def doublehandler(self, event): pass def accept(self, card): MovingStack.accept(self, card) if card.value == KING: for s in self.game.suits: card = s.cards[-1] if card.value != KING: return self.game.win() self.game.deal() class RowStack(MovingStack): def __init__(self, game, i): self.index = i self.x = MARGIN + XSPACING * i self.y = MARGIN + YSPACING Stack.__init__(self, game) def __repr__(self): return "RowStack(game, %d)" % self.index def placecard(self, card): offset = 0 for c in self.cards: if c is card: break if c.face_shown: offset = offset + 2*MARGIN else: offset = offset + OFFSET card.moveto(self.x, self.y + offset) | class RowStack(OpenStack): | def doublehandler(self, event): |
if card.value != topcard.value - 1: return 0 if card.color == topcard.color: return 0 return 1 | return card.color != topcard.color and card.value == topcard.value - 1 def position(self, card): y = self.y for c in self.cards: if c == card: break if c.face_shown: y = y + 2*MARGIN else: y = y + OFFSET card.moveto(self.x, y) | def acceptable(self, cards): |
self.buttonframe = Frame(self.master, background=BACKGROUND) self.buttonframe.pack(fill=X) self.dealbutton = Button(self.buttonframe, | self.canvas = Canvas(self.master, background=BACKGROUND, highlightthickness=0, width=NROWS*XSPACING, height=3*YSPACING + 20 + MARGIN) self.canvas.pack(fill=BOTH, expand=TRUE) self.dealbutton = Button(self.canvas, | def __init__(self, master): |
self.dealbutton.pack(side=LEFT) self.canvas = Canvas(self.master, background=BACKGROUND, highlightthickness=0, width=NROWS*XSPACING, height=3*YSPACING) self.canvas.pack(fill=BOTH, expand=TRUE) self.deck = Deck(self) | Window(self.canvas, MARGIN, 3*YSPACING + 20, window=self.dealbutton, anchor=SW) x = MARGIN y = MARGIN self.deck = Deck(x, y, self) x = x + XSPACING self.opendeck = OpenStack(x, y, self) | def __init__(self, master): |
self.pool = PoolStack(self) self.turned = TurnedStack(self) | x = x + XSPACING | def __init__(self, master): |
self.suits.append(SuitStack(self, i)) | x = x + XSPACING self.suits.append(SuitStack(x, y, self)) x = MARGIN y = y + YSPACING | def __init__(self, master): |
self.rows.append(RowStack(self, i)) | self.rows.append(RowStack(x, y, self)) x = x + XSPACING | def __init__(self, master): |
cards = self.deck.allcards | cards = [] for s in self.suits: cards = cards + s.cards if not cards: return | def win(self): |
def reset(self): self.pool.reset() self.turned.reset() for stack in self.rows + self.suits: stack.reset() self.deck.reset() | def reset(self): |
|
r.accept(card) | r.add(card) | def deal(self): |
try: | def reset(self): for stack in [self.opendeck] + self.suits + self.rows: | def deal(self): |
self.pool.accept(self.deck.deal()) except IndexError: pass | card = stack.deal() if not card: break self.deck.add(card) card.showback() | def deal(self): |
if y.hasattr('__setstate__'): | if hasattr(y, '__setstate__'): | def _copy_inst(x): if hasattr(x, '__copy__'): return x.__copy__() if hasattr(x, '__getinitargs__'): args = x.__getinitargs__() else: args = () y = apply(x.__class__, args) if hasattr(x, '__getstate__'): state = x.__getstate__() else: state = x.__dict__ if y.hasattr('__setstate__'): y.__setstate__(state) else: for key in state.keys(): setattr(y, key, state[key]) return y |
if y.hasattr('__setstate__'): | if hasattr(y, '__setstate__'): | def _deepcopy_inst(x, memo): if hasattr(x, '__deepcopy__'): return x.__deepcopy__() if hasattr(x, '__getinitargs__'): args = x.__getinitargs__() args = deepcopy(args, memo) else: args = () y = apply(x.__class__, args) memo[id(x)] = y if hasattr(x, '__getstate__'): state = x.__getstate__() else: state = x.__dict__ state = deepcopy(state, memo) if y.hasattr('__setstate__'): y.__setstate__(state) else: for key in state.keys(): setattr(y, key, state[key]) return y |
libraries, library_dirs) | libraries, library_dirs, build_info) | def build_extensions (self, extensions): |
import Scrap | from Carbon import Scrap | def domenu_copy(self, *args): sel = self.getselectedobjects() selitems = [] for key, value, dummy, dummy in sel: selitems.append(double_repr(key, value)) text = string.join(selitems, '\r') if text: import Scrap Scrap.ZeroScrap() Scrap.PutScrap('TEXT', text) |
self.checkequal(('http://www.python.org', '', ''), S, 'rpartition', '?') | self.checkequal(('', '', 'http://www.python.org'), S, 'rpartition', '?') | def test_rpartition(self): |
host, XXX = splithost(r_type) if '@' in host: user_pass, host = host.split('@', 1) if ':' in user_pass: user, password = user_pass.split(':', 1) user_pass = base64.encodestring('%s:%s' % (unquote(user), unquote(password))).strip() req.add_header('Proxy-authorization', 'Basic ' + user_pass) | if not type or r_type.isdigit(): type = orig_type host = proxy else: host, r_host = splithost(r_type) user_pass, host = splituser(host) user, password = splitpasswd(user_pass) if user and password: user, password = user_pass.split(':', 1) user_pass = base64.encodestring('%s:%s' % (unquote(user), unquote(password))).strip() req.add_header('Proxy-authorization', 'Basic ' + user_pass) | def proxy_open(self, req, proxy, type): orig_type = req.get_type() type, r_type = splittype(proxy) host, XXX = splithost(r_type) if '@' in host: user_pass, host = host.split('@', 1) if ':' in user_pass: user, password = user_pass.split(':', 1) user_pass = base64.encodestring('%s:%s' % (unquote(user), unquote(password))).strip() req.add_header('Proxy-authorization', 'Basic ' + user_pass) host = unquote(host) req.set_proxy(host, type) if orig_type == type: # let other handlers take care of it # XXX this only makes sense if the proxy is before the # other handlers return None else: # need to start over, because the other handlers don't # grok the proxy's URL type return self.parent.open(req) |
self.d.GetDialogWindow().ShowWindow() | self.w.ShowWindow() | def __init__(self, title="Working...", maxval=100, label="", id=263): self.maxval = maxval self.curval = -1 self.d = GetNewDialog(id, -1) self.label(label) self._update(0) self.d.AutoSizeDialog() self.title(title) self.d.GetDialogWindow().ShowWindow() self.d.DrawDialog() |
self.d.BringToFront() self.d.HideWindow() | self.w.BringToFront() self.w.HideWindow() del self.w | def __del__( self ): self.d.BringToFront() self.d.HideWindow() del self.d |
w = self.d.GetDialogWindow() w.BringToFront() w.SetWTitle(newstr) | self.w.BringToFront() self.w.SetWTitle(newstr) | def title(self, newstr=""): """title(text) - Set title of progress window""" w = self.d.GetDialogWindow() w.BringToFront() w.SetWTitle(newstr) |
self.d.GetDialogWindow().BringToFront() | self.w.BringToFront() | def label( self, *newstr ): """label(text) - Set text in progress box""" self.d.GetDialogWindow().BringToFront() if newstr: self._label = lf2cr(newstr[0]) text_h = self.d.GetDialogItemAsControl(2) SetDialogItemText(text_h, self._label) |
return "-R" + dir | compiler = os.path.basename(sysconfig.get_config_var("CC")) if compiler == "gcc" or compiler == "g++": return "-Wl,-R" + dir else: return "-R" + dir | def runtime_library_dir_option (self, dir): return "-R" + dir |
tarinfo = self.tarfile.next() if not tarinfo: self.tarfile._loaded = True raise StopIteration | if not self.tarfile._loaded: tarinfo = self.tarfile.next() if not tarinfo: self.tarfile._loaded = True raise StopIteration else: try: tarinfo = self.tarfile.members[self.index] except IndexError: raise StopIteration self.index += 1 | def next(self): """Return the next item using TarFile's next() method. When all members have been read, set TarFile as _loaded. """ tarinfo = self.tarfile.next() if not tarinfo: self.tarfile._loaded = True raise StopIteration return tarinfo |
print "reinitialize_command: command=%s" % command print " before: have_run =", self.have_run | def reinitialize_command (self, command, reinit_subcommands=0): """Reinitializes a command to the state it was in when first returned by 'get_command_obj()': ie., initialized but not yet finalized. This provides the opportunity to sneak option values in programmatically, overriding or supplementing user-supplied values from the config files and command line. You'll have to re-finalize the command object (by calling 'finalize_options()' or 'ensure_finalized()') before using it for real. |
|
print " after: have_run =", self.have_run | def reinitialize_command (self, command, reinit_subcommands=0): """Reinitializes a command to the state it was in when first returned by 'get_command_obj()': ie., initialized but not yet finalized. This provides the opportunity to sneak option values in programmatically, overriding or supplementing user-supplied values from the config files and command line. You'll have to re-finalize the command object (by calling 'finalize_options()' or 'ensure_finalized()') before using it for real. |
|
print (" reinitializing sub-commands: %s" % command.get_sub_commands()) | def reinitialize_command (self, command, reinit_subcommands=0): """Reinitializes a command to the state it was in when first returned by 'get_command_obj()': ie., initialized but not yet finalized. This provides the opportunity to sneak option values in programmatically, overriding or supplementing user-supplied values from the config files and command line. You'll have to re-finalize the command object (by calling 'finalize_options()' or 'ensure_finalized()') before using it for real. |
|
if version > 7.0: self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1") else: self.set_macro("FrameworkSDKDir", net, "sdkinstallroot") | try: if version > 7.0: self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1") else: self.set_macro("FrameworkSDKDir", net, "sdkinstallroot") except KeyError, exc: raise DistutilsPlatformError, \ ("The .NET Framework SDK needs to be installed before " "building extensions for Python.") | def load_macros(self, version): vsbase = r"Software\Microsoft\VisualStudio\%0.1f" % version self.set_macro("VCInstallDir", vsbase + r"\Setup\VC", "productdir") self.set_macro("VSInstallDir", vsbase + r"\Setup\VS", "productdir") net = r"Software\Microsoft\.NETFramework" self.set_macro("FrameworkDir", net, "installroot") if version > 7.0: self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1") else: self.set_macro("FrameworkSDKDir", net, "sdkinstallroot") |
ad = self.getaddress() if ad: return ad + self.getaddrlist() else: return [] | result = [] while 1: ad = self.getaddress() if ad: result += ad else: break return result | def getaddrlist(self): """Parse all addresses. |
fullurl = unwrap(fullurl) | fullurl = unwrap(toBytes(fullurl)) | def open(self, fullurl, data=None): """Use URLopener().open(file) instead of open(file, 'r').""" fullurl = unwrap(fullurl) if self.tempcache and self.tempcache.has_key(fullurl): filename, headers = self.tempcache[fullurl] fp = open(filename, 'rb') return addinfourl(fp, headers, fullurl) type, url = splittype(fullurl) if not type: type = 'file' if self.proxies.has_key(type): proxy = self.proxies[type] type, proxyhost = splittype(proxy) host, selector = splithost(proxyhost) url = (host, fullurl) # Signal special case to open_*() else: proxy = None name = 'open_' + type self.type = type if '-' in name: # replace - with _ name = string.join(string.split(name, '-'), '_') if not hasattr(self, name): if proxy: return self.open_unknown_proxy(proxy, fullurl, data) else: return self.open_unknown(fullurl, data) try: if data is None: return getattr(self, name)(url) else: return getattr(self, name)(url, data) except socket.error, msg: raise IOError, ('socket error', msg), sys.exc_info()[2] |
type, url = splittype(fullurl) if not type: type = 'file' if self.proxies.has_key(type): proxy = self.proxies[type] type, proxyhost = splittype(proxy) | urltype, url = splittype(fullurl) if not urltype: urltype = 'file' if self.proxies.has_key(urltype): proxy = self.proxies[urltype] urltype, proxyhost = splittype(proxy) | def open(self, fullurl, data=None): """Use URLopener().open(file) instead of open(file, 'r').""" fullurl = unwrap(fullurl) if self.tempcache and self.tempcache.has_key(fullurl): filename, headers = self.tempcache[fullurl] fp = open(filename, 'rb') return addinfourl(fp, headers, fullurl) type, url = splittype(fullurl) if not type: type = 'file' if self.proxies.has_key(type): proxy = self.proxies[type] type, proxyhost = splittype(proxy) host, selector = splithost(proxyhost) url = (host, fullurl) # Signal special case to open_*() else: proxy = None name = 'open_' + type self.type = type if '-' in name: # replace - with _ name = string.join(string.split(name, '-'), '_') if not hasattr(self, name): if proxy: return self.open_unknown_proxy(proxy, fullurl, data) else: return self.open_unknown(fullurl, data) try: if data is None: return getattr(self, name)(url) else: return getattr(self, name)(url, data) except socket.error, msg: raise IOError, ('socket error', msg), sys.exc_info()[2] |
name = 'open_' + type self.type = type | name = 'open_' + urltype self.type = urltype | def open(self, fullurl, data=None): """Use URLopener().open(file) instead of open(file, 'r').""" fullurl = unwrap(fullurl) if self.tempcache and self.tempcache.has_key(fullurl): filename, headers = self.tempcache[fullurl] fp = open(filename, 'rb') return addinfourl(fp, headers, fullurl) type, url = splittype(fullurl) if not type: type = 'file' if self.proxies.has_key(type): proxy = self.proxies[type] type, proxyhost = splittype(proxy) host, selector = splithost(proxyhost) url = (host, fullurl) # Signal special case to open_*() else: proxy = None name = 'open_' + type self.type = type if '-' in name: # replace - with _ name = string.join(string.split(name, '-'), '_') if not hasattr(self, name): if proxy: return self.open_unknown_proxy(proxy, fullurl, data) else: return self.open_unknown(fullurl, data) try: if data is None: return getattr(self, name)(url) else: return getattr(self, name)(url, data) except socket.error, msg: raise IOError, ('socket error', msg), sys.exc_info()[2] |
url = unwrap(url) | url = unwrap(toBytes(url)) | def retrieve(self, url, filename=None, reporthook=None, data=None): """retrieve(url) returns (filename, None) for a local object or (tempfilename, headers) for a remote object.""" url = unwrap(url) if self.tempcache and self.tempcache.has_key(url): return self.tempcache[url] type, url1 = splittype(url) if not filename and (not type or type == 'file'): try: fp = self.open_local_file(url1) hdrs = fp.info() del fp return url2pathname(splithost(url1)[1]), hdrs except IOError, msg: pass fp = self.open(url, data) headers = fp.info() if not filename: import tempfile garbage, path = splittype(url) garbage, path = splithost(path or "") path, garbage = splitquery(path or "") path, garbage = splitattr(path or "") suffix = os.path.splitext(path)[1] filename = tempfile.mktemp(suffix) self.__tempfiles.append(filename) result = filename, headers if self.tempcache is not None: self.tempcache[url] = result tfp = open(filename, 'wb') bs = 1024*8 size = -1 blocknum = 1 if reporthook: if headers.has_key("content-length"): size = int(headers["Content-Length"]) reporthook(0, bs, size) block = fp.read(bs) if reporthook: reporthook(1, bs, size) while block: tfp.write(block) block = fp.read(bs) blocknum = blocknum + 1 if reporthook: reporthook(blocknum, bs, size) fp.close() tfp.close() del fp del tfp return result |
if type(url) is type(""): | if type(url) is types.StringType: | def open_http(self, url, data=None): """Use HTTP protocol.""" import httplib user_passwd = None if type(url) is type(""): host, selector = splithost(url) if host: user_passwd, host = splituser(host) host = unquote(host) realhost = host else: host, selector = url urltype, rest = splittype(selector) url = rest user_passwd = None if string.lower(urltype) != 'http': realhost = None else: realhost, rest = splithost(rest) if realhost: user_passwd, realhost = splituser(realhost) if user_passwd: selector = "%s://%s%s" % (urltype, realhost, rest) #print "proxy via http:", host, selector if not host: raise IOError, ('http error', 'no host given') if user_passwd: import base64 auth = string.strip(base64.encodestring(user_passwd)) else: auth = None h = httplib.HTTP(host) if data is not None: h.putrequest('POST', selector) h.putheader('Content-type', 'application/x-www-form-urlencoded') h.putheader('Content-length', '%d' % len(data)) else: h.putrequest('GET', selector) if auth: h.putheader('Authorization', 'Basic %s' % auth) if realhost: h.putheader('Host', realhost) for args in self.addheaders: apply(h.putheader, args) h.endheaders() if data is not None: h.send(data + '\r\n') errcode, errmsg, headers = h.getreply() fp = h.getfile() if errcode == 200: return addinfourl(fp, headers, "http:" + url) else: if data is None: return self.http_error(url, fp, errcode, errmsg, headers) else: return self.http_error(url, fp, errcode, errmsg, headers, data) |
if type(url) is type(""): | if type(url) in types.StringTypes: | def open_https(self, url, data=None): """Use HTTPS protocol.""" import httplib user_passwd = None if type(url) is type(""): host, selector = splithost(url) if host: user_passwd, host = splituser(host) host = unquote(host) realhost = host else: host, selector = url urltype, rest = splittype(selector) url = rest user_passwd = None if string.lower(urltype) != 'https': realhost = None else: realhost, rest = splithost(rest) if realhost: user_passwd, realhost = splituser(realhost) if user_passwd: selector = "%s://%s%s" % (urltype, realhost, rest) #print "proxy via https:", host, selector if not host: raise IOError, ('https error', 'no host given') if user_passwd: import base64 auth = string.strip(base64.encodestring(user_passwd)) else: auth = None h = httplib.HTTPS(host, 0, key_file=self.key_file, cert_file=self.cert_file) if data is not None: h.putrequest('POST', selector) h.putheader('Content-type', 'application/x-www-form-urlencoded') h.putheader('Content-length', '%d' % len(data)) else: h.putrequest('GET', selector) if auth: h.putheader('Authorization: Basic %s' % auth) if realhost: h.putheader('Host', realhost) for args in self.addheaders: apply(h.putheader, args) h.endheaders() if data is not None: h.send(data + '\r\n') errcode, errmsg, headers = h.getreply() fp = h.getfile() if errcode == 200: return addinfourl(fp, headers, url) else: if data is None: return self.http_error(url, fp, errcode, errmsg, headers) else: return self.http_error(url, fp, errcode, errmsg, headers, data) |
if os.sep != '/' and os.sep in pathname: raise ValueError, \ "path '%s' cannot contain '%c' character" % \ (pathname, os.sep) paths = string.split (pathname, '/') return apply (os.path.join, paths) | if os.sep != '/': if os.sep in pathname: raise ValueError, \ "path '%s' cannot contain '%c' character" % (pathname, os.sep) else: paths = string.split (pathname, '/') return apply (os.path.join, paths) | def native_path (pathname): """Return 'pathname' as a name that will work on the native filesystem, i.e. split it on '/' and put it back together again using the current directory separator. Needed because filenames in the setup script are always supplied in Unix style, and have to be converted to the local convention before we can actually use them in the filesystem. Raises ValueError if 'pathname' is absolute (starts with '/') or contains local directory separators (unless the local separator is '/', of course).""" if pathname[0] == '/': raise ValueError, "path '%s' cannot be absolute" % pathname if pathname[-1] == '/': raise ValueError, "path '%s' cannot end with '/'" % pathname if os.sep != '/' and os.sep in pathname: raise ValueError, \ "path '%s' cannot contain '%c' character" % \ (pathname, os.sep) paths = string.split (pathname, '/') return apply (os.path.join, paths) else: return pathname |
return s[:1] == '/' | return s.startswith('/') | def isabs(s): """Test whether a path is absolute""" return s[:1] == '/' |
if b[:1] == '/': | if b.startswith('/'): | def join(a, *p): """Join two or more pathname components, inserting '/' as needed""" path = a for b in p: if b[:1] == '/': path = b elif path == '' or path[-1:] == '/': path = path + b else: path = path + '/' + b return path |
elif path == '' or path[-1:] == '/': path = path + b | elif path == '' or path.endswith('/'): path += b | def join(a, *p): """Join two or more pathname components, inserting '/' as needed""" path = a for b in p: if b[:1] == '/': path = b elif path == '' or path[-1:] == '/': path = path + b else: path = path + '/' + b return path |
path = path + '/' + b | path += '/' + b | def join(a, *p): """Join two or more pathname components, inserting '/' as needed""" path = a for b in p: if b[:1] == '/': path = b elif path == '' or path[-1:] == '/': path = path + b else: path = path + '/' + b return path |
while head[-1] == '/': head = head[:-1] | head = head.rstrip('/') | def split(p): """Split a pathname. Returns tuple "(head, tail)" where "tail" is everything after the final slash. Either part may be empty.""" i = p.rfind('/') + 1 head, tail = p[:i], p[i:] if head and head != '/'*len(head): while head[-1] == '/': head = head[:-1] return head, tail |
if path[:1] != '~': | if not path.startswith('~'): | def expanduser(path): """Expand ~ and ~user constructions. If user or $HOME is unknown, do nothing.""" if path[:1] != '~': return path i, n = 1, len(path) while i < n and path[i] != '/': i = i + 1 if i == 1: if not 'HOME' in os.environ: import pwd userhome = pwd.getpwuid(os.getuid())[5] else: userhome = os.environ['HOME'] else: import pwd try: pwent = pwd.getpwnam(path[1:i]) except KeyError: return path userhome = pwent[5] if userhome[-1:] == '/': i = i + 1 return userhome + path[i:] |
i = i + 1 | i += 1 | def expanduser(path): """Expand ~ and ~user constructions. If user or $HOME is unknown, do nothing.""" if path[:1] != '~': return path i, n = 1, len(path) while i < n and path[i] != '/': i = i + 1 if i == 1: if not 'HOME' in os.environ: import pwd userhome = pwd.getpwuid(os.getuid())[5] else: userhome = os.environ['HOME'] else: import pwd try: pwent = pwd.getpwnam(path[1:i]) except KeyError: return path userhome = pwent[5] if userhome[-1:] == '/': i = i + 1 return userhome + path[i:] |
userhome = pwd.getpwuid(os.getuid())[5] | userhome = pwd.getpwuid(os.getuid()).pw_dir | def expanduser(path): """Expand ~ and ~user constructions. If user or $HOME is unknown, do nothing.""" if path[:1] != '~': return path i, n = 1, len(path) while i < n and path[i] != '/': i = i + 1 if i == 1: if not 'HOME' in os.environ: import pwd userhome = pwd.getpwuid(os.getuid())[5] else: userhome = os.environ['HOME'] else: import pwd try: pwent = pwd.getpwnam(path[1:i]) except KeyError: return path userhome = pwent[5] if userhome[-1:] == '/': i = i + 1 return userhome + path[i:] |
userhome = pwent[5] if userhome[-1:] == '/': i = i + 1 | userhome = pwent.pw_dir if userhome.endswith('/'): i += 1 | def expanduser(path): """Expand ~ and ~user constructions. If user or $HOME is unknown, do nothing.""" if path[:1] != '~': return path i, n = 1, len(path) while i < n and path[i] != '/': i = i + 1 if i == 1: if not 'HOME' in os.environ: import pwd userhome = pwd.getpwuid(os.getuid())[5] else: userhome = os.environ['HOME'] else: import pwd try: pwent = pwd.getpwnam(path[1:i]) except KeyError: return path userhome = pwent[5] if userhome[-1:] == '/': i = i + 1 return userhome + path[i:] |
if name[:1] == '{' and name[-1:] == '}': | if name.startswith('{') and name.endswith('}'): | def expandvars(path): """Expand shell variables of form $var and ${var}. Unknown variables are left unchanged.""" global _varprog if '$' not in path: return path if not _varprog: import re _varprog = re.compile(r'\$(\w+|\{[^}]*\})') i = 0 while True: m = _varprog.search(path, i) if not m: break i, j = m.span(0) name = m.group(1) if name[:1] == '{' and name[-1:] == '}': name = name[1:-1] if name in os.environ: tail = path[j:] path = path[:i] + os.environ[name] i = len(path) path = path + tail else: i = j return path |
path = path + tail | path += tail | def expandvars(path): """Expand shell variables of form $var and ${var}. Unknown variables are left unchanged.""" global _varprog if '$' not in path: return path if not _varprog: import re _varprog = re.compile(r'\$(\w+|\{[^}]*\})') i = 0 while True: m = _varprog.search(path, i) if not m: break i, j = m.span(0) name = m.group(1) if name[:1] == '{' and name[-1:] == '}': name = name[1:-1] if name in os.environ: tail = path[j:] path = path[:i] + os.environ[name] i = len(path) path = path + tail else: i = j return path |
main() | def testtype(type, example): a = array.array(type) a.append(example) if verbose: print 40*'*' print 'array after append: ', a a.typecode a.itemsize if a.typecode in ('i', 'b', 'h', 'l'): a.byteswap() if a.typecode == 'c': f = open(TESTFN, "w") f.write("The quick brown fox jumps over the lazy dog.\n") f.close() f = open(TESTFN, 'r') a.fromfile(f, 10) f.close() if verbose: print 'char array with 10 bytes of TESTFN appended: ', a a.fromlist(['a', 'b', 'c']) if verbose: print 'char array with list appended: ', a a.insert(0, example) if verbose: print 'array of %s after inserting another:' % a.typecode, a f = open(TESTFN, 'w') a.tofile(f) f.close() a.tolist() a.tostring() if verbose: print 'array of %s converted to a list: ' % a.typecode, a.tolist() if verbose: print 'array of %s converted to a string: ' \ % a.typecode, `a.tostring()` if type == 'c': a = array.array(type, "abcde") a[:-1] = a if a != array.array(type, "abcdee"): raise TestFailed, "array(%s) self-slice-assign (head)" % `type` a = array.array(type, "abcde") a[1:] = a if a != array.array(type, "aabcde"): raise TestFailed, "array(%s) self-slice-assign (tail)" % `type` a = array.array(type, "abcde") a[1:-1] = a if a != array.array(type, "aabcdee"): raise TestFailed, "array(%s) self-slice-assign (cntr)" % `type` else: a = array.array(type, [1, 2, 3, 4, 5]) a[:-1] = a if a != array.array(type, [1, 2, 3, 4, 5, 5]): raise TestFailed, "array(%s) self-slice-assign (head)" % `type` a = array.array(type, [1, 2, 3, 4, 5]) a[1:] = a if a != array.array(type, [1, 1, 2, 3, 4, 5]): raise TestFailed, "array(%s) self-slice-assign (tail)" % `type` a = array.array(type, [1, 2, 3, 4, 5]) a[1:-1] = a if a != array.array(type, [1, 1, 2, 3, 4, 5, 5]): raise TestFailed, "array(%s) self-slice-assign (cntr)" % `type` |
|
def test_warning(self): warnings.filterwarnings("error", category=RuntimeWarning, message="mktemp") self.assertRaises(RuntimeWarning, tempfile.mktemp, (), { 'dir': self.dir }) | def test_warning(self): # mktemp issues a warning when used warnings.filterwarnings("error", category=RuntimeWarning, message="mktemp") self.assertRaises(RuntimeWarning, tempfile.mktemp, (), { 'dir': self.dir }) |
|
return self.socket.recvfrom(max_packet_size) | return self.socket.recvfrom(self.max_packet_size) | def get_request(self): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.