signature:
def db_to_specifier ( db_string ) :
    """Return the database specifier for a database string .
 This accepts a database name or URL , and returns a database specifier in the
 format accepted by ` ` specifier _ to _ db ` ` . It is recommended that you consult
 the documentation for that function for an explanation of the format ."""

implementation:
local_match = PLAIN_RE . match ( db_string )
remote_match = URL_RE . match ( db_string )
# If this looks like a local specifier :
if local_match :
    return 'local:' + local_match . groupdict ( ) [ 'database' ]
# If this looks like a remote specifier :
elif remote_match : # Just a fancy way of getting 3 variables in 2 lines . . .
    hostname , portnum , database = map ( remote_match . groupdict ( ) . get , ( 'hostname' , 'portnum' , 'database' ) )
    local_url = settings . _ ( 'COUCHDB_SERVER' , 'http://127.0.0.1:5984/' )
    localhost , localport = urlparse . urlparse ( local_url ) [ 1 ] . split ( ':' )
    # If it ' s the local server , then return a local specifier .
    if ( localhost == hostname ) and ( localport == portnum ) :
        return 'local:' + database
    # Otherwise , prepare and return the remote specifier .
    return 'remote:%s:%s:%s' % ( hostname , portnum , database )
# Throw a wobbly .
raise ValueError ( 'Invalid database string: %r' % ( db_string , ) )


signature:
def get_db_from_db ( db_string ) :
    """Return a CouchDB database instance from a database string ."""

implementation:
server = get_server_from_db ( db_string )
local_match = PLAIN_RE . match ( db_string )
remote_match = URL_RE . match ( db_string )
# If this looks like a local specifier :
if local_match :
    return server [ local_match . groupdict ( ) [ 'database' ] ]
elif remote_match :
    return server [ remote_match . groupdict ( ) [ 'database' ] ]
raise ValueError ( 'Invalid database string: %r' % ( db_string , ) )


signature:
def ensure_specifier_exists ( db_spec ) :
    """Make sure a DB specifier exists , creating it if necessary ."""

implementation:
local_match = LOCAL_RE . match ( db_spec )
remote_match = REMOTE_RE . match ( db_spec )
plain_match = PLAIN_RE . match ( db_spec )
if local_match :
    db_name = local_match . groupdict ( ) . get ( 'database' )
    server = shortcuts . get_server ( )
    if db_name not in server :
        server . create ( db_name )
    return True
elif remote_match :
    hostname , portnum , database = map ( remote_match . groupdict ( ) . get , ( 'hostname' , 'portnum' , 'database' ) )
    server = shortcuts . get_server ( server_url = ( 'http://%s:%s' % ( hostname , portnum ) ) )
    if database not in server :
        server . create ( database )
    return True
elif plain_match :
    db_name = plain_match . groupdict ( ) . get ( 'database' )
    server = shortcuts . get_server ( )
    if db_name not in server :
        server . create ( db_name )
    return True
return False


signature:
def coerce ( value1 , value2 , default = None ) :
    """Exclude NoSet objec
 . . code - block : :
 > > > coerce ( NoSet , ' value ' )
 ' value '"""

implementation:
if value1 is not NoSet :
    return value1
elif value2 is not NoSet :
    return value2
else :
    return default


signature:
def get_events_vote_cluster ( self , delegate_address ) :
    '''Returns all transactions and forged blocks by voters clustered around a single delegate _ address'''

