signature:
def urlunparse ( data ) :
    """Put a parsed URL back together again . This may result in a
 slightly different , but equivalent URL , if the URL that was parsed
 originally had redundant delimiters , e . g . a ? with an empty query
 ( the draft states that these are equivalent ) ."""

implementation:
scheme , netloc , url , params , query , fragment = data
if params :
    url = "%s;%s" % ( url , params )
return urlunsplit ( ( scheme , netloc , url , query , fragment ) )


signature:
def urlunsplit ( data ) :
    """Combine the elements of a tuple as returned by urlsplit ( ) into a
 complete URL as a string . The data argument can be any five - item iterable .
 This may result in a slightly different , but equivalent URL , if the URL that
 was parsed originally had unnecessary delimiters ( for example , a ? with an
 empty query ; the RFC states that these are equivalent ) ."""

implementation:
scheme , netloc , url , query , fragment = data
if netloc or ( scheme and scheme in uses_netloc and url [ : 2 ] != '//' ) :
    if url and url [ : 1 ] != '/' :
        url = '/' + url
    url = '//' + ( netloc or '' ) + url
if scheme :
    url = scheme + ':' + url
if query :
    url = url + '?' + query
if fragment :
    url = url + '#' + fragment
return url


signature:
def urljoin ( base , url , allow_fragments = True ) :
    """Join a base URL and a possibly relative URL to form an absolute
 interpretation of the latter ."""

implementation:
if not base :
    return url
if not url :
    return base
bscheme , bnetloc , bpath , bparams , bquery , bfragment = urlparse ( base , '' , allow_fragments )
scheme , netloc , path , params , query , fragment = urlparse ( url , bscheme , allow_fragments )
if scheme != bscheme or scheme not in uses_relative :
    return url
if scheme in uses_netloc :
    if netloc :
        return urlunparse ( ( scheme , netloc , path , params , query , fragment ) )
    netloc = bnetloc
if path [ : 1 ] == '/' :
    return urlunparse ( ( scheme , netloc , path , params , query , fragment ) )
if not path and not params :
    path = bpath
    params = bparams
    if not query :
        query = bquery
    return urlunparse ( ( scheme , netloc , path , params , query , fragment ) )
segments = bpath . split ( '/' ) [ : - 1 ] + path . split ( '/' )
# XXX The stuff below is bogus in various ways . . .
if segments [ - 1 ] == '.' :
    segments [ - 1 ] = ''
while '.' in segments :
    segments . remove ( '.' )
while 1 :
    i = 1
    n = len ( segments ) - 1
    while i < n :
        if ( segments [ i ] == '..' and segments [ i - 1 ] not in ( '' , '..' ) ) :
            del segments [ i - 1 : i + 1 ]
            break
        i = i + 1
    else :
        break
if segments == [ '' , '..' ] :
    segments [ - 1 ] = ''
elif len ( segments ) >= 2 and segments [ - 1 ] == '..' :
    segments [ - 2 : ] = [ '' ]
return urlunparse ( ( scheme , netloc , '/' . join ( segments ) , params , query , fragment ) )


signature:
def urldefrag ( url ) :
    """Removes any existing fragment from URL .
 Returns a tuple of the defragmented URL and the fragment . If
 the URL contained no fragments , the second element is the
 empty string ."""

implementation:
if '#' in url :
    s , n , p , a , q , frag = urlparse ( url )
    defrag = urlunparse ( ( s , n , p , a , q , '' ) )
    return defrag , frag
else :
    return url , ''


signature:
def unquote ( s ) :
    """unquote ( ' abc % 20def ' ) - > ' abc def ' ."""

implementation:
if _is_unicode ( s ) :
    if '%' not in s :
        return s
    bits = _asciire . split ( s )
    res = [ bits [ 0 ] ]
    append = res . append
    for i in range ( 1 , len ( bits ) , 2 ) :
        append ( unquote ( str ( bits [ i ] ) ) . decode ( 'latin1' ) )
        append ( bits [ i + 1 ] )
    return '' . join ( res )
bits = s . split ( '%' )
# fastpath
if len ( bits ) == 1 :
    return s
res = [ bits [ 0 ] ]
append = res . append
for item in bits [ 1 : ] :
    try :
        append ( _hextochr [ item [ : 2 ] ] )
        append ( item [ 2 : ] )
    except KeyError :
        append ( '%' )
        append ( item )
return '' . join ( res )


signature:
def parse_qs ( qs , keep_blank_values = 0 , strict_parsing = 0 ) :
    """Parse a query given as a string argument .
 Arguments :
 qs : percent - encoded query string to be parsed
 keep _ blank _ values : flag indicating whether blank values in
 percent - encoded queries should be treated as blank strings .
 A true value indicates that blanks should be retained as
 blank strings . The default false value indicates that
 blank values are to be ignored and treated as if they were
 not included .
 strict _ parsing : flag indicating what to do with parsing errors .
 If false ( the default ) , errors are silently ignored .
 If true , errors raise a ValueError exception ."""

implementation:
dict = { }
for name , value in parse_qsl ( qs , keep_blank_values , strict_parsing ) :
    if name in dict :
        dict [ name ] . append ( value )
    else :
        dict [ name ] = [ value ]
return dict


signature:
def parse_qsl ( qs , keep_blank_values = 0 , strict_parsing = 0 ) :
    """Parse a query given as a string argument .
 Arguments :
 qs : percent - encoded query string to be parsed
 keep _ blank _ values : flag indicating whether blank values in
 percent - encoded queries should be treated as blank strings . A
 true value indicates that blanks should be retained as blank
 strings . The default false value indicates that blank values
 are to be ignored and treated as if they were not included .
 strict _ parsing : flag indicating what to do with parsing errors . If
 false ( the default ) , errors are silently ignored . If true ,
 errors raise a ValueError exception .
 Returns a list , as G - d intended ."""

implementation:
pairs = [ s2 for s1 in qs . split ( '&' ) for s2 in s1 . split ( ';' ) ]
r = [ ]
for name_value in pairs :
    if not name_value and not strict_parsing :
        continue
    nv = name_value . split ( '=' , 1 )
    if len ( nv ) != 2 :
        if strict_parsing :
            raise ValueError , "bad query field: %r" % ( name_value , )
        # Handle case of a control - name with no equal sign
        if keep_blank_values :
            nv . append ( '' )
        else :
            continue
    if len ( nv [ 1 ] ) or keep_blank_values :
        name = unquote ( nv [ 0 ] . replace ( '+' , ' ' ) )
        value = unquote ( nv [ 1 ] . replace ( '+' , ' ' ) )
        r . append ( ( name , value ) )
return r


signature:
def _replace ( _self , ** kwds ) :
    'Return a new SplitResult object replacing specified fields with new values'

implementation:
result = _self . _make ( map ( kwds . pop , ( 'scheme' , 'netloc' , 'path' , 'query' , 'fragment' ) , _self ) )
if kwds :
    raise ValueError ( 'Got unexpected field names: %r' % kwds . keys ( ) )
return result


signature:
def getlines ( filename , module_globals = None ) :
    """Get the lines for a file from the cache .
 Update the cache if it doesn ' t contain an entry for this file already ."""

implementation:
if filename in cache :
    return cache [ filename ] [ 2 ]
try :
    return updatecache ( filename , module_globals )
except MemoryError :
    clearcache ( )
    return [ ]


signature:
def checkcache ( filename = None ) :
    """Discard cache entries that are out of date .
 ( This is not checked upon each call ! )"""

implementation:
if filename is None :
    filenames = cache . keys ( )
else :
    if filename in cache :
        filenames = [ filename ]
    else :
        return
for filename in filenames :
    size , mtime , lines , fullname = cache [ filename ]
    if mtime is None :
        continue
        # no - op for files loaded via a _ _ loader _ _
    try :
        stat = os . stat ( fullname )
    except os . error :
        del cache [ filename ]
        continue
    if size != stat . st_size or mtime != stat . st_mtime :
        del cache [ filename ]


signature:
def updatecache ( filename , module_globals = None ) :
    """Update a cache entry and return its list of lines .
 If something ' s wrong , print a message , discard the cache entry ,
 and return an empty list ."""

implementation:
if filename in cache :
    del cache [ filename ]
if not filename or ( filename . startswith ( '<' ) and filename . endswith ( '>' ) ) :
    return [ ]
fullname = filename
try :
    stat = os . stat ( fullname )
except OSError :
    basename = filename
    # Try for a _ _ loader _ _ , if available
    if module_globals and '__loader__' in module_globals :
        name = module_globals . get ( '__name__' )
        loader = module_globals [ '__loader__' ]
        get_source = getattr ( loader , 'get_source' , None )
        if name and get_source :
            try :
                data = get_source ( name )
            except ( ImportError , IOError ) :
                pass
            else :
                if data is None : # No luck , the PEP302 loader cannot find the source
                # for this module .
                    return [ ]
                cache [ filename ] = ( len ( data ) , None , [ line + '\n' for line in data . splitlines ( ) ] , fullname )
                return cache [ filename ] [ 2 ]
    # Try looking through the module search path , which is only useful
    # when handling a relative filename .
    if os . path . isabs ( filename ) :
        return [ ]
    for dirname in sys . path : # When using imputil , sys . path may contain things other than
    # strings ; ignore them when it happens .
        try :
            fullname = os . path . join ( dirname , basename )
        except ( TypeError , AttributeError ) : # Not sufficiently string - like to do anything useful with .
            continue
        try :
            stat = os . stat ( fullname )
            break
        except os . error :
            pass
    else :
        return [ ]
try :
    with open ( fullname , 'rU' ) as fp :
        lines = fp . readlines ( )
except IOError :
    return [ ]
if lines and not lines [ - 1 ] . endswith ( '\n' ) :
    lines [ - 1 ] += '\n'
size , mtime = stat . st_size , stat . st_mtime
cache [ filename ] = size , mtime , lines , fullname
return lines


signature:
def isfile ( path ) :
    """Test whether a path is a regular file"""

implementation:
try :
    st = os . stat ( path )
except os . error :
    return False
return stat . S_ISREG ( st . st_mode )


signature:
def isdir ( s ) :
    """Return true if the pathname refers to an existing directory ."""

implementation:
try :
    st = os . stat ( s )
except os . error :
    return False
return stat . S_ISDIR ( st . st_mode )


signature:
def commonprefix ( m ) :
    "Given a list of pathnames , returns the longest common leading component"

implementation:
if not m :
    return ''
s1 = min ( m )
s2 = max ( m )
for i , c in enumerate ( s1 ) :
    if c != s2 [ i ] :
        return s1 [ : i ]
return s1


signature:
def _splitext ( p , sep , altsep , extsep ) :
    """Split the extension from a pathname .
 Extension is everything from the last dot to the end , ignoring
 leading dots . Returns " ( root , ext ) " ; ext may be empty ."""

implementation:
sepIndex = p . rfind ( sep )
if altsep :
    altsepIndex = p . rfind ( altsep )
    sepIndex = max ( sepIndex , altsepIndex )
dotIndex = p . rfind ( extsep )
if dotIndex > sepIndex : # skip all leading dots
    filenameIndex = sepIndex + 1
    while filenameIndex < dotIndex :
        if p [ filenameIndex ] != extsep :
            return p [ : dotIndex ] , p [ dotIndex : ]
        filenameIndex += 1
return p , ''


signature:
def wrap ( text , width = 70 , ** kwargs ) :
    """Wrap a single paragraph of text , returning a list of wrapped lines .
 Reformat the single paragraph in ' text ' so it fits in lines of no
 more than ' width ' columns , and return a list of wrapped lines . By
 default , tabs in ' text ' are expanded with string . expandtabs ( ) , and
 all other whitespace characters ( including newline ) are converted to
 space . See TextWrapper class for available keyword args to customize
 wrapping behaviour ."""

implementation:
w = TextWrapper ( width = width , ** kwargs )
return w . wrap ( text )


signature:
def fill ( text , width = 70 , ** kwargs ) :
    """Fill a single paragraph of text , returning a new string .
 Reformat the single paragraph in ' text ' to fit in lines of no more
 than ' width ' columns , and return a new string containing the entire
 wrapped paragraph . As with wrap ( ) , tabs are expanded and other
 whitespace characters converted to space . See TextWrapper class for
 available keyword args to customize wrapping behaviour ."""

