signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def remove_group ( self , group ) : """Remove the specified group ."""
if not isinstance ( group , Group ) : raise TypeError ( "group must be Group" ) if group not in self . groups : raise ValueError ( "Group doesn't exist / is not bound to this database." ) # save num entries and children before removal to avoid for loop problems num_entries = len ( group . entries ) for i in xra...
def delete_resource ( resource_name , key , identifier_fields , profile = 'pagerduty' , subdomain = None , api_key = None ) : '''delete any pagerduty resource Helper method for absent ( ) example : delete _ resource ( " users " , key , [ " id " , " name " , " email " ] ) # delete by id or name or email'''
resource = get_resource ( resource_name , key , identifier_fields , profile , subdomain , api_key ) if resource : if __opts__ [ 'test' ] : return 'would delete' # flush the resource _ cache , because we ' re modifying a resource del __context__ [ 'pagerduty_util.resource_cache' ] [ resource_name ] ...
def GetDatasetsProto ( self , datasets , features = None ) : """Generates the feature stats proto from dictionaries of feature values . Args : datasets : An array of dictionaries , one per dataset , each one containing : - ' entries ' : The dictionary of features in the dataset from the parsed examples . ...
features_seen = set ( ) whitelist_features = set ( features ) if features else None all_datasets = self . datasets_proto ( ) # TODO ( jwexler ) : Add ability to generate weighted feature stats # if there is a specified weight feature in the dataset . # Initialize each dataset for dataset in datasets : all_datasets ...
def teneye ( dim , order ) : """Create tensor with superdiagonal all one , rest zeros"""
I = zeros ( dim ** order ) for f in range ( dim ) : idd = f for i in range ( 1 , order ) : idd = idd + dim ** ( i - 1 ) * ( f - 1 ) I [ idd ] = 1 return I . reshape ( ones ( order ) * dim )
def _ParseYamlFromFile ( filedesc ) : """Parses given YAML file ."""
content = filedesc . read ( ) return yaml . Parse ( content ) or collections . OrderedDict ( )
def setValue ( self , p_float ) : """Override method to set a value to show it as 0 to 100. : param p _ float : The float number that want to be set . : type p _ float : float"""
p_float = p_float * 100 super ( PercentageSpinBox , self ) . setValue ( p_float )
def setParameter ( self , parameterName , index , parameterValue ) : """Set the value of a Spec parameter ."""
spec = self . getSpec ( ) if parameterName not in spec [ 'parameters' ] : raise Exception ( "Unknown parameter: " + parameterName ) setattr ( self , parameterName , parameterValue )
def create ( parser : Parser , obj : PersistedObject = None ) : """Helper method provided because we actually can ' t put that in the constructor , it creates a bug in Nose tests https : / / github . com / nose - devs / nose / issues / 725 : param parser : : param obj : : return :"""
if obj is not None : return _InvalidParserException ( 'Error ' + str ( obj ) + ' cannot be parsed using ' + str ( parser ) + ' since ' + ' this parser does not support ' + obj . get_pretty_file_mode ( ) ) else : return _InvalidParserException ( 'Error this parser is neither SingleFile nor MultiFile !' )
def action ( arguments ) : """Given parsed arguments , filter input files ."""
if arguments . quality_window_mean_qual and not arguments . quality_window : raise ValueError ( "--quality-window-mean-qual specified without " "--quality-window" ) if trie is None or triefind is None : raise ValueError ( 'Missing Bio.trie and/or Bio.triefind modules. Cannot continue' ) filters = [ ] input_type...
def list_container_objects ( self , container , prefix = None , delimiter = None ) : """List container objects : param container : container name ( Container is equivalent to Bucket term in Amazon ) . : param prefix : prefix query : param delimiter : string to delimit the queries on"""
LOG . debug ( 'list_container_objects() with %s is success.' , self . driver ) return self . driver . list_container_objects ( container , prefix , delimiter )
def create_subscriber ( self ) : '''Create a subscriber instance using specified addresses and message types .'''
if self . subscriber is None : if self . topics : self . subscriber = NSSubscriber ( self . services , self . topics , addr_listener = True , addresses = self . addresses , nameserver = self . nameserver ) self . recv = self . subscriber . start ( ) . recv
def connect ( self , frame , response = None ) : """Handle CONNECT command : Establishes a new connection and checks auth ( if applicable ) ."""
self . engine . log . debug ( "CONNECT" ) if self . engine . authenticator : login = frame . headers . get ( 'login' ) passcode = frame . headers . get ( 'passcode' ) if not self . engine . authenticator . authenticate ( login , passcode ) : raise AuthError ( "Authentication failed for %s" % login )...
def authors ( self ) : '''Queryset for all distinct authors this course had so far . Important for statistics . Note that this may be different from the list of people being registered for the course , f . e . when they submit something and the leave the course .'''
qs = self . _valid_submissions ( ) . values_list ( 'authors' , flat = True ) . distinct ( ) return qs
def store ( self , packages ) : """Store and return packages for install"""
dwn , install , comp_sum , uncomp_sum = ( [ ] for i in range ( 4 ) ) # name = data [ 0] # location = data [ 1] # size = data [ 2] # unsize = data [ 3] for pkg in packages : for pk , loc , comp , uncomp in zip ( self . data [ 0 ] , self . data [ 1 ] , self . data [ 2 ] , self . data [ 3 ] ) : if ( pk and pkg...
def echo_html ( self , url_str ) : '''Show the HTML'''
logger . info ( 'info echo html: {0}' . format ( url_str ) ) condition = self . gen_redis_kw ( ) url_arr = self . parse_url ( url_str ) sig = url_arr [ 0 ] num = ( len ( url_arr ) - 2 ) // 2 catinfo = MCategory . get_by_uid ( sig ) if catinfo . pid == '0000' : condition [ 'def_cat_pid' ] = sig else : condition ...
def json_compat_obj_decode ( data_type , obj , caller_permissions = None , alias_validators = None , strict = True , old_style = False , for_msgpack = False ) : """Decodes a JSON - compatible object based on its data type into a representative Python object . Args : data _ type ( Validator ) : Validator for s...
decoder = PythonPrimitiveToStoneDecoder ( caller_permissions , alias_validators , for_msgpack , old_style , strict ) if isinstance ( data_type , bv . Primitive ) : return decoder . make_stone_friendly ( data_type , obj , True ) else : return decoder . json_compat_obj_decode_helper ( data_type , obj )
def highlight_line ( self , payload ) : """: type payload : str : param payload : string to highlight , on chosen line"""
index_of_payload = self . target_line . lower ( ) . index ( payload . lower ( ) ) end_of_payload = index_of_payload + len ( payload ) self . target_line = u'{}{}{}' . format ( self . target_line [ : index_of_payload ] , self . apply_highlight ( self . target_line [ index_of_payload : end_of_payload ] ) , self . target_...
def append ( self , action ) : '''Add a undoable to the stack , using ` ` receiver . append ( ) ` ` .'''
if self . _receiver is not None : self . _receiver . append ( action ) if self . _receiver is self . _undos : self . _redos . clear ( ) self . docallback ( )
def equals ( key , value ) : '''Used to make sure the minion ' s grain key / value matches . Returns ` ` True ` ` if matches otherwise ` ` False ` ` . . . versionadded : : 2017.7.0 CLI Example : . . code - block : : bash salt ' * ' grains . equals fqdn < expected _ fqdn > salt ' * ' grains . equals syst...
return six . text_type ( value ) == six . text_type ( get ( key ) )
def _get_all_cmd_line_scopes ( ) : """Return all scopes that may be explicitly specified on the cmd line , in no particular order . Note that this includes only task scope , and not , say , subsystem scopes , as those aren ' t specifiable on the cmd line ."""
all_scopes = { GLOBAL_SCOPE } for goal in Goal . all ( ) : for task in goal . task_types ( ) : all_scopes . add ( task . get_scope_info ( ) . scope ) return all_scopes
def readSIFGraph ( filename ) : p = sif_parser . Parser ( filename ) """input : string , name of a file containing a Bioquali - like graph description output : asp . TermSet , with atoms matching the contents of the input file Parses a Bioquali - like graph description , and returns a TermSet object . W...
accu = TermSet ( ) file = open ( filename , 'r' ) s = file . readline ( ) while s != "" : try : accu = p . parse ( s ) except EOFError : break s = file . readline ( ) return accu
def find_inouts_mp ( voxel_grid , datapts , ** kwargs ) : """Multi - threaded ins and outs finding ( using multiprocessing ) : param voxel _ grid : voxel grid : param datapts : data points : return : in - outs"""
tol = kwargs . get ( 'tol' , 10e-8 ) num_procs = kwargs . get ( 'num_procs' , 4 ) with pool_context ( processes = num_procs ) as pool : filled = pool . map ( partial ( is_point_inside_voxel , ptsarr = datapts , tol = tol ) , voxel_grid ) return filled
def get_bundle ( self , current_bundle , url_kwargs , context_kwargs ) : """Returns the bundle to get the alias view from . If ' self . bundle _ attr ' is set , that bundle that it points to will be returned , otherwise the current _ bundle will be returned ."""
if self . bundle_attr : if self . bundle_attr == PARENT : return current_bundle . parent view , name = current_bundle . get_view_and_name ( self . bundle_attr ) return view return current_bundle
def set_random_seed ( ) : """Set the random seed from flag everywhere ."""
tf . set_random_seed ( FLAGS . random_seed ) random . seed ( FLAGS . random_seed ) np . random . seed ( FLAGS . random_seed )
def delete ( self , key , ** kwargs ) : """DeleteRange deletes the given range from the key - value store . A delete request increments the revision of the key - value store and generates a delete event in the event history for every deleted key . : param key : : param kwargs : : return :"""
payload = { "key" : _encode ( key ) , } payload . update ( kwargs ) result = self . post ( self . get_url ( "/kv/deleterange" ) , json = payload ) if 'deleted' in result : return True return False
def _parse_shape_list ( shape_list , crs ) : """Checks if the given list of shapes is in correct format and parses geometry objects : param shape _ list : The parameter ` shape _ list ` from class initialization : type shape _ list : list ( shapely . geometry . multipolygon . MultiPolygon or shapely . geometry ...
if not isinstance ( shape_list , list ) : raise ValueError ( 'Splitter must be initialized with a list of shapes' ) return [ AreaSplitter . _parse_shape ( shape , crs ) for shape in shape_list ]
def get_assets ( self ) : """: calls : ` GET / repos / : owner / : repo / releases / : release _ id / assets < https : / / developer . github . com / v3 / repos / releases / # list - assets - for - a - release > ` _ : rtype : : class : ` github . PaginatedList . PaginatedList `"""
return github . PaginatedList . PaginatedList ( github . GitReleaseAsset . GitReleaseAsset , self . _requester , self . url + "/assets" , None )
def read_cache ( cachefile , coltype = LIGOTimeGPS , sort = None , segment = None ) : """Read a LAL - or FFL - format cache file as a list of file paths Parameters cachefile : ` str ` , ` file ` Input file or file path to read . coltype : ` LIGOTimeGPS ` , ` int ` , optional Type for GPS times . sort : ...
# open file if not isinstance ( cachefile , FILE_LIKE ) : with open ( file_path ( cachefile ) , 'r' ) as fobj : return read_cache ( fobj , coltype = coltype , sort = sort , segment = segment ) # read file cache = [ x . path for x in _iter_cache ( cachefile , gpstype = coltype ) ] # sieve and sort if segment...
def main ( ) : """Program entry point ."""
global cf_verbose , cf_show_comment , cf_charset global cf_extract , cf_test_read , cf_test_unrar global cf_test_memory psw = None # parse args try : opts , args = getopt . getopt ( sys . argv [ 1 : ] , 'p:C:hvcxtRM' ) except getopt . error as ex : print ( str ( ex ) , file = sys . stderr ) sys . exit ( 1 )...
def group_list ( ) : '''. . versionadded : : 2014.1.0 Lists all groups known by yum on this system CLI Example : . . code - block : : bash salt ' * ' pkg . group _ list'''
ret = { 'installed' : [ ] , 'available' : [ ] , 'installed environments' : [ ] , 'available environments' : [ ] , 'available languages' : { } } section_map = { 'installed groups:' : 'installed' , 'available groups:' : 'available' , 'installed environment groups:' : 'installed environments' , 'available environment grou...
def get_fileservice_dir ( ) : """example settings file FILESERVICE _ CONFIG = { ' store _ dir ' : ' / var / lib / geoserver _ data / fileservice _ store '"""
conf = getattr ( settings , 'FILESERVICE_CONFIG' , { } ) dir = conf . get ( 'store_dir' , './fileservice_store' ) return os . path . normpath ( dir ) + os . sep
def read ( self , chunk_size = None ) : """Return chunk _ size of bytes , starting from self . pos , from self . content ."""
if chunk_size : data = self . content [ self . pos : self . pos + chunk_size ] self . pos += len ( data ) return data else : return self . content
def _reset_plain ( self ) : '''Create a BlockText from the captured lines and clear _ text .'''
if self . _text : self . _blocks . append ( BlockText ( '\n' . join ( self . _text ) ) ) self . _text . clear ( )
def current_user ( ) : """This method returns a user instance for jwt token data attached to the current flask app ' s context"""
user_id = current_user_id ( ) guard = current_guard ( ) user = guard . user_class . identify ( user_id ) PraetorianError . require_condition ( user is not None , "Could not identify the current user from the current id" , ) return user
def pop ( self , queue_name ) : """Pops a task off the queue . : param queue _ name : The name of the queue . Usually handled by the ` ` Gator ` ` instance . : type queue _ name : string : returns : The data for the task . : rtype : string"""
cls = self . __class__ queue = cls . queues . get ( queue_name , [ ] ) if queue : task_id = queue . pop ( 0 ) return cls . task_data . pop ( task_id , None )
def accept ( self ) : """accept a connection attempt from a remote client returns a two - tuple with the ssl - context - wrapped connection , and the address of the remote client"""
while 1 : try : sock , addr = self . _sock . accept ( ) return ( type ( self ) ( sock , keyfile = self . keyfile , certfile = self . certfile , server_side = True , cert_reqs = self . cert_reqs , ssl_version = self . ssl_version , ca_certs = self . ca_certs , do_handshake_on_connect = self . do_hand...
def squad ( R_in , t_in , t_out ) : """Spherical " quadrangular " interpolation of rotors with a cubic spline This is the best way to interpolate rotations . It uses the analog of a cubic spline , except that the interpolant is confined to the rotor manifold in a natural way . Alternative methods involving ...
if R_in . size == 0 or t_out . size == 0 : return np . array ( ( ) , dtype = np . quaternion ) # This list contains an index for each ` t _ out ` such that # t _ in [ i - 1 ] < = t _ out < t _ in [ i ] # Note that ` side = ' right ' ` is much faster in my tests # i _ in _ for _ out = t _ in . searchsorted ( t _ out...
def save_anim ( self , fig , animate , init , bitrate = 10000 , fps = 30 ) : """Not functional - - TODO"""
from matplotlib import animation anim = animation . FuncAnimation ( fig , animate , init_func = init , frames = 360 , interval = 20 ) FFMpegWriter = animation . writers [ 'ffmpeg' ] writer = FFMpegWriter ( bitrate = bitrate , fps = fps ) # Save # self . avi_path = self . base_dir + self . short_name + '.avi' anim . sav...
def rpoplpush ( self , sourcekey , destkey , * , encoding = _NOTSET ) : """Atomically returns and removes the last element ( tail ) of the list stored at source , and pushes the element at the first element ( head ) of the list stored at destination ."""
return self . execute ( b'RPOPLPUSH' , sourcekey , destkey , encoding = encoding )
def replace_namespaced_pod_status ( self , name , namespace , body , ** kwargs ) : """replace status of the specified Pod This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . replace _ namespaced _ pod _ status ( n...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . replace_namespaced_pod_status_with_http_info ( name , namespace , body , ** kwargs ) else : ( data ) = self . replace_namespaced_pod_status_with_http_info ( name , namespace , body , ** kwargs ) return data
def _release_lock ( self ) : """Release our lock if we have one"""
if not self . _has_lock ( ) : return # if someone removed our file beforhand , lets just flag this issue # instead of failing , to make it more usable . lfp = self . _lock_file_path ( ) try : rmfile ( lfp ) except OSError : pass self . _owns_lock = False
def streamRead ( self , size ) : """Send or receive a chunk of data . : arg size : Amount of data requested ."""
size = int ( size ) data = self . stream . read ( size ) size = len ( data ) if size == 0 : self . _close ( ) return dict ( message = "Finished" , size = 0 ) self . _sendResult ( dict ( message = "reading..." , stream = True , size = size ) ) sys . stdout . write ( data )
def _fit ( self , minimizing_function_args , iterative_fitting , initial_params , params_size , disp , tol = 1e-6 , fit_method = "Nelder-Mead" , maxiter = 2000 , ** kwargs ) : """Fit function for fitters ."""
ll = [ ] sols = [ ] if iterative_fitting <= 0 : raise ValueError ( "iterative_fitting parameter should be greater than 0 as of lifetimes v0.2.1" ) if iterative_fitting > 1 and initial_params is not None : raise ValueError ( "iterative_fitting and initial_params should not be both set, as no improvement could be...
def prepare_renderable ( request , test_case_result , is_admin ) : """Return a completed Renderable ."""
test_case = test_case_result . test_case file_directory = request . registry . settings [ 'file_directory' ] sha1 = test_case_result . diff . sha1 if test_case_result . diff else None kwargs = { 'number' : test_case . id , 'group' : test_case . testable . name , 'name' : test_case . name , 'points' : test_case . points...
def project_present ( name , description = None , enabled = True , profile = None , ** connection_args ) : '''Ensures that the keystone project exists Alias for tenant _ present from V2 API to fulfill V3 API naming convention . . . versionadded : : 2016.11.0 name The name of the project to manage descri...
return tenant_present ( name , description = description , enabled = enabled , profile = profile , ** connection_args )
def to_bytes ( obj , encoding = 'utf-8' , errors = None , nonstring = 'simplerepr' ) : """Make sure that a string is a byte string : arg obj : An object to make sure is a byte string . In most cases this will be either a text string or a byte string . However , with ` ` nonstring = ' simplerepr ' ` ` , this c...
if isinstance ( obj , binary_type ) : return obj # We ' re given a text string # If it has surrogates , we know because it will decode original_errors = errors if errors in _COMPOSED_ERROR_HANDLERS : if HAS_SURROGATEESCAPE : errors = 'surrogateescape' elif errors == 'surrogate_or_strict' : e...
def extract_genotypes ( self , bytes ) : """Extracts encoded genotype data from binary formatted file . : param bytes : array of bytes pulled from the . bed file : return : standard python list containing the genotype data Only ind _ count genotypes will be returned ( even if there are a handful of extra pa...
genotypes = [ ] for b in bytes : for i in range ( 0 , 4 ) : v = ( ( b >> ( i * 2 ) ) & 3 ) genotypes . append ( self . geno_conversions [ v ] ) return genotypes [ 0 : self . ind_count ]
def url_mod ( url : str , new_params : dict ) -> str : """Modifies existing URL by setting / overriding specified query string parameters . Note : Does not support multiple querystring parameters with identical name . : param url : Base URL / path to modify : param new _ params : Querystring parameters to set...
from urllib . parse import urlparse , parse_qsl , urlunparse , urlencode res = urlparse ( url ) query_params = dict ( parse_qsl ( res . query ) ) for k , v in new_params . items ( ) : if v is None : query_params [ str ( k ) ] = '' else : query_params [ str ( k ) ] = str ( v ) parts = list ( res ...
def template_response ( self , template_name , headers = { } , ** values ) : """Constructs a response , allowing custom template name and content _ type"""
response = make_response ( self . render_template ( template_name , ** values ) ) for field , value in headers . items ( ) : response . headers . set ( field , value ) return response
def _initialize_attributes ( model_class , name , bases , attrs ) : """Initialize the attributes of the model ."""
model_class . _attributes = { } for k , v in attrs . iteritems ( ) : if isinstance ( v , Attribute ) : model_class . _attributes [ k ] = v v . name = v . name or k
def xpathRegisterVariable ( self , name , ns_uri , value ) : """Register a variable with the XPath context"""
ret = libxml2mod . xmlXPathRegisterVariable ( self . _o , name , ns_uri , value ) return ret
def parse_init_dat ( infile ) : """Parse the main init . dat file which contains the modeling results The first line of the file init . dat contains stuff like : : "120 easy 40 8" The other lines look like this : : " 161 11.051 1 1guqA MUSTER " and getting the first 10 gives you the top 10 templates used ...
# TODO : would be nice to get top 10 templates instead of just the top init_dict = { } log . debug ( '{}: reading file...' . format ( infile ) ) with open ( infile , 'r' ) as f : # Get first 2 lines of file head = [ next ( f ) . strip ( ) for x in range ( 2 ) ] summary = head [ 0 ] . split ( ) difficulty = summary ...
def predict ( self , lon , lat , ** kwargs ) : """distance , abs _ mag , r _ physical"""
assert self . classifier is not None , 'ERROR' pred = np . zeros ( len ( lon ) ) cut_geometry , flags_geometry = self . applyGeometry ( lon , lat ) x_test = [ ] for key , operation in self . config [ 'operation' ] [ 'params_intrinsic' ] : assert operation . lower ( ) in [ 'linear' , 'log' ] , 'ERROR' if operati...
def validate_account_alias ( iam_client , account_alias ) : """Exit if list _ account _ aliases doesn ' t include account _ alias ."""
# Super overkill here using pagination when an account can only # have a single alias , but at least this implementation should be # future - proof current_account_aliases = [ ] paginator = iam_client . get_paginator ( 'list_account_aliases' ) response_iterator = paginator . paginate ( ) for page in response_iterator :...
def warn_attribs ( loc , node , recognised_attribs , reqd_attribs = None ) : '''Error checking of XML input : check that the given node has certain required attributes , and does not have any unrecognised attributes . Arguments : - ` loc ` : a string with some information about the location of the error i...
if reqd_attribs is None : reqd_attribs = recognised_attribs found_attribs = set ( node . keys ( ) ) if reqd_attribs - found_attribs : print ( loc , 'missing <{0}> attributes' . format ( node . tag ) , reqd_attribs - found_attribs ) if found_attribs - recognised_attribs : print ( loc , 'unrecognised <{0}> pr...
def field_date_to_json ( self , day ) : """Convert a date to a date triple ."""
if isinstance ( day , six . string_types ) : day = parse_date ( day ) return [ day . year , day . month , day . day ] if day else None
def commit ( self , container , repository = None , tag = None , message = None , author = None , changes = None , conf = None ) : """Commit a container to an image . Similar to the ` ` docker commit ` ` command . Args : container ( str ) : The image hash of the container repository ( str ) : The repository...
params = { 'container' : container , 'repo' : repository , 'tag' : tag , 'comment' : message , 'author' : author , 'changes' : changes } u = self . _url ( "/commit" ) return self . _result ( self . _post_json ( u , data = conf , params = params ) , json = True )
def graph ( self , fnm = None , size = None , fntsz = None , fntfm = None , clrgen = None , rmsz = False , prog = 'dot' ) : """Construct call graph Parameters fnm : None or string , optional ( default None ) Filename of graph file to be written . File type is determined by the file extentions ( e . g . dot ...
# Default colour generation function if clrgen is None : clrgen = lambda n : self . _clrgen ( n , 0.330 , 0.825 ) # Generate color list clrlst = clrgen ( len ( self . group ) ) # Initialise a pygraphviz graph g = pgv . AGraph ( strict = False , directed = True , landscape = False , rankdir = 'LR' , newrank = True ,...
def centerLatLon ( self ) : """Get the center lat / lon of model"""
# GET CENTROID FROM GSSHA GRID gssha_grid = self . getGrid ( ) min_x , max_x , min_y , max_y = gssha_grid . bounds ( ) x_ext , y_ext = transform ( gssha_grid . proj , Proj ( init = 'epsg:4326' ) , [ min_x , max_x , min_x , max_x ] , [ min_y , max_y , max_y , min_y ] , ) return np . mean ( y_ext ) , np . mean ( x_ext )
def mol3d ( self ) : """Return record in MOL format with 3D coordinates calculated"""
if self . _mol3d is None : apiurl = 'http://www.chemspider.com/MassSpecAPI.asmx/GetRecordMol?csid=%s&calc3d=true&token=%s' % ( self . csid , TOKEN ) response = urlopen ( apiurl ) tree = ET . parse ( response ) self . _mol3d = tree . getroot ( ) . text return self . _mol3d
def _set_ldp_eol ( self , v , load = False ) : """Setter method for ldp _ eol , mapped from YANG variable / mpls _ config / router / mpls / mpls _ cmds _ holder / ldp / ldp _ holder / ldp _ eol ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ ldp _ eol is c...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = ldp_eol . ldp_eol , is_container = 'container' , presence = True , yang_name = "ldp-eol" , rest_name = "eol" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , exte...
def _task_periodic ( self ) : """This is a callback that is registered to be called periodically from the legion . The legion chooses when it might be called , typically when it is otherwise idle ."""
log = self . _params . get ( 'log' , self . _discard ) log . debug ( "periodic" ) self . manage ( )
def on_connection_state_change ( self , event_type , callback ) : """Register a callback for a specific connection state change . Register a callback to be triggered when the connection changes to the specified state , signified by a ConnectionEvent . The callback must be a coroutine . Args : event _ type...
listeners = self . _connection_state_listeners . get ( event_type , [ ] ) listeners . append ( callback ) self . _connection_state_listeners [ event_type ] = listeners
def _check_token ( self ) : """Simple Mercedes me API ."""
need_token = ( self . _token_info is None or self . auth_handler . is_token_expired ( self . _token_info ) ) if need_token : new_token = self . auth_handler . refresh_access_token ( self . _token_info [ 'refresh_token' ] ) # skip when refresh failed if new_token is None : return self . _token_in...
def __init_keystone_session_v2 ( self , check = False ) : """Create and return a session object using Keystone API v2."""
from keystoneauth1 import loading as keystone_v2 loader = keystone_v2 . get_plugin_loader ( 'password' ) auth = loader . load_from_options ( auth_url = self . _os_auth_url , username = self . _os_username , password = self . _os_password , project_name = self . _os_tenant_name , ) sess = keystoneauth1 . session . Sessi...
def params ( self , hidden = True ) : """Gets all instance parameters , and their * cast * values . : return : dict of the form : ` ` { < name > : < value > , . . . } ` ` : rtype : : class : ` dict `"""
param_names = self . class_param_names ( hidden = hidden ) return dict ( ( name , getattr ( self , name ) ) for name in param_names )
def _parse_format ( cls , fmt ) : """Attempt to convert a SPEAD format specification to a numpy dtype . Where necessary , ` O ` is used . Raises ValueError If the format is illegal"""
fields = [ ] if not fmt : raise ValueError ( 'empty format' ) for code , length in fmt : if length == 0 : raise ValueError ( 'zero-length field (bug_compat mismatch?)' ) if ( ( code in ( 'u' , 'i' ) and length in ( 8 , 16 , 32 , 64 ) ) or ( code == 'f' and length in ( 32 , 64 ) ) ) : fields ...
def get_online_version ( ) : """Download update info and parse it ."""
# prevent getting a cached answer headers = { 'Pragma' : 'no-cache' , 'Cache-Control' : 'no-cache' } content , info = get_content ( UPDATE_URL , addheaders = headers ) if content is None : return content , info version , url = None , None for line in content . splitlines ( ) : if line . startswith ( VERSION_TAG...
def find_candidates ( document ) : """Finds cadidate nodes for the readable version of the article . Here ' s we ' re going to remove unlikely nodes , find scores on the rest , clean up and return the final best match ."""
nodes_to_score = set ( ) should_remove = set ( ) for node in document . iter ( ) : if is_unlikely_node ( node ) : logger . debug ( "We should drop unlikely: %s %r" , node . tag , node . attrib ) should_remove . add ( node ) elif is_bad_link ( node ) : logger . debug ( "We should drop bad...
def add_handler ( self , type , actions , ** kwargs ) : """Add an event handler to be processed by this session . type - The type of the event ( pygame . QUIT , pygame . KEYUP ETC ) . actions - The methods which should be called when an event matching this specification is received . more than one action can ...
l = self . _events . get ( type , [ ] ) h = Handler ( self , type , kwargs , actions ) l . append ( h ) self . _events [ type ] = l return h
def parseXRDS ( text ) : """Parse the given text as an XRDS document . @ return : ElementTree containing an XRDS document @ raises XRDSError : When there is a parse error or the document does not contain an XRDS ."""
try : element = ElementTree . XML ( text ) except XMLError , why : exc = XRDSError ( 'Error parsing document as XML' ) exc . reason = why raise exc else : tree = ElementTree . ElementTree ( element ) if not isXRDS ( tree ) : raise XRDSError ( 'Not an XRDS document' ) return tree
def flag ( self , payload ) : """Set a single flag on a resource . : param payload : t : can be one of make _ public , make _ private , make _ shareable , make _ not _ shareable , make _ discoverable , make _ not _ discoverable : return : empty but with 202 status _ code"""
url = "{url_base}/resource/{pid}/flag/" . format ( url_base = self . hs . url_base , pid = self . pid ) r = self . hs . _request ( 'POST' , url , None , payload ) return r
def GetMatchingShape ( pattern_poly , trip , matches , max_distance , verbosity = 0 ) : """Tries to find a matching shape for the given pattern Poly object , trip , and set of possibly matching Polys from which to choose a match ."""
if len ( matches ) == 0 : print ( 'No matching shape found within max-distance %d for trip %s ' % ( max_distance , trip . trip_id ) ) return None if verbosity >= 1 : for match in matches : print ( "match: size %d" % match . GetNumPoints ( ) ) scores = [ ( pattern_poly . GreedyPolyMatchDist ( match )...
def _readable_flags ( transport ) : """Method that turns bit flags into a human readable list Args : transport ( dict ) : transport info , specifically needs a ' flags ' key with bit _ flags Returns : list : a list of human readable flags ( e . g . [ ' syn _ ack ' , ' fin ' , ' rst ' , . . . ]"""
if 'flags' not in transport : return None _flag_list = [ ] flags = transport [ 'flags' ] if flags & dpkt . tcp . TH_SYN : if flags & dpkt . tcp . TH_ACK : _flag_list . append ( 'syn_ack' ) else : _flag_list . append ( 'syn' ) elif flags & dpkt . tcp . TH_FIN : if flags & dpkt . tcp . TH_...
def append_minidom_xml_to_elementtree_xml ( parent , xml , recursive = False , attributes = None ) : """Recursively , Given an ElementTree . Element as parent , and a minidom instance as xml , append the tags and content from xml to parent Used primarily for adding a snippet of XML with < italic > tags attr...
# Get the root tag name if recursive is False : tag_name = xml . documentElement . tagName node = xml . getElementsByTagName ( tag_name ) [ 0 ] new_elem = SubElement ( parent , tag_name ) if attributes : for attribute in attributes : if xml . documentElement . getAttribute ( attribut...
def _load_module ( module_name , path ) : '''A helper function invoked on the server to tell it to import a module .'''
# TODO : handle the case that the module is already loaded try : # First try to find a non - builtin , non - frozen , non - special # module using the client ' s search path fd , filename , info = imp . find_module ( module_name , path ) except ImportError : # The above will fail for builtin , frozen , or special #...
def uploadchannel_wrapper ( chef , args , options ) : """Call ` uploadchannel ` with SushiBar monitoring and progress reporting enabled . Args :"""
try : args_and_options = args . copy ( ) args_and_options . update ( options ) uploadchannel ( chef , ** args_and_options ) config . SUSHI_BAR_CLIENT . report_stage ( 'COMPLETED' , 0 ) except Exception as e : if config . SUSHI_BAR_CLIENT : config . SUSHI_BAR_CLIENT . report_stage ( 'FAILURE'...
def deleteSelected ( self ) : 'Delete all selected rows .'
ndeleted = self . deleteBy ( self . isSelected ) nselected = len ( self . _selectedRows ) self . _selectedRows . clear ( ) if ndeleted != nselected : error ( 'expected %s' % nselected )
def delete_experiment ( self ) : '''Deletes the experiment . See also : func : ` tmserver . api . experiment . delete _ experiment ` : class : ` tmlib . models . experiment . ExperimentReference ` : class : ` tmlib . models . experiment . Experiment `'''
logger . info ( 'delete experiment "%s"' , self . experiment_name ) url = self . _build_api_url ( '/experiments/{experiment_id}' . format ( experiment_id = self . _experiment_id ) ) res = self . _session . delete ( url ) res . raise_for_status ( ) del self . __experiment_id
def shift_right_3d ( x , pad_value = None ) : """Shift the second dimension of x right by one ."""
if pad_value is None : shifted_targets = tf . pad ( x , [ [ 0 , 0 ] , [ 1 , 0 ] , [ 0 , 0 ] ] ) [ : , : - 1 , : ] else : shifted_targets = tf . concat ( [ pad_value , x ] , axis = 1 ) [ : , : - 1 , : ] return shifted_targets
def get_scalar ( self , cursor , index = 0 ) : """Returns a single value from the first returned record from a cursor . By default it will get cursor . fecthone ( ) [ 0 ] which works with tuples and namedtuples . For dict cursor it is necessary to specify index . This method will not work with cursors that aren...
if isinstance ( index , int ) : return cursor . fetchone ( ) [ index ] else : return get_value ( cursor . fetchone ( ) , index )
def _parse_layer_info ( list_of_layers , resources ) : """Creates a list of Layer objects that are represented by the resources and the list of layers Parameters list _ of _ layers List ( str ) List of layers that are defined within the Layers Property on a function resources dict The Resources dictionary...
layers = [ ] for layer in list_of_layers : # If the layer is a string , assume it is the arn if isinstance ( layer , six . string_types ) : layers . append ( LayerVersion ( layer , None ) ) continue # In the list of layers that is defined within a template , you can reference a LayerVersion reso...
def upgrade_mt_translation ( self , uid , properties = None ) : """: param uid : : param properties : This is suppose to be a dictionary with new properties values to be replaced on the upgraded job : return :"""
api_url = self . api_url uri = 'mt_translation/{}/' . format ( uid ) url = "{}{}" . format ( api_url , uri ) data = { "status" : "upgrade" , "properties" : properties } return requests . patch ( url , headers = self . headers , data = json . dumps ( data ) )
def normalize ( color ) : """Returns an hex color Parameters : color : string Color representation in rgba | rgb | hex Example : normalize ( ' # f03 ' )"""
if type ( color ) == tuple : color = to_rgba ( * color ) if 'rgba' in color : return rgb_to_hex ( rgba_to_rgb ( color ) ) elif 'rgb' in color : return rgb_to_hex ( color ) elif '#' in color : if len ( color ) == 7 : return color else : color = color [ 1 : ] return '#' + '' . ...
def _format_output ( self , outfile_name , out_type ) : """Prepend proper output prefix to output filename"""
outfile_name = self . _absolute ( outfile_name ) outparts = outfile_name . split ( "/" ) outparts [ - 1 ] = self . _out_format % ( out_type , outparts [ - 1 ] ) return '/' . join ( outparts )
def is_role ( path ) : """Determine if a path is an ansible role ."""
seems_legit = False for folder in c . ANSIBLE_FOLDERS : if os . path . exists ( os . path . join ( path , folder ) ) : seems_legit = True return seems_legit
def prepare_synteny ( tourfile , lastfile , odir , p , opts ) : """Prepare synteny plots for movie ( ) ."""
qbedfile , sbedfile = get_bed_filenames ( lastfile , p , opts ) qbedfile = op . abspath ( qbedfile ) sbedfile = op . abspath ( sbedfile ) qbed = Bed ( qbedfile , sorted = False ) contig_to_beds = dict ( qbed . sub_beds ( ) ) # Create a separate directory for the subplots and movie mkdir ( odir , overwrite = True ) os ....
def _request ( self , url , values = None ) : """Send a request and read response . Sends a get request if values are None , post request otherwise ."""
if values : json_data = json . dumps ( values ) request = urllib2 . Request ( url , json_data . encode ( ) ) request . add_header ( 'content-type' , 'application/json' ) request . add_header ( 'authorization' , self . _auth ) connection = urllib2 . urlopen ( request ) response = connection . rea...
def get_assessment_offered_mdata ( ) : """Return default mdata map for AssessmentOffered"""
return { 'level' : { 'element_label' : { 'text' : 'level' , 'languageTypeId' : str ( DEFAULT_LANGUAGE_TYPE ) , 'scriptTypeId' : str ( DEFAULT_SCRIPT_TYPE ) , 'formatTypeId' : str ( DEFAULT_FORMAT_TYPE ) , } , 'instructions' : { 'text' : 'accepts an osid.id.Id object' , 'languageTypeId' : str ( DEFAULT_LANGUAGE_TYPE ) ,...
def is_collection ( object_type , strict : bool = False ) -> bool : """Utility method to check if a type is a subclass of typing . { List , Dict , Set , Tuple } or of list , dict , set , tuple . If strict is set to True , the method will return True only if the class IS directly one of the base collection cla...
if object_type is None or object_type is Any or is_union_type ( object_type ) or is_typevar ( object_type ) : return False elif strict : return object_type == dict or object_type == list or object_type == tuple or object_type == set or get_base_generic_type ( object_type ) == Dict or get_base_generic_type ( obj...
def read_namespaced_deployment_status ( self , name , namespace , ** kwargs ) : """read status of the specified Deployment This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . read _ namespaced _ deployment _ statu...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . read_namespaced_deployment_status_with_http_info ( name , namespace , ** kwargs ) else : ( data ) = self . read_namespaced_deployment_status_with_http_info ( name , namespace , ** kwargs ) return data
def page ( self , sim = values . unset , status = values . unset , direction = values . unset , transport = values . unset , page_token = values . unset , page_number = values . unset , page_size = values . unset ) : """Retrieve a single page of CommandInstance records from the API . Request is executed immediate...
params = values . of ( { 'Sim' : sim , 'Status' : status , 'Direction' : direction , 'Transport' : transport , 'PageToken' : page_token , 'Page' : page_number , 'PageSize' : page_size , } ) response = self . _version . page ( 'GET' , self . _uri , params = params , ) return CommandPage ( self . _version , response , se...
def line_step ( ) -> Union [ Tuple [ int , int ] , Tuple [ None , None ] ] : """After calling line _ init returns ( x , y ) points of the line . Once all points are exhausted this function will return ( None , None ) Returns : Union [ Tuple [ int , int ] , Tuple [ None , None ] ] : The next ( x , y ) point ...
x = ffi . new ( "int *" ) y = ffi . new ( "int *" ) ret = lib . TCOD_line_step ( x , y ) if not ret : return x [ 0 ] , y [ 0 ] return None , None
def slicing_singlevalue ( arg , length ) : """Internally used ."""
if isinstance ( arg , slice ) : start , stop , step = arg . indices ( length ) i = start if step > 0 : while i < stop : yield i i += step else : while i > stop : yield i i += step else : try : i = arg . __index__ ( ) except ...
def _call_and_serialize ( cls , method , data , refresh = False ) : """Call the remote method with data , and optionally refresh . Args : method ( callable ) : The method on the Authenticated Five9 object that should be called . data ( dict ) : A data dictionary that will be passed as the first and only p...
method ( data ) if refresh : return cls . read ( method . __self__ , data [ cls . __uid_field__ ] ) else : return cls . deserialize ( cls . _get_non_empty_dict ( data ) )
def scale_means ( self , hs_dims = None , prune = False ) : """Return list of column and row scaled means for this slice . If a row / col doesn ' t have numerical values , return None for the corresponding dimension . If a slice only has 1D , return only the column scaled mean ( as numpy array ) . If both row...
scale_means = self . _cube . scale_means ( hs_dims , prune ) if self . ca_as_0th : # If slice is used as 0th CA , then we need to observe the 1st dimension , # because the 0th dimension is CA items , which is only used for slicing # ( and thus doesn ' t have numerical values , and also doesn ' t constitute any # dimens...
def operate_selected_rows ( self , operator ) : '''对选中的条目进行操作 . operator - 处理函数'''
model , tree_paths = self . selection . get_selected_rows ( ) if not tree_paths : return fs_ids = [ ] for tree_path in tree_paths : fs_ids . append ( model [ tree_path ] [ FSID_COL ] ) for fs_id in fs_ids : row = self . get_row_by_fsid ( fs_id ) if not row : return operator ( row , scan = Fa...
def started_after ( self , date ) : '''Leaves only those objects whose first version started after the specified date . : param date : date string to use in calculation'''
dt = Timestamp ( date ) starts = self . groupby ( self . _oid ) . apply ( lambda df : df . _start . min ( ) ) oids = set ( starts [ starts > dt ] . index . tolist ( ) ) return self [ self . _oid . apply ( lambda v : v in oids ) ]
def estimate_completion ( self ) : """Estimate completion time for a task . : returns : deferred that when fired returns a datetime object for the estimated , or the actual datetime , or None if we could not estimate a time for this task method ."""
if self . completion_ts : # Task is already complete . Return the exact completion time : defer . returnValue ( self . completed ) # Get the timestamps from the descendent task that ' s doing the work : if self . method == 'build' or self . method == 'image' : subtask_completion = yield self . estimate_descende...
def uriunsplit ( uri ) : """Reverse of urisplit ( ) > > > uriunsplit ( ( ' scheme ' , ' authority ' , ' path ' , ' query ' , ' fragment ' ) ) " scheme : / / authority / path ? query # fragment " """
( scheme , authority , path , query , fragment ) = uri result = '' if scheme : result += scheme + ':' if authority : result += '//' + authority if path : result += path if query : result += '?' + query if fragment : result += '#' + fragment return result