implementation:
delegate_pubkey = self . account_details ( address = delegate_address ) [ 'public_key' ]
plusvote = '+{delegate_pubkey}' . format ( delegate_pubkey = delegate_pubkey )
resultset = self . _cursor . execute_and_fetchall ( """
            SELECT *
             FROM (
            SELECT
            trs."{transactions[id]}" AS a,
            'transaction' AS b,
            trs."{transactions[amount]}" AS c,
            trs."{transactions[timestamp]}" AS d,
            trs."{transactions[recipient_id]}" AS e,
            trs."{transactions[sender_id]}" AS f,
            trs."{transactions[rawasset]}" AS g,
            trs."{transactions[type]}" AS h,
            trs."{transactions[fee]}" AS i,
            trs."{transactions[block_id]}" AS j,
            blocks."{blocks[height]}" AS k
            FROM {transactions[table]} AS trs
            INNER JOIN {blocks[table]} AS blocks
                 ON (blocks."{blocks[id]}" = trs."{transactions[block_id]}")
            WHERE trs."{transactions[sender_id]}" IN
              (SELECT trs."{transactions[sender_id]}"
               FROM {transactions[table]} AS trs, {votes[table]} AS votes
               WHERE trs."{transactions[id]}" = votes."{votes[transaction_id]}"
               AND votes."{votes[votes]}" = '{plusvote}')
            OR trs."{transactions[recipient_id]}" IN
              (SELECT trs."{transactions[sender_id]}"
               FROM {transactions[table]} AS trs, {votes[table]} AS votes
               WHERE trs."{transactions[id]}" = votes."{votes[transaction_id]}"
               AND votes."{votes[votes]}" = '{plusvote}')
            UNION
            SELECT
            blocks."{blocks[id]}" AS a,
            'block' AS b,
            blocks."{blocks[reward]}"as c,
            blocks."{blocks[total_fee]}" AS d,
            ENCODE(mem."{mem_accounts[public_key]}"::BYTEA, 'hex') AS e,
            mem."{mem_accounts[address]}" AS f,
            mem."{mem_accounts[username]}" AS g,
            NULL AS h,
            blocks."{blocks[timestamp]}" AS i,
            NULL AS j,
            blocks."{blocks[height]}" AS k
            FROM blocks
              INNER JOIN {mem_accounts[table]} AS mem
              ON (mem."{mem_accounts[public_key]}" = blocks."{blocks[generator_public_key]}")
            WHERE
            blocks."{blocks[generator_public_key]}" IN (
                    SELECT mem2."{mem_accounts[public_key]}"
                    FROM {mem_accounts[table]} mem2
                    WHERE mem2."{mem_accounts[address]}" IN
                    (SELECT trs."{transactions[sender_id]}"
                     FROM {transactions[table]} AS trs, {votes[table]} AS votes
                     WHERE trs."{transactions[id]}" = votes."{votes[transaction_id]}"
                     AND votes."{votes[votes]}" = '{plusvote}')
               )) total

            ORDER BY total.k ASC;""" . format ( address = delegate_address , transactions = self . scheme [ 'transactions' ] , blocks = self . scheme [ 'blocks' ] , mem_accounts = self . scheme [ 'mem_accounts' ] , mem_accounts2delegates = self . scheme [ 'mem_accounts2delegates' ] , votes = self . scheme [ 'votes' ] , plusvote = plusvote ) )
res = { }
for i in resultset :
    if i [ 1 ] == 'transaction' :
        res . update ( { i [ 0 ] : { 'tx_id' : i [ 0 ] , 'event_type' : i [ 1 ] , 'amount' : i [ 2 ] , 'timestamp' : i [ 3 ] , 'recipient_id' : i [ 4 ] , 'sender_id' : i [ 5 ] , 'rawasset' : i [ 6 ] , 'type' : i [ 7 ] , 'fee' : i [ 8 ] , 'block_id' : i [ 9 ] , 'height' : i [ 10 ] } } )
    elif i [ 1 ] == 'block' :
        res . update ( { i [ 0 ] : { 'block_id' : i [ 0 ] , 'event_type' : i [ 1 ] , 'reward' : i [ 2 ] , 'total_fee' : i [ 3 ] , 'timestamp' : i [ 8 ] , 'address' : i [ 5 ] , 'username' : i [ 6 ] , 'public_key' : i [ 4 ] , 'height' : i [ 10 ] } } )
return res


signature:
def tbw ( self , delegate_address , blacklist = None , share_fees = False , compound_interest = False ) :
    """This function doesn ' t work yet . Instead use legacy . trueshare ( ) for a functional tbw script"""