implementation:
w = TextWrapper ( width = width , ** kwargs )
return w . fill ( text )


signature:
def dedent ( text ) :
    """Remove any common leading whitespace from every line in ` text ` .
 This can be used to make triple - quoted strings line up with the left
 edge of the display , while still presenting them in the source code
 in indented form .
 Note that tabs and spaces are both treated as whitespace , but they
 are not equal : the lines " hello " and " \\ thello " are
 considered to have no common leading whitespace . ( This behaviour is
 new in Python 2.5 ; older versions of this module incorrectly
 expanded tabs before searching for common leading whitespace . )"""

implementation:
# Look for the longest leading string of spaces and tabs common to
# all lines .
margin = None
text = _whitespace_only_re . sub ( '' , text )
indents = _leading_whitespace_re . findall ( text )
for indent in indents :
    if margin is None :
        margin = indent
    # Current line more deeply indented than previous winner :
    # no change ( previous winner is still on top ) .
    elif indent . startswith ( margin ) :
        pass
    # Current line consistent with and no deeper than previous winner :
    # it ' s the new winner .
    elif margin . startswith ( indent ) :
        margin = indent
    # Find the largest common whitespace between current line and previous
    # winner .
    else :
        for i , ( x , y ) in enumerate ( zip ( margin , indent ) ) :
            if x != y :
                margin = margin [ : i ]
                break
        else :
            margin = margin [ : len ( indent ) ]
# sanity check ( testing / debugging only )
if 0 and margin :
    for line in text . split ( "\n" ) :
        assert not line or line . startswith ( margin ) , "line = %r, margin = %r" % ( line , margin )
if margin :
    text = re . sub ( r'(?m)^' + margin , '' , text )
return text


signature:
def _munge_whitespace ( self , text ) :
    """_ munge _ whitespace ( text : string ) - > string
 Munge whitespace in text : expand tabs and convert all other
 whitespace characters to spaces . Eg . " foo \\ tbar \\ n \\ nbaz "
 becomes " foo bar baz " ."""

implementation:
if self . expand_tabs : # text = text . expandtabs ( )
    text = ' ' . join ( ( ' ' . join ( text . split ( '\n' ) ) ) . split ( '\t' ) )
if self . replace_whitespace : # if isinstance ( text , str ) :
# text = text . translate ( self . whitespace _ trans )
# elif isinstance ( text , _ unicode ) :
# text = text . translate ( self . unicode _ whitespace _ trans )
    text = ' ' . join ( ' ' . join ( text . split ( '\n' ) ) . split ( '\t' ) )
return text


signature:
def _split ( self , text ) :
    """_ split ( text : string ) - > [ string ]
 Split the text to wrap into indivisible chunks . Chunks are
 not quite the same as words ; see _ wrap _ chunks ( ) for full
 details . As an example , the text
 Look , goof - ball - - use the - b option !
 breaks into the following chunks :
 ' Look , ' , ' ' , ' goof - ' , ' ball ' , ' ' , ' - - ' , ' ' ,
 ' use ' , ' ' , ' the ' , ' ' , ' - b ' , ' ' , ' option ! '
 if break _ on _ hyphens is True , or in :
 ' Look , ' , ' ' , ' goof - ball ' , ' ' , ' - - ' , ' ' ,
 ' use ' , ' ' , ' the ' , ' ' , ' - b ' , ' ' , option ! '
 otherwise ."""

implementation:
if isinstance ( text , _unicode ) :
    if self . break_on_hyphens :
        pat = self . wordsep_re_uni
    else :
        pat = self . wordsep_simple_re_uni
else :
    if self . break_on_hyphens :
        pat = self . wordsep_re
    else :
        pat = self . wordsep_simple_re
chunks = pat . split ( text )
# chunks = filter ( None , chunks ) # remove empty chunks
chunks = [ x for x in chunks if x is not None ]
return chunks


signature:
def _fix_sentence_endings ( self , chunks ) :
    """_ fix _ sentence _ endings ( chunks : [ string ] )
 Correct for sentence endings buried in ' chunks ' . Eg . when the
 original text contains " . . . foo . \\ nBar . . . " , munge _ whitespace ( )
 and split ( ) will convert that to [ . . . , " foo . " , " " , " Bar " , . . . ]
 which has one too few spaces ; this method simply changes the one
 space to two ."""

implementation:
i = 0
patsearch = self . sentence_end_re . search
while i < len ( chunks ) - 1 :
    if chunks [ i + 1 ] == " " and patsearch ( chunks [ i ] ) :
        chunks [ i + 1 ] = "  "
        i += 2
    else :
        i += 1


signature:
def _handle_long_word ( self , reversed_chunks , cur_line , cur_len , width ) :
    """_ handle _ long _ word ( chunks : [ string ] ,
 cur _ line : [ string ] ,
 cur _ len : int , width : int )
 Handle a chunk of text ( most likely a word , not whitespace ) that
 is too long to fit in any line ."""

implementation:
# Figure out when indent is larger than the specified width , and make
# sure at least one character is stripped off on every pass
if width < 1 :
    space_left = 1
else :
    space_left = width - cur_len
# If we ' re allowed to break long words , then do so : put as much
# of the next chunk onto the current line as will fit .
if self . break_long_words :
    cur_line . append ( reversed_chunks [ - 1 ] [ : space_left ] )
    reversed_chunks [ - 1 ] = reversed_chunks [ - 1 ] [ space_left : ]
# Otherwise , we have to preserve the long word intact . Only add
# it to the current line if there ' s nothing already there - -
# that minimizes how much we violate the width constraint .
elif not cur_line :
    cur_line . append ( reversed_chunks . pop ( ) )


signature:
def _wrap_chunks ( self , chunks ) :
    """_ wrap _ chunks ( chunks : [ string ] ) - > [ string ]
 Wrap a sequence of text chunks and return a list of lines of
 length ' self . width ' or less . ( If ' break _ long _ words ' is false ,
 some lines may be longer than this . ) Chunks correspond roughly
 to words and the whitespace between them : each chunk is
 indivisible ( modulo ' break _ long _ words ' ) , but a line break can
 come between any two chunks . Chunks should not have internal
 whitespace ; ie . a chunk is either all whitespace or a " word " .
 Whitespace chunks will be removed from the beginning and end of
 lines , but apart from that whitespace is preserved ."""

implementation:
lines = [ ]
if self . width <= 0 :
    raise ValueError ( "invalid width %r (must be > 0)" % self . width )
# Arrange in reverse order so items can be efficiently popped
# from a stack of chucks .
chunks . reverse ( )
while chunks : # Start the list of chunks that will make up the current line .
# cur _ len is just the length of all the chunks in cur _ line .
    cur_line = [ ]
    cur_len = 0
    # Figure out which static string will prefix this line .
    if lines :
        indent = self . subsequent_indent
    else :
        indent = self . initial_indent
    # Maximum width for this line .
    width = self . width - len ( indent )
    # First chunk on line is whitespace - - drop it , unless this
    # is the very beginning of the text ( ie . no lines started yet ) .
    if self . drop_whitespace and chunks [ - 1 ] . strip ( ) == '' and lines : # del chunks [ - 1]
        chunks . pop ( )
    while chunks :
        l = len ( chunks [ - 1 ] )
        # Can at least squeeze this chunk onto the current line .
        if cur_len + l <= width :
            cur_line . append ( chunks . pop ( ) )
            cur_len += l
        # Nope , this line is full .
        else :
            break
    # The current line is full , and the next chunk is too big to
    # fit on * any * line ( not just this one ) .
    if chunks and len ( chunks [ - 1 ] ) > width :
        self . _handle_long_word ( chunks , cur_line , cur_len , width )
    # If the last chunk on this line is all whitespace , drop it .
    if self . drop_whitespace and cur_line and cur_line [ - 1 ] . strip ( ) == '' : # del cur _ line [ - 1]
        cur_line . pop ( )
    # Convert current line back to a string and store it in list
    # of all lines ( return value ) .
    if cur_line :
        lines . append ( indent + '' . join ( cur_line ) )
return lines


signature:
def wrap ( self , text ) :
    """wrap ( text : string ) - > [ string ]
 Reformat the single paragraph in ' text ' so it fits in lines of
 no more than ' self . width ' columns , and return a list of wrapped
 lines . Tabs in ' text ' are expanded with string . expandtabs ( ) ,
 and all other whitespace characters ( including newline ) are
 converted to space ."""

implementation:
text = self . _munge_whitespace ( text )
chunks = self . _split ( text )
if self . fix_sentence_endings :
    self . _fix_sentence_endings ( chunks )
return self . _wrap_chunks ( chunks )


signature:
def _long2bytesBigEndian ( n , blocksize = 0 ) :
    """Convert a long integer to a byte string .
 If optional blocksize is given and greater than zero , pad the front
 of the byte string with binary zeros so that the length is a multiple
 of blocksize ."""

implementation:
# After much testing , this algorithm was deemed to be the fastest .
s = b''
pack = struct . pack
while n > 0 :
    s = pack ( '>I' , n & 0xffffffff ) + s
    n = n >> 32
# Strip off leading zeros .
for i in range ( len ( s ) ) :
    if s [ i ] != '\000' :
        break
else : # Only happens when n = = 0.
    s = '\000'
    i = 0
s = s [ i : ]
# Add back some pad bytes . This could be done more efficiently
# w . r . t . the de - padding being done above , but sigh . . .
if blocksize > 0 and len ( s ) % blocksize :
    s = ( blocksize - len ( s ) % blocksize ) * '\000' + s
return s


signature:
def _bytelist2longBigEndian ( list ) :
    "Transform a list of characters into a list of longs ."

implementation:
imax = len ( list ) // 4
hl = [ 0 ] * imax
j = 0
i = 0
while i < imax :
    b0 = ord ( list [ j ] ) << 24
    b1 = ord ( list [ j + 1 ] ) << 16
    b2 = ord ( list [ j + 2 ] ) << 8
    b3 = ord ( list [ j + 3 ] )
    hl [ i ] = b0 | b1 | b2 | b3
    i = i + 1
    j = j + 4
return hl


signature:
def init ( self ) :
    "Initialize the message - digest and set all fields to zero ."

implementation:
self . length = 0
self . input = [ ]
# Initial 160 bit message digest ( 5 times 32 bit ) .
self . H0 = 0x67452301
self . H1 = 0xEFCDAB89
self . H2 = 0x98BADCFE
self . H3 = 0x10325476
self . H4 = 0xC3D2E1F0


signature:
def _transform ( self , W ) :
    for t in range ( 16 , 80 ) :
        W . append ( _rotateLeft ( W [ t - 3 ] ^ W [ t - 8 ] ^ W [ t - 14 ] ^ W [ t - 16 ] , 1 ) & 0xffffffff )
    A = self . H0
    B = self . H1
    C = self . H2
    D = self . H3
    E = self . H4
    """This loop was unrolled to gain about 10 % in speed
 for t in range ( 0 , 80 ) :
 TEMP = _ rotateLeft ( A , 5 ) + f [ t / 20 ] + E + W [ t ] + K [ t / 20]
 E = D
 D = C
 C = _ rotateLeft ( B , 30 ) & 0xfffff
 B = A
 A = TEMP & 0xfffff"""

implementation:
for t in range ( 0 , 20 ) :
    TEMP = _rotateLeft ( A , 5 ) + ( ( B & C ) | ( ( ~ B ) & D ) ) + E + W [ t ] + K [ 0 ]
    E = D
    D = C
    C = _rotateLeft ( B , 30 ) & 0xffffffff
    B = A
    A = TEMP & 0xffffffff
for t in range ( 20 , 40 ) :
    TEMP = _rotateLeft ( A , 5 ) + ( B ^ C ^ D ) + E + W [ t ] + K [ 1 ]
    E = D
    D = C
    C = _rotateLeft ( B , 30 ) & 0xffffffff
    B = A
    A = TEMP & 0xffffffff
