signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def col ( loc , strg ) : """Returns current column within a string , counting newlines as line separators . The first column is number 1. Note : the default parsing behavior is to expand tabs in the input string before starting the parsing process . See L { I { ParserElement . parseString } < ParserElement . ...
s = strg return 1 if loc < len ( s ) and s [ loc ] == '\n' else loc - s . rfind ( "\n" , 0 , loc )
def call_external_subprocess ( command_list , stdin_filename = None , stdout_filename = None , stderr_filename = None , env = None ) : """Run the command and arguments in the command _ list . Will search the system PATH for commands to execute , but no shell is started . Redirects any selected outputs to the gi...
if stdin_filename : stdin = open ( stdin_filename , "r" ) else : stdin = None if stdout_filename : stdout = open ( stdout_filename , "w" ) else : stdout = None if stderr_filename : stderr = open ( stderr_filename , "w" ) else : stderr = None subprocess . check_call ( command_list , stdin = stdin...
def set_log_level ( self ) : """Set log level according to command - line options @ returns : logger object"""
if self . options . debug : self . logger . setLevel ( logging . DEBUG ) elif self . options . quiet : self . logger . setLevel ( logging . ERROR ) else : self . logger . setLevel ( logging . INFO ) self . logger . addHandler ( logging . StreamHandler ( ) ) return self . logger
def _create_lock_object ( self , key ) : '''Returns a lock object , split for testing'''
return redis_lock . Lock ( self . redis_conn , key , expire = self . settings [ 'REDIS_LOCK_EXPIRATION' ] , auto_renewal = True )
def post_json ( self , url , data , cls = None , ** kwargs ) : """POST data to the api - server : param url : resource location ( eg : " / type / uuid " ) : type url : str : param cls : JSONEncoder class : type cls : JSONEncoder"""
kwargs [ 'data' ] = to_json ( data , cls = cls ) kwargs [ 'headers' ] = self . default_headers return self . post ( url , ** kwargs ) . json ( )
def get_deck ( self ) : """Returns parent : Deck : of a : Placeable :"""
trace = self . get_trace ( ) # Find decks in trace , prepend with [ None ] in case nothing was found res = [ None ] + [ item for item in trace if isinstance ( item , Deck ) ] # Pop last ( and hopefully only Deck ) or None if there is no deck return res . pop ( )
def snip_string ( string , max_len = 20 , snip_string = '...' , snip_point = 0.5 ) : """Snips a string so that it is no longer than max _ len , replacing deleted characters with the snip _ string . The snip is done at snip _ point , which is a fraction between 0 and 1, indicating relatively where along the st...
if len ( string ) <= max_len : new_string = string else : visible_len = ( max_len - len ( snip_string ) ) start_len = int ( visible_len * snip_point ) end_len = visible_len - start_len new_string = string [ 0 : start_len ] + snip_string if end_len > 0 : new_string += string [ - end_len :...
def _print_context ( # pragma : no cover filename , secret , count , total , plugin_settings , additional_header_lines = None , force = False , ) : """: type filename : str : param filename : the file currently scanned . : type secret : dict , in PotentialSecret . json ( ) format : param secret : the secret ,...
print ( '{} {} {} {}\n{} {}\n{} {}' . format ( colorize ( 'Secret: ' , AnsiColor . BOLD ) , colorize ( str ( count ) , AnsiColor . PURPLE ) , colorize ( 'of' , AnsiColor . BOLD ) , colorize ( str ( total ) , AnsiColor . PURPLE ) , colorize ( 'Filename: ' , AnsiColor . BOLD ) , colorize ( filename , AnsiColor . PU...
def remove_cache_tier ( self , cache_pool ) : """Removes a cache tier from Ceph . Flushes all dirty objects from writeback pools and waits for that to complete . : param cache _ pool : six . string _ types . The cache tier pool name to remove . : return : None"""
# read - only is easy , writeback is much harder mode = get_cache_mode ( self . service , cache_pool ) if mode == 'readonly' : check_call ( [ 'ceph' , '--id' , self . service , 'osd' , 'tier' , 'cache-mode' , cache_pool , 'none' ] ) check_call ( [ 'ceph' , '--id' , self . service , 'osd' , 'tier' , 'remove' , s...
def get_transformation ( name : str ) : """Get a transformation function and error if its name is not registered . : param name : The name of a function to look up : return : A transformation function : raises MissingPipelineFunctionError : If the given function name is not registered"""
func = mapped . get ( name ) if func is None : raise MissingPipelineFunctionError ( '{} is not registered as a pipeline function' . format ( name ) ) return func
def anoteElements ( ax , anotelist , showAccName = False , efilter = None , textypos = None , ** kwargs ) : """annotate elements to axes : param ax : matplotlib axes object : param anotelist : element annotation object list : param showAccName : tag name for accelerator tubes ? default is False , show accel...
defaultstyle = { 'alpha' : 0.8 , 'arrowprops' : dict ( arrowstyle = '->' ) , 'rotation' : - 60 , 'fontsize' : 'small' } defaultstyle . update ( kwargs ) anote_list = [ ] if efilter is None : for anote in anotelist : if textypos is None : textxypos = tuple ( anote [ 'textpos' ] ) else : ...
def promote_artifacts ( self , promote_stage = 'latest' ) : """Promote artifact version to dest . Args : promote _ stage ( string ) : Stage that is being promoted"""
if promote_stage . lower ( ) == 'alpha' : self . _sync_to_uri ( self . s3_canary_uri ) elif promote_stage . lower ( ) == 'canary' : self . _sync_to_uri ( self . s3_latest_uri ) else : self . _sync_to_uri ( self . s3_latest_uri )
def explain_template_loading_attempts ( app , template , attempts ) : """This should help developers understand what failed . Mostly the same as : func : ` flask . debughelpers . explain _ template _ loading _ attempts ` , except here we ' ve extended it to support showing what : class : ` UnchainedJinjaLoader ...
from flask import Flask , Blueprint from flask . debughelpers import _dump_loader_info from flask . globals import _request_ctx_stack template , expected_priors = parse_template ( template ) info = [ f'Locating {pretty_num(expected_priors + 1)} template "{template}":' ] total_found = 0 blueprint = None reqctx = _reques...
def _pump ( self ) : '''Attempts to process the next command in the queue if one exists and the driver is not currently busy .'''
while ( not self . _busy ) and len ( self . _queue ) : cmd = self . _queue . pop ( 0 ) self . _name = cmd [ 2 ] try : cmd [ 0 ] ( * cmd [ 1 ] ) except Exception as e : self . notify ( 'error' , exception = e ) if self . _debug : traceback . print_exc ( )
def sortedby2 ( item_list , * args , ** kwargs ) : """sorts ` ` item _ list ` ` using key _ list Args : item _ list ( list ) : list to sort * args : multiple lists to sort by * * kwargs : reverse ( bool ) : sort order is descending if True else acscending Returns : list : ` ` list _ ` ` sorted by the ...
assert all ( [ len ( item_list ) == len_ for len_ in map ( len , args ) ] ) reverse = kwargs . get ( 'reverse' , False ) key = operator . itemgetter ( * range ( 1 , len ( args ) + 1 ) ) tup_list = list ( zip ( item_list , * args ) ) # print ( tup _ list ) try : sorted_tups = sorted ( tup_list , key = key , reverse ...
def get_repl_lag ( self , master_status ) : """Given two ' members ' elements from rs . status ( ) , return lag between their optimes ( in secs ) ."""
member_status = self . get_member_rs_status ( ) if not member_status : raise MongoctlException ( "Unable to determine replicaset status for" " member '%s'" % self . id ) return get_member_repl_lag ( member_status , master_status )
def get_channels ( self , condensed = False ) : '''Grabs all channels in the slack team Args : condensed ( bool ) : if true triggers list condensing functionality Returns : dic : Dict of channels in Slack team . See also : https : / / api . slack . com / methods / channels . list'''
channel_list = self . slack_client . api_call ( 'channels.list' ) if not channel_list . get ( 'ok' ) : return None if condensed : channels = [ { 'id' : item . get ( 'id' ) , 'name' : item . get ( 'name' ) } for item in channel_list . get ( 'channels' ) ] return channels else : return channel_list
def deploy_local ( self , dotfiles , target_root = None ) : """Deploy dotfiles to a local path ."""
if target_root is None : target_root = self . args . path for source_path , target_path in dotfiles . items ( ) : source_path = path . join ( self . source , source_path ) target_path = path . join ( target_root , target_path ) if path . isfile ( target_path ) or path . islink ( target_path ) : ...
def ls ( ctx , name , list_formatted ) : """List EC2 instances"""
session = create_session ( ctx . obj [ 'AWS_PROFILE_NAME' ] ) ec2 = session . resource ( 'ec2' ) if name == '*' : instances = ec2 . instances . filter ( ) else : condition = { 'Name' : 'tag:Name' , 'Values' : [ name ] } instances = ec2 . instances . filter ( Filters = [ condition ] ) out = format_output ( i...
def actnorm_scale ( name , x , logscale_factor = 3. , reverse = False , init = False ) : """Per - channel scaling of x ."""
x_shape = common_layers . shape_list ( x ) with tf . variable_scope ( name , reuse = tf . AUTO_REUSE ) : # Variance initialization logic . assert len ( x_shape ) == 2 or len ( x_shape ) == 4 if len ( x_shape ) == 2 : x_var = tf . reduce_mean ( x ** 2 , [ 0 ] , keepdims = True ) logdet_factor = 1...
def getDignities ( self ) : """Returns the dignities belonging to this object ."""
info = self . getInfo ( ) dignities = [ dign for ( dign , objID ) in info . items ( ) if objID == self . obj . id ] return dignities
def __write_edit_tmpl ( tag_key , tag_list ) : '''Generate the HTML file for editing . : param tag _ key : key of the tags . : param tag _ list : list of the tags . : return : None'''
edit_file = os . path . join ( OUT_DIR , 'edit' , 'edit_' + tag_key . split ( '_' ) [ 1 ] + '.html' ) edit_widget_arr = [ ] for sig in tag_list : html_sig = '_' . join ( [ 'html' , sig ] ) # var _ html = eval ( ' html _ vars . ' + html _ sig ) var_html = HTML_DICS [ html_sig ] if var_html [ 'type' ] in ...
def iter_services ( self , service_group = None ) : """Args : service _ group : optional name of service group Returns : if service _ group is omitted or None , an Iterator over all flattened service records in the service registry if service _ group is present , an Iterator over all service records in that...
if service_group is not None : if service_group not in EFConfig . SERVICE_GROUPS : raise RuntimeError ( "service registry: {} doesn't have '{}' section listed in EFConfig" . format ( self . _service_registry_file , service_group ) ) return self . service_registry_json [ service_group ] . iteritems ( ) e...
def team ( self , team , simple = False ) : """Get data on a single specified team . : param team : Team to get data for . : param simple : Get only vital data . : return : Team object with data on specified team ."""
return Team ( self . _get ( 'team/%s%s' % ( self . team_key ( team ) , '/simple' if simple else '' ) ) )
def to_glyphs_font_attributes ( self , source , master , is_initial ) : """Copy font attributes from ` ufo ` either to ` self . font ` or to ` master ` . Arguments : self - - The UFOBuilder ufo - - The current UFO being read master - - The current master being written is _ initial - - True iff this the fi...
if is_initial : _set_glyphs_font_attributes ( self , source ) else : _compare_and_merge_glyphs_font_attributes ( self , source )
def _cdf ( self , xloc , dist , cache ) : """Cumulative distribution function ."""
return evaluation . evaluate_forward ( dist , numpy . e ** xloc , cache = cache )
def paddr ( address ) : """Parse a string representation of an address . This function is the inverse of : func : ` saddr ` ."""
if not isinstance ( address , six . string_types ) : raise TypeError ( 'expecting a string' ) if address . startswith ( '[' ) : p1 = address . find ( ']:' ) if p1 == - 1 : raise ValueError return ( address [ 1 : p1 ] , int ( address [ p1 + 2 : ] ) ) elif ':' in address : p1 = address . find ...
def marvcli_restore ( file ) : """Restore previously dumped database"""
data = json . load ( file ) site = create_app ( ) . site site . restore_database ( ** data )
def add_volume ( self , colorchange = True , column = None , name = '' , str = '{name}' , ** kwargs ) : """Add ' volume ' study to QuantFigure . studies Parameters : colorchange : bool If True then each volume bar will have a fill color depending on if ' base ' had a positive or negative change compared t...
if not column : column = self . _d [ 'volume' ] up_color = kwargs . pop ( 'up_color' , self . theme [ 'up_color' ] ) down_color = kwargs . pop ( 'down_color' , self . theme [ 'down_color' ] ) study = { 'kind' : 'volume' , 'name' : name , 'params' : { 'colorchange' : colorchange , 'base' : 'close' , 'column' : colum...
def _get_bufsize_linux ( iface ) : '''Return network interface buffer information using ethtool'''
ret = { 'result' : False } cmd = '/sbin/ethtool -g {0}' . format ( iface ) out = __salt__ [ 'cmd.run' ] ( cmd ) pat = re . compile ( r'^(.+):\s+(\d+)$' ) suffix = 'max-' for line in out . splitlines ( ) : res = pat . match ( line ) if res : ret [ res . group ( 1 ) . lower ( ) . replace ( ' ' , '-' ) + s...
def docfrom ( base ) : """Decorator to set a function ' s docstring from another function ."""
def setdoc ( func ) : func . __doc__ = ( getattr ( base , '__doc__' ) or '' ) + ( func . __doc__ or '' ) return func return setdoc
def getCallSet ( self , id_ ) : """Returns a CallSet with the specified id , or raises a CallSetNotFoundException if it does not exist ."""
if id_ not in self . _callSetIdMap : raise exceptions . CallSetNotFoundException ( id_ ) return self . _callSetIdMap [ id_ ]
def option ( value , default = '' , omit_opts = False , omit_master = False , omit_pillar = False ) : '''Pass in a generic option and receive the value that will be assigned CLI Example : . . code - block : : bash salt ' * ' config . option redis . host'''
if not omit_opts : if value in __opts__ : return __opts__ [ value ] if not omit_master : if value in __pillar__ . get ( 'master' , { } ) : return __pillar__ [ 'master' ] [ value ] if not omit_pillar : if value in __pillar__ : return __pillar__ [ value ] if value in DEFAULTS : ret...
def _matches_billing ( price , hourly ) : """Return True if the price object is hourly and / or monthly ."""
return any ( [ hourly and price . get ( 'hourlyRecurringFee' ) is not None , not hourly and price . get ( 'recurringFee' ) is not None ] )
def flatten_probas ( probas , labels , ignore = None ) : """Flattens predictions in the batch"""
B , C , H , W = probas . size ( ) probas = probas . permute ( 0 , 2 , 3 , 1 ) . contiguous ( ) . view ( - 1 , C ) # B * H * W , C = P , C labels = labels . view ( - 1 ) if ignore is None : return probas , labels valid = ( labels != ignore ) vprobas = probas [ valid . nonzero ( ) . squeeze ( ) ] vlabels = labels [ v...
def new ( self ) : # type : ( ) - > None '''A method to create a new UDF Anchor Volume Structure . Parameters : None . Returns : Nothing .'''
if self . _initialized : raise pycdlibexception . PyCdlibInternalError ( 'UDF Anchor Volume Structure already initialized' ) self . desc_tag = UDFTag ( ) self . desc_tag . new ( 2 ) # FIXME : we should let the user set serial _ number self . main_vd_length = 32768 self . main_vd_extent = 0 # This will get set later...
def fix_input_files_for_numbered_seq ( sourceDir , suffix , timestamp , containers ) : """Fixes files used as input when pre - processing MPL - containers in their numbered form ."""
# Fix input files for each MPL - container type . for container in containers : files = glob . glob ( os . path . join ( sourceDir , container , container + '*' + suffix ) ) for currentFile in sorted ( files ) : fix_header_comment ( currentFile , timestamp )
def to_timedelta ( arg , unit = 'ns' , box = True , errors = 'raise' ) : """Convert argument to timedelta . Timedeltas are absolute differences in times , expressed in difference units ( e . g . days , hours , minutes , seconds ) . This method converts an argument from a recognized timedelta format / value in...
unit = parse_timedelta_unit ( unit ) if errors not in ( 'ignore' , 'raise' , 'coerce' ) : raise ValueError ( "errors must be one of 'ignore', " "'raise', or 'coerce'}" ) if unit in { 'Y' , 'y' , 'M' } : warnings . warn ( "M and Y units are deprecated and " "will be removed in a future version." , FutureWarning ...
def max ( self ) : """Maximum , ignorning nans ."""
if "max" not in self . attrs . keys ( ) : def f ( dataset , s ) : return np . nanmax ( dataset [ s ] ) self . attrs [ "max" ] = np . nanmax ( list ( self . chunkwise ( f ) . values ( ) ) ) return self . attrs [ "max" ]
async def _get_popular_people_page ( self , page = 1 ) : """Get a specific page of popular person data . Arguments : page ( : py : class : ` int ` , optional ) : The page to get . Returns : : py : class : ` dict ` : The page data ."""
return await self . get_data ( self . url_builder ( 'person/popular' , url_params = OrderedDict ( page = page ) , ) )
def get_node_id ( nuc_or_sat , namespace = None ) : """return the node ID of the given nucleus or satellite"""
node_type = get_node_type ( nuc_or_sat ) if node_type == 'leaf' : leaf_id = nuc_or_sat [ 0 ] . leaves ( ) [ 0 ] if namespace is not None : return '{0}:{1}' . format ( namespace , leaf_id ) else : return string ( leaf_id ) # else : node _ type = = ' span ' span_start = nuc_or_sat [ 0 ] . leav...
def arcball_map_to_sphere ( point , center , radius ) : """Return unit sphere coordinates from window coordinates ."""
v0 = ( point [ 0 ] - center [ 0 ] ) / radius v1 = ( center [ 1 ] - point [ 1 ] ) / radius n = v0 * v0 + v1 * v1 if n > 1.0 : # position outside of sphere n = math . sqrt ( n ) return numpy . array ( [ v0 / n , v1 / n , 0.0 ] ) else : return numpy . array ( [ v0 , v1 , math . sqrt ( 1.0 - n ) ] )
def connect ( self , datas = None ) : """Connects ` ` Pipers ` ` in the order input - > output . See ` ` Piper . connect ` ` . According to the pipes ( topology ) . If " datas " is given will connect the input ` ` Pipers ` ` to the input data see : ` ` Dagger . connect _ inputs ` ` . Argumensts : - datas ( ...
# if data connect inputs if datas : self . connect_inputs ( datas ) # connect the remaining pipers postorder = self . postorder ( ) self . log . debug ( '%s trying to connect in the order %s' % ( repr ( self ) , repr ( postorder ) ) ) for piper in postorder : if not piper . connected and self [ piper ] . nodes ...
def get_portal_cik ( self , portal_name ) : """Retrieves portal object according to ' portal _ name ' and returns its cik ."""
portal = self . get_portal_by_name ( portal_name ) cik = portal [ 2 ] [ 1 ] [ 'info' ] [ 'key' ] return cik
def get_client_address ( self ) : """Returns an auth token dictionary for making calls to eventhub REST API . : rtype : str"""
return "amqps://{}:{}@{}.{}:5671/{}" . format ( urllib . parse . quote_plus ( self . policy ) , urllib . parse . quote_plus ( self . sas_key ) , self . sb_name , self . namespace_suffix , self . eh_name )
async def save ( self , db ) : """Save the object to Redis ."""
kwargs = { } for col in self . _auto_columns : if not self . has_real_data ( col . name ) : kwargs [ col . name ] = await col . auto_generate ( db , self ) self . __dict__ . update ( kwargs ) # we have to delete the old index key stale_object = await self . __class__ . load ( db , identifier = self . identi...
def check_orthogonal ( angle ) : """Check the given Dinf angle based on D8 flow direction encoding code by ArcGIS"""
flow_dir_taudem = - 1 flow_dir = - 1 if MathClass . floatequal ( angle , FlowModelConst . e ) : flow_dir_taudem = FlowModelConst . e flow_dir = 1 elif MathClass . floatequal ( angle , FlowModelConst . ne ) : flow_dir_taudem = FlowModelConst . ne flow_dir = 128 elif MathClass . floatequal ( angle , FlowM...
def _to_binpoly ( x ) : '''Convert a Galois Field ' s number into a nice polynomial'''
if x <= 0 : return "0" b = 1 # init to 2 ^ 0 = 1 c = [ ] # stores the degrees of each term of the polynomials i = 0 # counter for b = 2 ^ i while x > 0 : b = ( 1 << i ) # generate a number power of 2 : 2 ^ 0 , 2 ^ 1 , 2 ^ 2 , . . . , 2 ^ i . Equivalent to b = 2 ^ i if x & b : # then check if x is divisi...
def _advance_params ( self ) : """Explicitly generate new values for these parameters only when appropriate ."""
for p in [ 'x' , 'y' , 'direction' ] : self . force_new_dynamic_value ( p ) self . last_time = self . time_fn ( )
def as_protein ( structure , filter_residues = True ) : """Exposes methods in the Bio . Struct . Protein module . Parameters : - filter _ residues boolean ; removes non - aa residues through Bio . PDB . Polypeptide is _ aa function [ Default : True ] Returns a new structure object ."""
from ssbio . biopython . Bio . Struct . Protein import Protein return Protein . from_structure ( structure , filter_residues )
def visit_copy_command ( element , compiler , ** kw ) : """Returns the actual sql query for the CopyCommand class ."""
qs = """COPY {table}{columns} FROM :data_location WITH CREDENTIALS AS :credentials {format} {parameters}""" parameters = [ ] bindparams = [ sa . bindparam ( 'data_location' , value = element . data_location , type_ = sa . String , ) , sa . bindparam ( 'credentials' , value = element . credential...
def virtual_machine_convert_to_managed_disks ( name , resource_group , ** kwargs ) : # pylint : disable = invalid - name '''. . versionadded : : 2019.2.0 Converts virtual machine disks from blob - based to managed disks . Virtual machine must be stop - deallocated before invoking this operation . : param name...
compconn = __utils__ [ 'azurearm.get_client' ] ( 'compute' , ** kwargs ) try : # pylint : disable = invalid - name vm = compconn . virtual_machines . convert_to_managed_disks ( resource_group_name = resource_group , vm_name = name ) vm . wait ( ) vm_result = vm . result ( ) result = vm_result . as_dict ...
def memoize ( fn ) : """Simple reset - able memoization decorator for functions and methods , assumes that all arguments to the function can be hashed and compared ."""
cache = { } @ wraps ( fn ) def wrapped_fn ( * args , ** kwargs ) : cache_key = _memoize_cache_key ( args , kwargs ) try : return cache [ cache_key ] except KeyError : value = fn ( * args , ** kwargs ) cache [ cache_key ] = value return value def clear_cache ( ) : cache . ...
def _merge_intervals ( self , min_depth ) : """Merge overlapping intervals . This method is called only once in the constructor ."""
def add_interval ( ret , start , stop ) : if min_depth is not None : shift = 2 * ( 29 - min_depth ) mask = ( int ( 1 ) << shift ) - 1 if stop - start < mask : ret . append ( ( start , stop ) ) else : ofs = start & mask st = start if ofs...
def user_stats ( request ) : """Get user statistics for selected groups of items time : time in format ' % Y - % m - % d _ % H : % M : % S ' used for practicing user : identifier of the user ( only for stuff users ) username : username of user ( only for users with public profile ) filters : - - use t...
timer ( 'user_stats' ) response = { } data = None if request . method == "POST" : data = json . loads ( request . body . decode ( "utf-8" ) ) [ "filters" ] if "filters" in request . GET : data = load_query_json ( request . GET , "filters" ) if data is None : return render_json ( request , { } , template = '...
def import_key ( ctx , slot , management_key , pin , private_key , pin_policy , touch_policy , password ) : """Import a private key . Write a private key to one of the slots on the YubiKey . SLOT PIV slot to import the private key to . PRIVATE - KEY File containing the private key . Use ' - ' to use stdin .""...
dev = ctx . obj [ 'dev' ] controller = ctx . obj [ 'controller' ] _ensure_authenticated ( ctx , controller , pin , management_key ) data = private_key . read ( ) while True : if password is not None : password = password . encode ( ) try : private_key = parse_private_key ( data , password ) ...
def parse_comment ( doc_comment , next_line ) : r"""Split the raw comment text into a dictionary of tags . The main comment body is included as ' doc ' . > > > comment = get _ doc _ comments ( read _ file ( ' examples / module . js ' ) ) [ 4 ] [ 0] > > > parse _ comment ( strip _ stars ( comment ) , ' ' ) [ '...
sections = re . split ( '\n\s*@' , doc_comment ) tags = { 'doc' : sections [ 0 ] . strip ( ) , 'guessed_function' : guess_function_name ( next_line ) , 'guessed_params' : guess_parameters ( next_line ) } for section in sections [ 1 : ] : tag , body = split_tag ( section ) if tag in tags : existing = tag...
def find_elements_by_class_name ( self , name ) : """Finds elements by class name . : Args : - name : The class name of the elements to find . : Returns : - list of WebElement - a list with elements if any was found . An empty list if not : Usage : elements = driver . find _ elements _ by _ class _ na...
return self . find_elements ( by = By . CLASS_NAME , value = name )
def get_continent ( self , callsign , timestamp = timestamp_now ) : """Returns the continent Identifier of a callsign Args : callsign ( str ) : Amateur Radio callsign timestamp ( datetime , optional ) : datetime in UTC ( tzinfo = pytz . UTC ) Returns : str : continent identified Raises : KeyError : No...
return self . get_all ( callsign , timestamp ) [ const . CONTINENT ]
def get_rates ( self , mmin , mmax = np . inf ) : """Returns the cumulative rates greater than Mmin : param float mmin : Minimum magnitude"""
nsrcs = self . number_sources ( ) for iloc , source in enumerate ( self . source_model ) : print ( "Source Number %s of %s, Name = %s, Typology = %s" % ( iloc + 1 , nsrcs , source . name , source . __class__ . __name__ ) ) if isinstance ( source , CharacteristicFaultSource ) : self . _get_fault_rates ( ...
def write_to_file ( data , path ) : """Export extracted fields to xml Appends . xml to path if missing and generates xml file in specified directory , if not then in root Parameters data : dict Dictionary of extracted fields path : str directory to save generated xml file Notes Do give file name to ...
if path . endswith ( '.xml' ) : filename = path else : filename = path + '.xml' tag_data = ET . Element ( 'data' ) xml_file = open ( filename , "w" ) i = 0 for line in data : i += 1 tag_item = ET . SubElement ( tag_data , 'item' ) tag_date = ET . SubElement ( tag_item , 'date' ) tag_desc = ET . ...
def merge_list ( self , new_list ) : """Add new CM servers to the list : param new _ list : a list of ` ` ( ip , port ) ` ` tuples : type new _ list : : class : ` list `"""
total = len ( self . list ) for ip , port in new_list : if ( ip , port ) not in self . list : self . mark_good ( ( ip , port ) ) if len ( self . list ) > total : self . _LOG . debug ( "Added %d new CM addresses." % ( len ( self . list ) - total ) )
def get_md5 ( self , filename ) : """Returns the md5 checksum of the provided file name ."""
with open ( filename , 'rb' ) as f : m = hashlib . md5 ( f . read ( ) ) return m . hexdigest ( )
def main ( ) : """main method"""
# initialize parser usage = "usage: %prog [-u USER] [-p PASSWORD] [-t TITLE] [-s selection] url" parser = OptionParser ( usage , version = "%prog " + instapaperlib . __version__ ) parser . add_option ( "-u" , "--user" , action = "store" , dest = "user" , metavar = "USER" , help = "instapaper username" ) parser . add_op...
def hook ( self , function , dependencies = None ) : """Tries to load a hook Args : function ( func ) : Function that will be called when the event is called Kwargs : dependencies ( str ) : String or Iterable with modules whose hooks should be called before this one Raises : : class : TypeError Note t...
if not isinstance ( dependencies , ( Iterable , type ( None ) , str ) ) : raise TypeError ( "Invalid list of dependencies provided!" ) # Tag the function with its dependencies if not hasattr ( function , "__deps__" ) : function . __deps__ = dependencies # If a module is loaded before all its dependencies are lo...
def get_neuroglancer_link ( self , resource , resolution , x_range , y_range , z_range , ** kwargs ) : """Get a neuroglancer link of the cutout specified from the host specified in the remote configuration step . Args : resource ( intern . resource . Resource ) : Resource compatible with cutout operations . r...
return self . _volume . get_neuroglancer_link ( resource , resolution , x_range , y_range , z_range , ** kwargs )
def get_distribution_names ( self ) : """Return all the distribution names known to this locator ."""
result = set ( ) page = self . get_page ( self . base_url ) if not page : raise DistlibException ( 'Unable to get %s' % self . base_url ) for match in self . _distname_re . finditer ( page . data ) : result . add ( match . group ( 1 ) ) return result
def _parent_changed ( self , parent ) : """From Parentable : Called when the parent changed update the constraints and priors view , so that constraining is automized for the parent ."""
from . index_operations import ParameterIndexOperationsView # if getattr ( self , " _ in _ init _ " ) : # import ipdb ; ipdb . set _ trace ( ) # self . constraints . update ( param . constraints , start ) # self . priors . update ( param . priors , start ) offset = parent . _offset_for ( self ) for name , iop in list (...
def disconnect ( self , close = True ) : """Logs off the session : param close : Will close all tree connects in a session"""
if not self . _connected : # already disconnected so let ' s return return if close : for open in list ( self . open_table . values ( ) ) : open . close ( False ) for tree in list ( self . tree_connect_table . values ( ) ) : tree . disconnect ( ) log . info ( "Session: %s - Logging off of SM...
def lookupEncoding ( encoding ) : """Return the python codec name corresponding to an encoding or None if the string doesn ' t correspond to a valid encoding ."""
if isinstance ( encoding , binary_type ) : try : encoding = encoding . decode ( "ascii" ) except UnicodeDecodeError : return None if encoding is not None : try : return webencodings . lookup ( encoding ) except AttributeError : return None else : return None
def _read_openjp2_common ( self ) : """Read a JPEG 2000 image using libopenjp2. Returns ndarray or lst Either the image as an ndarray or a list of ndarrays , each item corresponding to one band ."""
with ExitStack ( ) as stack : filename = self . filename stream = opj2 . stream_create_default_file_stream ( filename , True ) stack . callback ( opj2 . stream_destroy , stream ) codec = opj2 . create_decompress ( self . _codec_format ) stack . callback ( opj2 . destroy_codec , codec ) opj2 . se...
def set_level ( self , level , realms ) : """Set the realm level in the realms hierarchy : return : None"""
self . level = level if not self . level : logger . info ( "- %s" , self . get_name ( ) ) else : logger . info ( " %s %s" , '+' * self . level , self . get_name ( ) ) self . all_sub_members = [ ] self . all_sub_members_names = [ ] for child in sorted ( self . realm_members ) : child = realms . find_by_name ...
def best_detection ( detections , predictions , minimum_overlap = 0.2 , relative_prediction_threshold = 0.25 ) : """best _ detection ( detections , predictions , [ minimum _ overlap ] , [ relative _ prediction _ threshold ] ) - > bounding _ box , prediction Computes the best detection for the given detections and...
# remove all negative predictions since they harm the calculation of the weights detections = [ detections [ i ] for i in range ( len ( detections ) ) if predictions [ i ] > 0 ] predictions = [ predictions [ i ] for i in range ( len ( predictions ) ) if predictions [ i ] > 0 ] if not detections : raise ValueError (...
def add_child_to_subtree ( self , parent_word_id , tree ) : '''Searches for the tree with * parent _ word _ id * from the current subtree ( from this tree and from all of its subtrees ) . If the parent tree is found , attaches the given * tree * as its child . If the parent tree is not found , the current tre...
if ( self . word_id == parent_word_id ) : self . add_child_to_self ( tree ) elif ( self . children ) : for child in self . children : child . add_child_to_subtree ( parent_word_id , tree )
def new_signing_keys ( self ) : """Access the new _ signing _ keys : returns : twilio . rest . api . v2010 . account . new _ signing _ key . NewSigningKeyList : rtype : twilio . rest . api . v2010 . account . new _ signing _ key . NewSigningKeyList"""
if self . _new_signing_keys is None : self . _new_signing_keys = NewSigningKeyList ( self . _version , account_sid = self . _solution [ 'sid' ] , ) return self . _new_signing_keys
def _cimdatetime_constructor ( loader , node ) : """PyYAML constructor function for CIMDateTime objects . This is needed for yaml . safe _ load ( ) to support CIMDateTime ."""
cimdatetime_str = loader . construct_scalar ( node ) cimdatetime = CIMDateTime ( cimdatetime_str ) return cimdatetime
def subscribe ( self , transport , data ) : """adds a transport to a channel"""
self . add ( transport , address = data . get ( 'hx_subscribe' ) . encode ( ) ) self . send ( data [ 'hx_subscribe' ] , { 'message' : "%r is listening" % transport } )
def trace_plot ( precisions , path , n_edges = 20 , ground_truth = None , edges = [ ] ) : """Plot the change in precision ( or covariance ) coefficients as a function of changing lambda and l1 - norm . Always ignores diagonals . Parameters precisions : array of len ( path ) 2D ndarray , shape ( n _ features ,...
_check_path ( path ) assert len ( path ) == len ( precisions ) assert len ( precisions ) > 0 path = np . array ( path ) dim , _ = precisions [ 0 ] . shape # determine which indices to track if not edges : base_precision = np . copy ( precisions [ - 1 ] ) base_precision [ np . triu_indices ( base_precision . sha...
def cloned_workspace ( clone_config , chdir = True ) : """Create a cloned workspace and yield it . This creates a workspace for a with - block and cleans it up on exit . By default , this will also change to the workspace ' s ` clone _ dir ` for the duration of the with - block . Args : clone _ config : T...
workspace = ClonedWorkspace ( clone_config ) original_dir = os . getcwd ( ) if chdir : os . chdir ( workspace . clone_dir ) try : yield workspace finally : os . chdir ( original_dir ) workspace . cleanup ( )
def parse_template_config ( template_config_data ) : """> > > from tests import doctest _ utils > > > convert _ html _ to _ text = registration _ settings . VERIFICATION _ EMAIL _ HTML _ TO _ TEXT _ CONVERTER # noqa : E501 > > > parse _ template _ config ( { } ) # doctest : + IGNORE _ EXCEPTION _ DETAIL Trace...
try : subject_template_name = template_config_data [ 'subject' ] except KeyError : raise ImproperlyConfigured ( "No 'subject' key found" ) body_template_name = template_config_data . get ( 'body' ) text_body_template_name = template_config_data . get ( 'text_body' ) html_body_template_name = template_config_dat...
def description_of ( lines , name = 'stdin' ) : """Return a string describing the probable encoding of a file or list of strings . : param lines : The lines to get the encoding of . : type lines : Iterable of bytes : param name : Name of file or collection of lines : type name : str"""
u = UniversalDetector ( ) for line in lines : u . feed ( line ) u . close ( ) result = u . result if result [ 'encoding' ] : return '{0}: {1} with confidence {2}' . format ( name , result [ 'encoding' ] , result [ 'confidence' ] ) else : return '{0}: no result' . format ( name )
def unshare_project ( project_id , usernames , ** kwargs ) : """Un - share a project with a list of users , identified by their usernames ."""
user_id = kwargs . get ( 'user_id' ) proj_i = _get_project ( project_id ) proj_i . check_share_permission ( user_id ) for username in usernames : user_i = _get_user ( username ) # Set the owner ship on the network itself proj_i . unset_owner ( user_i . id , write = write , share = share ) db . DBSession . f...
def retry_failure_fab_dev_delete ( self , tenant_id , fw_data , fw_dict ) : """Retry the failure cases for delete . This module calls routine in fabric to retry the failure cases for delete . If device is not successfully cfg / uncfg , it calls the device manager routine to cfg / uncfg the device ."""
result = fw_data . get ( 'result' ) . split ( '(' ) [ 0 ] name = dfa_dbm . DfaDBMixin . get_project_name ( self , tenant_id ) fw_dict [ 'tenant_name' ] = name is_fw_virt = self . is_device_virtual ( ) if result == fw_constants . RESULT_FW_DELETE_INIT : if self . fwid_attr [ tenant_id ] . is_fw_drvr_created ( ) : ...
def delete_row ( self , ind ) : """remove self . df row at ind inplace"""
self . df = pd . concat ( [ self . df [ : ind ] , self . df [ ind + 1 : ] ] , sort = True ) return self . df
def ExtractCredentialsFromPathSpec ( self , path_spec ) : """Extracts credentials from a path specification . Args : path _ spec ( PathSpec ) : path specification to extract credentials from ."""
credentials = manager . CredentialsManager . GetCredentials ( path_spec ) for identifier in credentials . CREDENTIALS : value = getattr ( path_spec , identifier , None ) if value is None : continue self . SetCredential ( path_spec , identifier , value )
def _get_stream ( self , multiprocess = False ) : """Get the stream used to store the flaky report . If this nose run is going to use the multiprocess plugin , then use a multiprocess - list backed StringIO proxy ; otherwise , use the default stream . : param multiprocess : Whether or not this test run is...
if multiprocess : from flaky . multiprocess_string_io import MultiprocessingStringIO return MultiprocessingStringIO ( ) return self . _stream
def clone_with_new_elements ( self , new_elements ) : """Create another VariantCollection of the same class and with same state ( including metadata ) but possibly different entries . Warning : metadata is a dictionary keyed by variants . This method leaves that dictionary as - is , which may result in extran...
kwargs = self . to_dict ( ) kwargs [ "variants" ] = new_elements return self . from_dict ( kwargs )
def _on_status_message ( self , sequence , topic , message ) : """Process a status message received Args : sequence ( int ) : The sequence number of the packet received topic ( string ) : The topic this message was received on message ( dict ) : The message itself"""
self . _logger . debug ( "Received message on (topic=%s): %s" % ( topic , message ) ) try : conn_key = self . _find_connection ( topic ) except ArgumentError : self . _logger . warn ( "Dropping message that does not correspond with a known connection, message=%s" , message ) return if messages . ConnectionR...
def aspects ( self , obj ) : """Returns true if this star aspects another object . Fixed stars only aspect by conjunctions ."""
dist = angle . closestdistance ( self . lon , obj . lon ) return abs ( dist ) < self . orb ( )
def _tree_to_labels ( X , single_linkage_tree , min_cluster_size = 10 , cluster_selection_method = 'eom' , allow_single_cluster = False , match_reference_implementation = False ) : """Converts a pretrained tree and cluster size into a set of labels and probabilities ."""
condensed_tree = condense_tree ( single_linkage_tree , min_cluster_size ) stability_dict = compute_stability ( condensed_tree ) labels , probabilities , stabilities = get_clusters ( condensed_tree , stability_dict , cluster_selection_method , allow_single_cluster , match_reference_implementation ) return ( labels , pro...
def create_object ( self , alias , * args , ** kwargs ) : """Constructs the type with the given alias using the given args and kwargs . NB : aliases may be the alias ' object type itself if that type is known . : API : public : param alias : Either the type alias or the type itself . : type alias : string |...
object_type = self . _type_aliases . get ( alias ) if object_type is None : raise KeyError ( 'There is no type registered for alias {0}' . format ( alias ) ) return object_type ( * args , ** kwargs )
def named ( self , name , predicate = None , index = None ) : """Retrieves a set of Match objects that have the given name . : param name : : type name : str : param predicate : : type predicate : : param index : : type index : int : return : set of matches : rtype : set [ Match ]"""
return filter_index ( _BaseMatches . _base ( self . _name_dict [ name ] ) , predicate , index )
def url_fix_common_typos ( url ) : """Fix common typos in given URL like forgotten colon ."""
if url . startswith ( "http//" ) : url = "http://" + url [ 6 : ] elif url . startswith ( "https//" ) : url = "https://" + url [ 7 : ] return url
def gdalwarp ( src , dst , options ) : """a simple wrapper for : osgeo : func : ` gdal . Warp ` Parameters src : str , : osgeo : class : ` ogr . DataSource ` or : osgeo : class : ` gdal . Dataset ` the input data set dst : str the output data set options : dict additional parameters passed to gdal . W...
try : out = gdal . Warp ( dst , src , options = gdal . WarpOptions ( ** options ) ) except RuntimeError as e : raise RuntimeError ( '{}:\n src: {}\n dst: {}\n options: {}' . format ( str ( e ) , src , dst , options ) ) out = None
def _write_html_pages ( root , tlobjects , methods , layer , input_res ) : """Generates the documentation HTML files from from ` ` scheme . tl ` ` to ` ` / methods ` ` and ` ` / constructors ` ` , etc ."""
# Save ' Type : [ Constructors ] ' for use in both : # * Seeing the return type or constructors belonging to the same type . # * Generating the types documentation , showing available constructors . paths = { k : root / v for k , v in ( ( 'css' , 'css' ) , ( 'arrow' , 'img/arrow.svg' ) , ( 'search.js' , 'js/search.js' ...
def transform_pil_image ( self , pil_image ) : '''Uses : py : meth : ` PIL . Image . Image . transform ` to scale down the image . Based on ` this stackoverflow discussions < http : / / stackoverflow . com / a / 940368/907060 > ` _ , uses : attr : ` PIL . Image . ANTIALIAS `'''
max_width = min ( self . dimensions [ 0 ] or float ( 'inf' ) , pil_image . size [ 0 ] ) max_height = min ( self . dimensions [ 1 ] or float ( 'inf' ) , pil_image . size [ 1 ] ) max_dimensions = ( max_width , max_height ) pil_image . thumbnail ( max_dimensions , Image . ANTIALIAS ) return pil_image
def perform_permissions_check ( self , user , obj , perms ) : """Performs the permissions check ."""
return self . request . forum_permission_handler . can_access_moderation_queue ( user )
def disable_paging ( self , delay_factor = 1 ) : """Disable paging is only available with specific roles so it may fail ."""
check_command = "get system status | grep Virtual" output = self . send_command_timing ( check_command ) self . allow_disable_global = True self . vdoms = False self . _output_mode = "more" if "Virtual domain configuration: enable" in output : self . vdoms = True vdom_additional_command = "config global" ou...
def small_integer ( self , column , auto_increment = False , unsigned = False ) : """Create a new small integer column on the table . : param column : The column : type column : str : type auto _ increment : bool : type unsigned : bool : rtype : Fluent"""
return self . _add_column ( "small_integer" , column , auto_increment = auto_increment , unsigned = unsigned )
def sizes ( args ) : """% prog sizes gaps . bed a . fasta b . fasta Take the flanks of gaps within a . fasta , map them onto b . fasta . Compile the results to the gap size estimates in b . The output is detailed below : Columns are : 1 . A scaffold 2 . Start position 3 . End position 4 . Gap identifi...
from jcvi . formats . base import DictFile from jcvi . apps . align import blast p = OptionParser ( sizes . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) gapsbed , afasta , bfasta = args pf = gapsbed . rsplit ( "." , 1 ) [ 0 ] extbed = pf + ".ext.bed" e...