implementation:
if not blacklist :
    blacklist = [ ]
delegate_public_key = self . account_details ( address = delegate_address ) [ 'public_key' ]
height_at_calculation = self . node_height_details ( ) [ 'height' ]
# string format of the rawasset
minvote = '{{"votes":["-{0}"]}}' . format ( delegate_public_key )
plusvote = '{{"votes":["+{0}"]}}' . format ( delegate_public_key )
events = self . get_events_vote_cluster ( delegate_address )
votes = self . get_historic_voters ( delegate_address )
blocks = self . get_blocks ( delegate_address )
# create a map of voters
voter_dict = { }
for voter in votes :
    voter_dict . update ( { voter : { 'balance' : 0.0 , 'status' : False , 'last_payout' : votes [ voter ] [ 'height' ] , 'share' : 0.0 , 'vote_height' : votes [ voter ] [ 'height' ] , 'blocks_forged' : [ ] } } )
for blacklisted_address in blacklist :
    voter_dict . pop ( blacklisted_address , None )
last_payout = self . get_last_out_transactions ( delegate_address )
# not all voters have had a payout , thus a KeyError is thrown
for payout in last_payout :
    try :
        voter_dict [ payout ] [ 'last_payout' ] = last_payout [ payout ] [ 'height' ]
    except KeyError :
        pass
# the change in the previous state of the voter _ dict . This is added to the voterdict if
# no state change occurs in the blockchain .
delta_state = { }
no_state_change = False
block_keys = sorted ( list ( blocks . keys ( ) ) )
block_nr = 0
try :
    for id in events : # calculating poolbalances and updating shares
        if events [ id ] [ 'height' ] > blocks [ block_keys [ block_nr ] ] [ 'height' ] : # if the state is the same for the votepool , the previous calculation can be reused .
            block_nr += 1
            if no_state_change :
                for x in delta_state :
                    voter_dict [ x ] [ 'share' ] += delta_state [ x ]
                continue
            # update pool balances
            poolbalance = 0
            delta_state = { }
            for i in voter_dict : # here we update the poolbalance
                if compound_interest :
                    balance = voter_dict [ i ] [ 'balance' ] + voter_dict [ i ] [ 'share' ]
                else :
                    balance = voter_dict [ i ] [ 'balance' ]
                if voter_dict [ i ] [ 'status' ] : # if not voter _ dict [ i ] [ ' balance ' ] < 0:
                    poolbalance += balance
                    # else :
                    # raise exceptions . NegativeBalanceError ( ' balance lower than zero for : { 0 } . balance : { 1 } ' . format ( i , voter _ dict [ i ] [ ' balance ' ] ) )
            # here we calculate the share per voter
            for i in voter_dict :
                if compound_interest :
                    balance = voter_dict [ i ] [ 'balance' ] + voter_dict [ i ] [ 'share' ]
                else :
                    balance = voter_dict [ i ] [ 'balance' ]
                if voter_dict [ i ] [ 'status' ] and voter_dict [ i ] [ 'last_payout' ] < blocks [ block_keys [ block_nr ] ] [ 'height' ] :
                    if share_fees :
                        share = ( balance / poolbalance ) * ( blocks [ block_keys [ block_nr ] ] [ 'reward' ] + blocks [ block_keys [ block_nr ] ] [ 'totalFee' ] )
                    else :
                        share = ( balance / poolbalance ) * blocks [ block_keys [ block_nr ] ] [ 'reward' ]
                    voter_dict [ i ] [ 'share' ] += share
                    delta_state . update ( { i : share } )
            no_state_change = True
            continue
        # parsing an event
        no_state_change = False
        if events [ id ] [ 'event_type' ] == 'transaction' :
            if events [ id ] [ 'recipient_id' ] == 'Acw2vAVA48TcV8EnoBmZKJdV8bxnW6Y4E9' :
                print ( events [ id ] [ 'amount' ] )
        # parsing a transaction
        if events [ id ] [ 'event_type' ] == 'transaction' :
            if events [ id ] [ 'recipient_id' ] in voter_dict :
                voter_dict [ events [ id ] [ 'recipient_id' ] ] [ 'balance' ] += events [ id ] [ 'amount' ]
            if events [ id ] [ 'sender_id' ] in voter_dict :
                voter_dict [ events [ id ] [ 'sender_id' ] ] [ 'balance' ] -= ( events [ id ] [ 'amount' ] + events [ id ] [ 'fee' ] )
            if events [ id ] [ 'sender_id' ] in voter_dict and events [ id ] [ 'type' ] == 3 and plusvote in events [ id ] [ 'rawasset' ] :
                voter_dict [ events [ id ] [ 'sender_id' ] ] [ 'status' ] = True
            if events [ id ] [ 'sender_id' ] in voter_dict and events [ id ] [ 'type' ] == 3 and minvote in events [ id ] [ 'rawasset' ] :
                voter_dict [ events [ id ] [ 'sender_id' ] ] [ 'status' ] = False
        # parsing a forged block ( if forged by a voter )
        if events [ id ] [ 'event_type' ] == 'block' :
            voter_dict [ events [ id ] [ 'address' ] ] [ 'balance' ] += ( events [ id ] [ 'reward' ] + events [ id ] [ 'total_fee' ] )
    # the transaction for loop ends with the final transaction . However more blocks may be forged . This copies
    # the final delta share and adds it to the share x the amount of blocks left .
    remaining_blocks = len ( block_keys ) - block_nr - 1
    for i in range ( remaining_blocks ) :
        for x in delta_state :
            voter_dict [ x ] [ 'share' ] += delta_state [ x ]
    # and indexerror indicates that we have ran out of forged blocks , thus the calculation is done ( blocks [ block _ nr ]
    # throw the error )