for t in range ( 40 , 60 ) :
    TEMP = _rotateLeft ( A , 5 ) + ( ( B & C ) | ( B & D ) | ( C & D ) ) + E + W [ t ] + K [ 2 ]
    E = D
    D = C
    C = _rotateLeft ( B , 30 ) & 0xffffffff
    B = A
    A = TEMP & 0xffffffff
for t in range ( 60 , 80 ) :
    TEMP = _rotateLeft ( A , 5 ) + ( B ^ C ^ D ) + E + W [ t ] + K [ 3 ]
    E = D
    D = C
    C = _rotateLeft ( B , 30 ) & 0xffffffff
    B = A
    A = TEMP & 0xffffffff
self . H0 = ( self . H0 + A ) & 0xffffffff
self . H1 = ( self . H1 + B ) & 0xffffffff
self . H2 = ( self . H2 + C ) & 0xffffffff
self . H3 = ( self . H3 + D ) & 0xffffffff
self . H4 = ( self . H4 + E ) & 0xffffffff


signature:
def digest ( self ) :
    """Terminate the message - digest computation and return digest .
 Return the digest of the strings passed to the update ( )
 method so far . This is a 16 - byte string which may contain
 non - ASCII characters , including null bytes ."""

implementation:
H0 = self . H0
H1 = self . H1
H2 = self . H2
H3 = self . H3
H4 = self . H4
input = [ ] + self . input
count = [ ] + self . count
index = ( self . count [ 1 ] >> 3 ) & 0x3f
if index < 56 :
    padLen = 56 - index
else :
    padLen = 120 - index
padding = [ '\200' ] + [ '\000' ] * 63
self . update ( padding [ : padLen ] )
# Append length ( before padding ) .
bits = _bytelist2longBigEndian ( self . input [ : 56 ] ) + count
self . _transform ( bits )
# Store state in digest .
digest = _long2bytesBigEndian ( self . H0 , 4 ) + _long2bytesBigEndian ( self . H1 , 4 ) + _long2bytesBigEndian ( self . H2 , 4 ) + _long2bytesBigEndian ( self . H3 , 4 ) + _long2bytesBigEndian ( self . H4 , 4 )
self . H0 = H0
self . H1 = H1
self . H2 = H2
self . H3 = H3
self . H4 = H4
self . input = input
self . count = count
return digest


signature:
def next ( self , eof_token = False ) :
    """Returns token at ` ` offset ` ` as a : class : ` Token ` and advances ` ` offset ` `
 to point past the end of the token , where the token has :
 - * range * which is a : class : ` pythonparser . source . Range ` that includes
 the token but not surrounding whitespace ,
 - * kind * which is a string containing one of Python keywords or operators ,
 ` ` newline ` ` , ` ` float ` ` , ` ` int ` ` , ` ` complex ` ` , ` ` strbegin ` ` ,
 ` ` strdata ` ` , ` ` strend ` ` , ` ` ident ` ` , ` ` indent ` ` , ` ` dedent ` ` or ` ` eof ` `
 ( if ` ` eof _ token ` ` is True ) .
 - * value * which is the flags as lowercase string if * kind * is ` ` strbegin ` ` ,
 the string contents if * kind * is ` ` strdata ` ` ,
 the numeric value if * kind * is ` ` float ` ` , ` ` int ` ` or ` ` complex ` ` ,
 the identifier if * kind * is ` ` ident ` ` and ` ` None ` ` in any other case .
 : param eof _ token : if true , will return a token with kind ` ` eof ` `
 when the input is exhausted ; if false , will raise ` ` StopIteration ` ` ."""

implementation:
if len ( self . queue ) == 0 :
    self . _refill ( eof_token )
return self . queue . pop ( 0 )


signature:
def peek ( self , eof_token = False ) :
    """Same as : meth : ` next ` , except the token is not dequeued ."""

implementation:
if len ( self . queue ) == 0 :
    self . _refill ( eof_token )
return self . queue [ - 1 ]


signature:
def enterabs ( self , time , priority , action , argument ) :
    """Enter a new event in the queue at an absolute time .
 Returns an ID for the event which can be used to remove it ,
 if necessary ."""

implementation:
event = Event ( time , priority , action , argument )
heapq . heappush ( self . _queue , event )
return event


signature:
def run ( self ) :
    """Execute events until the queue is empty .
 When there is a positive delay until the first event , the
 delay function is called and the event is left in the queue ;
 otherwise , the event is removed from the queue and executed
 ( its action function is called , passing it the argument ) . If
 the delay function returns prematurely , it is simply
 restarted .
 It is legal for both the delay function and the action
 function to modify the queue or to raise an exception ;
 exceptions are not caught but the scheduler ' s state remains
 well - defined so run ( ) may be called again .
 A questionable hack is added to allow other threads to run :
 just after an event is executed , a delay of 0 is executed , to
 avoid monopolizing the CPU when other threads are also
 runnable ."""

implementation:
# localize variable access to minimize overhead
# and to improve thread safety
q = self . _queue
delayfunc = self . delayfunc
timefunc = self . timefunc
pop = heapq . heappop
while q : # TODO : modified part of grumpy version .
    checked_event = q [ 0 ]
    time , priority , action , argument = checked_event . get_fields ( )
    now = timefunc ( )
    if now < time :
        delayfunc ( time - now )
    else :
        event = pop ( q )
        # Verify that the event was not removed or altered
        # by another thread after we last looked at q [ 0 ] .
        if event is checked_event :
            action ( * argument )
            delayfunc ( 0 )
            # Let other threads run
        else :
            heapq . heappush ( q , event )


signature:
def queue ( self ) :
    """An ordered list of upcoming events .
 Events are named tuples with fields for :
 time , priority , action , arguments"""

implementation:
# Use heapq to sort the queue rather than using ' sorted ( self . _ queue ) ' .
# With heapq , two events scheduled at the same time will show in
# the actual order they would be retrieved .
events = self . _queue [ : ]
return map ( heapq . heappop , [ events ] * len ( events ) )


signature:
def register_dialect ( name , dialect = None , ** kwargs ) :
    """Create a mapping from a string name to a dialect class .
 dialect = csv . register _ dialect ( name , dialect )"""

implementation:
if not isinstance ( name , basestring ) :
    raise TypeError ( "dialect name must be a string or unicode" )
dialect = _call_dialect ( dialect , kwargs )
_dialects [ name ] = dialect


signature:
def field_size_limit ( limit = undefined ) :
    """Sets an upper limit on parsed fields .
 csv . field _ size _ limit ( [ limit ] )
 Returns old limit . If limit is not given , no new limit is set and
 the old limit is returned"""

implementation:
global _field_limit
old_limit = _field_limit
if limit is not undefined :
    if not isinstance ( limit , ( int , long ) ) :
        raise TypeError ( "int expected, got %s" % ( limit . __class__ . __name__ , ) )
    _field_limit = limit
return old_limit


signature:
def copy ( x ) :
    """Shallow copy operation on arbitrary Python objects .
 See the module ' s _ _ doc _ _ string for more info ."""

implementation:
cls = type ( x )
copier = _copy_dispatch . get ( cls )
if copier :
    return copier ( x )
copier = getattr ( cls , "__copy__" , None )
if copier :
    return copier ( x )
reductor = dispatch_table . get ( cls )
if reductor :
    rv = reductor ( x )
else :
    reductor = getattr ( x , "__reduce_ex__" , None )
    if reductor :
        rv = reductor ( 2 )
    else :
        reductor = getattr ( x , "__reduce__" , None )
        if reductor :
            rv = reductor ( )
        else :
            raise Error ( "un(shallow)copyable object of type %s" % cls )
return _reconstruct ( x , rv , 0 )


signature:
def deepcopy ( x , memo = None , _nil = [ ] ) :
    """Deep copy operation on arbitrary Python objects .
 See the module ' s _ _ doc _ _ string for more info ."""

implementation:
if memo is None :
    memo = { }
d = id ( x )
y = memo . get ( d , _nil )
if y is not _nil :
    return y
cls = type ( x )
copier = _deepcopy_dispatch . get ( cls )
if copier :
    y = copier ( x , memo )
else :
    try :
        issc = issubclass ( cls , type )
    except TypeError : # cls is not a class ( old Boost ; see SF # 502085)
        issc = 0
    if issc :
        y = _deepcopy_atomic ( x , memo )
    else :
        copier = getattr ( x , "__deepcopy__" , None )
        if copier :
            y = copier ( memo )
        else :
            reductor = dispatch_table . get ( cls )
            if reductor :
                rv = reductor ( x )
            else :
                reductor = getattr ( x , "__reduce_ex__" , None )
                if reductor :
                    rv = reductor ( 2 )
                else :
                    reductor = getattr ( x , "__reduce__" , None )
                    if reductor :
                        rv = reductor ( )
                    else :
                        raise Error ( "un(deep)copyable object of type %s" % cls )
            y = _reconstruct ( x , rv , 1 , memo )
memo [ d ] = y
_keep_alive ( x , memo )
# Make sure x lives at least as long as d
return y


signature:
def _keep_alive ( x , memo ) :
    """Keeps a reference to the object x in the memo .
 Because we remember objects by their id , we have
 to assure that possibly temporary objects are kept
 alive by referencing them .
 We store a reference at the id of the memo , which should
 normally not be used unless someone tries to deepcopy
 the memo itself . . ."""

implementation:
try :
    memo [ id ( memo ) ] . append ( x )
except KeyError : # aha , this is the first one : - )
    memo [ id ( memo ) ] = [ x ]


signature:
def warnpy3k ( message , category = None , stacklevel = 1 ) :
    """Issue a deprecation warning for Python 3 . x related changes .
 Warnings are omitted unless Python is started with the - 3 option ."""

implementation:
if sys . py3kwarning :
    if category is None :
        category = DeprecationWarning
    warn ( message , category , stacklevel + 1 )


signature:
def _show_warning ( message , category , filename , lineno , file = None , line = None ) :
    """Hook to write a warning to a file ; replace if you like ."""

implementation:
if file is None :
    file = sys . stderr
    if file is None : # sys . stderr is None - warnings get lost
        return
try :
    file . write ( formatwarning ( message , category , filename , lineno , line ) )
except ( IOError , UnicodeError ) :
    pass
# the file ( probably stderr ) is invalid - this warning gets lost .


signature:
def formatwarning ( message , category , filename , lineno , line = None ) :
    """Function to format a warning the standard way ."""

implementation:
try :
    unicodetype = unicode
except NameError :
    unicodetype = ( )
try :
    message = str ( message )
except UnicodeEncodeError :
    pass
s = "%s: %s: %s\n" % ( lineno , category . __name__ , message )
line = linecache . getline ( filename , lineno ) if line is None else line
if line :
    line = line . strip ( )
    if isinstance ( s , unicodetype ) and isinstance ( line , str ) :
        line = unicode ( line , 'latin1' )
    s += "  %s\n" % line
if isinstance ( s , unicodetype ) and isinstance ( filename , str ) :
    enc = sys . getfilesystemencoding ( )
    if enc :
        try :
            filename = unicode ( filename , enc )
        except UnicodeDecodeError :
            pass
s = "%s:%s" % ( filename , s )
return s


signature:
def filterwarnings ( action , message = "" , category = Warning , module = "" , lineno = 0 , append = 0 ) :
    """Insert an entry into the list of warnings filters ( at the front ) .
 ' action ' - - one of " error " , " ignore " , " always " , " default " , " module " ,
 or " once "
 ' message ' - - a regex that the warning message must match
 ' category ' - - a class that the warning must be a subclass of
 ' module ' - - a regex that the module name must match
 ' lineno ' - - an integer line number , 0 matches all warnings
 ' append ' - - if true , append to the list of filters"""

implementation:
assert action in ( "error" , "ignore" , "always" , "default" , "module" , "once" ) , "invalid action: %r" % ( action , )
assert isinstance ( message , basestring ) , "message must be a string"
assert isinstance ( category , type ) , "category must be a class"
assert issubclass ( category , Warning ) , "category must be a Warning subclass"
assert isinstance ( module , basestring ) , "module must be a string"
assert isinstance ( lineno , int ) and lineno >= 0 , "lineno must be an int >= 0"
item = ( action , re . compile ( message , re . I ) , category , re . compile ( module ) , lineno )
if append :
    filters . append ( item )
