signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def status_gps_send ( self , csFails , gpsQuality , msgsType , posStatus , magVar , magDir , modeInd , force_mavlink1 = False ) : '''This contains the status of the GPS readings csFails : Number of times checksum has failed ( uint16 _ t ) gpsQuality : The quality indicator , 0 = fix not available or invalid , 1...
return self . send ( self . status_gps_encode ( csFails , gpsQuality , msgsType , posStatus , magVar , magDir , modeInd ) , force_mavlink1 = force_mavlink1 )
def isInCache ( self ) : """Return True if audio data for this segment is present in cache , False otherwise ."""
url = self . buildUrl ( cache_friendly = True ) return url in __class__ . cache
def _get_format_name_loader_mapping ( self ) : """: return : Mappings of format - name and loader class . : rtype : dict"""
loader_table = self . _get_common_loader_mapping ( ) loader_table . update ( { "excel" : ExcelTableFileLoader , "json_lines" : JsonLinesTableTextLoader , "markdown" : MarkdownTableTextLoader , "mediawiki" : MediaWikiTableTextLoader , "ssv" : CsvTableFileLoader , } ) return loader_table
def change_url_query_params ( url , params ) : """Add GET - parameters to URL . If parameters are exist then they will be changed . url - URL , string value params - dict { ' GET - parameter name ' : ' value ' }"""
url_parts = list ( urlparse . urlparse ( url ) ) query = dict ( urlparse . parse_qsl ( url_parts [ 4 ] ) ) query . update ( params ) url_parts [ 4 ] = urllib . urlencode ( encode_url_query_params ( query ) ) return urlparse . urlunparse ( url_parts )
def process_action ( self ) : """Process the action and update the related object , returns a boolean if a change is made ."""
if self . publish_version == self . UNPUBLISH_CHOICE : actioned = self . _unpublish ( ) else : actioned = self . _publish ( ) # Only log if an action was actually taken if actioned : self . _log_action ( ) return actioned
def create_environment_file ( path = "~/overcloud-env.json" , control_scale = 1 , compute_scale = 1 , ceph_storage_scale = 0 , block_storage_scale = 0 , swift_storage_scale = 0 ) : """Create a heat environment file Create the heat environment file with the scale parameters . : param control _ scale : Scale valu...
env_path = os . path . expanduser ( path ) with open ( env_path , 'w+' ) as f : f . write ( json . dumps ( { "parameters" : { "ControllerCount" : control_scale , "ComputeCount" : compute_scale , "CephStorageCount" : ceph_storage_scale , "BlockStorageCount" : block_storage_scale , "ObjectStorageCount" : swift_storag...
def get_assessments_by_ids ( self , assessment_ids ) : """Gets an ` ` AssessmentList ` ` corresponding to the given ` ` IdList ` ` . In plenary mode , the returned list contains all of the assessments specified in the ` ` Id ` ` list , in the order of the list , including duplicates , or an error results if a...
# Implemented from template for # osid . resource . ResourceLookupSession . get _ resources _ by _ ids # NOTE : This implementation currently ignores plenary view collection = JSONClientValidated ( 'assessment' , collection = 'Assessment' , runtime = self . _runtime ) object_id_list = [ ] for i in assessment_ids : ...
def enable_code_breakpoint ( self , dwProcessId , address ) : """Enables the code breakpoint at the given address . @ see : L { define _ code _ breakpoint } , L { has _ code _ breakpoint } , L { enable _ one _ shot _ code _ breakpoint } , L { disable _ code _ breakpoint } L { erase _ code _ breakpoint }...
p = self . system . get_process ( dwProcessId ) bp = self . get_code_breakpoint ( dwProcessId , address ) if bp . is_running ( ) : self . __del_running_bp_from_all_threads ( bp ) bp . enable ( p , None )
def SOAPAction ( self , Action , responseElement , params = "" , recursive = False ) : """Generate the SOAP action call . : type Action : str : type responseElement : str : type params : str : type recursive : bool : param Action : The action to perform on the device : param responseElement : The XML el...
# Authenticate client if self . authenticated is None : self . authenticated = self . auth ( ) auth = self . authenticated # If not legacy protocol , ensure auth ( ) is called for every call if not self . use_legacy_protocol : self . authenticated = None if auth is None : return None payload = self . reques...
def lastId ( self ) -> BaseReference : """Last child ' s id of current TextualNode"""
if self . childIds is not None : if len ( self . childIds ) > 0 : return self . childIds [ - 1 ] return None else : raise NotImplementedError
def make_4gaussians_image ( noise = True ) : """Make an example image containing four 2D Gaussians plus a constant background . The background has a mean of 5. If ` ` noise ` ` is ` True ` , then Gaussian noise with a mean of 0 and a standard deviation of 5 is added to the output image . Parameters nois...
table = Table ( ) table [ 'amplitude' ] = [ 50 , 70 , 150 , 210 ] table [ 'x_mean' ] = [ 160 , 25 , 150 , 90 ] table [ 'y_mean' ] = [ 70 , 40 , 25 , 60 ] table [ 'x_stddev' ] = [ 15.2 , 5.1 , 3. , 8.1 ] table [ 'y_stddev' ] = [ 2.6 , 2.5 , 3. , 4.7 ] table [ 'theta' ] = np . array ( [ 145. , 20. , 0. , 60. ] ) * np . p...
def update_headers ( self , header_args ) : '''Given a set of headers , update both the user - agent and additional headers for the remote browser . header _ args must be a dict . Keys are the names of the corresponding HTTP header . return value is a 2 - tuple of the results of the user - agent update , ...
assert isinstance ( header_args , dict ) , "header_args must be a dict, passed type was %s" % ( type ( header_args ) , ) ua = header_args . pop ( 'User-Agent' , None ) ret_1 = None if ua : ret_1 = self . Network_setUserAgentOverride ( userAgent = ua ) ret_2 = self . Network_setExtraHTTPHeaders ( headers = header_ar...
def transformer_encoder ( encoder_input , encoder_self_attention_bias , hparams , name = "encoder" , nonpadding = None , save_weights_to = None , make_image_summary = True , losses = None , attn_bias_for_padding = None ) : """A stack of transformer layers . Args : encoder _ input : a Tensor encoder _ self _ a...
x = encoder_input attention_dropout_broadcast_dims = ( common_layers . comma_separated_string_to_integer_list ( getattr ( hparams , "attention_dropout_broadcast_dims" , "" ) ) ) mlperf_log . transformer_print ( key = mlperf_log . MODEL_HP_NUM_HIDDEN_LAYERS , value = hparams . num_encoder_layers or hparams . num_hidden_...
def UCRTIncludes ( self ) : """Microsoft Universal C Runtime SDK Include"""
if self . vc_ver < 14.0 : return [ ] include = os . path . join ( self . si . UniversalCRTSdkDir , 'include' ) return [ os . path . join ( include , '%sucrt' % self . _ucrt_subdir ) ]
def change_length ( self , parameter , value ) : r"""Change the length of a certain parameter to a certain value . Args parameter : str The name of the parameter to change the length for value : str The value to set the parameter to"""
self . preamble . append ( UnsafeCommand ( 'setlength' , arguments = [ parameter , value ] ) )
def assd ( result , reference , voxelspacing = None , connectivity = 1 ) : """Average symmetric surface distance . Computes the average symmetric surface distance ( ASD ) between the binary objects in two images . Parameters result : array _ like Input data containing objects . Can be any type but will be...
assd = numpy . mean ( ( asd ( result , reference , voxelspacing , connectivity ) , asd ( reference , result , voxelspacing , connectivity ) ) ) return assd
def query_target ( target_chembl_id ) : """Query ChEMBL API target by id Parameters target _ chembl _ id : str Returns target : dict dict parsed from json that is unique for the target"""
query_dict = { 'query' : 'target' , 'params' : { 'target_chembl_id' : target_chembl_id , 'limit' : 1 } } res = send_query ( query_dict ) target = res [ 'targets' ] [ 0 ] return target
def Serghides_1 ( Re , eD ) : r'''Calculates Darcy friction factor using the method in Serghides ( 1984) [2 ] _ as shown in [ 1 ] _ . . . math : : f = \ left [ A - \ frac { ( B - A ) ^ 2 } { C - 2B + A } \ right ] ^ { - 2} . . math : : A = - 2 \ log _ { 10 } \ left [ \ frac { \ epsilon / D } { 3.7 } + \ f...
A = - 2 * log10 ( eD / 3.7 + 12 / Re ) B = - 2 * log10 ( eD / 3.7 + 2.51 * A / Re ) C = - 2 * log10 ( eD / 3.7 + 2.51 * B / Re ) return ( A - ( B - A ) ** 2 / ( C - 2 * B + A ) ) ** - 2
def angle_diff ( start_a = [ 0.0 ] , end_a = [ 0.0 ] , direction = True ) : '''Return difference in angle from start _ a to end _ a . Direction follows the right - hand - rule so positive is counter - clockwise .'''
assert isinstance ( start_a , list ) assert isinstance ( end_a , list ) l_angle = len ( start_a ) assert l_angle > 0 assert l_angle == len ( end_a ) for i in start_a : assert isinstance ( i , float ) assert abs ( i ) <= 2 * pi for i in end_a : assert isinstance ( i , float ) assert abs ( i ) <= 2 * pi a...
def coverage ( self , bug : Bug ) -> TestSuiteCoverage : """Provides coverage information for each test within the test suite for the program associated with this bug . Parameters : bug : the bug for which to compute coverage . Returns : a test suite coverage report for the given bug ."""
# determine the location of the coverage map on disk fn = os . path . join ( self . __installation . coverage_path , "{}.coverage.yml" . format ( bug . name ) ) # is the coverage already cached ? if so , load . if os . path . exists ( fn ) : return TestSuiteCoverage . from_file ( fn ) # if we don ' t have coverage ...
def get_stats ( self ) : """Return performance data for the module responder . : returns : Dict containing keys : * ` get _ module _ count ` : Integer count of : data : ` mitogen . core . GET _ MODULE ` messages received . * ` get _ module _ secs ` : Floating point total seconds spent servicing : data :...
return { 'get_module_count' : self . responder . get_module_count , 'get_module_secs' : self . responder . get_module_secs , 'good_load_module_count' : self . responder . good_load_module_count , 'good_load_module_size' : self . responder . good_load_module_size , 'bad_load_module_count' : self . responder . bad_load_m...
def layout_route ( self , request ) : r"""Fetches the custom layout specified by the config file in the logdir . If more than 1 run contains a layout , this method merges the layouts by merging charts within individual categories . If 2 categories with the same name are found , the charts within are merged . ...
body = self . layout_impl ( ) return http_util . Respond ( request , body , 'application/json' )
def matches_to_marker_results ( df ) : """Perfect BLAST matches to marker results dict Parse perfect BLAST matches to marker results dict . Args : df ( pandas . DataFrame ) : DataFrame of perfect BLAST matches Returns : dict : cgMLST330 marker names to matching allele numbers"""
assert isinstance ( df , pd . DataFrame ) from collections import defaultdict d = defaultdict ( list ) for idx , row in df . iterrows ( ) : marker = row [ 'marker' ] d [ marker ] . append ( row ) marker_results = { } for k , v in d . items ( ) : if len ( v ) > 1 : logging . debug ( 'Multiple potenti...
def plotOptMod ( verNObg3gray , VERgray ) : """called from either readTranscar . py or hist - feasibility / plotsnew . py"""
if VERgray is None and verNObg3gray is None : return fg = figure ( ) ax2 = fg . gca ( ) # summed ( as camera would see ) if VERgray is not None : z = VERgray . alt_km Ek = VERgray . energy_ev . values # ax1 . semilogx ( VERgray , z , marker = ' ' , label = ' filt ' , color = ' b ' ) props = { 'boxst...
def unregister ( self , command ) : """Unregisters an existing command , so that this command is no longer available on the command line interface . This function is mainly used during plugin deactivation . : param command : Name of the command"""
if command not in self . _commands . keys ( ) : self . log . warning ( "Can not unregister command %s" % command ) else : # Click does not have any kind of a function to unregister / remove / deactivate already added commands . # So we need to delete the related objects manually from the click internal commands dic...
def _parse_args ( self , freqsAngles = True , _firstFlip = False , * args ) : """Helper function to parse the arguments to the _ _ call _ _ and actionsFreqsAngles functions"""
from galpy . orbit import Orbit RasOrbit = False integrated = True # whether the orbit was already integrated when given if len ( args ) == 5 or len ( args ) == 3 : # pragma : no cover raise IOError ( "Must specify phi for actionAngleIsochroneApprox" ) if len ( args ) == 6 or len ( args ) == 4 : if len ( args )...
def do_until ( lambda_expr , timeout = WTF_TIMEOUT_MANAGER . NORMAL , sleep = 0.5 , message = None ) : '''A retry wrapper that ' ll keep performing the action until it succeeds . ( main differnce between do _ until and wait _ until is do _ until will keep trying until a value is returned , while wait until will...
__check_condition_parameter_is_function ( lambda_expr ) end_time = datetime . now ( ) + timedelta ( seconds = timeout ) last_exception = None while datetime . now ( ) < end_time : try : return lambda_expr ( ) except Exception as e : last_exception = e time . sleep ( sleep ) if message : ...
def build ( self ) : """Creates the objects from the JSON response ."""
if self . json [ 'sys' ] [ 'type' ] == 'Array' : return self . _build_array ( ) return self . _build_item ( self . json )
def report_exception ( self , filename , exc ) : """This method is used when self . parser raises an Exception so that we can report a customized : class : ` EventReport ` object with info the exception ."""
# Build fake event . event = AbinitError ( src_file = "Unknown" , src_line = 0 , message = str ( exc ) ) return EventReport ( filename , events = [ event ] )
def dividedBy ( self , a ) : """Divide ."""
return Vector ( self . x / a , self . y / a , self . z / a )
def rotate_view ( self , axis_ind = 0 , angle = 0 ) : """Rotate the camera view . Args : axis _ ind : Index of axis to rotate . Defaults to 0 , i . e . , a - axis . angle : Angle to rotate by . Defaults to 0."""
camera = self . ren . GetActiveCamera ( ) if axis_ind == 0 : camera . Roll ( angle ) elif axis_ind == 1 : camera . Azimuth ( angle ) else : camera . Pitch ( angle ) self . ren_win . Render ( )
def compute_output ( self , o , output_shape = None ) : """Compute output of multihead attention . Args : o : a Tensor with dimensions query _ heads _ dims + { value _ dim } + other _ dims output _ shape : an optional Shape Returns : a Tensor with shape : { output _ dim } + other _ dims"""
if self . combine_dims : o = mtf . transpose ( o , o . shape - self . o_dims + self . o_dims ) o = mtf . replace_dimensions ( o , self . o_dims , self . wo . shape . dims [ 0 ] ) reduced_dims = [ self . wo . shape . dims [ 0 ] ] else : reduced_dims = self . o_dims return mtf . einsum ( [ o , self . wo ]...
def fixed_legend_filter_field ( self , fixed_legend_filter_field ) : """Sets the fixed _ legend _ filter _ field of this ChartSettings . Statistic to use for determining whether a series is displayed on the fixed legend # noqa : E501 : param fixed _ legend _ filter _ field : The fixed _ legend _ filter _ field ...
allowed_values = [ "CURRENT" , "MEAN" , "MEDIAN" , "SUM" , "MIN" , "MAX" , "COUNT" ] # noqa : E501 if fixed_legend_filter_field not in allowed_values : raise ValueError ( "Invalid value for `fixed_legend_filter_field` ({0}), must be one of {1}" # noqa : E501 . format ( fixed_legend_filter_field , allowed_values...
def write ( self , f ) : """write control data section to a file Parameters f : file handle or string filename"""
if isinstance ( f , str ) : f = open ( f , 'w' ) f . write ( "pcf\n" ) f . write ( "* control data\n" ) for line in CONTROL_VARIABLE_LINES : [ f . write ( self . formatted_values [ name . replace ( '[' , '' ) . replace ( ']' , '' ) ] ) for name in line . split ( ) ] f . write ( '\n' )
def delete_expired_users ( self ) : """Checks for expired users and delete ' s the ` ` User ` ` associated with it . Skips if the user ` ` is _ staff ` ` . : return : A list containing the deleted users ."""
deleted_users = [ ] for user in self . filter ( is_staff = False , is_active = False ) : if user . activation_key_expired ( ) : deleted_users . append ( user ) user . delete ( ) return deleted_users
def LoadFromXml ( self , node , handle ) : """Method updates the object from the xml representation of the managed object ."""
self . SetHandle ( handle ) if node . hasAttributes ( ) : # attributes = node . _ get _ attributes ( ) # attCount = attributes . _ get _ length ( ) attributes = node . attributes attCount = len ( attributes ) for i in range ( attCount ) : attNode = attributes . item ( i ) # attr = UcsUtils ....
def sle ( actual , predicted ) : """Computes the squared log error . This function computes the squared log error between two numbers , or for element between a pair of lists or numpy arrays . Parameters actual : int , float , list of numbers , numpy array The ground truth value predicted : same type as...
return ( np . power ( np . log ( np . array ( actual ) + 1 ) - np . log ( np . array ( predicted ) + 1 ) , 2 ) )
def _eval_dtype ( cls , value ) : """Convert dtype into canonical form , check its applicability and return info . Parameters value : np . dtype or something convertible to it . Returns value : np . dtype type _ info : Information about the dtype"""
value = np . dtype ( value ) if value . kind in "iu" : type_info = np . iinfo ( value ) elif value . kind == "f" : type_info = np . finfo ( value ) else : raise RuntimeError ( "Unsupported dtype. Only integer/floating-point types are supported." ) return value , type_info
def SecurityCheck ( self , func , request , * args , ** kwargs ) : """Wrapping function ."""
if self . IAP_HEADER not in request . headers : return werkzeug_wrappers . Response ( "Unauthorized" , status = 401 ) jwt = request . headers . get ( self . IAP_HEADER ) try : request . user , _ = validate_iap . ValidateIapJwtFromComputeEngine ( jwt , self . cloud_project_id , self . backend_service_id ) re...
def endElement ( self , name ) : """Callback run at the end of each XML element"""
content = '' . join ( self . _contentList ) if name == 'xtvd' : self . _progress . endItems ( ) else : try : if self . _context == 'stations' : self . _endStationsNode ( name , content ) elif self . _context == 'lineups' : self . _endLineupsNode ( name , content ) ...
def _compile_column_metadata ( row , keys , number ) : """Compile column metadata from one excel row ( " 9 part data " ) : param list row : Row of cells : param list keys : Variable header keys : return dict : Column metadata"""
# Store the variable keys by index in a dictionary _column = { } _interpretation = { } _calibration = { } _physical = { } # Use the header keys to place the column data in the dictionary if keys : for idx , key in enumerate ( keys ) : _key_low = key . lower ( ) # Special case : Calibration data ...
def from_ ( cls , gsim ) : """Generate a trivial GsimLogicTree from a single GSIM instance ."""
ltbranch = N ( 'logicTreeBranch' , { 'branchID' : 'b1' } , nodes = [ N ( 'uncertaintyModel' , text = str ( gsim ) ) , N ( 'uncertaintyWeight' , text = '1.0' ) ] ) lt = N ( 'logicTree' , { 'logicTreeID' : 'lt1' } , nodes = [ N ( 'logicTreeBranchingLevel' , { 'branchingLevelID' : 'bl1' } , nodes = [ N ( 'logicTreeBranchS...
def only_root_can_read ( self , root_group_can_read = True ) : """Checks if only root is allowed to read the file ( and anyone else is forbidden from reading ) . Write and execute bits are not checked . The read bits for root user / group are not checked because root can read / write anything regardless of th...
requirements = True # The final answer is progressively assembled in this variable . requirements &= self . owner == 'root' requirements &= not self . others_can_read ( ) if root_group_can_read : if self . group != 'root' : # if group is not root , group must not be able to read requirements &= not self . g...
def dumps ( graphs , triples = False , cls = PENMANCodec , ** kwargs ) : """Serialize each graph in * graphs * to the PENMAN format . Args : graphs : an iterable of Graph objects triples : if True , write graphs as triples instead of as PENMAN Returns : the string of serialized graphs"""
codec = cls ( ** kwargs ) strings = [ codec . encode ( g , triples = triples ) for g in graphs ] return '\n\n' . join ( strings )
def _batch_write_item ( self , items ) : """Make a BatchWriteItem call to Dynamo"""
kwargs = { 'RequestItems' : { self . tablename : items , } , 'ReturnConsumedCapacity' : self . return_capacity , 'ReturnItemCollectionMetrics' : self . return_item_collection_metrics , } return self . connection . call ( 'batch_write_item' , ** kwargs )
def bind_function ( f , dispatcher , * accept_args , ** accept_kwargs ) : """Bind a function to a dispatcher . Takes accept _ args , and accept _ kwargs and creates and ArgSpec instance , adding that to the MNDFunction which annotates the function : param f : function to wrap : param accept _ args : : par...
argspec = ArgSpec ( None , * accept_args , ** accept_kwargs ) mnd = MNDFunction ( f , dispatcher , argspec ) f . __mnd__ = mnd return f
def _role_present ( ret , IdentityPoolId , AuthenticatedRole , UnauthenticatedRole , conn_params ) : '''Helper function to set the Roles to the identity pool'''
r = __salt__ [ 'boto_cognitoidentity.get_identity_pool_roles' ] ( IdentityPoolName = '' , IdentityPoolId = IdentityPoolId , ** conn_params ) if r . get ( 'error' ) : ret [ 'result' ] = False failure_comment = ( 'Failed to get existing identity pool roles: ' '{0}' . format ( r [ 'error' ] . get ( 'message' , r [...
def dropLocalUser ( self , login , user ) : """Parameters : - login - user"""
self . send_dropLocalUser ( login , user ) self . recv_dropLocalUser ( )
def restart_service ( service_name , minimum_running_time = None ) : '''Restart OpenStack service immediately , or only if it ' s running longer than specified value CLI Example : . . code - block : : bash salt ' * ' openstack _ mng . restart _ service neutron salt ' * ' openstack _ mng . restart _ servic...
if minimum_running_time : ret_code = False # get system services list for interesting openstack service services = __salt__ [ 'cmd.run' ] ( [ '/usr/bin/openstack-service' , 'list' , service_name ] ) . split ( '\n' ) for service in services : service_info = __salt__ [ 'service.show' ] ( service )...
def _filter ( self , event ) : '''Take an event and run it through configured filters . Returns True if event should be stored , else False'''
tag = event [ 'tag' ] if self . opts [ 'event_return_whitelist' ] : ret = False else : ret = True for whitelist_match in self . opts [ 'event_return_whitelist' ] : if fnmatch . fnmatch ( tag , whitelist_match ) : ret = True break for blacklist_match in self . opts [ 'event_return_blacklist' ...
def list ( self , end_date = values . unset , event_type = values . unset , minutes = values . unset , reservation_sid = values . unset , start_date = values . unset , task_queue_sid = values . unset , task_sid = values . unset , worker_sid = values . unset , workflow_sid = values . unset , task_channel = values . unse...
return list ( self . stream ( end_date = end_date , event_type = event_type , minutes = minutes , reservation_sid = reservation_sid , start_date = start_date , task_queue_sid = task_queue_sid , task_sid = task_sid , worker_sid = worker_sid , workflow_sid = workflow_sid , task_channel = task_channel , sid = sid , limit ...
def _validate ( self , val ) : """val must be None or one of the objects in self . objects ."""
if not self . check_on_set : self . _ensure_value_is_in_objects ( val ) return if not ( val in self . objects or ( self . allow_None and val is None ) ) : # CEBALERT : can be called before _ _ init _ _ has called # super ' s _ _ init _ _ , i . e . before attrib _ name has been set . try : attrib_nam...
def validate_names ( self , category_name , probe_name ) : """Validate the category and probe name : - Category name must be alpha - numeric + ' . ' , no leading / trailing digit or ' . ' . - Probe name must be alpha - numeric + ' _ ' , no leading / trailing digit or ' _ ' . : param category _ name : the name...
# Enforce a maximum length on category and probe names . MAX_NAME_LENGTH = 40 for n in [ category_name , probe_name ] : if len ( n ) > MAX_NAME_LENGTH : raise ParserError ( ( "Name '{}' exceeds maximum name length of {} characters.\n" "See: {}#the-yaml-definition-file" ) . format ( n , MAX_NAME_LENGTH , BAS...
def from_bson_voronoi_list ( bson_nb_voro_list , structure ) : """Returns the voronoi _ list needed for the VoronoiContainer object from a bson - encoded voronoi _ list ( composed of vlist and bson _ nb _ voro _ list ) . : param vlist : List of voronoi objects : param bson _ nb _ voro _ list : List of periodi...
voronoi_list = [ None ] * len ( bson_nb_voro_list ) for isite , voro in enumerate ( bson_nb_voro_list ) : if voro is None or voro == 'None' : continue voronoi_list [ isite ] = [ ] for psd , dd in voro : struct_site = structure [ dd [ 'index' ] ] periodic_site = PeriodicSite ( struct_...
def main ( ) : """main Entrypoint to this script . This will execute the functionality as a standalone element"""
src_dir = sys . argv [ 1 ] os . chdir ( src_dir ) config = get_config ( src_dir ) cmd = 'python -c "import f5;print(f5.__version__)"' version = subprocess . check_output ( [ cmd ] , shell = True ) . strip ( ) tmp_dist = "/var/deb_dist" project = config [ 'project' ] tmp_dist = "/var/deb_dist" os_version = "1404" deb_di...
def display ( self , image ) : """Takes a 24 - bit RGB : py : mod : ` PIL . Image ` and dumps it to the daisy - chained WS2812 neopixels ."""
assert ( image . mode == self . mode ) assert ( image . size == self . size ) ws = self . _ws m = self . _mapping for idx , ( red , green , blue ) in enumerate ( image . getdata ( ) ) : color = ( red << 16 ) | ( green << 8 ) | blue ws . ws2811_led_set ( self . _channel , m [ idx ] , color ) self . _flush ( )
def first ( self , limit = 1 , columns = None ) : """Execute the query and get the first results : param limit : The number of results to get : type limit : int : param columns : The columns to get : type columns : list : return : The result : rtype : mixed"""
if not columns : columns = [ '*' ] results = self . take ( limit ) . get ( columns ) if len ( results ) > 0 : return results [ 0 ] return
def call ( self , method , * args ) : """Make a call to a ` Responder ` and return the result"""
payload = self . build_payload ( method , args ) logging . debug ( '* Client will send payload: {}' . format ( payload ) ) self . send ( payload ) res = self . receive ( ) assert payload [ 2 ] == res [ 'ref' ] return res [ 'result' ] , res [ 'error' ]
def is_up ( self ) : '''Return True if the interface is up , False otherwise .'''
# Get existing device flags ifreq = struct . pack ( '16sh' , self . name , 0 ) flags = struct . unpack ( '16sh' , fcntl . ioctl ( sockfd , SIOCGIFFLAGS , ifreq ) ) [ 1 ] # Set new flags if flags & IFF_UP : return True else : return False
def __camel_case ( word ) : """Convert underscore naming into camel case naming : param str word : : return str :"""
word = word . lower ( ) if '_' in word : split_word = word . split ( '_' ) else : split_word = word . split ( ) if len ( split_word ) > 0 : for i , word in enumerate ( split_word ) : if i > 0 : split_word [ i ] = word . title ( ) strings = '' . join ( split_word ) return strings
def resolve_caveat ( self , cav ) : '''Resolves the given caveat ( string ) by using resolve to map from its schema namespace to the appropriate prefix . If there is no registered prefix for the namespace , it returns an error caveat . If cav . namespace is empty or cav . location is non - empty , it return...
# TODO : If a namespace isn ' t registered , try to resolve it by # resolving it to the latest compatible version that is # registered . if cav . namespace == '' or cav . location != '' : return cav prefix = self . resolve ( cav . namespace ) if prefix is None : err_cav = error_caveat ( 'caveat {} in unregister...
def post_message2 ( consumers , lti_key , url , body , method = 'POST' , content_type = 'application/xml' ) : """Posts a signed message to LTI consumer using LTI 2.0 format : param : consumers : consumers from config : param : lti _ key : key to find appropriate consumer : param : url : post url : param : b...
# pylint : disable = too - many - arguments ( response , _ ) = _post_patched_request ( consumers , lti_key , body , url , method , content_type , ) is_success = response . status == 200 log . debug ( "is success %s" , is_success ) return is_success
def load_growth ( self , model ) : """Load and validate all data files ."""
data = self . config . get ( "growth" ) if data is None : return experiments = data . get ( "experiments" ) if experiments is None or len ( experiments ) == 0 : return path = self . get_path ( data , join ( "data" , "experimental" , "growth" ) ) for exp_id , exp in iteritems ( experiments ) : if exp is None...
def html_header ( ) : """Get a standard html header for wrapping content in . : returns : A header containing a web page preamble in html - up to and including the body open tag . : rtype : str"""
file_path = resources_path ( 'header.html' ) with codecs . open ( file_path , 'r' , encoding = 'utf8' ) as header_file : content = header_file . read ( ) content = content . replace ( 'PATH' , resources_path ( ) ) return content
def try_binding ( self ) : """Searches for the required service if needed : raise BundleException : Invalid ServiceReference found"""
with self . _lock : if self . services : # We already are alive ( not our first call ) # = > we are updated through service events return # Get all matching services refs = self . _context . get_all_service_references ( self . requirement . specification , self . requirement . filter ) if no...
def _pywrap_tensorflow ( ) : """Provide pywrap _ tensorflow access in TensorBoard . pywrap _ tensorflow cannot be accessed from tf . python . pywrap _ tensorflow and needs to be imported using ` from tensorflow . python import pywrap _ tensorflow ` . Therefore , we provide a separate accessor function for i...
try : from tensorboard . compat import notf # pylint : disable = g - import - not - at - top except ImportError : try : from tensorflow . python import pywrap_tensorflow # pylint : disable = g - import - not - at - top return pywrap_tensorflow except ImportError : pass fr...
def get_cached_resource_size ( self , resource_name ) : """meterer . get _ cached _ resource _ size ( resource _ name ) - > dict Retrieve cached information about the given resource . The resulting dict has the following structure : " size " : int , # Size of the resource " recorded _ time " : float , # Uni...
size_data = self . cache . get ( "SIZE:%s" % resource_name ) if size_data is None : return None return json_loads ( size_data )
def seek ( self , offset : int = 0 , * args , ** kwargs ) : """A shortcut to ` ` self . fp . seek ` ` ."""
return self . fp . seek ( offset , * args , ** kwargs )
def serialize ( self , value , # type : Any state # type : _ ProcessorState ) : # type : ( . . . ) - > ET . Element """Serialize the value to a new element and returns the element ."""
dict_value = self . _converter . to_dict ( value ) return self . _dictionary . serialize ( dict_value , state )
def search ( request , template = "search_results.html" , extra_context = None ) : """Display search results . Takes an optional " contenttype " GET parameter in the form " app - name . ModelName " to limit search results to a single model ."""
query = request . GET . get ( "q" , "" ) page = request . GET . get ( "page" , 1 ) per_page = settings . SEARCH_PER_PAGE max_paging_links = settings . MAX_PAGING_LINKS try : parts = request . GET . get ( "type" , "" ) . split ( "." , 1 ) search_model = apps . get_model ( * parts ) search_model . objects . s...
def getImportPeople ( self ) : """Return an L { ImportPeopleWidget } which is a child of this fragment and which will add people to C { self . organizer } ."""
fragment = ImportPeopleWidget ( self . organizer ) fragment . setFragmentParent ( self ) return fragment
def mask ( self , pattern ) : """A drawing operator that paints the current source using the alpha channel of : obj : ` pattern ` as a mask . ( Opaque areas of : obj : ` pattern ` are painted with the source , transparent areas are not painted . ) : param pattern : A : class : ` Pattern ` object ."""
cairo . cairo_mask ( self . _pointer , pattern . _pointer ) self . _check_status ( )
def realtimeBar ( self , reqId , time , open , high , low , close , volume , wap , count ) : """realtimeBar ( EWrapper self , TickerId reqId , long time , double open , double high , double low , double close , long volume , double wap , int count )"""
return _swigibpy . EWrapper_realtimeBar ( self , reqId , time , open , high , low , close , volume , wap , count )
def setNs ( self , node ) : """Associate a namespace to a node , a posteriori ."""
if node is None : node__o = None else : node__o = node . _o libxml2mod . xmlSetNs ( node__o , self . _o )
def ekrcei ( handle , segno , recno , column , nelts = _SPICE_EK_EKRCEX_ROOM_DEFAULT ) : """Read data from an integer column in a specified EK record . http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / ekrcei _ c . html : param handle : Handle attached to EK file . : type handle ...
handle = ctypes . c_int ( handle ) segno = ctypes . c_int ( segno ) recno = ctypes . c_int ( recno ) column = stypes . stringToCharP ( column ) nvals = ctypes . c_int ( ) ivals = stypes . emptyIntVector ( nelts ) isnull = ctypes . c_int ( ) libspice . ekrcei_c ( handle , segno , recno , column , ctypes . byref ( nvals ...
def disconnect ( self , device ) : """Disconnect using protocol specific method ."""
self . device . ctrl . sendcontrol ( 'd' ) self . device . ctrl . send ( "c." ) self . log ( "CONSOLE SERVER disconnect" ) try : self . device . ctrl . send ( chr ( 4 ) ) except OSError : self . log ( "Protocol already disconnected" )
def branches ( self ) : """# TODO : description"""
for branch in self . _grid . graph_edges ( ) : if branch [ 'branch' ] . ring == self : yield branch
def aligner ( seqj , seqi , method = 'global' , gap_open = - 7 , gap_extend = - 7 , gap_double = - 7 , matrix = submat . DNA_SIMPLE . matrix , alphabet = submat . DNA_SIMPLE . alphabet ) : '''Calculates the alignment of two sequences . The global method uses a global Needleman - Wunsh algorithm , local does a a l...
amatrix = as_ord_matrix ( matrix , alphabet ) NONE , LEFT , UP , DIAG = range ( 4 ) # NONE is 0 max_j = len ( seqj ) max_i = len ( seqi ) if max_j > max_i : flip = 1 seqi , seqj = seqj , seqi max_i , max_j = max_j , max_i else : flip = 0 F = np . zeros ( ( max_i + 1 , max_j + 1 ) , dtype = np . float32 ...
def navdatapush ( self ) : """Pushes the current : referenceframe : out to clients . : return :"""
try : self . fireEvent ( referenceframe ( { 'data' : self . referenceframe , 'ages' : self . referenceages } ) , "navdata" ) self . intervalcount += 1 if self . intervalcount == self . passiveinterval and len ( self . referenceframe ) > 0 : self . fireEvent ( broadcast ( 'users' , { 'component' : 'h...
def get_sys_info ( ) : "Returns system information as a dict"
blob = [ ] # get full commit hash commit = None if os . path . isdir ( ".git" ) and os . path . isdir ( "xarray" ) : try : pipe = subprocess . Popen ( 'git log --format="%H" -n 1' . split ( " " ) , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) so , serr = pipe . communicate ( ) excep...
def orient_page ( infiles , output_file , log , context ) : """Work out orientation correct for each page . We ask Ghostscript to draw a preview page , which will rasterize with the current / Rotate applied , and then ask Tesseract which way the page is oriented . If the value of / Rotate is correct ( e . g ....
options = context . get_options ( ) page_pdf = next ( ii for ii in infiles if ii . endswith ( '.page.pdf' ) ) if not options . rotate_pages : re_symlink ( page_pdf , output_file , log ) return preview = next ( ii for ii in infiles if ii . endswith ( '.preview.jpg' ) ) orient_conf = tesseract . get_orientation (...
def extract_traits ( self , entity ) : """Extract data required to classify entity . : param object entity : : return : namedtuple consisting of characteristic traits and match flag : rtype : matchbox . box . Trait"""
traits = getattr ( entity , self . _characteristic ) if traits is not None and isinstance ( traits , Hashable ) : traits = [ traits ] return Trait ( traits , getattr ( entity , self . _characteristic + '_match' , True ) )
def eval_str_to_list ( input_str : str ) -> List [ str ] : """Turn str into str or tuple ."""
inner_cast = ast . literal_eval ( input_str ) # type : List [ str ] if isinstance ( inner_cast , list ) : return inner_cast else : raise ValueError
def _api_call ( self , method , target , args = None ) : """Create a Request object and execute the call to the API Server . Parameters method ( str ) HTTP request ( e . g . ' POST ' ) . target ( str ) The target URL with leading slash ( e . g . ' / v1 / products ' ) . args ( dict ) Optional dictionar...
self . refresh_oauth_credential ( ) request = Request ( auth_session = self . session , api_host = self . api_host , method = method , path = target , args = args , ) return request . execute ( )
def _add_datetimelike_methods ( cls ) : """Add in the datetimelike methods ( as we may have to override the superclass ) ."""
def __add__ ( self , other ) : # dispatch to ExtensionArray implementation result = self . _data . __add__ ( maybe_unwrap_index ( other ) ) return wrap_arithmetic_op ( self , other , result ) cls . __add__ = __add__ def __radd__ ( self , other ) : # alias for _ _ add _ _ return self . __add__ ( other ) cls ...
def persist ( self ) : """持久化会话信息"""
with open ( self . persist_file , 'w+' ) as f : json . dump ( { 'cookies' : self . cookies , 'user_alias' : self . user_alias , } , f , indent = 2 ) self . logger . debug ( 'persist session to <%s>' % self . persist_file )
def form_number ( self ) : """Returns the model ' s form number , a helpful heuristic for classifying tides ."""
k1 , o1 , m2 , s2 = ( np . extract ( self . model [ 'constituent' ] == c , self . model [ 'amplitude' ] ) for c in [ constituent . _K1 , constituent . _O1 , constituent . _M2 , constituent . _S2 ] ) return ( k1 + o1 ) / ( m2 + s2 )
def adapt_for_peptides ( self ) : """Adapt visualization for peptide ligands and interchain contacts"""
cmd . hide ( 'sticks' , self . ligname ) cmd . set ( 'cartoon_color' , 'lightorange' , self . ligname ) cmd . show ( 'cartoon' , self . ligname ) cmd . show ( 'sticks' , "byres *-L" ) cmd . util . cnc ( self . ligname ) cmd . remove ( '%sCartoon and chain %s' % ( self . protname , self . plcomplex . chain ) ) cmd . set...
def iscoplanar ( coords ) : r'''Determines if given pores are coplanar with each other Parameters coords : array _ like List of pore coords to check for coplanarity . At least 3 pores are required . Returns A boolean value of whether given points are coplanar ( True ) or not ( False )'''
coords = sp . array ( coords , ndmin = 1 ) if sp . shape ( coords ) [ 0 ] < 3 : raise Exception ( 'At least 3 input pores are required' ) Px = coords [ : , 0 ] Py = coords [ : , 1 ] Pz = coords [ : , 2 ] # Do easy check first , for common coordinate if sp . shape ( sp . unique ( Px ) ) [ 0 ] == 1 : return True ...
def _repr_fits_horizontal_ ( self , ignore_width = False ) : """Check if full repr fits in horizontal boundaries imposed by the display options width and max _ columns . In case off non - interactive session , no boundaries apply . ignore _ width is here so ipnb + HTML output can behave the way users expect...
width , height = get_console_size ( ) max_columns = options . display . max_columns nb_columns = len ( self . columns ) # exceed max columns if ( ( max_columns and nb_columns > max_columns ) or ( ( not ignore_width ) and width and nb_columns > ( width // 2 ) ) ) : return False if ( ignore_width # used by repr _ htm...
def unpause_tube ( self , tube ) : """Unpause a tube which was previously paused with : func : ` pause _ tube ( ) ` . . . seealso : : : func : ` pause _ tube ( ) `"""
with self . _sock_ctx ( ) as socket : self . _send_message ( 'pause-tube {0} 0' . format ( tube ) , socket ) return self . _receive_word ( socket , b'PAUSED' )
def _nonzero ( self ) : """Equivalent numpy ' s nonzero but returns a tuple of Varibles ."""
# TODO we should replace dask ' s native nonzero # after https : / / github . com / dask / dask / issues / 1076 is implemented . nonzeros = np . nonzero ( self . data ) return tuple ( Variable ( ( dim ) , nz ) for nz , dim in zip ( nonzeros , self . dims ) )
def create_package_file ( root , master_package , subroot , py_files , opts , subs ) : """Build the text of the file and write the file ."""
package = os . path . split ( root ) [ - 1 ] text = format_heading ( 1 , '%s Package' % package ) # add each package ' s module for py_file in py_files : if shall_skip ( os . path . join ( root , py_file ) ) : continue is_package = py_file == INIT py_file = os . path . splitext ( py_file ) [ 0 ] ...
def AddObject ( self , path , interface , properties , methods ) : '''Add a new D - Bus object to the mock path : D - Bus object path interface : Primary D - Bus interface name of this object ( where properties and methods will be put on ) properties : A property _ name ( string ) → value map with initial ...
if path in objects : raise dbus . exceptions . DBusException ( 'object %s already exists' % path , name = 'org.freedesktop.DBus.Mock.NameError' ) obj = DBusMockObject ( self . bus_name , path , interface , properties ) # make sure created objects inherit the log file stream obj . logfile = self . logfile obj . obje...
def p_statement_border ( p ) : """statement : BORDER expr"""
p [ 0 ] = make_sentence ( 'BORDER' , make_typecast ( TYPE . ubyte , p [ 2 ] , p . lineno ( 1 ) ) )
def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_rx_vnport_ka ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) fcoe_get_interface = ET . Element ( "fcoe_get_interface" ) config = fcoe_get_interface output = ET . SubElement ( fcoe_get_interface , "output" ) fcoe_intf_list = ET . SubElement ( output , "fcoe-intf-list" ) fcoe_intf_fcoe_port_id_key = ET . SubElement ( fcoe_intf_list , "fcoe-intf-f...
def trace ( self , urls = None , ** overrides ) : """Sets the acceptable HTTP method to TRACE"""
if urls is not None : overrides [ 'urls' ] = urls return self . where ( accept = 'TRACE' , ** overrides )
def _process_backend_kwargs ( self , kwargs ) : """Simple utility to retrieve kwargs in predetermined order . Also checks whether the values of the backend arguments do not violate the backend capabilities ."""
# Verify given argument with capability of the backend app = self . _vispy_canvas . app capability = app . backend_module . capability if kwargs [ 'context' ] . shared . name : # name already assigned : shared if not capability [ 'context' ] : raise RuntimeError ( 'Cannot share context with this backend' ) ...
def protect ( self , developers_can_push = False , developers_can_merge = False , ** kwargs ) : """Protect the branch . Args : developers _ can _ push ( bool ) : Set to True if developers are allowed to push to the branch developers _ can _ merge ( bool ) : Set to True if developers are allowed to merge t...
id = self . get_id ( ) . replace ( '/' , '%2F' ) path = '%s/%s/protect' % ( self . manager . path , id ) post_data = { 'developers_can_push' : developers_can_push , 'developers_can_merge' : developers_can_merge } self . manager . gitlab . http_put ( path , post_data = post_data , ** kwargs ) self . _attrs [ 'protected'...
def missing_requirements_command ( missing_programs , installation_string , filename , unused_lines ) : """Pseudo - command to be used when requirements are missing ."""
verb = 'is' if len ( missing_programs ) > 1 : verb = 'are' return { filename : { 'skipped' : [ '%s %s not installed. %s' % ( ', ' . join ( missing_programs ) , verb , installation_string ) ] } }