signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_providing_power_source_type ( self ) : """Looks through all power supplies in POWER _ SUPPLY _ PATH . If there is an AC adapter online returns POWER _ TYPE _ AC . If there is a discharging battery , returns POWER _ TYPE _ BATTERY . Since the order of supplies is arbitrary , whatever found first is ret...
for supply in os . listdir ( POWER_SUPPLY_PATH ) : supply_path = os . path . join ( POWER_SUPPLY_PATH , supply ) try : type = self . power_source_type ( supply_path ) if type == common . POWER_TYPE_AC : if self . is_ac_online ( supply_path ) : return common . POWER_TY...
def connect_generators ( self , debug = False ) : """Connects LV generators ( graph nodes ) to grid ( graph ) Args debug : bool , defaults to False If True , information is printed during process"""
self . _graph = lv_connect . lv_connect_generators ( self . grid_district , self . _graph , debug )
def subset ( self , logic , update = False ) : """subset create a specific phenotype based on a logic , logic is a ' SubsetLogic ' class , take union of all the phenotypes listed . If none are listed use all phenotypes . take the intersection of all the scored calls . Args : logic ( SubsetLogic ) : A subs...
pnames = self . phenotypes snames = self . scored_names data = self . copy ( ) values = [ ] phenotypes = logic . phenotypes if len ( phenotypes ) == 0 : phenotypes = pnames removing = set ( self . phenotypes ) - set ( phenotypes ) for k in phenotypes : if k not in pnames : raise ValueError ( "phenotype ...
def delete ( name , region = None , key = None , keyid = None , profile = None ) : '''Delete an ELB . CLI example to delete an ELB : . . code - block : : bash salt myminion boto _ elb . delete myelb region = us - east - 1'''
conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile ) if not exists ( name , region , key , keyid , profile ) : return True try : conn . delete_load_balancer ( name ) log . info ( 'Deleted ELB %s.' , name ) return True except boto . exception . BotoServerError as error : ...
def generate_create_view ( self ) : """Generate class based view for CreateView"""
name = model_class_form ( self . model + 'CreateView' ) create_args = dict ( form_class = self . get_actual_form ( 'create' ) , model = self . get_model_class , template_name = self . get_template ( 'create' ) , permissions = self . view_permission ( 'create' ) , permission_required = self . check_permission_required ,...
def certs ( self , entity_id , descriptor , use = "signing" ) : '''Returns certificates for the given Entity'''
ent = self [ entity_id ] def extract_certs ( srvs ) : res = [ ] for srv in srvs : if "key_descriptor" in srv : for key in srv [ "key_descriptor" ] : if "use" in key and key [ "use" ] == use : for dat in key [ "key_info" ] [ "x509_data" ] : ...
def staticMovingAverage ( arr , fineness = 10 ) : """smooth [ arr ] using moving average"""
s0 = arr . shape [ 0 ] window_len = int ( round ( s0 / fineness ) ) start = arr [ 0 ] + arr [ 0 ] - arr [ window_len - 1 : 0 : - 1 ] end = arr [ - 1 ] + arr [ - 1 ] - arr [ - 1 : - window_len : - 1 ] s = np . r_ [ start , arr , end ] w = np . ones ( window_len , 'd' ) w /= w . sum ( ) a0 = np . convolve ( w , s , mode ...
def eval_objfn ( self ) : r"""Compute components of objective function as well as total contribution to objective function . The objective function is : math : ` \ | \ mathbf { x } \ | _ 1 ` and the constraint violation measure is : math : ` P ( \ mathbf { x } ) - \ mathbf { x } ` where : math : ` P ( \ mat...
obj = np . linalg . norm ( ( self . wl1 * self . obfn_g0var ( ) ) . ravel ( ) , 1 ) cns = np . linalg . norm ( sl . proj_l2ball ( self . obfn_g1var ( ) , self . S , self . epsilon , axes = 0 ) - self . obfn_g1var ( ) ) return ( obj , cns )
def plot_images ( self , outfile ) : """Generates a POSCAR with the calculated diffusion path with respect to the first endpoint . : param outfile : Output file for the POSCAR"""
sum_struct = self . __images [ 0 ] . sites for image in self . __images : for site_i in self . __relax_sites : sum_struct . append ( PeriodicSite ( image . sites [ site_i ] . specie , image . sites [ site_i ] . frac_coords , self . __images [ 0 ] . lattice , to_unit_cell = True , coords_are_cartesian = Fals...
def write_case_data ( self , file ) : """Writes the case data as CSV ."""
writer = self . _get_writer ( file ) writer . writerow ( [ "Name" , "base_mva" ] ) writer . writerow ( [ self . case . name , self . case . base_mva ] )
def curve_to ( self , x , y , x2 , y2 , x3 , y3 ) : """draw a curve . ( x2 , y2 ) is the middle point of the curve"""
self . _add_instruction ( "curve_to" , x , y , x2 , y2 , x3 , y3 )
def set_file_encoding ( self , path , encoding ) : """Cache encoding for the specified file path . : param path : path of the file to cache : param encoding : encoding to cache"""
try : map = json . loads ( self . _settings . value ( 'cachedFileEncodings' ) ) except TypeError : map = { } map [ path ] = encoding self . _settings . setValue ( 'cachedFileEncodings' , json . dumps ( map ) )
def execute_with_scope ( expr , scope , aggcontext = None , clients = None , ** kwargs ) : """Execute an expression ` expr ` , with data provided in ` scope ` . Parameters expr : ibis . expr . types . Expr The expression to execute . scope : collections . Mapping A dictionary mapping : class : ` ~ ibis . ...
op = expr . op ( ) # Call pre _ execute , to allow clients to intercept the expression before # computing anything * and * before associating leaf nodes with data . This # allows clients to provide their own data for each leaf . if clients is None : clients = list ( find_backends ( expr ) ) if aggcontext is None : ...
def proxy_upload ( self , path , filename , content_type = None , content_encoding = None , cb = None , num_cb = None ) : """This is the main function that uploads . We assume the bucket and key ( = = path ) exists . What we do here is simple . Calculate the headers we will need , ( e . g . md5 , content - type...
from boto . connection import AWSAuthConnection import mimetypes from hashlib import md5 import base64 BufferSize = 65536 # # set to something very small to make sure # # chunking is working properly fp = open ( filename ) headers = { 'Content-Type' : content_type } if content_type is None : content_type = mimetype...
def n_at_a_time ( items : List [ int ] , n : int , fillvalue : str ) -> Iterator [ Tuple [ Union [ int , str ] ] ] : """Returns an iterator which groups n items at a time . Any final partial tuple will be padded with the fillvalue > > > list ( n _ at _ a _ time ( [ 1 , 2 , 3 , 4 , 5 ] , 2 , ' X ' ) ) [ ( 1 , ...
it = iter ( items ) return itertools . zip_longest ( * [ it ] * n , fillvalue = fillvalue )
def assemble_phi5_works_filepaths ( ) : """Reads PHI5 index and builds a list of absolute filepaths ."""
plaintext_dir_rel = '~/cltk_data/latin/text/phi5/individual_works/' plaintext_dir = os . path . expanduser ( plaintext_dir_rel ) all_filepaths = [ ] for author_code in PHI5_WORKS_INDEX : author_data = PHI5_WORKS_INDEX [ author_code ] works = author_data [ 'works' ] for work in works : f = os . path ...
def update ( self , initiation_actions = values . unset ) : """Update the AssistantInitiationActionsInstance : param dict initiation _ actions : The initiation _ actions : returns : Updated AssistantInitiationActionsInstance : rtype : twilio . rest . preview . understand . assistant . assistant _ initiation _...
return self . _proxy . update ( initiation_actions = initiation_actions , )
def add_remote_link ( self , issue , destination , globalId = None , application = None , relationship = None ) : """Add a remote link from an issue to an external application and returns a remote link Resource for it . ` ` object ` ` should be a dict containing at least ` ` url ` ` to the linked external URL and...
try : applicationlinks = self . applicationlinks ( ) except JIRAError as e : applicationlinks = [ ] # In many ( if not most ) configurations , non - admin users are # not allowed to list applicationlinks ; if we aren ' t allowed , # let ' s let people try to add remote links anyway , we just # w...
def set_transition_down ( self , p_self ) : '''Set the downbeat - tracking transition matrix according to self - loop probabilities . Parameters p _ self : None , float in ( 0 , 1 ) , or np . ndarray [ shape = ( 2 , ) ] Optional self - loop probability ( ies ) , used for Viterbi decoding'''
if p_self is None : self . down_transition = None else : self . down_transition = transition_loop ( 2 , p_self )
def check_results ( tmp_ ) : """Return a 3 tuple for something ."""
# TODO : Fix this to work with more meaningful names if tmp_ [ 't' ] > 0 : if tmp_ [ 'l' ] > 0 : if tmp_ [ 'rr' ] > 0 or tmp_ [ 'ra' ] > 1 : print 1 , 3 , tmp_ return 3 elif tmp_ [ 'cr' ] > 0 or tmp_ [ 'ca' ] > 1 : print 2 , 3 , tmp_ return 3 e...
def restrict ( self , index_array ) : """Generate a view restricted to a subset of indices ."""
new_shape = index_array . shape [ 0 ] , index_array . shape [ 0 ] return OnFlySymMatrix ( self . get_row , new_shape , DC_start = self . DC_start , DC_end = self . DC_end , rows = self . rows , restrict_array = index_array )
def expect ( p , prefixes , confidential = False ) : """Read a line and return it without required prefix ."""
resp = p . stdout . readline ( ) log . debug ( '%s -> %r' , p . args , resp if not confidential else '********' ) for prefix in prefixes : if resp . startswith ( prefix ) : return resp [ len ( prefix ) : ] raise UnexpectedError ( resp )
def arnoldi_projected ( H , P , k , ortho = 'mgs' ) : """Compute ( perturbed ) Arnoldi relation for projected operator . Assume that you have computed an Arnoldi relation . . math : : A V _ n = V _ { n + 1 } \\ underline { H } _ n where : math : ` V _ { n + 1} \\ in \\ mathbb { C } ^ { N , n + 1 } ` has ort...
n = H . shape [ 1 ] dtype = find_common_dtype ( H , P ) invariant = H . shape [ 0 ] == n hlast = 0 if invariant else H [ - 1 , - 1 ] H = get_linearoperator ( ( n , n ) , H if invariant else H [ : - 1 , : ] ) P = get_linearoperator ( ( n , n ) , P ) v = P * numpy . eye ( n , 1 ) maxiter = n - k + 1 F = numpy . zeros ( (...
def create_sitemap ( app , exception ) : """Generates the sitemap . xml from the collected HTML page links"""
if ( not app . config [ 'html_theme_options' ] . get ( 'base_url' , '' ) or exception is not None or not app . sitemap_links ) : return filename = app . outdir + "/sitemap.xml" print ( "Generating sitemap.xml in %s" % filename ) root = ET . Element ( "urlset" ) root . set ( "xmlns" , "http://www.sitemaps.org/schema...
def insert_self_to_empty_and_insert_all_intemediate ( self , optimized ) : """For each state qi of the PDA , we add the rule Aii - > e For each triplet of states qi , qj and qk , we add the rule Aij - > Aik Akj . Args : optimized ( bool ) : Enable or Disable optimization - Do not produce O ( n ^ 3)"""
for state_a in self . statediag : self . rules . append ( 'A' + repr ( state_a . id ) + ',' + repr ( state_a . id ) + ': @empty_set' ) # If CFG is not requested , avoid the following O ( n ^ 3 ) rule . # It can be solved and a string can be generated faster with BFS of DFS if optimized == 0 : fo...
def get_fun ( fun ) : '''Return a dict of the last function called for all minions'''
serv = _get_serv ( ret = None ) ret = { } for minion in serv . smembers ( 'minions' ) : ind_str = '{0}:{1}' . format ( minion , fun ) try : jid = serv . get ( ind_str ) except Exception : continue if not jid : continue data = serv . get ( '{0}:{1}' . format ( minion , jid ) )...
def temporary_file ( mode ) : """Cross platform temporary file creation . This is an alternative to ` ` tempfile . NamedTemporaryFile ` ` that also works on windows and avoids the " file being used by another process " error ."""
tempdir = tempfile . gettempdir ( ) basename = 'tmpfile-%s' % ( uuid . uuid4 ( ) ) full_filename = os . path . join ( tempdir , basename ) if 'w' not in mode : # We need to create the file before we can open # it in ' r ' mode . open ( full_filename , 'w' ) . close ( ) try : with open ( full_filename , mode ) a...
def serialized_task ( self , task : Task ) -> Tuple [ str , str ] : """Returns the name of the task definition file and its contents ."""
return f"{task.hash}.json" , task . json
def load_from_file ( swag_path , swag_type = 'yml' , root_path = None ) : """Load specs from YAML file"""
if swag_type not in ( 'yaml' , 'yml' ) : raise AttributeError ( "Currently only yaml or yml supported" ) # TODO : support JSON try : enc = detect_by_bom ( swag_path ) with codecs . open ( swag_path , encoding = enc ) as yaml_file : return yaml_file . read ( ) except IOError : # not in the same d...
def create_node ( hostname , username , password , name , address , trans_label = None ) : '''A function to connect to a bigip device and create a node . hostname The host / address of the bigip device username The iControl REST username password The iControl REST password name The name of the node ...
# build session bigip_session = _build_session ( username , password , trans_label ) # construct the payload payload = { } payload [ 'name' ] = name payload [ 'address' ] = address # post to REST try : response = bigip_session . post ( BIG_IP_URL_BASE . format ( host = hostname ) + '/ltm/node' , data = salt . utils...
def load_yaml ( task : Task , file : str ) -> Result : """Loads a yaml file . Arguments : file : path to the file containing the yaml file to load Examples : Simple example with ` ` ordered _ dict ` ` : : > nr . run ( task = load _ yaml , file = " mydata . yaml " ) Returns : Result object with the f...
with open ( file , "r" ) as f : yml = ruamel . yaml . YAML ( typ = "safe" ) data = yml . load ( f ) return Result ( host = task . host , result = data )
def with_name ( self , name ) : """Sets the name scope for future operations ."""
with self . g . as_default ( ) , tf . variable_scope ( name ) as var_scope : name_scope = scopes . get_current_name_scope ( ) return _DeferredLayer ( self . bookkeeper , None , ( ) , { } , scope = ( name_scope , var_scope ) , defaults = self . _defaults , pass_through = self , partial_context = self . _partial_...
def _set_enabled_zone ( self , v , load = False ) : """Setter method for enabled _ zone , mapped from YANG variable / brocade _ zone _ rpc / show _ zoning _ enabled _ configuration / output / enabled _ configuration / enabled _ zone ( list ) If this variable is read - only ( config : false ) in the source YANG ...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = YANGListType ( "zone_name" , enabled_zone . enabled_zone , yang_name = "enabled-zone" , rest_name = "enabled-zone" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_helper , yang_keys...
def add_entity_info ( data_api , struct_inflator ) : """Add the entity info to the structure . : param data _ api the interface to the decoded data : param struct _ inflator the interface to put the data into the client object"""
for entity in data_api . entity_list : struct_inflator . set_entity_info ( entity [ "chainIndexList" ] , entity [ "sequence" ] , entity [ "description" ] , entity [ "type" ] )
def available ( self , context ) : """Determine if this actions is available in this ` context ` . : param context : a dict whose content is left to application needs ; if : attr : ` . condition ` is a callable it receives ` context ` in parameter ."""
if not self . _enabled : return False try : return self . pre_condition ( context ) and self . _check_condition ( context ) except Exception : return False
def convolutional_barycenter2d ( A , reg , weights = None , numItermax = 10000 , stopThr = 1e-9 , stabThr = 1e-30 , verbose = False , log = False ) : """Compute the entropic regularized wasserstein barycenter of distributions A where A is a collection of 2D images . The function solves the following optimizatio...
if weights is None : weights = np . ones ( A . shape [ 0 ] ) / A . shape [ 0 ] else : assert ( len ( weights ) == A . shape [ 0 ] ) if log : log = { 'err' : [ ] } b = np . zeros_like ( A [ 0 , : , : ] ) U = np . ones_like ( A ) KV = np . ones_like ( A ) cpt = 0 err = 1 # build the convolution operator t = n...
def create_dbinstance ( self , id , allocated_storage , instance_class , master_username , master_password , port = 3306 , engine = 'MySQL5.1' , db_name = None , param_group = None , security_groups = None , availability_zone = None , preferred_maintenance_window = None , backup_retention_period = None , preferred_back...
params = { 'DBInstanceIdentifier' : id , 'AllocatedStorage' : allocated_storage , 'DBInstanceClass' : instance_class , 'Engine' : engine , 'MasterUsername' : master_username , 'MasterUserPassword' : master_password , 'Port' : port , 'MultiAZ' : str ( multi_az ) . lower ( ) , 'AutoMinorVersionUpgrade' : str ( auto_minor...
def wait_to_start ( self , allow_failure = False ) : """Wait for the thread to actually starts ."""
self . _started . wait ( ) if self . _crashed and not allow_failure : self . _thread . join ( ) raise RuntimeError ( 'Setup failed, see {} Traceback' 'for details.' . format ( self . _thread . name ) )
def assign ( self , variables = None , ** variables_kwargs ) : """Assign new data variables to a Dataset , returning a new object with all the original variables in addition to the new ones . Parameters variables : mapping , value pairs Mapping from variables names to the new values . If the new values ar...
variables = either_dict_or_kwargs ( variables , variables_kwargs , 'assign' ) data = self . copy ( ) # do all calculations first . . . results = data . _calc_assign_results ( variables ) # . . . and then assign data . update ( results ) return data
def save_load ( jid , load , minions = None ) : '''Save the load to the specified jid'''
log . debug ( 'sqlite3 returner <save_load> called jid: %s load: %s' , jid , load ) conn = _get_conn ( ret = None ) cur = conn . cursor ( ) sql = '''INSERT INTO jids (jid, load) VALUES (:jid, :load)''' cur . execute ( sql , { 'jid' : jid , 'load' : salt . utils . json . dumps ( load ) } ) _close_conn ( conn )
def compute ( self , runner_results , setup = False , poll = False , ignore_errors = False ) : '''walk through all results and increment stats'''
for ( host , value ) in runner_results . get ( 'contacted' , { } ) . iteritems ( ) : if not ignore_errors and ( ( 'failed' in value and bool ( value [ 'failed' ] ) ) or ( 'rc' in value and value [ 'rc' ] != 0 ) ) : self . _increment ( 'failures' , host ) elif 'skipped' in value and bool ( value [ 'skipp...
def connect ( nickname , server_def , debug = None , timeout = 10 ) : """Connect and confirm server works by testing for a known class in the default namespace or if there is no default namespace defined , in all the possible interop namespaces . returns a WBEMConnection object or None if the connection fails...
url = server_def . url conn = pywbem . WBEMConnection ( url , ( server_def . user , server_def . password ) , default_namespace = server_def . implementation_namespace , no_verification = server_def . no_verification , timeout = timeout ) if debug : conn . debug = True ns = server_def . implementation_namespace if ...
def state_nums ( ) : """Get a dictionary of state names mapped to their ' legend ' value . Returns : dictionary of state names mapped to their numeric value"""
st_nums = { } fname = pkg_resources . resource_filename ( __name__ , 'resources/States.csv' ) with open ( fname , 'rU' ) as csvfile : reader = csv . reader ( csvfile , delimiter = ',' ) i = 0 for row in reader : st_nums [ row [ 0 ] ] = i i = i + 1 return st_nums
def get_hashed_filename ( name , file , suffix = None ) : """Gets a new filename for the provided file of the form " oldfilename . hash . ext " . If the old filename looks like it already contains a hash , it will be replaced ( so you don ' t end up with names like " pic . hash . hash . ext " )"""
basename , hash , ext = split_filename ( name ) file . seek ( 0 ) new_hash = '.%s' % md5 ( file . read ( ) ) . hexdigest ( ) [ : 12 ] if suffix is not None : basename = '%s_%s' % ( basename , suffix ) return '%s%s%s' % ( basename , new_hash , ext )
def validate ( self , vat_deets ) : """Validates an existing VAT identification number against VIES ."""
request = self . _get ( 'validation' , vat_deets ) return self . responder ( request )
def _thread_listen ( self ) : """The main & listen loop ."""
while self . _running : try : rest = requests . get ( URL_LISTEN . format ( self . _url ) , timeout = self . _timeout ) if rest . status_code == 200 : self . _queue . put ( rest . json ( ) ) else : _LOGGER . error ( 'QSUSB response code %s' , rest . status_code ) ...
def init ( app_id , app_key = None , master_key = None , hook_key = None ) : """初始化 LeanCloud 的 AppId / AppKey / MasterKey : type app _ id : string _ types : param app _ id : 应用的 Application ID : type app _ key : None or string _ types : param app _ key : 应用的 Application Key : type master _ key : None or ...
if ( not app_key ) and ( not master_key ) : raise RuntimeError ( 'app_key or master_key must be specified' ) global APP_ID , APP_KEY , MASTER_KEY , HOOK_KEY APP_ID = app_id APP_KEY = app_key MASTER_KEY = master_key if hook_key : HOOK_KEY = hook_key else : HOOK_KEY = os . environ . get ( 'LEANCLOUD_APP_HOOK_...
def datetime_to_str ( dt = 'now' , no_fractions = False ) : """The Last - Modified data in ISO8601 syntax , Z notation . The lastmod is stored as unix timestamp which is already in UTC . At preesent this code will return 6 decimal digits if any fraction of a second is given . It would perhaps be better to r...
if ( dt is None ) : return None elif ( dt == 'now' ) : dt = time . time ( ) if ( no_fractions ) : dt = int ( dt ) else : dt += 0.0000001 # improve rounding to microseconds return datetime . utcfromtimestamp ( dt ) . isoformat ( ) + 'Z'
def can_create_objectives ( self ) : """Tests if this user can create Objectives . A return of true does not guarantee successful authorization . A return of false indicates that it is known creating an Objective will result in a PermissionDenied . This is intended as a hint to an application that may opt n...
url_path = construct_url ( 'authorization' , bank_id = self . _catalog_idstr ) return self . _get_request ( url_path ) [ 'objectiveHints' ] [ 'canCreate' ]
def validate_input ( self , validation_definition ) : """In this example we are using external validation to verify that min is less than max . If validate _ input does not raise an Exception , the input is assumed to be valid . Otherwise it prints the exception as an error message when telling splunkd that t...
# Get the parameters from the ValidationDefinition object , # then typecast the values as floats minimum = float ( validation_definition . parameters [ "min" ] ) maximum = float ( validation_definition . parameters [ "max" ] ) if minimum >= maximum : raise ValueError ( "min must be less than max; found min=%f, max=...
def render_hidden ( name , value ) : """render as hidden widget"""
if isinstance ( value , list ) : return MultipleHiddenInput ( ) . render ( name , value ) return HiddenInput ( ) . render ( name , value )
def app_token ( vault_client , app_id , user_id ) : """Returns a vault token based on the app and user id ."""
resp = vault_client . auth_app_id ( app_id , user_id ) if 'auth' in resp and 'client_token' in resp [ 'auth' ] : return resp [ 'auth' ] [ 'client_token' ] else : raise aomi . exceptions . AomiCredentials ( 'invalid apptoken' )
def _report_container_count ( self , containers_by_id ) : """Report container count per state"""
m_func = FUNC_MAP [ GAUGE ] [ self . use_histogram ] per_state_count = defaultdict ( int ) filterlambda = lambda ctr : not self . _is_container_excluded ( ctr ) containers = list ( filter ( filterlambda , containers_by_id . values ( ) ) ) for ctr in containers : per_state_count [ ctr . get ( 'State' , '' ) ] += 1 f...
def recv_file_from_host ( src_file , dst_filename , filesize , dst_mode = 'wb' ) : """Function which runs on the pyboard . Matches up with send _ file _ to _ remote ."""
import sys import ubinascii if HAS_BUFFER : try : import pyb usb = pyb . USB_VCP ( ) except : try : import machine usb = machine . USB_VCP ( ) except : usb = None if usb and usb . isconnected ( ) : # We don ' t want 0x03 bytes in the data t...
def cancel_orders ( self , market_id , instructions , customer_ref = None ) : """Cancel all bets OR cancel all bets on a market OR fully or partially cancel particular orders on a market . : param str market _ id : If not supplied all bets are cancelled : param list instructions : List of ` CancelInstruction ...
return self . make_api_request ( 'Sports' , 'cancelOrders' , utils . get_kwargs ( locals ( ) ) , model = models . CancelExecutionReport , )
def _register_update ( self , replot = False , fmt = { } , force = False , todefault = False ) : """Register new formatoptions for updating Parameters replot : bool Boolean that determines whether the data specific formatoptions shall be updated in any case or not . Note , if ` dims ` is not empty or any ...
self . replot = self . replot or replot if self . plotter is not None : self . plotter . _register_update ( replot = self . replot , fmt = fmt , force = force , todefault = todefault )
def _parse_command_line ( ) : """Configure and parse our command line flags ."""
parser = argparse . ArgumentParser ( ) parser . add_argument ( '--portserver_static_pool' , type = str , default = '15000-24999' , help = 'Comma separated N-P Range(s) of ports to manage (inclusive).' ) parser . add_argument ( '--portserver_unix_socket_address' , type = str , default = '@unittest-portserver' , help = '...
def Nu_Kitoh ( Re , Pr , H = None , G = None , q = None ) : r'''Calculates internal convection Nusselt number for turbulent vertical upward flow in a pipe under supercritical conditions according to [ 1 ] _ , also shown in [ 2 ] _ , [ 3 ] _ and [ 4 ] _ . Depends on fluid enthalpy , mass flux , and heat flux ....
if H and G and q : qht = 200. * G ** 1.2 if H < 1.5E6 : fc = 2.9E-8 + 0.11 / qht elif 1.5E6 <= H <= 3.3E6 : fc = - 8.7E-8 - 0.65 / qht else : fc = - 9.7E-7 + 1.3 / qht m = 0.69 - 81000. / qht + fc * q else : m = 0.69 return 0.015 * Re ** 0.85 * Pr ** m
def create_profile ( hostname , username , password , profile_type , name , ** kwargs ) : r'''A function to connect to a bigip device and create a profile . hostname The host / address of the bigip device username The iControl REST username password The iControl REST password profile _ type The type...
ret = { 'name' : name , 'changes' : { } , 'result' : False , 'comment' : '' } if __opts__ [ 'test' ] : return _test_output ( ret , 'create' , params = { 'hostname' : hostname , 'username' : username , 'password' : password , 'profile_type' : profile_type , 'name' : name } ) # is this profile currently configured ? ...
def iterate_dictionary ( d , path , squash_single = False ) : """Takes a dict , and a path delimited with slashes like A / B / C / D , and returns a list of objects found at all leaf nodes at all trajectories ` dict [ A ] [ B ] [ C ] [ D ] ` . It does this using BFS not DFS . The word " leaf " hereby refers to an...
path_parts = path . split ( "/" ) return_list = [ ] if len ( path_parts ) == 0 : # no search string return d else : try : sub_dicts = [ d ] # BFS , start with root node for i in range ( 0 , len ( path_parts ) ) : # BFS new_sub_dicts = [ ] for s in sub_dicts : ...
def _aggregate_one_result ( self , sock_info , slave_ok , cmd , collation = None , session = None ) : """Internal helper to run an aggregate that returns a single result ."""
result = self . _command ( sock_info , cmd , slave_ok , codec_options = self . __write_response_codec_options , read_concern = self . read_concern , collation = collation , session = session ) batch = result [ 'cursor' ] [ 'firstBatch' ] return batch [ 0 ] if batch else None
def one ( self , default = None , as_dict = False , as_ordereddict = False ) : """Returns a single record for the RecordCollection , ensuring that it is the only record , or returns ` default ` . If ` default ` is an instance or subclass of Exception , then raise it instead of returning it ."""
# Ensure that we don ' t have more than one row . try : self [ 1 ] except IndexError : return self . first ( default = default , as_dict = as_dict , as_ordereddict = as_ordereddict ) else : raise ValueError ( 'RecordCollection contained more than one row. ' 'Expects only one row when using ' 'RecordCollecti...
def adjust_locations ( ast_node , first_lineno , first_offset ) : """Adjust the locations of the ast nodes , offsetting them to the new lineno and column offset"""
line_delta = first_lineno - 1 def _fix ( node ) : if 'lineno' in node . _attributes : lineno = node . lineno col = node . col_offset # adjust the offset on the first line if lineno == 1 : col += first_offset lineno += line_delta node . lineno = lineno ...
def _check_logged_user ( self ) : """Check if a user is logged . Otherwise , an error is raised ."""
if not self . _env or not self . _password or not self . _login : raise error . InternalError ( "Login required" )
def generate ( env ) : """Add Builders and construction variables for SunPRO C + + ."""
path , cxx , shcxx , version = get_cppc ( env ) if path : cxx = os . path . join ( path , cxx ) shcxx = os . path . join ( path , shcxx ) cplusplus . generate ( env ) env [ 'CXX' ] = cxx env [ 'SHCXX' ] = shcxx env [ 'CXXVERSION' ] = version env [ 'SHCXXFLAGS' ] = SCons . Util . CLVar ( '$CXXFLAGS -KPIC' ) env ...
def get_default_ca_certs ( ) : """Try to find out system path with ca certificates . This path is cached and returned . If no path is found out , None is returned ."""
# pylint : disable = protected - access if not hasattr ( get_default_ca_certs , '_path' ) : for path in get_default_ca_cert_paths ( ) : if os . path . exists ( path ) : get_default_ca_certs . _path = path break else : get_default_ca_certs . _path = None return get_default...
def has_child_logs ( self , log_id ) : """Tests if a log has any children . arg : log _ id ( osid . id . Id ) : the ` ` Id ` ` of a log return : ( boolean ) - ` ` true ` ` if the ` ` log _ id ` ` has children , ` ` false ` ` otherwise raise : NotFound - ` ` log _ id ` ` is not found raise : NullArgument -...
# Implemented from template for # osid . resource . BinHierarchySession . has _ child _ bins if self . _catalog_session is not None : return self . _catalog_session . has_child_catalogs ( catalog_id = log_id ) return self . _hierarchy_session . has_children ( id_ = log_id )
def certify_date ( value , required = True ) : """Certifier for datetime . date values . : param value : The value to be certified . : param bool required : Whether the value can be ` None ` Defaults to True . : raises CertifierTypeError : The type is invalid"""
if certify_required ( value = value , required = required , ) : return if not isinstance ( value , date ) : raise CertifierTypeError ( message = "expected timestamp (date∂), but value is of type {cls!r}" . format ( cls = value . __class__ . __name__ ) , value = value , required = required , )
def updateNodeCapabilitiesResponse ( self , nodeId , node , vendorSpecific = None ) : """CNRegister . updateNodeCapabilities ( session , nodeId , node ) → boolean https : / / releases . dataone . org / online / api - documentation - v2.0.1 / apis / CN _ AP Is . html # CNRegister . updateNodeCapabilities . Arg...
mmp_dict = { 'node' : ( 'node.xml' , node . toxml ( 'utf-8' ) ) } return self . PUT ( [ 'node' , nodeId ] , fields = mmp_dict , headers = vendorSpecific )
def plot_ts ( fignum , dates , ts ) : """plot the geomagnetic polarity time scale Parameters _ _ _ _ _ fignum : matplotlib figure number dates : bounding dates for plot ts : time scale ck95 , gts04 , or gts12"""
vertical_plot_init ( fignum , 10 , 3 ) TS , Chrons = pmag . get_ts ( ts ) p = 1 X , Y = [ ] , [ ] for d in TS : if d <= dates [ 1 ] : if d >= dates [ 0 ] : if len ( X ) == 0 : ind = TS . index ( d ) X . append ( TS [ ind - 1 ] ) Y . append ( p % 2 ...
def geom ( self ) : """Geometry information . : class : ` _ Geometry ` instance holding geometry information . It is issued from binary files holding field information . It is set to None if not available for this time step ."""
if self . _header is UNDETERMINED : binfiles = self . step . sdat . binfiles_set ( self . step . isnap ) if binfiles : self . _header = stagyyparsers . fields ( binfiles . pop ( ) , only_header = True ) elif self . step . sdat . hdf5 : xmf = self . step . sdat . hdf5 / 'Data.xmf' sel...
def is_cms_app ( app_name ) : """Return whether the given application is a CMS app"""
for pat in appsettings . FLUENT_DASHBOARD_CMS_APP_NAMES : if fnmatch ( app_name , pat ) : return True return False
def verify_address ( self , addr1 = "" , addr2 = "" , city = "" , fname = "" , lname = "" , phone = "" , province = "" , postal = "" , country = "" , email = "" , recordID = "" , freeform = "" ) : """verify _ address Builds a JSON request to send to Melissa data . Takes in all needed address info . Args : add...
data = { "TransmissionReference" : "" , "CustomerID" : self . custID , "Actions" : "Check" , "Options" : "" , "Columns" : "" , "Records" : [ { "RecordID" : recordID , "CompanyName" : "" , "FullName" : fname + " " + lname , "AddressLine1" : addr1 , "AddressLine2" : addr2 , "Suite" : "" , "City" : city , "State" : provin...
def permanently_delete ( self , tickets ) : """Permanently delete ticket . ` See Zendesk API docs < https : / / developer . zendesk . com / rest _ api / docs / support / tickets # delete - ticket - permanently > ` _ Ticket should be softly deleted first with regular ` delete ` method . : param tickets : Ticket ...
endpoint_kwargs = dict ( ) if isinstance ( tickets , collections . Iterable ) : endpoint_kwargs [ 'destroy_ids' ] = [ i . id for i in tickets ] else : endpoint_kwargs [ 'id' ] = tickets . id url = self . _build_url ( self . endpoint . deleted ( ** endpoint_kwargs ) ) deleted_ticket_job_id = self . _delete ( url...
def ball_count ( cls , ball_tally , strike_tally , pitch_res ) : """Ball / Strike counter : param ball _ tally : Ball telly : param strike _ tally : Strike telly : param pitch _ res : pitching result ( Retrosheet format ) : return : ball count , strike count"""
b , s = ball_tally , strike_tally if pitch_res == "B" : if ball_tally < 4 : b += 1 elif pitch_res == "S" or pitch_res == "C" or pitch_res == "X" : if strike_tally < 3 : s += 1 elif pitch_res == "F" : if strike_tally < 2 : s += 1 return b , s
def implicitly_declare_ro ( instructions : List [ AbstractInstruction ] ) : """Implicitly declare a register named ` ` ro ` ` for backwards compatibility with Quil 1. There used to be one un - named hunk of classical memory . Now there are variables with declarations . Instead of : : MEASURE 0 [ 0] You must...
ro_addrs : List [ int ] = [ ] for instr in instructions : if isinstance ( instr , Declare ) : # The user has declared their own memory # so they are responsible for all declarations and memory references . return instructions if isinstance ( instr , Measurement ) : if instr . classical_reg i...
def bfloat16_activations_var_getter ( getter , * args , ** kwargs ) : """A custom getter function for float32 parameters and bfloat16 activations . Args : getter : custom getter * args : arguments * * kwargs : keyword arguments Returns : variables with the correct dtype . Raises : KeyError : if " dt...
requested_dtype = kwargs [ "dtype" ] if requested_dtype == tf . bfloat16 : kwargs [ "dtype" ] = tf . float32 var = getter ( * args , ** kwargs ) # This if statement is needed to guard the cast , because batch norm # assigns directly to the return value of this custom getter . The cast # makes the return value not a...
def subarc_between_points ( self , p_from = None , p_to = None ) : '''Given two points on the arc , extract a sub - arc between those points . No check is made to verify the points are actually on the arc . It is basically a wrapper around subarc ( point _ as _ angle ( p _ from ) , point _ as _ angle ( p _ to )...
a_from = self . point_as_angle ( p_from ) if p_from is not None else None a_to = self . point_as_angle ( p_to ) if p_to is not None else None return self . subarc ( a_from , a_to )
def plot_fit ( self , ** kwargs ) : """Plots the fit of the model Returns None ( plots data and the fit )"""
import matplotlib . pyplot as plt import seaborn as sns figsize = kwargs . get ( 'figsize' , ( 10 , 7 ) ) if self . latent_variables . estimated is False : raise Exception ( "No latent variables estimated!" ) else : date_index = self . index [ self . lags : self . data [ 0 ] . shape [ 0 ] ] mu , Y = self . ...
def getPysamVariants ( self , referenceName , startPosition , endPosition ) : """Returns an iterator over the pysam VCF records corresponding to the specified query ."""
if referenceName in self . _chromFileMap : varFileName = self . _chromFileMap [ referenceName ] referenceName , startPosition , endPosition = self . sanitizeVariantFileFetch ( referenceName , startPosition , endPosition ) cursor = self . getFileHandle ( varFileName ) . fetch ( referenceName , startPosition ...
def _get_column_type ( self , column ) : """Return ' numeric ' if the column is of type integer or real , otherwise return ' string ' ."""
ctype = column . GetType ( ) if ctype in [ ogr . OFTInteger , ogr . OFTReal ] : return 'numeric' else : return 'string'
def crop ( self , height , width , crop_ci , crop_cj ) : """Convert to new camera intrinsics for crop of image from original camera . Parameters height : int height of crop window width : int width of crop window crop _ ci : int row of crop window center crop _ cj : int col of crop window center ...
cx = self . cx + float ( width - 1 ) / 2 - crop_cj cy = self . cy + float ( height - 1 ) / 2 - crop_ci cropped_intrinsics = CameraIntrinsics ( frame = self . frame , fx = self . fx , fy = self . fy , skew = self . skew , cx = cx , cy = cy , height = height , width = width ) return cropped_intrinsics
def from_file ( self , fname , binary = False , ** kwargs ) : """Initialize the class instance from gridded data in a file . Usage x = SHGrid . from _ file ( fname , [ binary , * * kwargs ] ) Returns x : SHGrid class instance Parameters fname : str The filename containing the gridded data . For text f...
if binary is False : data = _np . loadtxt ( fname , ** kwargs ) elif binary is True : data = _np . load ( fname , ** kwargs ) else : raise ValueError ( 'binary must be True or False. ' 'Input value is {:s}' . format ( binary ) ) if _np . iscomplexobj ( data ) : kind = 'complex' else : kind = 'real' ...
def set_group_member_unorphan ( self , member_id , unorphan_info ) : """Make an orphan member trigger into an group trigger . : param member _ id : Orphan Member Trigger id to be assigned into a group trigger : param unorphan _ info : Only context and dataIdMap are used when changing back to a non - orphan . ...
data = self . _serialize_object ( unorphan_info ) data = self . _service_url ( [ 'triggers' , 'groups' , 'members' , member_id , 'unorphan' ] ) return Trigger ( self . _put ( url , data ) )
def primary_from_id ( self , tax_id ) : """Returns primary taxonomic name associated with tax _ id"""
s = select ( [ self . names . c . tax_name ] , and_ ( self . names . c . tax_id == tax_id , self . names . c . is_primary ) ) res = s . execute ( ) output = res . fetchone ( ) if not output : msg = 'value "{}" not found in names.tax_id' . format ( tax_id ) raise ValueError ( msg ) else : return output [ 0 ]
def load_collided_alias ( self ) : """Load ( create , if not exist ) the collided alias file ."""
# w + creates the alias config file if it does not exist open_mode = 'r+' if os . path . exists ( GLOBAL_COLLIDED_ALIAS_PATH ) else 'w+' with open ( GLOBAL_COLLIDED_ALIAS_PATH , open_mode ) as collided_alias_file : collided_alias_str = collided_alias_file . read ( ) try : self . collided_alias = json . ...
def _read_header ( stream , decoder , strict = False ) : """Read AMF L { Message } header from the stream . @ type stream : L { BufferedByteStream < pyamf . util . BufferedByteStream > } @ param decoder : An AMF0 decoder . @ param strict : Use strict decoding policy . Default is C { False } . Will raise a L...
name_len = stream . read_ushort ( ) name = stream . read_utf8_string ( name_len ) required = bool ( stream . read_uchar ( ) ) data_len = stream . read_ulong ( ) pos = stream . tell ( ) data = decoder . readElement ( ) if strict and pos + data_len != stream . tell ( ) : raise pyamf . DecodeError ( "Data read from st...
def _update_table_fallbacks ( self , table_toplevels ) : """Updates the fallbacks on all the table elements to make relative table access possible . Raises DuplicateKeysError if appropriate ."""
if len ( self . elements ) <= 1 : return def parent_of ( toplevel ) : # Returns an TopLevel parent of the given entry , or None . for parent_toplevel in table_toplevels : if toplevel . name . sub_names [ : - 1 ] == parent_toplevel . name . sub_names : return parent_toplevel for entry in tabl...
def get_child_repositories ( self , repository_id ) : """Gets the children of the given repository . arg : repository _ id ( osid . id . Id ) : the ` ` Id ` ` to query return : ( osid . repository . RepositoryList ) - the children of the repository raise : NotFound - ` ` repository _ id ` ` not found rais...
# Implemented from template for # osid . resource . BinHierarchySession . get _ child _ bins if self . _catalog_session is not None : return self . _catalog_session . get_child_catalogs ( catalog_id = repository_id ) return RepositoryLookupSession ( self . _proxy , self . _runtime ) . get_repositories_by_ids ( list...
def add_op_create_replicated_pool ( self , name , replica_count = 3 , pg_num = None , weight = None , group = None , namespace = None , app_name = None , max_bytes = None , max_objects = None ) : """Adds an operation to create a replicated pool . : param name : Name of pool to create : type name : str : param...
if pg_num and weight : raise ValueError ( 'pg_num and weight are mutually exclusive' ) self . ops . append ( { 'op' : 'create-pool' , 'name' : name , 'replicas' : replica_count , 'pg_num' : pg_num , 'weight' : weight , 'group' : group , 'group-namespace' : namespace , 'app-name' : app_name , 'max-bytes' : max_bytes...
def _set_community ( self , v , load = False ) : """Setter method for community , mapped from YANG variable / routing _ system / route _ map / content / set / community ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ community is considered as a private ...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = community . community , is_container = 'container' , presence = False , yang_name = "community" , rest_name = "community" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths ...
def aggressive_tree_merge ( odb , tree_shas ) : """: return : list of BaseIndexEntries representing the aggressive merge of the given trees . All valid entries are on stage 0 , whereas the conflicting ones are left on stage 1 , 2 or 3 , whereas stage 1 corresponds to the common ancestor tree , 2 to our tree a...
out = [ ] out_append = out . append # one and two way is the same for us , as we don ' t have to handle an existing # index , instrea if len ( tree_shas ) in ( 1 , 2 ) : for entry in traverse_tree_recursive ( odb , tree_shas [ - 1 ] , '' ) : out_append ( _tree_entry_to_baseindexentry ( entry , 0 ) ) # E...
def anneal ( args ) : """% prog anneal agpfile contigs . fasta Merge adjacent overlapping contigs and make new AGP file . By default it will also anneal lines like these together ( unless - - nozipshreds ) : scaffold4 1 1608 1 W ca - bacs . 5638 . frag11.22000-23608 1 1608 - scaffold4 1609 1771 2 N 163 scaf...
p = OptionParser ( anneal . __doc__ ) p . set_align ( pctid = GoodPct , hitlen = GoodOverlap ) p . add_option ( "--hang" , default = GoodOverhang , type = "int" , help = "Maximum overhang length [default: %default]" ) p . set_outdir ( outdir = "outdir" ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( a...
def unset ( self , key ) : """Delete object indexed by < key >"""
try : try : self . bucket . delete ( key ) except couchbase . exception . MemcachedError , inst : if str ( inst ) == "Memcached error #1: Not found" : # for some reason the py cb client raises an error when # a key isnt found , instead we just want a none value . return ...
def trace_inspect ( self ) : """A decorator that allows to inspect / change the trace data ."""
def decorator ( f ) : self . tracer . inspector = f return f return decorator
def get_data ( self , collection ) : """Return serialized list of data objects on collection that user has ` view ` permission on ."""
data = self . _filter_queryset ( 'view_data' , collection . data . all ( ) ) return self . _serialize_data ( data )
def inserir ( self , name ) : """Inserts a new Brand and returns its identifier : param name : Brand name . String with a minimum 3 and maximum of 100 characters : return : Dictionary with the following structure : { ' marca ' : { ' id ' : < id _ brand > } } : raise InvalidParameterError : Name is null and ...
brand_map = dict ( ) brand_map [ 'name' ] = name code , xml = self . submit ( { 'brand' : brand_map } , 'POST' , 'brand/' ) return self . response ( code , xml )
def validate_access_permission ( self , valid_permissions ) : """: param valid _ permissions : List of permissions that access is allowed . : type valid _ permissions : | list | / | tuple | : raises ValueError : If the | attr _ mode | is invalid . : raises IOError : If the | attr _ mode | not in the ` ` v...
self . check_connection ( ) if typepy . is_null_string ( self . mode ) : raise ValueError ( "mode is not set" ) if self . mode not in valid_permissions : raise IOError ( "invalid access: expected-mode='{}', current-mode='{}'" . format ( "' or '" . join ( valid_permissions ) , self . mode ) )
def get_payments_of_credit_note_per_page ( self , credit_note_id , per_page = 1000 , page = 1 ) : """Get payments of credit note per page : param credit _ note _ id : the credit note id : param per _ page : How many objects per page . Default : 1000 : param page : Which page . Default : 1 : return : list"""
return self . _get_resource_per_page ( resource = CREDIT_NOTE_PAYMENTS , per_page = per_page , page = page , params = { 'credit_note_id' : credit_note_id } , )
def cube ( target , pore_diameter = 'pore.diameter' , throat_area = 'throat.area' ) : r"""Calculates internal surface area of pore bodies assuming they are cubes then subtracts the area of the neighboring throats . Parameters target : OpenPNM Object The object for which these values are being calculated . T...
network = target . project . network D = target [ pore_diameter ] Tn = network . find_neighbor_throats ( pores = target . Ps , flatten = False ) Tsurf = _np . array ( [ _np . sum ( network [ throat_area ] [ Ts ] ) for Ts in Tn ] ) value = 6 * D ** 2 - Tsurf return value