except IndexError :
    raise
return voter_dict , height_at_calculation


signature:
def onebyone ( transform , loglikelihood , parameter_names , prior , start = 0.5 , ftol = 0.1 , disp = 0 , nsteps = 40000 , parallel = False , find_uncertainties = False , ** args ) :
    """* * Convex optimization based on Brent ' s method * *
 A strict assumption of one optimum between the parameter limits is used .
 The bounds are narrowed until it is found , i . e . the likelihood function is flat
 within the bounds .
 * If optimum outside bracket , expands bracket until contained .
 * Thus guaranteed to return local optimum .
 * Supports parallelization ( multiple parameters are treated independently )
 * Supports finding ML uncertainties ( Delta - Chi ^ 2 = 1)
 Very useful for 1-3d problems .
 Otherwise useful , reproducible / deterministic algorithm for finding the minimum in
 well - behaved likelihoods , where the parameters are weakly independent ,
 or to find a good starting point .
 Optimizes each parameter in order , assuming they are largely independent .
 For 1 - dimensional algorithm used , see : func : ` jbopt . opt _ grid `
 : param ftol : difference in values at which the function can be considered flat
 : param compute _ errors : compute standard deviation of gaussian around optimum"""

implementation:
def minfunc ( cube ) :
    cube = numpy . array ( cube )
    if ( cube <= 1e-10 ) . any ( ) or ( cube >= 1 - 1e-10 ) . any ( ) :
        return 1e100
    params = transform ( cube )
    l = loglikelihood ( params )
    p = prior ( params )
    if numpy . isinf ( p ) and p < 0 :
        print '    prior rejection'
        return - 1e300
    if numpy . isnan ( l ) :
        return - 1e300
    return - l - p
if parallel :
    func = opt_grid_parallel
else :
    func = opt_grid