else :
    filters . insert ( 0 , item )


signature:
def simplefilter ( action , category = Warning , lineno = 0 , append = 0 ) :
    """Insert a simple entry into the list of warnings filters ( at the front ) .
 A simple filter matches all modules and messages .
 ' action ' - - one of " error " , " ignore " , " always " , " default " , " module " ,
 or " once "
 ' category ' - - a class that the warning must be a subclass of
 ' lineno ' - - an integer line number , 0 matches all warnings
 ' append ' - - if true , append to the list of filters"""

implementation:
assert action in ( "error" , "ignore" , "always" , "default" , "module" , "once" ) , "invalid action: %r" % ( action , )
assert isinstance ( lineno , int ) and lineno >= 0 , "lineno must be an int >= 0"
item = ( action , None , category , None , lineno )
if append :
    filters . append ( item )
else :
    filters . insert ( 0 , item )


signature:
def warn ( message , category = None , stacklevel = 1 ) :
    """Issue a warning , or maybe ignore it or raise an exception ."""

implementation:
# Check if message is already a Warning object
if isinstance ( message , Warning ) :
    category = message . __class__
# Check category argument
if category is None :
    category = UserWarning
assert issubclass ( category , Warning )
# Get context information
try :
    caller = sys . _getframe ( stacklevel )
except ValueError :
    globals = sys . __dict__
    lineno = 1
else :
    globals = caller . f_globals
    lineno = caller . f_lineno
if '__name__' in globals :
    module = globals [ '__name__' ]
else :
    module = "<string>"
filename = globals . get ( '__file__' )
if filename :
    fnl = filename . lower ( )
    if fnl . endswith ( ( ".pyc" , ".pyo" ) ) :
        filename = filename [ : - 1 ]
else :
    if module == "__main__" :
        try :
            filename = sys . argv [ 0 ]
        except AttributeError : # embedded interpreters don ' t have sys . argv , see bug # 839151
            filename = '__main__'
    if not filename :
        filename = module
registry = globals . setdefault ( "__warningregistry__" , { } )
warn_explicit ( message , category , filename , lineno , module , registry , globals )


signature:
def _hash ( self ) :
    """Compute the hash value of a set .
 Note that we don ' t define _ _ hash _ _ : not all sets are hashable .
 But if you define a hashable set type , its _ _ hash _ _ should
 call this function .
 This must be compatible _ _ eq _ _ .
 All sets ought to compare equal if they contain the same
 elements , regardless of how they are implemented , and
 regardless of the order of the elements ; so there ' s not much
 freedom for _ _ eq _ _ or _ _ hash _ _ . We match the algorithm used
 by the built - in frozenset type ."""


signature:
def remove ( self , value ) :
    """Remove an element . If not a member , raise a KeyError ."""

implementation:
if value not in self :
    raise KeyError ( value )
self . discard ( value )


signature:
def pop ( self ) :
    """Return the popped value . Raise KeyError if empty ."""

implementation:
it = iter ( self )
try :
    value = next ( it )
except StopIteration :
    raise KeyError
self . discard ( value )
return value


signature:
def update ( * args , ** kwds ) :
    '''D . update ( [ E , ] * * F ) - > None . Update D from mapping / iterable E and F .
 If E present and has a . keys ( ) method , does : for k in E : D [ k ] = E [ k ]
 If E present and lacks . keys ( ) method , does : for ( k , v ) in E : D [ k ] = v
 In either case , this is followed by : for k , v in F . items ( ) : D [ k ] = v'''

implementation:
if not args :
    raise TypeError ( "descriptor 'update' of 'MutableMapping' object " "needs an argument" )
self = args [ 0 ]
args = args [ 1 : ]
if len ( args ) > 1 :
    raise TypeError ( 'update expected at most 1 arguments, got %d' % len ( args ) )
if args :
    other = args [ 0 ]
    if isinstance ( other , Mapping ) :
        for key in other :
            self [ key ] = other [ key ]
    elif hasattr ( other , "keys" ) :
        for key in other . keys ( ) :
            self [ key ] = other [ key ]
    else :
        for key , value in other :
            self [ key ] = value
for key , value in kwds . items ( ) :
    self [ key ] = value


signature:
def index ( self , value ) :
    '''S . index ( value ) - > integer - - return first index of value .
 Raises ValueError if the value is not present .'''

implementation:
for i , v in enumerate ( self ) :
    if v == value :
        return i
raise ValueError


signature:
def reverse ( self ) :
    'S . reverse ( ) - - reverse * IN PLACE *'