n_params = len ( parameter_names )
start = start + numpy . zeros ( n_params )
ret = func ( start , minfunc , [ ( 1e-10 , 1 - 1e-10 ) ] * n_params , ftol = ftol , disp = disp , compute_errors = find_uncertainties )
if find_uncertainties :
    c0 = ret [ 0 ]
    p0 = transform ( c0 )
    stdev = numpy . zeros ( n_params )
    lower = numpy . zeros ( n_params )
    upper = numpy . zeros ( n_params )
    for i , ( lo , hi ) in enumerate ( ret [ 1 ] ) :
        c1 = numpy . copy ( c0 )
        c1 [ i ] = lo
        c2 = numpy . copy ( c0 )
        c2 [ i ] = hi
        p1 = transform ( c1 )
        p2 = transform ( c2 )
        stdev [ i ] = numpy . abs ( p2 [ i ] - p1 [ i ] ) / 2
        lower [ i ] = min ( p2 [ i ] , p1 [ i ] )
        upper [ i ] = max ( p2 [ i ] , p1 [ i ] )
    return dict ( start = ret [ 0 ] , maximum = p0 , stdev = stdev , upper = upper , lower = lower , method = 'opt_grid' )
else :
    return dict ( start = ret , maximum = transform ( ret ) , method = 'opt_grid' )


signature:
def parse_hub_key ( key ) :
    """Parse a hub key into a dictionary of component parts
 : param key : str , a hub key
 : returns : dict , hub key split into parts
 : raises : ValueError"""

implementation:
if key is None :
    raise ValueError ( 'Not a valid key' )
match = re . match ( PATTERN , key )
if not match :
    match = re . match ( PATTERN_S0 , key )
    if not match :
        raise ValueError ( 'Not a valid key' )
    return dict ( map ( normalise_part , zip ( [ p for p in PARTS_S0 . keys ( ) ] , match . groups ( ) ) ) )
return dict ( zip ( PARTS . keys ( ) , match . groups ( ) ) )


signature:
def match_part ( string , part ) :
    """Raise an exception if string doesn ' t match a part ' s regex
 : param string : str
 : param part : a key in the PARTS dict
 : raises : ValueError , TypeError"""

implementation:
if not string or not re . match ( '^(' + PARTS [ part ] + ')$' , string ) :
    raise ValueError ( '{} should match {}' . format ( part , PARTS [ part ] ) )


signature:
def generate_hub_key ( resolver_id , hub_id , repository_id , entity_type , entity_id = None ) :
    """Create and return an array of hub keys
 : param resolver _ id : the service that can resolve this key
 : param hub _ id : the unique id of the hub
 : param repository _ id : the type of id that the provider recognises
 : param entity _ type : the type of the entity to which the key refers .
 : param entity _ id : ID of entity ( UUID )
 : returns : a hub key
 : raises :
 : AttributeError : if a parameter has a bad value
 : TypeError : if a parameter has a bad value
 : ValueError : if a parameter has a bad value"""

implementation:
parsed = urlparse ( resolver_id )
if not parsed . scheme :
    parsed = parsed . _replace ( scheme = PROTOCOL , netloc = idna_encode ( parsed . path . lower ( ) ) , path = u'' )
else :
    parsed = parsed . _replace ( netloc = idna_encode ( parsed . netloc . lower ( ) ) )
resolver_id = urlunparse ( parsed )
hub_id = url_quote ( hub_id . lower ( ) )
if not entity_id :
    entity_id = str ( uuid . uuid4 ( ) ) . replace ( '-' , '' )
else :
    match_part ( entity_id , 'entity_id' )
# If any of these checks fail a ValueError exception is raised
match_part ( resolver_id , 'resolver_id' )
match_part ( hub_id , 'hub_id' )
match_part ( repository_id , 'repository_id' )
match_part ( entity_type , 'entity_type' )
hub_key = SEPARATOR . join ( [ resolver_id , SCHEMA , hub_id , repository_id , entity_type , entity_id ] )
return hub_key