implementation:
n = len ( self )
for i in range ( n // 2 ) :
    self [ i ] , self [ n - i - 1 ] = self [ n - i - 1 ] , self [ i ]


signature:
def go_str ( value ) :
    """Returns value as a valid Go string literal ."""

implementation:
io = StringIO . StringIO ( )
io . write ( '"' )
for c in value :
    if c in _ESCAPES :
        io . write ( _ESCAPES [ c ] )
    elif c in _SIMPLE_CHARS :
        io . write ( c )
    else :
        io . write ( r'\x{:02x}' . format ( ord ( c ) ) )
io . write ( '"' )
return io . getvalue ( )


signature:
def write_block ( self , block_ , body ) :
    """Outputs the boilerplate necessary for code blocks like functions .
 Args :
 block _ : The Block object representing the code block .
 body : String containing Go code making up the body of the code block ."""

implementation:
self . write ( 'for ; πF.State() >= 0; πF.PopCheckpoint() {' )
with self . indent_block ( ) :
    self . write ( 'switch πF.State() {' )
    self . write ( 'case 0:' )
    for checkpoint in block_ . checkpoints :
        self . write_tmpl ( 'case $state: goto Label$state' , state = checkpoint )
    self . write ( 'default: panic("unexpected function state")' )
    self . write ( '}' )
    # Assume that body is aligned with goto labels .
    with self . indent_block ( - 1 ) :
        self . write ( body )
self . write ( '}' )


signature:
def acquire ( self , blocking = 1 ) :
    """Acquire a lock , blocking or non - blocking .
 When invoked without arguments : if this thread already owns the lock ,
 increment the recursion level by one , and return immediately . Otherwise ,
 if another thread owns the lock , block until the lock is unlocked . Once
 the lock is unlocked ( not owned by any thread ) , then grab ownership , set
 the recursion level to one , and return . If more than one thread is
 blocked waiting until the lock is unlocked , only one at a time will be
 able to grab ownership of the lock . There is no return value in this
 case .
 When invoked with the blocking argument set to true , do the same thing
 as when called without arguments , and return true .
 When invoked with the blocking argument set to false , do not block . If a
 call without an argument would block , return false immediately ;
 otherwise , do the same thing as when called without arguments , and
 return true ."""

implementation:
me = _get_ident ( )
if self . __owner == me :
    self . __count = self . __count + 1
    if __debug__ :
        self . _note ( "%s.acquire(%s): recursive success" , self , blocking )
    return 1
rc = self . __block . acquire ( blocking )
if rc :
    self . __owner = me
    self . __count = 1
    if __debug__ :
        self . _note ( "%s.acquire(%s): initial success" , self , blocking )
else :
    if __debug__ :
        self . _note ( "%s.acquire(%s): failure" , self , blocking )
return rc


signature:
def release ( self ) :
    """Release a lock , decrementing the recursion level .
 If after the decrement it is zero , reset the lock to unlocked ( not owned
 by any thread ) , and if any other threads are blocked waiting for the
 lock to become unlocked , allow exactly one of them to proceed . If after
 the decrement the recursion level is still nonzero , the lock remains
 locked and owned by the calling thread .
 Only call this method when the calling thread owns the lock . A
 RuntimeError is raised if this method is called when the lock is
 unlocked .
 There is no return value ."""

implementation:
if self . __owner != _get_ident ( ) :
    raise RuntimeError ( "cannot release un-acquired lock" )
self . __count = count = self . __count - 1
if not count :
    self . __owner = None
    self . __block . release ( )
    if __debug__ :
        self . _note ( "%s.release(): final release" , self )
else :
    if __debug__ :
        self . _note ( "%s.release(): non-final release" , self )


signature:
def wait ( self , timeout = None ) :
    """Wait until notified or until a timeout occurs .
 If the calling thread has not acquired the lock when this method is
 called , a RuntimeError is raised .
 This method releases the underlying lock , and then blocks until it is
 awakened by a notify ( ) or notifyAll ( ) call for the same condition
 variable in another thread , or until the optional timeout occurs . Once
 awakened or timed out , it re - acquires the lock and returns .
 When the timeout argument is present and not None , it should be a
 floating point number specifying a timeout for the operation in seconds
 ( or fractions thereof ) .
 When the underlying lock is an RLock , it is not released using its
 release ( ) method , since this may not actually unlock the lock when it
 was acquired multiple times recursively . Instead , an internal interface
 of the RLock class is used , which really unlocks it even when it has
 been recursively acquired several times . Another internal interface is
 then used to restore the recursion level when the lock is reacquired ."""

implementation:
if not self . _is_owned ( ) :
    raise RuntimeError ( "cannot wait on un-acquired lock" )
waiter = _allocate_lock ( )
waiter . acquire ( )
self . __waiters . append ( waiter )
saved_state = self . _release_save ( )
try : # restore state no matter what ( e . g . , KeyboardInterrupt )
    if timeout is None :
        waiter . acquire ( )
        if __debug__ :
            self . _note ( "%s.wait(): got it" , self )
    else : # Balancing act : We can ' t afford a pure busy loop , so we
    # have to sleep ; but if we sleep the whole timeout time ,
    # we ' ll be unresponsive . The scheme here sleeps very
    # little at first , longer as time goes on , but never longer
    # than 20 times per second ( or the timeout time remaining ) .
        endtime = _time ( ) + timeout
        delay = 0.0005
        # 500 us - > initial delay of 1 ms
        while True :
            gotit = waiter . acquire ( 0 )
            if gotit :
                break
            remaining = endtime - _time ( )
            if remaining <= 0 :
                break
            delay = min ( delay * 2 , remaining , .05 )
            _sleep ( delay )
        if not gotit :
            if __debug__ :
                self . _note ( "%s.wait(%s): timed out" , self , timeout )
            try :
                self . __waiters . remove ( waiter )
            except ValueError :
                pass
        else :
            if __debug__ :
                self . _note ( "%s.wait(%s): got it" , self , timeout )
finally :
    self . _acquire_restore ( saved_state )


signature:
def notify ( self , n = 1 ) :
    """Wake up one or more threads waiting on this condition , if any .
 If the calling thread has not acquired the lock when this method is
 called , a RuntimeError is raised .
 This method wakes up at most n of the threads waiting for the condition
 variable ; it is a no - op if no threads are waiting ."""

implementation:
if not self . _is_owned ( ) :
    raise RuntimeError ( "cannot notify on un-acquired lock" )
__waiters = self . __waiters
waiters = __waiters [ : n ]
if not waiters :
    if __debug__ :
        self . _note ( "%s.notify(): no waiters" , self )
    return
self . _note ( "%s.notify(): notifying %d waiter%s" , self , n , n != 1 and "s" or "" )
for waiter in waiters :
    waiter . release ( )
    try :
        __waiters . remove ( waiter )
    except ValueError :
        pass


signature:
def acquire ( self , blocking = 1 ) :
    """Acquire a semaphore , decrementing the internal counter by one .
 When invoked without arguments : if the internal counter is larger than
 zero on entry , decrement it by one and return immediately . If it is zero
 on entry , block , waiting until some other thread has called release ( ) to
 make it larger than zero . This is done with proper interlocking so that
 if multiple acquire ( ) calls are blocked , release ( ) will wake exactly one
 of them up . The implementation may pick one at random , so the order in
 which blocked threads are awakened should not be relied on . There is no
 return value in this case .
 When invoked with blocking set to true , do the same thing as when called
 without arguments , and return true .
 When invoked with blocking set to false , do not block . If a call without
 an argument would block , return false immediately ; otherwise , do the
 same thing as when called without arguments , and return true ."""

implementation:
rc = False
with self . __cond :
    while self . __value == 0 :
        if not blocking :
            break
        if __debug__ :
            self . _note ( "%s.acquire(%s): blocked waiting, value=%s" , self , blocking , self . __value )
        self . __cond . wait ( )
    else :
        self . __value = self . __value - 1
        if __debug__ :
            self . _note ( "%s.acquire: success, value=%s" , self , self . __value )
        rc = True
return rc


signature:
def release ( self ) :
    """Release a semaphore , incrementing the internal counter by one .
 When the counter is zero on entry and another thread is waiting for it
 to become larger than zero again , wake up that thread ."""

implementation:
with self . __cond :
    self . __value = self . __value + 1
    if __debug__ :
        self . _note ( "%s.release: success, value=%s" , self , self . __value )
    self . __cond . notify ( )


signature:
def release ( self ) :
    """Release a semaphore , incrementing the internal counter by one .
 When the counter is zero on entry and another thread is waiting for it
 to become larger than zero again , wake up that thread .
 If the number of releases exceeds the number of acquires ,
 raise a ValueError ."""

implementation:
with self . __cond :
    if self . __value >= self . _initial_value :
        raise ValueError ( "Semaphore released too many times" )
    self . __value += 1
    self . __cond . notify ( )


signature:
def set ( self ) :
    """Set the internal flag to true .
 All threads waiting for the flag to become true are awakened . Threads
 that call wait ( ) once the flag is true will not block at all ."""

implementation:
with self . __cond :
    self . __flag = True
    self . __cond . notify_all ( )


signature:
def wait ( self , timeout = None ) :
    """Block until the internal flag is true .
 If the internal flag is true on entry , return immediately . Otherwise ,
 block until another thread calls set ( ) to set the flag to true , or until
 the optional timeout occurs .
 When the timeout argument is present and not None , it should be a
 floating point number specifying a timeout for the operation in seconds
 ( or fractions thereof ) .
 This method returns the internal flag on exit , so it will always return
 True except if a timeout is given and the operation times out ."""

implementation:
with self . __cond :
    if not self . __flag :
        self . __cond . wait ( timeout )
    return self . __flag


signature:
def start ( self ) :
    """Start the thread ' s activity .
 It must be called at most once per thread object . It arranges for the
 object ' s run ( ) method to be invoked in a separate thread of control .
 This method will raise a RuntimeError if called more than once on the
 same thread object ."""

implementation:
if not self . __initialized :
    raise RuntimeError ( "thread.__init__() not called" )
if self . __started . is_set ( ) :
    raise RuntimeError ( "threads can only be started once" )
if __debug__ :
    self . _note ( "%s.start(): starting thread" , self )
with _active_limbo_lock :
    _limbo [ self ] = self
try :
    _start_new_thread ( self . __bootstrap , ( ) )
except Exception :
    with _active_limbo_lock :
        del _limbo [ self ]
    raise
self . __started . wait ( )


signature:
def run ( self ) :
    """Method representing the thread ' s activity .
 You may override this method in a subclass . The standard run ( ) method
 invokes the callable object passed to the object ' s constructor as the
 target argument , if any , with sequential and keyword arguments taken
 from the args and kwargs arguments , respectively ."""

implementation:
try :
    if self . __target :
        self . __target ( * self . __args , ** self . __kwargs )
finally : # Avoid a refcycle if the thread is running a function with
# an argument that has a member that points to the thread .
    del self . __target , self . __args , self . __kwargs


signature:
def join ( self , timeout = None ) :
    """Wait until the thread terminates .
 This blocks the calling thread until the thread whose join ( ) method is
 called terminates - - either normally or through an unhandled exception
 or until the optional timeout occurs .
 When the timeout argument is present and not None , it should be a
 floating point number specifying a timeout for the operation in seconds
 ( or fractions thereof ) . As join ( ) always returns None , you must call
 isAlive ( ) after join ( ) to decide whether a timeout happened - - if the
 thread is still alive , the join ( ) call timed out .
 When the timeout argument is not present or None , the operation will
 block until the thread terminates .
 A thread can be join ( ) ed many times .
 join ( ) raises a RuntimeError if an attempt is made to join the current
 thread as that would cause a deadlock . It is also an error to join ( ) a
 thread before it has been started and attempts to do so raises the same
 exception ."""

implementation:
if not self . __initialized :
    raise RuntimeError ( "Thread.__init__() not called" )
if not self . __started . is_set ( ) :
    raise RuntimeError ( "cannot join thread before it is started" )
if self is current_thread ( ) :
    raise RuntimeError ( "cannot join current thread" )
if __debug__ :
    if not self . __stopped :
        self . _note ( "%s.join(): waiting until thread stops" , self )
self . __block . acquire ( )
try :
    if timeout is None :
        while not self . __stopped :
            self . __block . wait ( )
        if __debug__ :
            self . _note ( "%s.join(): thread stopped" , self )
    else :
        deadline = _time ( ) + timeout
        while not self . __stopped :
            delay = deadline - _time ( )
            if delay <= 0 :
                if __debug__ :
                    self . _note ( "%s.join(): timed out" , self )
                break
            self . __block . wait ( delay )
        else :
            if __debug__ :
                self . _note ( "%s.join(): thread stopped" , self )
finally :
    self . __block . release ( )


signature:
def _dump_registry ( cls , file = None ) :
    """Debug helper to print the ABC registry ."""

implementation:
print >> file , "Class: %s.%s" % ( cls . __module__ , cls . __name__ )
print >> file , "Inv.counter: %s" % ABCMeta . _abc_invalidation_counter
for name in sorted ( cls . __dict__ . keys ( ) ) :
    if name . startswith ( "_abc_" ) :
        value = getattr ( cls , name )
        print >> file , "%s: %r" % ( name , value )


signature:
def b2a_qp ( data , quotetabs = False , istext = True , header = False ) :
    """quotetabs = True means that tab and space characters are always
 quoted .
 istext = False means that \r and \n are treated as regular characters
 header = True encodes space characters with ' _ ' and requires
 real ' _ ' characters to be quoted ."""

implementation:
MAXLINESIZE = 76
# See if this string is using CRLF line ends
lf = data . find ( '\n' )
crlf = lf > 0 and data [ lf - 1 ] == '\r'
inp = 0
linelen = 0
odata = [ ]
while inp < len ( data ) :
    c = data [ inp ]
    if ( c > '~' or c == '=' or ( header and c == '_' ) or ( c == '.' and linelen == 0 and ( inp + 1 == len ( data ) or data [ inp + 1 ] == '\n' or data [ inp + 1 ] == '\r' ) ) or ( not istext and ( c == '\r' or c == '\n' ) ) or ( ( c == '\t' or c == ' ' ) and ( inp + 1 == len ( data ) ) ) or ( c <= ' ' and c != '\r' and c != '\n' and ( quotetabs or ( not quotetabs and ( c != '\t' and c != ' ' ) ) ) ) ) :
        linelen += 3
        if linelen >= MAXLINESIZE :
            odata . append ( '=' )
            if crlf :
                odata . append ( '\r' )
            odata . append ( '\n' )
            linelen = 3
        odata . append ( '=' + two_hex_digits ( ord ( c ) ) )
        inp += 1
    else :
        if ( istext and ( c == '\n' or ( inp + 1 < len ( data ) and c == '\r' and data [ inp + 1 ] == '\n' ) ) ) :
            linelen = 0
            # Protect against whitespace on end of line
            if ( len ( odata ) > 0 and ( odata [ - 1 ] == ' ' or odata [ - 1 ] == '\t' ) ) :
                ch = ord ( odata [ - 1 ] )
                odata [ - 1 ] = '='
                odata . append ( two_hex_digits ( ch ) )
            if crlf :
                odata . append ( '\r' )
            odata . append ( '\n' )
            if c == '\r' :
                inp += 2
            else :
                inp += 1
        else :
            if ( inp + 1 < len ( data ) and data [ inp + 1 ] != '\n' and ( linelen + 1 ) >= MAXLINESIZE ) :
                odata . append ( '=' )
                if crlf :
                    odata . append ( '\r' )
                odata . append ( '\n' )
                linelen = 0
            linelen += 1
            if header and c == ' ' :
                c = '_'
            odata . append ( c )
            inp += 1
return '' . join ( odata )


signature:
def rlecode_hqx ( s ) :
    """Run length encoding for binhex4.
 The CPython implementation does not do run length encoding
 of \x90 characters . This implementation does ."""

implementation:
if not s :
    return ''
result = [ ]
prev = s [ 0 ]
count = 1
# Add a dummy character to get the loop to go one extra round .
# The dummy must be different from the last character of s .
# In the same step we remove the first character , which has
# already been stored in prev .
if s [ - 1 ] == '!' :
    s = s [ 1 : ] + '?'
else :
    s = s [ 1 : ] + '!'
for c in s :
    if c == prev and count < 255 :
        count += 1
    else :
        if count == 1 :
            if prev != '\x90' :
                result . append ( prev )
            else :
                result += [ '\x90' , '\x00' ]
        elif count < 4 :
            if prev != '\x90' :
                result += [ prev ] * count
            else :
                result += [ '\x90' , '\x00' ] * count
        else :
            if prev != '\x90' :
                result += [ prev , '\x90' , chr ( count ) ]
            else :
                result += [ '\x90' , '\x00' , '\x90' , chr ( count ) ]
        count = 1
        prev = c
return '' . join ( result )


signature:
def _match_abbrev ( s , wordmap ) :
    """_ match _ abbrev ( s : string , wordmap : { string : Option } ) - > string
 Return the string key in ' wordmap ' for which ' s ' is an unambiguous
 abbreviation . If ' s ' is found to be ambiguous or doesn ' t match any of
 ' words ' , raise BadOptionError ."""

implementation:
# Is there an exact match ?
if s in wordmap :
    return s
else : # Isolate all words with s as a prefix .
    possibilities = [ word for word in wordmap . keys ( ) if word . startswith ( s ) ]
    # No exact match , so there had better be just one possibility .
    if len ( possibilities ) == 1 :
        return possibilities [ 0 ]
    elif not possibilities :
        raise BadOptionError ( s )
    else : # More than one possible completion : ambiguous prefix .
        possibilities . sort ( )
        raise AmbiguousOptionError ( s , possibilities )


signature:
def _format_text ( self , text ) :
    """Format a paragraph of free - form text for inclusion in the
 help output at the current indentation level ."""

implementation:
text_width = max ( self . width - self . current_indent , 11 )
indent = " " * self . current_indent
return textwrap . fill ( text , text_width , initial_indent = indent , subsequent_indent = indent )


signature:
def format_option_strings ( self , option ) :
    """Return a comma - separated list of option strings & metavariables ."""

implementation:
if option . takes_value ( ) :
    metavar = option . metavar or option . dest . upper ( )
    short_opts = [ self . _short_opt_fmt % ( sopt , metavar ) for sopt in option . _short_opts ]
    long_opts = [ self . _long_opt_fmt % ( lopt , metavar ) for lopt in option . _long_opts ]
else :
    short_opts = option . _short_opts
    long_opts = option . _long_opts
if self . short_first :
    opts = short_opts + long_opts
else :
    opts = long_opts + short_opts
return ", " . join ( opts )


signature:
def _update_careful ( self , dict ) :
    """Update the option values from an arbitrary dictionary , but only
 use keys from dict that already have a corresponding attribute
 in self . Any keys in dict without a corresponding attribute
 are silently ignored ."""

implementation:
for attr in dir ( self ) :
    if attr in dict :
        dval = dict [ attr ]
        if dval is not None :
            setattr ( self , attr , dval )


signature:
def add_option ( self , * args , ** kwargs ) :
    """add _ option ( Option )
 add _ option ( opt _ str , . . . , kwarg = val , . . . )"""

implementation:
if type ( args [ 0 ] ) in types . StringTypes :
    option = self . option_class ( * args , ** kwargs )
elif len ( args ) == 1 and not kwargs :
    option = args [ 0 ]
    if not isinstance ( option , Option ) :
        raise TypeError , "not an Option instance: %r" % option
else :
    raise TypeError , "invalid arguments"
self . _check_conflict ( option )
self . option_list . append ( option )
option . container = self
for opt in option . _short_opts :
    self . _short_opt [ opt ] = option
for opt in option . _long_opts :
    self . _long_opt [ opt ] = option
if option . dest is not None : # option has a dest , we need a default
    if option . default is not NO_DEFAULT :
        self . defaults [ option . dest ] = option . default
    elif option . dest not in self . defaults :
        self . defaults [ option . dest ] = None
return option


signature:
def destroy ( self ) :
    """Declare that you are done with this OptionParser . This cleans up
 reference cycles so the OptionParser ( and all objects referenced by
 it ) can be garbage - collected promptly . After calling destroy ( ) , the
 OptionParser is unusable ."""

implementation:
OptionContainer . destroy ( self )
for group in self . option_groups :
    group . destroy ( )
del self . option_list
del self . option_groups
del self . formatter


signature:
def parse_args ( self , args = None , values = None ) :
    """parse _ args ( args : [ string ] = sys . argv [ 1 : ] ,
 values : Values = None )
 - > ( values : Values , args : [ string ] )
 Parse the command - line options found in ' args ' ( default :
 sys . argv [ 1 : ] ) . Any errors result in a call to ' error ( ) ' , which
 by default prints the usage message to stderr and calls
 sys . exit ( ) with an error message . On success returns a pair
 ( values , args ) where ' values ' is a Values instance ( with all
 your option values ) and ' args ' is the list of arguments left
 over after parsing options ."""

implementation:
rargs = self . _get_args ( args )
if values is None :
    values = self . get_default_values ( )
# Store the halves of the argument list as attributes for the
# convenience of callbacks :
# rargs
# the rest of the command - line ( the " r " stands for
# " remaining " or " right - hand " )
# largs
# the leftover arguments - - ie . what ' s left after removing
# options and their arguments ( the " l " stands for " leftover "
# or " left - hand " )
self . rargs = rargs
self . largs = largs = [ ]
self . values = values
try :
    stop = self . _process_args ( largs , rargs , values )
except ( BadOptionError , OptionValueError ) , err :
    self . error ( str ( err ) )
args = largs + rargs
return self . check_values ( values , args )


signature:
def print_help ( self , file = None ) :
    """print _ help ( file : file = stdout )
 Print an extended help message , listing all options and any
 help text provided with them , to ' file ' ( default stdout ) ."""

implementation:
if file is None :
    file = sys . stdout
encoding = self . _get_encoding ( file )
# file . write ( self . format _ help ( ) . encode ( encoding , " replace " ) )
file . write ( self . format_help ( ) )


signature:
def reverse ( self ) :
    "reverse * IN PLACE *"

implementation:
leftblock = self . left
rightblock = self . right
leftindex = self . leftndx
rightindex = self . rightndx
for i in range ( self . length // 2 ) : # Validate that pointers haven ' t met in the middle
    assert leftblock != rightblock or leftindex < rightindex
    # Swap
    ( rightblock [ rightindex ] , leftblock [ leftindex ] ) = ( leftblock [ leftindex ] , rightblock [ rightindex ] )
    # Advance left block / index pair
    leftindex += 1
    if leftindex == n :
        leftblock = leftblock [ RGTLNK ]
        assert leftblock is not None
        leftindex = 0
    # Step backwards with the right block / index pair
    rightindex -= 1
    if rightindex == - 1 :
        rightblock = rightblock [ LFTLNK ]
        assert rightblock is not None
        rightindex = n - 1


signature:
def insort_right ( a , x , lo = 0 , hi = None ) :
    """Insert item x in list a , and keep it sorted assuming a is sorted .
 If x is already in a , insert it to the right of the rightmost x .
 Optional args lo ( default 0 ) and hi ( default len ( a ) ) bound the
 slice of a to be searched ."""

implementation:
if lo < 0 :
    raise ValueError ( 'lo must be non-negative' )
if hi is None :
    hi = len ( a )
while lo < hi :
    mid = ( lo + hi ) // 2
    if x < a [ mid ] :
        hi = mid
    else :
        lo = mid + 1
a . insert ( lo , x )


signature:
def bisect_right ( a , x , lo = 0 , hi = None ) :
    """Return the index where to insert item x in list a , assuming a is sorted .
 The return value i is such that all e in a [ : i ] have e < = x , and all e in
 a [ i : ] have e > x . So if x already appears in the list , a . insert ( x ) will
 insert just after the rightmost x already there .
 Optional args lo ( default 0 ) and hi ( default len ( a ) ) bound the
 slice of a to be searched ."""

implementation:
if lo < 0 :
    raise ValueError ( 'lo must be non-negative' )
if hi is None :
    hi = len ( a )
while lo < hi :
    mid = ( lo + hi ) // 2
    if x < a [ mid ] :
        hi = mid
    else :
        lo = mid + 1
return lo


signature:
def bisect_left ( a , x , lo = 0 , hi = None ) :
    """Return the index where to insert item x in list a , assuming a is sorted .
 The return value i is such that all e in a [ : i ] have e < x , and all e in
 a [ i : ] have e > = x . So if x already appears in the list , a . insert ( x ) will
 insert just before the leftmost x already there .
 Optional args lo ( default 0 ) and hi ( default len ( a ) ) bound the
 slice of a to be searched ."""

implementation:
if lo < 0 :
    raise ValueError ( 'lo must be non-negative' )
if hi is None :
    hi = len ( a )
while lo < hi :
    mid = ( lo + hi ) // 2
    if a [ mid ] < x :
        lo = mid + 1
    else :
        hi = mid
return lo


signature:
def lock ( self , function , argument ) :
    """Lock a mutex , call the function with supplied argument
 when it is acquired . If the mutex is already locked , place
 function and argument in the queue ."""

implementation:
if self . testandset ( ) :
    function ( argument )
else :
    self . queue . append ( ( function , argument ) )


signature:
def unlock ( self ) :
    """Unlock a mutex . If the queue is not empty , call the next
 function with its argument ."""

implementation:
if self . queue :
    function , argument = self . queue . popleft ( )
    function ( argument )
else :
    self . locked = False


signature:
def clear ( self ) :
    'od . clear ( ) - > None . Remove all items from od .'

implementation:
root = self . __root
root [ : ] = [ root , root , None ]
self . __map . clear ( )
dict . clear ( self )


signature:
def popitem ( self , last = True ) :
    '''od . popitem ( ) - > ( k , v ) , return and remove a ( key , value ) pair .
 Pairs are returned in LIFO order if last is true or FIFO order if false .'''

implementation:
if not self :
    raise KeyError ( 'dictionary is empty' )
key = next ( reversed ( self ) if last else iter ( self ) )
value = self . pop ( key )
return key , value


signature:
def fromkeys ( cls , iterable , value = None ) :
    '''OD . fromkeys ( S [ , v ] ) - > New ordered dictionary with keys from S .
 If not specified , the value defaults to None .'''

implementation:
self = cls ( )
for key in iterable :
    self [ key ] = value
return self


signature:
def update ( * args , ** kwds ) :
    '''Like dict . update ( ) but add counts instead of replacing them .
 Source can be an iterable , a dictionary , or another Counter instance .
 > > > c = Counter ( ' which ' )
 > > > c . update ( ' witch ' ) # add elements from another iterable
 > > > d = Counter ( ' watch ' )
 > > > c . update ( d ) # add elements from another counter
 > > > c [ ' h ' ] # four ' h ' in which , witch , and watch'''

implementation:
# The regular dict . update ( ) operation makes no sense here because the
# replace behavior results in the some of original untouched counts
# being mixed - in with all of the other counts for a mismash that
# doesn ' t have a straight - forward interpretation in most counting
# contexts . Instead , we implement straight - addition . Both the inputs
# and outputs are allowed to contain zero and negative counts .
if not args :
    raise TypeError ( "descriptor 'update' of 'Counter' object " "needs an argument" )
self = args [ 0 ]
args = args [ 1 : ]
if len ( args ) > 1 :
    raise TypeError ( 'expected at most 1 arguments, got %d' % len ( args ) )
iterable = args [ 0 ] if args else None
if iterable is not None :
    if isinstance ( iterable , Mapping ) :
        if self :
            self_get = self . get
            for elem , count in iterable . iteritems ( ) :
                self [ elem ] = self_get ( elem , 0 ) + count
        else :
            super ( Counter , self ) . update ( iterable )
            # fast path when counter is empty
    else :
        self_get = self . get
        for elem in iterable :
            self [ elem ] = self_get ( elem , 0 ) + 1
if kwds :
    self . update ( kwds )


signature:
def subtract ( * args , ** kwds ) :
    '''Like dict . update ( ) but subtracts counts instead of replacing them .
 Counts can be reduced below zero . Both the inputs and outputs are
 allowed to contain zero and negative counts .
 Source can be an iterable , a dictionary , or another Counter instance .
 > > > c = Counter ( ' which ' )
 > > > c . subtract ( ' witch ' ) # subtract elements from another iterable
 > > > c . subtract ( Counter ( ' watch ' ) ) # subtract elements from another counter
 > > > c [ ' h ' ] # 2 in which , minus 1 in witch , minus 1 in watch
 > > > c [ ' w ' ] # 1 in which , minus 1 in witch , minus 1 in watch'''

implementation:
if not args :
    raise TypeError ( "descriptor 'subtract' of 'Counter' object " "needs an argument" )
self = args [ 0 ]
args = args [ 1 : ]
if len ( args ) > 1 :
    raise TypeError ( 'expected at most 1 arguments, got %d' % len ( args ) )
iterable = args [ 0 ] if args else None
if iterable is not None :
    self_get = self . get
    if isinstance ( iterable , Mapping ) :
        for elem , count in iterable . items ( ) :
            self [ elem ] = self_get ( elem , 0 ) - count
    else :
        for elem in iterable :
            self [ elem ] = self_get ( elem , 0 ) - 1
if kwds :
    self . subtract ( kwds )


signature:
def digest ( self ) :
    """Terminate the message - digest computation and return digest .
 Return the digest of the strings passed to the update ( )
 method so far . This is a 16 - byte string which may contain
 non - ASCII characters , including null bytes ."""

implementation:
A = self . A
B = self . B
C = self . C
D = self . D
input = [ ] + self . input
count = [ ] + self . count
index = ( self . count [ 0 ] >> 3 ) & 0x3f
if index < 56 :
    padLen = 56 - index
else :
    padLen = 120 - index
padding = [ b'\200' ] + [ b'\000' ] * 63
self . update ( padding [ : padLen ] )
# Append length ( before padding ) .
bits = _bytelist2long ( self . input [ : 56 ] ) + count
self . _transform ( bits )
# Store state in digest .
digest = struct . pack ( "<IIII" , self . A , self . B , self . C , self . D )
self . A = A
self . B = B
self . C = C
self . D = D
self . input = input
self . count = count
return digest


signature:
def copy ( self ) :
    """Return a clone object .
 Return a copy ( ' clone ' ) of the md5 object . This can be used
 to efficiently compute the digests of strings that share
 a common initial substring ."""

implementation:
if 0 : # set this to 1 to make the flow space crash
    return copy . deepcopy ( self )
clone = self . __class__ ( )
clone . length = self . length
clone . count = [ ] + self . count [ : ]
clone . input = [ ] + self . input
clone . A = self . A
clone . B = self . B
clone . C = self . C
clone . D = self . D
return clone


signature:
def compile ( pattern , flags , code , groups = 0 , groupindex = { } , indexgroup = [ None ] ) :
    """Compiles ( or rather just converts ) a pattern descriptor to a SRE _ Pattern
 object . Actual compilation to opcodes happens in sre _ compile ."""

implementation: return SRE_Pattern ( pattern , flags , code , groups , groupindex , indexgroup )


signature:
def search ( self , string , pos = 0 , endpos = sys . maxint ) :
    """Scan through string looking for a location where this regular
 expression produces a match , and return a corresponding MatchObject
 instance . Return None if no position in the string matches the
 pattern ."""

implementation:
state = _State ( string , pos , endpos , self . flags )
if state . search ( self . _code ) :
    return SRE_Match ( self , state )
else :
    return None


signature:
def findall ( self , string , pos = 0 , endpos = sys . maxint ) :
    """Return a list of all non - overlapping matches of pattern in string ."""

implementation:
matchlist = [ ]
state = _State ( string , pos , endpos , self . flags )
while state . start <= state . end :
    state . reset ( )
    state . string_position = state . start
    if not state . search ( self . _code ) :
        break
    match = SRE_Match ( self , state )
    if self . groups == 0 or self . groups == 1 :
        item = match . group ( self . groups )
    else :
        item = match . groups ( "" )
    matchlist . append ( item )
    if state . string_position == state . start :
        state . start += 1
    else :
        state . start = state . string_position
return matchlist


signature:
def sub ( self , repl , string , count = 0 ) :
    """Return the string obtained by replacing the leftmost non - overlapping
 occurrences of pattern in string by the replacement repl ."""

implementation: return self . _subx ( repl , string , count , False )


signature:
def subn ( self , repl , string , count = 0 ) :
    """Return the tuple ( new _ string , number _ of _ subs _ made ) found by replacing
 the leftmost non - overlapping occurrences of pattern with the replacement
 repl ."""

implementation: return self . _subx ( repl , string , count , True )


signature:
def split ( self , string , maxsplit = 0 ) :
    """Split string by the occurrences of pattern ."""

implementation:
splitlist = [ ]
state = _State ( string , 0 , sys . maxint , self . flags )
n = 0
last = state . start
while not maxsplit or n < maxsplit :
    state . reset ( )
    state . string_position = state . start
    if not state . search ( self . _code ) :
        break
    if state . start == state . string_position : # zero - width match
        if last == state . end : # or end of string
            break
        state . start += 1
        continue
    splitlist . append ( string [ last : state . start ] )
    # add groups ( if any )
    if self . groups :
        match = SRE_Match ( self , state )
        # TODO : Use . extend once it is implemented .
        # splitlist . extend ( list ( match . groups ( None ) ) )
        splitlist += ( list ( match . groups ( None ) ) )
    n += 1
    last = state . start = state . string_position
splitlist . append ( string [ last : state . end ] )
return splitlist


signature:
def finditer ( self , string , pos = 0 , endpos = sys . maxint ) :
    """Return a list of all non - overlapping matches of pattern in string ."""

implementation:
scanner = self . scanner ( string , pos , endpos )
return iter ( scanner . search , None )


signature:
def _create_regs ( self , state ) :
    """Creates a tuple of index pairs representing matched groups ."""

implementation:
regs = [ ( state . start , state . string_position ) ]
for group in range ( self . re . groups ) :
    mark_index = 2 * group
    if mark_index + 1 < len ( state . marks ) and state . marks [ mark_index ] is not None and state . marks [ mark_index + 1 ] is not None :
        regs . append ( ( state . marks [ mark_index ] , state . marks [ mark_index + 1 ] ) )
    else :
        regs . append ( ( - 1 , - 1 ) )
return tuple ( regs )


signature:
def groups ( self , default = None ) :
    """Returns a tuple containing all the subgroups of the match . The
 default argument is used for groups that did not participate in the
 match ( defaults to None ) ."""

implementation:
groups = [ ]
for indices in self . regs [ 1 : ] :
    if indices [ 0 ] >= 0 :
        groups . append ( self . string [ indices [ 0 ] : indices [ 1 ] ] )
    else :
        groups . append ( default )
return tuple ( groups )


signature:
def groupdict ( self , default = None ) :
    """Return a dictionary containing all the named subgroups of the match .
 The default argument is used for groups that did not participate in the
 match ( defaults to None ) ."""

implementation:
groupdict = { }
for key , value in self . re . groupindex . items ( ) :
    groupdict [ key ] = self . _get_slice ( value , default )
return groupdict


signature:
def group ( self , * args ) :
    """Returns one or more subgroups of the match . Each argument is either a
 group index or a group name ."""

implementation:
if len ( args ) == 0 :
    args = ( 0 , )
grouplist = [ ]
for group in args :
    grouplist . append ( self . _get_slice ( self . _get_index ( group ) , None ) )
if len ( grouplist ) == 1 :
    return grouplist [ 0 ]
else :
    return tuple ( grouplist )


signature:
def fast_search ( self , pattern_codes ) :
    """Skips forward in a string as fast as possible using information from
 an optimization info block ."""

implementation:
# pattern starts with a known prefix
# < 5 = length > < 6 = skip > < 7 = prefix data > < overlap data >
flags = pattern_codes [ 2 ]
prefix_len = pattern_codes [ 5 ]
prefix_skip = pattern_codes [ 6 ]
# don ' t really know what this is good for
prefix = pattern_codes [ 7 : 7 + prefix_len ]
overlap = pattern_codes [ 7 + prefix_len - 1 : pattern_codes [ 1 ] + 1 ]
pattern_codes = pattern_codes [ pattern_codes [ 1 ] + 1 : ]
i = 0
string_position = self . string_position
while string_position < self . end :
    while True :
        if ord ( self . string [ string_position ] ) != prefix [ i ] :
            if i == 0 :
                break
            else :
                i = overlap [ i ]
        else :
            i += 1
            if i == prefix_len : # found a potential match
                self . start = string_position + 1 - prefix_len
                self . string_position = string_position + 1 - prefix_len + prefix_skip
                if flags & SRE_INFO_LITERAL :
                    return True
                    # matched all of pure literal pattern
                if self . match ( pattern_codes [ 2 * prefix_skip : ] ) :
                    return True
                i = overlap [ i ]
            break
    string_position += 1
return False


signature:
def push_new_context ( self , pattern_offset ) :
    """Creates a new child context of this context and pushes it on the
 stack . pattern _ offset is the offset off the current code position to
 start interpreting from ."""

implementation:
child_context = _MatchContext ( self . state , self . pattern_codes [ self . code_position + pattern_offset : ] )
self . state . context_stack . append ( child_context )
return child_context


signature:
def match ( self , context ) :
    """Returns True if the current context matches , False if it doesn ' t and
 None if matching is not finished , ie must be resumed after child
 contexts have been matched ."""

implementation:
while context . remaining_codes ( ) > 0 and context . has_matched is None :
    opcode = context . peek_code ( )
    if not self . dispatch ( opcode , context ) :
        return None
if context . has_matched is None :
    context . has_matched = False
return context . has_matched


signature:
def dispatch ( self , opcode , context ) :
    """Dispatches a context on a given opcode . Returns True if the context
 is done matching , False if it must be resumed when next encountered ."""

implementation:
if id ( context ) in self . executing_contexts :
    generator = self . executing_contexts [ id ( context ) ]
    del self . executing_contexts [ id ( context ) ]
    has_finished = generator . next ( )
else :
    method = self . DISPATCH_TABLE . get ( opcode , _OpcodeDispatcher . unknown )
    has_finished = method ( self , context )
    if hasattr ( has_finished , "next" ) : # avoid using the types module
        generator = has_finished
        has_finished = generator . next ( )
if not has_finished :
    self . executing_contexts [ id ( context ) ] = generator
return has_finished


signature:
def check_charset ( self , ctx , char ) :
    """Checks whether a character matches set of arbitrary length . Assumes
 the code pointer is at the first member of the set ."""

implementation:
self . set_dispatcher . reset ( char )
save_position = ctx . code_position
result = None
while result is None :
    result = self . set_dispatcher . dispatch ( ctx . peek_code ( ) , ctx )
ctx . code_position = save_position
return result


signature:
def count_repetitions ( self , ctx , maxcount ) :
    """Returns the number of repetitions of a single item , starting from the
 current string position . The code pointer is expected to point to a
 REPEAT _ ONE operation ( with the repeated 4 ahead ) ."""

implementation:
count = 0
real_maxcount = ctx . state . end - ctx . string_position
if maxcount < real_maxcount and maxcount != MAXREPEAT :
    real_maxcount = maxcount
# XXX could special case every single character pattern here , as in C .
# This is a general solution , a bit hackisch , but works and should be
# efficient .
code_position = ctx . code_position
string_position = ctx . string_position
ctx . skip_code ( 4 )
reset_position = ctx . code_position
while count < real_maxcount : # this works because the single character pattern is followed by
# a success opcode
    ctx . code_position = reset_position
    self . dispatch ( ctx . peek_code ( ) , ctx )
    if ctx . has_matched is False : # could be None as well
        break
    count += 1
ctx . has_matched = None
ctx . code_position = code_position
ctx . string_position = string_position
return count


signature:
def extract ( s ) :
    """Return ( sign , intpart , fraction , expo ) or raise an exception :
 sign is ' + ' or ' - '
 intpart is 0 or more digits beginning with a nonzero
 fraction is 0 or more digits
 expo is an integer"""

implementation:
res = decoder . match ( s )
if res is None :
    raise NotANumber , s
sign , intpart , fraction , exppart = res . group ( 1 , 2 , 3 , 4 )
if sign == '+' :
    sign = ''
if fraction :
    fraction = fraction [ 1 : ]
if exppart :
    expo = int ( exppart [ 1 : ] )
else :
    expo = 0
return sign , intpart , fraction , expo


signature:
def unexpo ( intpart , fraction , expo ) :
    """Remove the exponent by changing intpart and fraction ."""

implementation:
if expo > 0 : # Move the point left
    f = len ( fraction )
    intpart , fraction = intpart + fraction [ : expo ] , fraction [ expo : ]
    if expo > f :
        intpart = intpart + '0' * ( expo - f )
elif expo < 0 : # Move the point right
    i = len ( intpart )
    intpart , fraction = intpart [ : expo ] , intpart [ expo : ] + fraction
    if expo < - i :
        fraction = '0' * ( - expo - i ) + fraction
return intpart , fraction


signature:
def roundfrac ( intpart , fraction , digs ) :
    """Round or extend the fraction to size digs ."""

implementation:
f = len ( fraction )
if f <= digs :
    return intpart , fraction + '0' * ( digs - f )
i = len ( intpart )
if i + digs < 0 :
    return '0' * - digs , ''
total = intpart + fraction
nextdigit = total [ i + digs ]
if nextdigit >= '5' : # Hard case : increment last digit , may have carry !
    n = i + digs - 1
    while n >= 0 :
        if total [ n ] != '9' :
            break
        n = n - 1
    else :
        total = '0' + total
        i = i + 1
        n = 0
    total = total [ : n ] + chr ( ord ( total [ n ] ) + 1 ) + '0' * ( len ( total ) - n - 1 )
    intpart , fraction = total [ : i ] , total [ i : ]
if digs >= 0 :
    return intpart , fraction [ : digs ]
else :
    return intpart [ : digs ] + '0' * - digs , ''


signature:
def fix ( x , digs ) :
    """Format x as [ - ] ddd . ddd with ' digs ' digits after the point
 and at least one digit before .
 If digs < = 0 , the point is suppressed ."""

implementation:
if type ( x ) != type ( '' ) :
    x = repr ( x )
try :
    sign , intpart , fraction , expo = extract ( x )
except NotANumber :
    return x
intpart , fraction = unexpo ( intpart , fraction , expo )
intpart , fraction = roundfrac ( intpart , fraction , digs )
while intpart and intpart [ 0 ] == '0' :
    intpart = intpart [ 1 : ]
if intpart == '' :
    intpart = '0'
if digs > 0 :
    return sign + intpart + '.' + fraction
else :
    return sign + intpart


signature:
def sci ( x , digs ) :
    """Format x as [ - ] d . dddE [ + - ] ddd with ' digs ' digits after the point
 and exactly one digit before .
 If digs is < = 0 , one digit is kept and the point is suppressed ."""

implementation:
if type ( x ) != type ( '' ) :
    x = repr ( x )
sign , intpart , fraction , expo = extract ( x )
if not intpart :
    while fraction and fraction [ 0 ] == '0' :
        fraction = fraction [ 1 : ]
        expo = expo - 1
    if fraction :
        intpart , fraction = fraction [ 0 ] , fraction [ 1 : ]
        expo = expo - 1
    else :
        intpart = '0'
else :
    expo = expo + len ( intpart ) - 1
    intpart , fraction = intpart [ 0 ] , intpart [ 1 : ] + fraction
digs = max ( 0 , digs )
intpart , fraction = roundfrac ( intpart , fraction , digs )
if len ( intpart ) > 1 :
    intpart , fraction , expo = intpart [ 0 ] , intpart [ 1 : ] + fraction [ : - 1 ] , expo + len ( intpart ) - 1
s = sign + intpart
if digs > 0 :
    s = s + '.' + fraction
e = repr ( abs ( expo ) )
e = '0' * ( 3 - len ( e ) ) + e
if expo < 0 :
    e = '-' + e
else :
    e = '+' + e
return s + 'e' + e


signature:
def getrandbits ( self , k ) :
    """getrandbits ( k ) - > x . Generates an int with k random bits ."""

implementation:
if k <= 0 :
    raise ValueError ( 'number of bits must be greater than zero' )
if k != int ( k ) :
    raise TypeError ( 'number of bits should be an integer' )
numbytes = ( k + 7 ) // 8
# bits / 8 and rounded up
x = _int_from_bytes ( _gorandom ( numbytes ) )
return x >> ( numbytes * 8 - k )


signature:
def _randbelow ( self , n ) :
    """Return a random int in the range [ 0 , n ) ."""

implementation:
# TODO
# change once int . bit _ length is implemented .
# k = n . bit _ length ( )
k = _int_bit_length ( n )
r = self . getrandbits ( k )
while r >= n :
    r = self . getrandbits ( k )
return r


signature:
def getopt ( args , shortopts , longopts = [ ] ) :
    """getopt ( args , options [ , long _ options ] ) - > opts , args
 Parses command line options and parameter list . args is the
 argument list to be parsed , without the leading reference to the
 running program . Typically , this means " sys . argv [ 1 : ] " . shortopts
 is the string of option letters that the script wants to
 recognize , with options that require an argument followed by a
 colon ( i . e . , the same format that Unix getopt ( ) uses ) . If
 specified , longopts is a list of strings with the names of the
 long options which should be supported . The leading ' - - '
 characters should not be included in the option name . Options
 which require an argument should be followed by an equal sign
 The return value consists of two elements : the first is a list of
 ( option , value ) pairs ; the second is the list of program arguments
 left after the option list was stripped ( this is a trailing slice
 of the first argument ) . Each option - and - value pair returned has
 the option as its first element , prefixed with a hyphen ( e . g . ,
 ' - x ' ) , and the option argument as its second element , or an empty
 string if the option has no argument . The options occur in the
 list in the same order in which they were found , thus allowing
 multiple occurrences . Long and short options may be mixed ."""

implementation:
opts = [ ]
if type ( longopts ) == type ( "" ) :
    longopts = [ longopts ]
else :
    longopts = list ( longopts )
while args and args [ 0 ] . startswith ( '-' ) and args [ 0 ] != '-' :
    if args [ 0 ] == '--' :
        args = args [ 1 : ]
        break
    if args [ 0 ] . startswith ( '--' ) :
        opts , args = do_longs ( opts , args [ 0 ] [ 2 : ] , longopts , args [ 1 : ] )
    else :
        opts , args = do_shorts ( opts , args [ 0 ] [ 1 : ] , shortopts , args [ 1 : ] )
return opts , args


signature:
def gnu_getopt ( args , shortopts , longopts = [ ] ) :
    """getopt ( args , options [ , long _ options ] ) - > opts , args
 This function works like getopt ( ) , except that GNU style scanning
 mode is used by default . This means that option and non - option
 arguments may be intermixed . The getopt ( ) function stops
 processing options as soon as a non - option argument is
 encountered .
 If the first character of the option string is ` + ' , or if the
 environment variable POSIXLY _ CORRECT is set , then option
 processing stops as soon as a non - option argument is encountered ."""

implementation:
opts = [ ]
prog_args = [ ]
if isinstance ( longopts , str ) :
    longopts = [ longopts ]
else :
    longopts = list ( longopts )
# Allow options after non - option arguments ?
if shortopts . startswith ( '+' ) :
    shortopts = shortopts [ 1 : ]
    all_options_first = True
elif os . environ . get ( "POSIXLY_CORRECT" ) :
    all_options_first = True
else :
    all_options_first = False
while args :
    if args [ 0 ] == '--' :
        prog_args += args [ 1 : ]
        break
    if args [ 0 ] [ : 2 ] == '--' :
        opts , args = do_longs ( opts , args [ 0 ] [ 2 : ] , longopts , args [ 1 : ] )
    elif args [ 0 ] [ : 1 ] == '-' and args [ 0 ] != '-' :
        opts , args = do_shorts ( opts , args [ 0 ] [ 1 : ] , shortopts , args [ 1 : ] )
    else :
        if all_options_first :
            prog_args += args
            break
        else :
            prog_args . append ( args [ 0 ] )
            args = args [ 1 : ]
return opts , prog_args


signature:
def filter ( names , pat ) :
    """Return the subset of the list NAMES that match PAT"""

implementation:
import os
# import posixpath
result = [ ]
# pat = os . path . normcase ( pat )
try :
    re_pat = _cache [ pat ]
except KeyError :
    res = translate ( pat )
    if len ( _cache ) >= _MAXCACHE : # _ cache . clear ( )
        globals ( ) [ '_cache' ] = { }
    _cache [ pat ] = re_pat = re . compile ( res )
match = re_pat . match
# if os . path is posixpath :
if 1 : # normcase on posix is NOP . Optimize it away from the loop .
    for name in names :
        if match ( name ) :
            result . append ( name )
else :
    for name in names :
        if match ( os . path . normcase ( name ) ) :
            result . append ( name )
return result


signature:
def fnmatchcase ( name , pat ) :
    """Test whether FILENAME matches PATTERN , including case .
 This is a version of fnmatch ( ) which doesn ' t case - normalize
 its arguments ."""

implementation:
try :
    re_pat = _cache [ pat ]
except KeyError :
    res = translate ( pat )
    if len ( _cache ) >= _MAXCACHE : # _ cache . clear ( )
        globals ( ) [ '_cache' ] = { }
    _cache [ pat ] = re_pat = re . compile ( res )
return re_pat . match ( name ) is not None


signature:
def translate ( pat ) :
    """Translate a shell PATTERN to a regular expression .
 There is no way to quote meta - characters ."""

implementation:
i , n = 0 , len ( pat )
res = ''
while i < n :
    c = pat [ i ]
    i = i + 1
    if c == '*' :
        res = res + '.*'
    elif c == '?' :
        res = res + '.'
    elif c == '[' :
        j = i
        if j < n and pat [ j ] == '!' :
            j = j + 1
        if j < n and pat [ j ] == ']' :
            j = j + 1
        while j < n and pat [ j ] != ']' :
            j = j + 1
        if j >= n :
            res = res + '\\['
        else :
            stuff = pat [ i : j ] . replace ( '\\' , '\\\\' )
            i = j + 1
            if stuff [ 0 ] == '!' :
                stuff = '^' + stuff [ 1 : ]
            elif stuff [ 0 ] == '^' :
                stuff = '\\' + stuff
            res = '%s[%s]' % ( res , stuff )
    else :
        res = res + re . escape ( c )
return res + '\Z(?ms)'


signature:
def task_done ( self ) :
    """Indicate that a formerly enqueued task is complete .
 Used by Queue consumer threads . For each get ( ) used to fetch a task ,
 a subsequent call to task _ done ( ) tells the queue that the processing
 on the task is complete .
 If a join ( ) is currently blocking , it will resume when all items
 have been processed ( meaning that a task _ done ( ) call was received
 for every item that had been put ( ) into the queue ) .
 Raises a ValueError if called more times than there were items
 placed in the queue ."""

implementation:
self . all_tasks_done . acquire ( )
try :
    unfinished = self . unfinished_tasks - 1
    if unfinished <= 0 :
        if unfinished < 0 :
            raise ValueError ( 'task_done() called too many times' )
        self . all_tasks_done . notify_all ( )
    self . unfinished_tasks = unfinished
finally :
    self . all_tasks_done . release ( )


signature:
def qsize ( self ) :
    """Return the approximate size of the queue ( not reliable ! ) ."""

implementation:
self . mutex . acquire ( )
n = self . _qsize ( )
self . mutex . release ( )
return n


signature:
def empty ( self ) :
    """Return True if the queue is empty , False otherwise ( not reliable ! ) ."""

implementation:
self . mutex . acquire ( )
n = not self . _qsize ( )
self . mutex . release ( )
return n


signature:
def full ( self ) :
    """Return True if the queue is full , False otherwise ( not reliable ! ) ."""

implementation:
self . mutex . acquire ( )
n = 0 < self . maxsize == self . _qsize ( )
self . mutex . release ( )
return n


signature:
def put ( self , item , block = True , timeout = None ) :
    """Put an item into the queue .
 If optional args ' block ' is true and ' timeout ' is None ( the default ) ,
 block if necessary until a free slot is available . If ' timeout ' is
 a non - negative number , it blocks at most ' timeout ' seconds and raises
 the Full exception if no free slot was available within that time .
 Otherwise ( ' block ' is false ) , put an item on the queue if a free slot
 is immediately available , else raise the Full exception ( ' timeout '
 is ignored in that case ) ."""

implementation:
self . not_full . acquire ( )
try :
    if self . maxsize > 0 :
        if not block :
            if self . _qsize ( ) == self . maxsize :
                raise Full
        elif timeout is None :
            while self . _qsize ( ) == self . maxsize :
                self . not_full . wait ( )
        elif timeout < 0 :
            raise ValueError ( "'timeout' must be a non-negative number" )
        else :
            endtime = _time ( ) + timeout
            while self . _qsize ( ) == self . maxsize :
                remaining = endtime - _time ( )
                if remaining <= 0.0 :
                    raise Full
                self . not_full . wait ( remaining )
    self . _put ( item )
    self . unfinished_tasks += 1
    self . not_empty . notify ( )
finally :
    self . not_full . release ( )


signature:
def calculate_transitive_deps ( modname , script , gopath ) :
    """Determines all modules that script transitively depends upon ."""

implementation:
deps = set ( )
def calc ( modname , script ) :
    if modname in deps :
        return
    deps . add ( modname )
    for imp in collect_imports ( modname , script , gopath ) :
        if imp . is_native :
            deps . add ( imp . name )
            continue
        parts = imp . name . split ( '.' )
        calc ( imp . name , imp . script )
        if len ( parts ) == 1 :
            continue
        # For submodules , the parent packages are also deps .
        package_dir , filename = os . path . split ( imp . script )
        if filename == '__init__.py' :
            package_dir = os . path . dirname ( package_dir )
        for i in xrange ( len ( parts ) - 1 , 0 , - 1 ) :
            modname = '.' . join ( parts [ : i ] )
            script = os . path . join ( package_dir , '__init__.py' )
            calc ( modname , script )
            package_dir = os . path . dirname ( package_dir )
calc ( modname , script )
deps . remove ( modname )
return deps


signature:
def _make_future_features ( node ) :
    """Processes a future import statement , returning set of flags it defines ."""

implementation:
assert isinstance ( node , ast . ImportFrom )
assert node . module == '__future__'
features = FutureFeatures ( )
for alias in node . names :
    name = alias . name
    if name in _FUTURE_FEATURES :
        if name not in _IMPLEMENTED_FUTURE_FEATURES :
            msg = 'future feature {} not yet implemented by grumpy' . format ( name )
            raise util . ParseError ( node , msg )
        setattr ( features , name , True )
    elif name == 'braces' :
        raise util . ParseError ( node , 'not a chance' )
    elif name not in _REDUNDANT_FUTURE_FEATURES :
        msg = 'future feature {} is not defined' . format ( name )
        raise util . ParseError ( node , msg )
return features


signature:
def parse_future_features ( mod ) :
    """Accumulates a set of flags for the compiler _ _ future _ _ imports ."""

implementation:
assert isinstance ( mod , ast . Module )
found_docstring = False
for node in mod . body :
    if isinstance ( node , ast . ImportFrom ) :
        if node . module == '__future__' :
            return node , _make_future_features ( node )
        break
    elif isinstance ( node , ast . Expr ) and not found_docstring :
        if not isinstance ( node . value , ast . Str ) :
            break
        found_docstring = True
    else :
        break
return None , FutureFeatures ( )