signature:
def compact ( db_spec , poll_interval = 0 ) :
    """Compact a CouchDB database with optional synchronicity .
 The ` ` compact ` ` function will compact a CouchDB database stored on an
 running CouchDB server . By default , this process occurs * asynchronously * ,
 meaning that the compaction will occur in the background . Often , you ' ll want
 to know when the process has completed ; for this reason , ` ` compact ` ` will
 return a function which , when called , will return the state of the
 compaction . If it has completed , ` ` True ` ` will be returned ; otherwise ,
 ` ` False ` ` . This may be called multiple times .
 Alternatively , you may opt to run ` ` compact ` ` in synchronous mode , for
 debugging or profiling purposes . If this is the case , an optional keyword
 argument ` ` poll _ interval ` ` is accepted , which should be a number ( in
 seconds ) representing the time to take between polls . A sensible default
 may be around 0.5 ( seconds ) .
 Because this function operates on database specifiers , you can choose to
 operate on the local server or any remote server ."""

implementation:
server = get_server_from_specifier ( db_spec )
db = get_db_from_specifier ( db_spec )
# Get logger
logger = logging . getLogger ( 'relax.couchdb.compact' )
logger . info ( 'Pre-compact size of %r: %s' % ( db_spec , repr_bytes ( db . info ( ) [ 'disk_size' ] ) , ) )
logger . debug ( 'POST ' + urlparse . urljoin ( db . resource . uri + '/' , '_compact' ) )
# Start compaction process by issuing a POST to ' / < db _ name > / _ compact ' .
resp_headers , resp_body = db . resource . post ( '/_compact' )
# Asynchronous compaction
if not poll_interval :
    if not ( resp_body . get ( 'ok' , False ) and resp_headers [ 'status' ] == '202' ) :
        err = CompactionError ( 'Compaction of %r failed.' )
        # Give the exception some useful information .
        err . response = ( resp_headers , resp_body )
        raise err
    # Return a function which , when called , will return whether or not the
    # compaction process is still running .
    def check_completed ( ) :
        logger . debug ( 'Polling database to check if compaction has completed' )
        logger . debug ( 'GET ' + db . resource . uri + '/' )
        db_info = db . info ( )
        completed = not db_info . get ( 'compact_running' , False )
        if completed and db_info . get ( 'disk_size' , None ) :
            logger . info ( 'Post-compact size of %r: %s' % ( db_spec , repr_bytes ( db_info [ 'disk_size' ] ) ) )
        return completed
    return check_completed
# Synchronous compaction
elif poll_interval > 0 :
    logger . debug ( 'Polling database to check if compaction has completed' )
    logger . debug ( 'GET ' + db . resource . uri + '/' )
    # Shows whether compaction is running or not .
    running = db . info ( ) . get ( 'compact_running' , False )
    # Poll the running state of the compaction .
    while running :
        time . sleep ( poll_interval )
        logger . debug ( 'Polling database to check if compaction has completed' )
        logger . debug ( 'GET ' + db . resource . uri + '/' )
        running = db . info ( ) . get ( 'compact_running' , False )
    size_after = db . info ( ) . get ( 'disk_size' , None )
    if size_after :
        logger . info ( 'Post-compact size of %r: %s' % ( db_spec , repr_bytes ( size_after ) ) )
    return True
else :
    raise ValueError ( 'Poll interval must be greater than zero.' )


signature:
def apply_defaults ( self , commands ) :
    """apply default settings to commands
 not static , shadow " self " in eval"""

implementation:
for command in commands :
    if 'action' in command and "()" in command [ 'action' ] :
        command [ 'action' ] = eval ( "self.{}" . format ( command [ 'action' ] ) )
    if command [ 'keys' ] [ 0 ] . startswith ( '-' ) :
        if 'required' not in command :
            command [ 'required' ] = False


signature:
def create_commands ( self , commands , parser ) :
    """add commands to parser"""

implementation:
self . apply_defaults ( commands )
def create_single_command ( command ) :
    keys = command [ 'keys' ]
    del command [ 'keys' ]
    kwargs = { }
    for item in command :
        kwargs [ item ] = command [ item ]
    parser . add_argument ( * keys , ** kwargs )
if len ( commands ) > 1 :
    for command in commands :
        create_single_command ( command )
else :
    create_single_command ( commands [ 0 ] )


signature:
def create_subparsers ( self , parser ) :
    """get config for subparser and create commands"""

implementation:
subparsers = parser . add_subparsers ( )
for name in self . config [ 'subparsers' ] :
    subparser = subparsers . add_parser ( name )
    self . create_commands ( self . config [ 'subparsers' ] [ name ] , subparser )


signature:
def show_version ( self ) :
    """custom command line action to show version"""

implementation:
class ShowVersionAction ( argparse . Action ) :
    def __init__ ( inner_self , nargs = 0 , ** kw ) :
        super ( ShowVersionAction , inner_self ) . __init__ ( nargs = nargs , ** kw )
    def __call__ ( inner_self , parser , args , value , option_string = None ) :
        print ( "{parser_name} version: {version}" . format ( parser_name = self . config . get ( "parser" , { } ) . get ( "prog" ) , version = self . prog_version ) )
return ShowVersionAction


signature:
def check_path_action ( self ) :
    """custom command line action to check file exist"""

implementation:
class CheckPathAction ( argparse . Action ) :
    def __call__ ( self , parser , args , value , option_string = None ) :
        if type ( value ) is list :
            value = value [ 0 ]
        user_value = value
        if option_string == 'None' :
            if not os . path . isdir ( value ) :
                _current_user = os . path . expanduser ( "~" )
                if not value . startswith ( _current_user ) and not value . startswith ( os . getcwd ( ) ) :
                    if os . path . isdir ( os . path . join ( _current_user , value ) ) :
                        value = os . path . join ( _current_user , value )
                    elif os . path . isdir ( os . path . join ( os . getcwd ( ) , value ) ) :
                        value = os . path . join ( os . getcwd ( ) , value )
                    else :
                        value = None
                else :
                    value = None
        elif option_string == '--template-name' :
            if not os . path . isdir ( value ) :
                if not os . path . isdir ( os . path . join ( args . target , value ) ) :
                    value = None
        if not value :
            logger . error ( "Could not to find path %s. Please provide " "correct path to %s option" , user_value , option_string )
            exit ( 1 )
        setattr ( args , self . dest , value )
return CheckPathAction


signature:
def new_user ( yaml_path ) :
    '''Return the consumer and oauth tokens with three - legged OAuth process and
 save in a yaml file in the user ' s home directory .'''

implementation:
print 'Retrieve API Key from https://www.shirts.io/accounts/api_console/'
api_key = raw_input ( 'Shirts.io API Key: ' )
tokens = { 'api_key' : api_key , }
yaml_file = open ( yaml_path , 'w+' )
yaml . dump ( tokens , yaml_file , indent = 2 )
yaml_file . close ( )
return tokens


signature:
def _AddPropertiesForExtensions ( descriptor , cls ) :
    """Adds properties for all fields in this protocol message type ."""

implementation:
extension_dict = descriptor . extensions_by_name
for extension_name , extension_field in extension_dict . items ( ) :
    constant_name = extension_name . upper ( ) + "_FIELD_NUMBER"
    setattr ( cls , constant_name , extension_field . number )


signature:
def _InternalUnpackAny ( msg ) :
    """Unpacks Any message and returns the unpacked message .
 This internal method is differnt from public Any Unpack method which takes
 the target message as argument . _ InternalUnpackAny method does not have
 target message type and need to find the message type in descriptor pool .
 Args :
 msg : An Any message to be unpacked .
 Returns :
 The unpacked message ."""

implementation:
type_url = msg . type_url
db = symbol_database . Default ( )
if not type_url :
    return None
# TODO ( haberman ) : For now we just strip the hostname . Better logic will be
# required .
type_name = type_url . split ( "/" ) [ - 1 ]
descriptor = db . pool . FindMessageTypeByName ( type_name )
if descriptor is None :
    return None
message_class = db . GetPrototype ( descriptor )
message = message_class ( )
message . ParseFromString ( msg . value )
return message