signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def diagnostics ( self ) : """Dictionary access to all diagnostic variables : type : dict"""
diag_dict = { } for key in self . _diag_vars : try : # diag _ dict [ key ] = getattr ( self , key ) # using self . _ _ dict _ _ doesn ' t count diagnostics defined as properties diag_dict [ key ] = self . __dict__ [ key ] except : pass return diag_dict
def validate_document_class ( option , value ) : """Validate the document _ class option ."""
if not issubclass ( value , ( abc . MutableMapping , RawBSONDocument ) ) : raise TypeError ( "%s must be dict, bson.son.SON, " "bson.raw_bson.RawBSONDocument, or a " "sublass of collections.MutableMapping" % ( option , ) ) return value
def do_close ( self , reason ) : """Called when channel _ close ( ) is received"""
if self . closed : return self . closed = True self . reason = reason self . incoming . close ( ) self . responses . close ( ) if not self . _closing : self . client . channel_failed ( self , Failure ( reason ) )
def types_of_coordination_environments ( self , anonymous = False ) : """Extract information on the different co - ordination environments present in the graph . : param anonymous : if anonymous , will replace specie names with A , B , C , etc . : return : a list of co - ordination environments , e . g . ...
motifs = set ( ) for idx , site in enumerate ( self . structure ) : centre_sp = site . species_string connected_sites = self . get_connected_sites ( idx ) connected_species = [ connected_site . site . species_string for connected_site in connected_sites ] labels = [ ] for sp in set ( connected_speci...
def read_galprop_rings_yaml ( self , galkey ) : """Read the yaml file for a partiuclar galprop key"""
galprop_rings_yaml = self . _name_factory . galprop_rings_yaml ( galkey = galkey , fullpath = True ) galprop_rings = yaml . safe_load ( open ( galprop_rings_yaml ) ) return galprop_rings
def attention_lm_moe_24b_diet ( ) : """Unnecessarily large model with 24B params - because we can ."""
hparams = attention_lm_moe_large_diet ( ) hparams . moe_hidden_sizes = "12288" hparams . moe_num_experts = 1024 hparams . batch_size = 4096 return hparams
def _file_type ( file ) : """Function intended for identification of the file type . Parameters file : file path File path . Returns out : str Identified file type ."""
# % % % % % Verification of file type % % % % % if "." in file : # File with known extension . file_type = file . split ( "." ) [ - 1 ] else : # File without known extension . file_type = magic . from_file ( file , mime = True ) . split ( "/" ) [ - 1 ] return file_type
def print_object_results ( obj_result ) : """Print the results of validating an object . Args : obj _ result : An ObjectValidationResults instance ."""
print_results_header ( obj_result . object_id , obj_result . is_valid ) if obj_result . warnings : print_warning_results ( obj_result , 1 ) if obj_result . errors : print_schema_results ( obj_result , 1 )
def safe_power ( a , b ) : """Same power of a ^ b : param a : Number a : param b : Number b : return : a ^ b"""
if abs ( a ) > MAX_POWER or abs ( b ) > MAX_POWER : raise ValueError ( 'Number too high!' ) return a ** b
def _uncompress_file ( self , path ) : '''Writes the current file into a file in the temporary directory . If that doesn ' t work , create a new file in the CDFs directory .'''
with self . file . open ( 'rb' ) as f : if ( self . cdfversion == 3 ) : data_start , data_size , cType , _ = self . _read_ccr ( 8 ) else : data_start , data_size , cType , _ = self . _read_ccr2 ( 8 ) if cType != 5 : return f . seek ( data_start ) decompressed_data = gzip . de...
def clone ( self , spec = None , ** overrides ) : """Clones the Dimension with new parameters Derive a new Dimension that inherits existing parameters except for the supplied , explicit overrides Args : spec ( tuple , optional ) : Dimension tuple specification * * overrides : Dimension parameter overrides...
settings = dict ( self . get_param_values ( ) , ** overrides ) if spec is None : spec = ( self . name , overrides . get ( 'label' , self . label ) ) if 'label' in overrides and isinstance ( spec , basestring ) : spec = ( spec , overrides [ 'label' ] ) elif 'label' in overrides and isinstance ( spec , tuple ) : ...
def readCache ( self , filename ) : """Load the graph from a cache file ."""
with open ( filename , 'rb' ) as f : self . modules = pickle . load ( f )
def convertTime ( self , time ) : """Convert a datetime object representing a time into a human - ready string that can be read , spoken aloud , etc . Args : time ( datetime . date ) : A datetime object to be converted into text . Returns : A string representation of the input time , ignoring any day - re...
# if ' : 00 ' , ignore reporting minutes m_format = "" if time . minute : m_format = ":%M" timeString = time . strftime ( "%I" + m_format + " %p" ) # if ' 07:30 ' , cast to ' 7:30' if not int ( timeString [ 0 ] ) : timeString = timeString [ 1 : ] return timeString
def toimage ( self , width = None , height = None ) : '''Return the current scene as a PIL Image . * * Example * * You can build your molecular viewer as usual and dump an image at any resolution supported by the video card ( up to the memory limits ) : : v = QtViewer ( ) # Add the renderers v . add _...
from . postprocessing import NoEffect effect = NoEffect ( self ) self . post_processing . append ( effect ) oldwidth , oldheight = self . width ( ) , self . height ( ) # self . initializeGL ( ) if None not in ( width , height ) : self . resize ( width , height ) self . resizeGL ( width , height ) else : wid...
def check_errors ( self , is_global = False ) : """Checks for errors and exits if any of them are critical . Args : is _ global : If True , check the global _ errors attribute . If false , check the error attribute ."""
errors = self . global_errors if is_global else self . errors if errors : print ( 'dfTimewolf encountered one or more errors:' ) for error , critical in errors : print ( '{0:s} {1:s}' . format ( 'CRITICAL: ' if critical else '' , error ) ) if critical : print ( 'Critical error found...
def export_lane_set ( process , lane_set , plane_element ) : """Creates ' laneSet ' element for exported BPMN XML file . : param process : an XML element ( ' process ' ) , from exported BPMN 2.0 document , : param lane _ set : dictionary with exported ' laneSet ' element attributes and child elements , : para...
lane_set_xml = eTree . SubElement ( process , consts . Consts . lane_set ) for key , value in lane_set [ consts . Consts . lanes ] . items ( ) : BpmnDiagramGraphExport . export_lane ( lane_set_xml , key , value , plane_element )
def rvpl ( self , prompt , error = 'Entered value is invalid' , intro = None , validator = lambda x : x != '' , clean = lambda x : x . strip ( ) , strict = True , default = None ) : """Start a read - validate - print loop The RVPL will read the user input , validate it , and loop until the entered value passes ...
if intro : self . pstd ( utils . rewrap_long ( intro ) ) val = self . read ( prompt , clean ) while not validator ( val ) : if not strict : return default if hasattr ( error , '__call__' ) : self . perr ( error ( val ) ) else : self . perr ( error ) val = self . read ( prompt...
def cmd_zip ( zip_file , sources , template = None , cwd = None , runas = None ) : '''. . versionadded : : 2015.5.0 In versions 2014.7 . x and earlier , this function was known as ` ` archive . zip ` ` . Uses the ` ` zip ` ` command to create zip files . This command is part of the ` Info - ZIP ` _ suite of...
cmd = [ 'zip' , '-r' ] cmd . append ( '{0}' . format ( zip_file ) ) cmd . extend ( _expand_sources ( sources ) ) return __salt__ [ 'cmd.run' ] ( cmd , cwd = cwd , template = template , runas = runas , python_shell = False ) . splitlines ( )
def set_alternative ( self , experiment_name , alternative ) : """Explicitly set the alternative the user is enrolled in for the specified experiment . This allows you to change a user between alternatives . The user and goal counts for the new alternative will be increment , but those for the old one will not ...
experiment = experiment_manager . get_experiment ( experiment_name ) if experiment : self . _set_enrollment ( experiment , alternative )
def bbox_horz_aligned ( box1 , box2 ) : """Returns true if the vertical center point of either span is within the vertical range of the other"""
if not ( box1 and box2 ) : return False # NEW : any overlap counts # return box1 . top < = box2 . bottom and box2 . top < = box1 . bottom box1_top = box1 . top + 1.5 box2_top = box2 . top + 1.5 box1_bottom = box1 . bottom - 1.5 box2_bottom = box2 . bottom - 1.5 return not ( box1_top > box2_bottom or box2_top > box1...
def match_path_against ( pathname , patterns , case_sensitive = True ) : """Determines whether the pathname matches any of the given wildcard patterns , optionally ignoring the case of the pathname and patterns . : param pathname : A path name that will be matched against a wildcard pattern . : param patter...
if case_sensitive : match_func = fnmatchcase pattern_transform_func = ( lambda w : w ) else : match_func = fnmatch pathname = pathname . lower ( ) pattern_transform_func = _string_lower for pattern in set ( patterns ) : pattern = pattern_transform_func ( pattern ) if match_func ( pathname , ...
def list_by_group ( self , id_egroup ) : """Search Group Equipment from by the identifier . : param id _ egroup : Identifier of the Group Equipment . Integer value and greater than zero . : return : Dictionary with the following structure : { ' equipaments ' : [ { ' nome ' : < name _ equipament > , ' grupos...
if id_egroup is None : raise InvalidParameterError ( u'The identifier of Group Equipament is invalid or was not informed.' ) url = 'equipment/group/' + str ( id_egroup ) + '/' code , xml = self . submit ( None , 'GET' , url ) return self . response ( code , xml )
def select ( self , ** kws ) : '''Find all servers with indicated protocol support . Shuffled . Filter by TOR support , and pruning level .'''
lst = [ i for i in self . values ( ) if i . select ( ** kws ) ] random . shuffle ( lst ) return lst
def filter ( self , value , model = None , context = None ) : """Filter Performs value filtering and returns filtered result . : param value : input value : param model : parent model being validated : param context : object , filtering context : return : filtered value"""
value = str ( value ) return value . upper ( )
def constructor ( self , name = None , function = None , return_type = None , arg_types = None , header_dir = None , header_file = None , recursive = None ) : """returns reference to constructor declaration , that is matched defined criteria"""
return ( self . _find_single ( self . _impl_matchers [ scopedef_t . constructor ] , name = name , function = function , decl_type = self . _impl_decl_types [ scopedef_t . constructor ] , return_type = return_type , arg_types = arg_types , header_dir = header_dir , header_file = header_file , recursive = recursive ) )
def get_int_relative ( strings : Sequence [ str ] , prefix1 : str , delta : int , prefix2 : str , ignoreleadingcolon : bool = False ) -> Optional [ int ] : """Fetches an int parameter via : func : ` get _ string _ relative ` ."""
return get_int_raw ( get_string_relative ( strings , prefix1 , delta , prefix2 , ignoreleadingcolon = ignoreleadingcolon ) )
def box ( df , s = None , title_from = None , subplots = False , figsize = ( 18 , 6 ) , groups = None , fcol = None , ecol = None , hatch = None , ylabel = "" , xlabel = "" ) : """Generate a box plot from pandas DataFrame with sample grouping . Plot group mean , median and deviations for specific values ( protein...
df = df . copy ( ) if type ( s ) == str : s = [ s ] if title_from is None : title_from = list ( df . index . names ) if groups is None : groups = list ( set ( df . columns . get_level_values ( 0 ) ) ) # Build the combined name / info string using label _ from ; replace the index title_idxs = get_index_list ...
async def _receive_reconfig_param ( self , param ) : """Handle a RE - CONFIG parameter ."""
self . __log_debug ( '<< %s' , param ) if isinstance ( param , StreamResetOutgoingParam ) : # mark closed inbound streams for stream_id in param . streams : self . _inbound_streams . pop ( stream_id , None ) # close data channel channel = self . _data_channels . get ( stream_id ) if ...
def volumes ( val , ** kwargs ) : # pylint : disable = unused - argument '''Should be a list of absolute paths'''
val = helpers . translate_stringlist ( val ) for item in val : if not os . path . isabs ( item ) : raise SaltInvocationError ( '\'{0}\' is not an absolute path' . format ( item ) ) return val
def start ( self , measurementId , durationInSeconds = None ) : """Initialises the device if required then enters a read loop taking data from the provider and passing it to the handler . It will continue until either breakRead is true or the duration ( if provided ) has passed . : return :"""
logger . info ( ">> measurement " + measurementId + ( ( " for " + str ( durationInSeconds ) ) if durationInSeconds is not None else " until break" ) ) self . failureCode = None self . measurementOverflowed = False self . dataHandler . start ( measurementId ) self . breakRead = False self . startTime = time . time ( ) s...
def _GetNormalizedTimestamp ( self ) : """Retrieves the normalized timestamp . Returns : decimal . Decimal : normalized timestamp , which contains the number of seconds since January 1 , 1970 00:00:00 and a fraction of second used for increased precision , or None if the normalized timestamp cannot be det...
if self . _normalized_timestamp is None : if ( self . _timestamp is not None and self . _timestamp >= 0 and self . _timestamp <= self . _UINT32_MAX ) : self . _normalized_timestamp = ( decimal . Decimal ( self . _timestamp ) - self . _HFS_TO_POSIX_BASE ) return self . _normalized_timestamp
def app_run ( app_name_or_id , alias = None , input_params = { } , always_retry = True , ** kwargs ) : """Invokes the / app - xxxx / run API method . For more info , see : https : / / wiki . dnanexus . com / API - Specification - v1.0.0 / Apps # API - method : - / app - xxxx % 5B / yyyy % 5D / run"""
input_params_cp = Nonce . update_nonce ( input_params ) fully_qualified_version = app_name_or_id + ( ( '/' + alias ) if alias else '' ) return DXHTTPRequest ( '/%s/run' % fully_qualified_version , input_params_cp , always_retry = always_retry , ** kwargs )
def run ( self ) : """Starts Pyro naming server with command line arguments ( see pyro documentation )"""
args = [ ] for arg in self . args : args . append ( arg ) Args = Pyro . util . ArgParser ( ) Args . parse ( args , 'hkmrvxn:p:b:c:d:s:i:1:2:' ) hostname = Args . getOpt ( 'n' , None ) identification = Args . getOpt ( 'i' , None ) port = None useNameServer = True if port : port = int ( port ) norange = ( port ==...
def create_view ( self , dataset , view , query , use_legacy_sql = None , project_id = None ) : """Create a new view in the dataset . Parameters dataset : str The dataset to create the view in view : str The name of the view to create query : dict A query that BigQuery executes when the view is refere...
project_id = self . _get_project_id ( project_id ) body = { 'tableReference' : { 'tableId' : view , 'projectId' : project_id , 'datasetId' : dataset } , 'view' : { 'query' : query } } if use_legacy_sql is not None : body [ 'view' ] [ 'useLegacySql' ] = use_legacy_sql try : view = self . bigquery . tables ( ) . ...
def _add_parameters ( self , parameter_map , parameter_list ) : """Populates the given parameter map with the list of parameters provided , resolving any reference objects encountered . Args : parameter _ map : mapping from parameter names to parameter objects parameter _ list : list of either parameter objec...
for parameter in parameter_list : if parameter . get ( '$ref' ) : # expand parameter from $ ref if not specified inline parameter = self . specification [ 'parameters' ] . get ( parameter . get ( '$ref' ) . split ( '/' ) [ - 1 ] ) parameter_map [ parameter [ 'name' ] ] = parameter
def i2osp ( self , long_integer , block_size ) : 'Convert a long integer into an octet string .'
hex_string = '%X' % long_integer if len ( hex_string ) > 2 * block_size : raise ValueError ( 'integer %i too large to encode in %i octets' % ( long_integer , block_size ) ) return a2b_hex ( hex_string . zfill ( 2 * block_size ) )
def process_text ( text , citation = None , offline = False , output_fname = default_output_fname , timeout = None ) : """Return a ReachProcessor by processing the given text . Parameters text : str The text to be processed . citation : Optional [ str ] A PubMed ID passed to be used in the evidence for th...
if offline : if not try_offline : logger . error ( 'Offline reading is not available.' ) return None try : api_ruler = reach_reader . get_api_ruler ( ) except ReachOfflineReadingError as e : logger . error ( e ) logger . error ( 'Cannot read offline because the REACH ...
def is_functional_group ( self , atom , group ) : """Given a pybel atom , look up if it belongs to a function group"""
n_atoms = [ a_neighbor . GetAtomicNum ( ) for a_neighbor in pybel . ob . OBAtomAtomIter ( atom . OBAtom ) ] if group in [ 'quartamine' , 'tertamine' ] and atom . atomicnum == 7 : # Nitrogen # It ' s a nitrogen , so could be a protonated amine or quaternary ammonium if '1' not in n_atoms and len ( n_atoms ) == 4 : ...
def decode_safely ( self , encoded_data ) : """Inverse for the ` encode _ safely ` function ."""
decoder = self . base_decoder result = settings . null try : result = pickle . loads ( decoder ( encoded_data ) ) except : warnings . warn ( "Could not load and deserialize the data." , RuntimeWarning ) return result
def attach ( self , image_in , sampler = None , show = True ) : """Attaches the relevant cross - sections to each axis . Parameters attach _ image : ndarray The image to be attached to the collage , once it is created . Must be atleast 3d . sampler : str or list or callable selection strategy : to ident...
if len ( image_in . shape ) < 3 : raise ValueError ( 'Image must be atleast 3D' ) # allowing the choice of new sampling for different invocations . if sampler is None : temp_sampler = self . sampler else : temp_sampler = sampler slicer = SlicePicker ( image_in = image_in , view_set = self . view_set , num_s...
def binary_operator ( op ) : """Factory function for making binary operator methods on a Filter subclass . Returns a function " binary _ operator " suitable for implementing functions like _ _ and _ _ or _ _ or _ _ ."""
# When combining a Filter with a NumericalExpression , we use this # attrgetter instance to defer to the commuted interpretation of the # NumericalExpression operator . commuted_method_getter = attrgetter ( method_name_for_op ( op , commute = True ) ) def binary_operator ( self , other ) : if isinstance ( self , Nu...
def simplify ( graph ) : """Simplify the CFG by merging / deleting statement nodes when possible : If statement B follows statement A and if B has no other predecessor besides A , then we can merge A and B into a new statement node . We also remove nodes which do nothing except redirecting the control flow ...
redo = True while redo : redo = False node_map = { } to_update = set ( ) for node in graph . nodes [ : ] : if node . type . is_stmt and node in graph : sucs = graph . all_sucs ( node ) if len ( sucs ) != 1 : continue suc = sucs [ 0 ] ...
def main ( vocab_path : str , elmo_config_path : str , elmo_weights_path : str , output_dir : str , batch_size : int , device : int , use_custom_oov_token : bool = False ) : """Creates ELMo word representations from a vocabulary file . These word representations are _ independent _ - they are the result of runnin...
# Load the vocabulary words and convert to char ids with open ( vocab_path , 'r' ) as vocab_file : tokens = vocab_file . read ( ) . strip ( ) . split ( '\n' ) # Insert the sentence boundary tokens which elmo uses at positions 1 and 2. if tokens [ 0 ] != DEFAULT_OOV_TOKEN and not use_custom_oov_token : raise Con...
def query ( self , table , hash_key , range_key_condition = None , attributes_to_get = None , request_limit = None , max_results = None , consistent_read = False , scan_index_forward = True , exclusive_start_key = None , item_class = Item ) : """Perform a query on the table . : type table : : class : ` boto . dyn...
rkc = self . dynamize_range_key_condition ( range_key_condition ) response = True n = 0 while response : if response is True : pass elif response . has_key ( "LastEvaluatedKey" ) : lek = response [ 'LastEvaluatedKey' ] exclusive_start_key = self . dynamize_last_evaluated_key ( lek ) ...
def add_axes_at_origin ( self , loc = None ) : """Add axes actor at the origin of a render window . Parameters loc : int , tuple , or list Index of the renderer to add the actor to . For example , ` ` loc = 2 ` ` or ` ` loc = ( 1 , 1 ) ` ` . When None , defaults to the active render window . Returns m...
self . _active_renderer_index = self . loc_to_index ( loc ) return self . renderers [ self . _active_renderer_index ] . add_axes_at_origin ( )
def __update_in_toto_layout_pubkeys ( self ) : '''NOTE : We assume that all the public keys needed to verify any in - toto root layout , or sublayout , metadata file has been directly signed by the top - level TUF targets role using * OFFLINE * keys . This is a reasonable assumption , as TUF does not offer me...
target_relpaths = [ ] targets = self . __updater . targets_of_role ( 'targets' ) for target in targets : target_relpath = target [ 'filepath' ] # Download this target only if it _ looks _ like a public key . if target_relpath . endswith ( '.pub' ) : # NOTE : Avoid recursively downloading in - toto metadata ...
def update_lbaas_member ( self , lbaas_member , lbaas_pool , body = None ) : """Updates a lbaas _ member ."""
return self . put ( self . lbaas_member_path % ( lbaas_pool , lbaas_member ) , body = body )
def failedToGetPerspective ( self , why , broker ) : """The login process failed , most likely because of an authorization failure ( bad password ) , but it is also possible that we lost the new connection before we managed to send our credentials ."""
log . msg ( "ReconnectingPBClientFactory.failedToGetPerspective" ) # put something useful in the logs if why . check ( pb . PBConnectionLost ) : log . msg ( "we lost the brand-new connection" ) # fall through elif why . check ( error . UnauthorizedLogin ) : log . msg ( "unauthorized login; check worker name...
def add_edge ( self , edge ) : """Adds Edges to the probnet dict . Parameters edge : < Element Link at Links Node in XML > etree Element consisting Variable tag . Examples > > > reader = ProbModelXMLReader ( ) > > > reader . add _ edge ( edge )"""
var1 = edge . findall ( 'Variable' ) [ 0 ] . attrib [ 'name' ] var2 = edge . findall ( 'Variable' ) [ 1 ] . attrib [ 'name' ] self . probnet [ 'edges' ] [ ( var1 , var2 ) ] = { } self . probnet [ 'edges' ] [ ( var1 , var2 ) ] [ 'directed' ] = edge . attrib [ 'directed' ] # TODO : check for the case of undirected graphs...
def run_forever ( self , * args , ** kwargs ) : """: type relax : float : param relax : seconds between each : meth : ` . getUpdates ` : type offset : int : param offset : initial ` ` offset ` ` parameter supplied to : meth : ` . getUpdates ` : type timeout : int : param timeout : ` ` timeout ` ` para...
collectloop = CollectLoop ( self . _handle ) updatesloop = GetUpdatesLoop ( self . _bot , lambda update : collectloop . input_queue . put ( _extract_message ( update ) [ 1 ] ) ) # feed messages to collect loop # feed events to collect loop self . _bot . scheduler . on_event ( collectloop . input_queue . put ) self . _b...
def getInitialArguments ( self ) : """Include L { organizer } ' s C { storeOwnerPerson } ' s name , and the name of L { initialPerson } and the value of L { initialState } , if they are set ."""
initialArguments = ( self . organizer . storeOwnerPerson . name , ) if self . initialPerson is not None : initialArguments += ( self . initialPerson . name , self . initialState ) return initialArguments
def permute_iter ( elements ) : """iterator : returns a perumation by each call ."""
if len ( elements ) <= 1 : yield elements else : for perm in permute_iter ( elements [ 1 : ] ) : for i in range ( len ( elements ) ) : yield perm [ : i ] + elements [ 0 : 1 ] + perm [ i : ]
def override_params ( opening_char = '{' , closing_char = '}' , separator_char = '|' ) : """Override some character settings @ type opening _ char : str @ param opening _ char : Opening character . Default : ' { ' @ type closing _ char : str @ param closing _ char : Closing character . Default : ' } ' @ t...
global char_separator , char_opening , char_closing char_separator = separator_char char_opening = opening_char char_closing = closing_char
def expand ( self , basedir , config , sourcedir , targetdir , cwd ) : """Validate that given paths are not the same . Args : basedir ( string ) : Project base directory used to prepend relative paths . If empty or equal to ' . ' , it will be filled with current directory path . config ( string ) : Settin...
# Expand home directory if any expanded_basedir = os . path . expanduser ( basedir ) expanded_config = os . path . expanduser ( config ) expanded_sourcedir = os . path . expanduser ( sourcedir ) expanded_targetdir = os . path . expanduser ( targetdir ) # If not absolute , base dir is prepended with current directory if...
def load_agent ( self ) : """Loads and initializes an agent using instance variables , registers for quick chat and sets render functions . : return : An instance of an agent , and the agent class file ."""
agent_class = self . agent_class_wrapper . get_loaded_class ( ) agent = agent_class ( self . name , self . team , self . index ) agent . init_match_config ( self . match_config ) agent . load_config ( self . bot_configuration . get_header ( "Bot Parameters" ) ) self . update_metadata_queue ( agent ) self . set_render_m...
def add_bus ( self , bus ) : """Add a bus for notification . : param can . BusABC bus : CAN bus instance ."""
if self . _loop is not None and hasattr ( bus , 'fileno' ) and bus . fileno ( ) >= 0 : # Use file descriptor to watch for messages reader = bus . fileno ( ) self . _loop . add_reader ( reader , self . _on_message_available , bus ) else : reader = threading . Thread ( target = self . _rx_thread , args = ( bu...
def show ( data , negate = False ) : """Show the stretched data ."""
from PIL import Image as pil data = np . array ( ( data - data . min ( ) ) * 255.0 / ( data . max ( ) - data . min ( ) ) , np . uint8 ) if negate : data = 255 - data img = pil . fromarray ( data ) img . show ( )
def _GetDateValuesWithEpoch ( self , number_of_days , date_time_epoch ) : """Determines date values . Args : number _ of _ days ( int ) : number of days since epoch . date _ time _ epoch ( DateTimeEpoch ) : date and time of the epoch . Returns : tuple [ int , int , int ] : year , month , day of month ."""
return self . _GetDateValues ( number_of_days , date_time_epoch . year , date_time_epoch . month , date_time_epoch . day_of_month )
def _DeepCopy ( self , obj ) : """Creates an object copy by serializing / deserializing it . RDFStruct . Copy ( ) doesn ' t deep - copy repeated fields which may lead to hard to catch bugs . Args : obj : RDFValue to be copied . Returns : A deep copy of the passed RDFValue ."""
precondition . AssertType ( obj , rdfvalue . RDFValue ) return obj . __class__ . FromSerializedString ( obj . SerializeToString ( ) )
def add_edge ( self , u , v , key = None , attr_dict = None , ** attr ) : """Version of add _ edge that only writes to the database once ."""
if attr_dict is None : attr_dict = attr else : try : attr_dict . update ( attr ) except AttributeError : raise NetworkXError ( "The attr_dict argument must be a dictionary." ) if u not in self . node : self . node [ u ] = { } if v not in self . node : self . node [ v ] = { } if v in ...
def _property_detect_type ( name , values ) : '''Detect the datatype of a property'''
value_type = 'str' if values . startswith ( 'on | off' ) : value_type = 'bool' elif values . startswith ( 'yes | no' ) : value_type = 'bool_alt' elif values in [ '<size>' , '<size> | none' ] : value_type = 'size' elif values in [ '<count>' , '<count> | none' , '<guid>' ] : value_type = 'numeric' elif na...
def format_items ( self , data , many ) : """Format data as a Resource object or list of Resource objects . See : http : / / jsonapi . org / format / # document - resource - objects"""
if many : return [ self . format_item ( item ) for item in data ] else : return self . format_item ( data )
def add_filter ( self , filter_id , description ) : """Add a filter line to the header . Arguments : filter _ id ( str ) : The id of the filter line description ( str ) : A description of the info line"""
filter_line = '##FILTER=<ID={0},Description="{1}">' . format ( filter_id , description ) logger . info ( "Adding filter line to vcf: {0}" . format ( filter_line ) ) self . parse_meta_data ( filter_line ) return
def _latch_file_info ( self ) : """Internal function to update the dictionaries keeping track of input and output files"""
self . _map_arguments ( self . args ) self . files . latch_file_info ( self . args ) self . sub_files . file_dict . clear ( ) self . sub_files . update ( self . files . file_dict ) for link in self . _links . values ( ) : self . sub_files . update ( link . files . file_dict ) self . sub_files . update ( link . ...
def acknowledge_incident ( self , service_key , incident_key , description = None , details = None ) : """Causes the referenced incident to enter the acknowledged state . Send an acknowledge event when someone is presently working on the incident ."""
return self . create_event ( service_key , description , "acknowledge" , details , incident_key )
def install_package ( self , client , package ) : """Install package on instance ."""
install_cmd = "{sudo} '{install} {package}'" . format ( sudo = self . get_sudo_exec_wrapper ( ) , install = self . get_install_cmd ( ) , package = package ) try : out = ipa_utils . execute_ssh_command ( client , install_cmd ) except Exception as error : raise IpaDistroException ( 'An error occurred installing p...
def p_levelsig ( self , p ) : 'levelsig : levelsig _ base'
p [ 0 ] = Sens ( p [ 1 ] , 'level' , lineno = p . lineno ( 1 ) ) p . set_lineno ( 0 , p . lineno ( 1 ) )
def siget ( fullname = "" ) : """Returns a softimage object given its fullname ."""
fullname = str ( fullname ) if not len ( fullname ) : return None return sidict . GetObject ( fullname , False )
def delta ( var , key , tusec = None ) : '''calculate slope'''
global last_delta if tusec is not None : tnow = tusec * 1.0e-6 else : import mavutil tnow = mavutil . mavfile_global . timestamp dv = 0 ret = 0 if key in last_delta : ( last_v , last_t , last_ret ) = last_delta [ key ] if last_t == tnow : return last_ret if tnow == last_t : ret =...
def _normalized_serial ( self ) : """Normalized serial name for usage in log filename . Some Android emulators use ip : port as their serial names , while on Windows ` : ` is not valid in filename , it should be sanitized first ."""
if self . _serial is None : return None normalized_serial = self . _serial . replace ( ' ' , '_' ) normalized_serial = normalized_serial . replace ( ':' , '-' ) return normalized_serial
def obo ( self ) : """str : the ` Term ` serialized in an Obo ` ` [ Term ] ` ` stanza . Note : The following guide was used : ftp : / / ftp . geneontology . org / pub / go / www / GO . format . obo - 1_4 . shtml"""
def add_tags ( stanza_list , tags ) : for tag in tags : if tag in self . other : if isinstance ( self . other [ tag ] , list ) : for attribute in self . other [ tag ] : stanza_list . append ( "{}: {}" . format ( tag , attribute ) ) else : ...
def update_from_json ( self , path = join ( 'config' , 'hdx_dataset_static.json' ) ) : # type : ( str ) - > None """Update dataset metadata with static metadata from JSON file Args : path ( str ) : Path to JSON dataset metadata . Defaults to config / hdx _ dataset _ static . json . Returns : None"""
super ( Dataset , self ) . update_from_json ( path ) self . separate_resources ( )
def generate ( self , field_name , field ) : """Tries to lookup a matching formfield generator ( lowercase field - classname ) and raises a NotImplementedError of no generator can be found ."""
if hasattr ( self , 'generate_%s' % field . __class__ . __name__ . lower ( ) ) : generator = getattr ( self , 'generate_%s' % field . __class__ . __name__ . lower ( ) ) return generator ( field_name , field , ( field . verbose_name or field_name ) . capitalize ( ) ) else : raise NotImplementedError ( '%s is...
def export_image_to_uri ( self , image_id , uri , ibm_api_key = None ) : """Export image into the given object storage : param int image _ id : The ID of the image : param string uri : The URI for object storage of the format swift : / / < objectStorageAccount > @ < cluster > / < container > / < objectPath > ...
if 'cos://' in uri : return self . vgbdtg . copyToIcos ( { 'uri' : uri , 'ibmApiKey' : ibm_api_key } , id = image_id ) else : return self . vgbdtg . copyToExternalSource ( { 'uri' : uri } , id = image_id )
def should_highlight ( self , req ) : """Check the given argument parameter to decide if highlights needed . argument value is expected to be ' 0 ' or ' 1'"""
try : return bool ( req . args and int ( req . args . get ( 'es_highlight' , 0 ) ) ) except ( AttributeError , TypeError ) : return False
def subscribe ( self , feedUrl ) : """Adds a feed to the top - level subscription list Ubscribing seems idempotent , you can subscribe multiple times without error returns True or throws HTTPError"""
response = self . httpPost ( ReaderUrl . SUBSCRIPTION_EDIT_URL , { 'ac' : 'subscribe' , 's' : feedUrl } ) # FIXME - need better return API if response and 'OK' in response : return True else : return False
def igphyml ( input_file = None , tree_file = None , root = None , verbose = False ) : '''Computes a phylogenetic tree using IgPhyML . . . note : : IgPhyML must be installed . It can be downloaded from https : / / github . com / kbhoehn / IgPhyML . Args : input _ file ( str ) : Path to a Phylip - formatted ...
if shutil . which ( 'igphyml' ) is None : raise RuntimeError ( 'It appears that IgPhyML is not installed.\nPlease install and try again.' ) # first , tree topology is estimated with the M0 / GY94 model igphyml_cmd1 = 'igphyml -i {} -m GY -w M0 -t e --run_id gy94' . format ( aln_file ) p1 = sp . Popen ( igphyml_cmd1...
def clear_source ( self ) : """stub"""
if ( self . get_source_metadata ( ) . is_read_only ( ) or self . get_source_metadata ( ) . is_required ( ) ) : raise NoAccess ( ) self . my_osid_object_form . _my_map [ 'texts' ] [ 'source' ] = self . _source_metadata [ 'default_string_values' ] [ 0 ]
def accept_freeware_license ( ) : '''different Eagle versions need differnt TAB count . 6.5 - > 2 6.6 - > 3 7.4 - > 2'''
ntab = 3 if version ( ) . startswith ( '6.6.' ) else 2 for _ in range ( ntab ) : EasyProcess ( 'xdotool key KP_Tab' ) . call ( ) time . sleep ( 0.5 ) EasyProcess ( 'xdotool key KP_Space' ) . call ( ) time . sleep ( 0.5 ) # say OK to any more question EasyProcess ( 'xdotool key KP_Space' ) . call ( )
def add_circuit_breaker ( self , circ_breaker ) : """Creates circuit breaker object and . . . Args circ _ breaker : CircuitBreakerDing0 Description # TODO"""
if circ_breaker not in self . _circuit_breakers and isinstance ( circ_breaker , CircuitBreakerDing0 ) : self . _circuit_breakers . append ( circ_breaker ) self . graph_add_node ( circ_breaker )
def time ( self ) : """Returns numpy array of datetime . time . The time part of the Timestamps ."""
# If the Timestamps have a timezone that is not UTC , # convert them into their i8 representation while # keeping their timezone and not using UTC if self . tz is not None and not timezones . is_utc ( self . tz ) : timestamps = self . _local_timestamps ( ) else : timestamps = self . asi8 return tslib . ints_to_...
def _new_stream ( self , idx ) : '''Randomly select and create a new stream . Parameters idx : int , [ 0 : n _ streams - 1] The stream index to replace'''
# Don ' t activate the stream if the weight is 0 or None if self . stream_weights_ [ idx ] : self . streams_ [ idx ] = self . streamers [ idx ] . iterate ( ) else : self . streams_ [ idx ] = None # Reset the sample count to zero self . stream_counts_ [ idx ] = 0
def anonymous ( self ) : """Gets the anonymous handler . Also tries to grab a class if the ` anonymous ` value is a string , so that we can define anonymous handlers that aren ' t defined yet ( like , when you ' re subclassing your basehandler into an anonymous one . )"""
if hasattr ( self . handler , 'anonymous' ) : anon = self . handler . anonymous if callable ( anon ) : return anon for klass in typemapper . keys ( ) : if anon == klass . __name__ : return klass return None
def line ( self , text = '' ) : '''A simple helper to write line with ` \n `'''
self . out . write ( text ) self . out . write ( '\n' )
def input_variables ( self , exclude_specials = True ) : """Get all variables that have never been written to . : return : A list of variables that are never written to ."""
def has_write_access ( accesses ) : return any ( acc for acc in accesses if acc . access_type == 'write' ) def has_read_access ( accesses ) : return any ( acc for acc in accesses if acc . access_type == 'read' ) input_variables = [ ] for variable , accesses in self . _variable_accesses . items ( ) : if not ...
def _set_extended ( self , v , load = False ) : """Setter method for extended , mapped from YANG variable / ipv6 _ acl / ipv6 / access _ list / extended ( list ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ extended is considered as a private method . Backends look...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = YANGListType ( "name" , extended . extended , yang_name = "extended" , rest_name = "extended" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_helper , yang_keys = 'name' , extension...
def keyPressEvent ( self , event ) : """Overloads the key press event to control keystroke modifications for \ the console widget . : param event | < QKeyEvent >"""
# enter | | return keys will apply the command if event . key ( ) in ( Qt . Key_Return , Qt . Key_Enter ) : self . applyCommand ( ) event . accept ( ) # home key will move the cursor to the home position elif event . key ( ) == Qt . Key_Home : self . gotoHome ( ) event . accept ( ) elif event . key ( ) ...
def tqx ( mt , x , t ) : """nqx : Returns the probability to die within n years at age x"""
return ( mt . lx [ x ] - mt . lx [ x + t ] ) / mt . lx [ x ]
def import_assist ( self , starting ) : """Return a list of ` ` ( name , module ) ` ` tuples This function tries to find modules that have a global name that starts with ` starting ` ."""
# XXX : breaking if gave up ! use generators result = [ ] for module in self . names : for global_name in self . names [ module ] : if global_name . startswith ( starting ) : result . append ( ( global_name , module ) ) return result
def select ( self , domain_or_name , query = '' , next_token = None , consistent_read = False ) : """Returns a set of Attributes for item names within domain _ name that match the query . The query must be expressed in using the SELECT style syntax rather than the original SimpleDB query language . Even thoug...
domain , domain_name = self . get_domain_and_name ( domain_or_name ) params = { 'SelectExpression' : query } if consistent_read : params [ 'ConsistentRead' ] = 'true' if next_token : params [ 'NextToken' ] = next_token try : return self . get_list ( 'Select' , params , [ ( 'Item' , self . item_cls ) ] , par...
def _populate_field_defaults ( self ) : """Populate the defaults of each field . This is done in a separate pass because defaults that specify a union tag require the union to have been defined ."""
for namespace in self . api . namespaces . values ( ) : for data_type in namespace . data_types : # Only struct fields can have default if not isinstance ( data_type , Struct ) : continue for field in data_type . fields : if not field . _ast_node . has_default : ...
def log_status ( self ) : '''show download status'''
if self . download_filename is None : print ( "No download" ) return dt = time . time ( ) - self . download_start speed = os . path . getsize ( self . download_filename ) / ( 1000.0 * dt ) m = self . entries . get ( self . download_lognum , None ) if m is None : size = 0 else : size = m . size highest =...
def t_to_min ( x ) : """Convert XML ' xs : duration type ' to decimal minutes , e . g . : t _ to _ min ( ' PT1H2M30S ' ) = = 62.5"""
g = re . match ( 'PT(?:(.*)H)?(?:(.*)M)?(?:(.*)S)?' , x ) . groups ( ) return sum ( 0 if g [ i ] is None else float ( g [ i ] ) * 60. ** ( 1 - i ) for i in range ( 3 ) )
def get_ids ( self , request_data , parameter_name = 'ids' ) : """Extract a list of integers from request data ."""
if parameter_name not in request_data : raise ParseError ( "`{}` parameter is required" . format ( parameter_name ) ) ids = request_data . get ( parameter_name ) if not isinstance ( ids , list ) : raise ParseError ( "`{}` parameter not a list" . format ( parameter_name ) ) if not ids : raise ParseError ( "`...
def make_placeholders ( seq , start = 1 ) : """Generate placeholders for the given sequence ."""
if len ( seq ) == 0 : raise ValueError ( 'Sequence must have at least one element.' ) param_style = Context . current ( ) . param_style placeholders = None if isinstance ( seq , dict ) : if param_style in ( 'named' , 'pyformat' ) : template = ':%s' if param_style == 'named' else '%%(%s)s' placeh...
def update_xml_element ( self ) : """Updates the xml element contents to matches the instance contents : returns : Updated XML element : rtype : lxml . etree . _ Element"""
if not hasattr ( self , 'xml_element' ) : self . xml_element = etree . Element ( self . name , nsmap = NSMAP ) if hasattr ( self , 'time' ) : self . xml_element . set ( 'time' , self . time_to_str ( ) ) if hasattr ( self , 'update' ) : self . xml_element . set ( 'update' , str ( self . update ) ) self . xml...
def stop_process ( self ) : """Stop the process . : raises : EnvironmentError if stopping fails due to unknown environment TestStepError if process stops with non - default returncode and return code is not ignored ."""
if self . read_thread is not None : self . logger . debug ( "stop_process::readThread.stop()-in" ) self . read_thread . stop ( ) self . logger . debug ( "stop_process::readThread.stop()-out" ) returncode = None if self . proc : self . logger . debug ( "os.killpg(%d)" , self . proc . pid ) for sig in...
def find_matching_link ( self , mode , group , addr ) : """Find a matching link in the current device . Mode : r | c is the mode of the link in the linked device This method will search for a corresponding link in the reverse direction . group : All - Link group number addr : Inteon address of the linked ...
found_rec = None mode_test = None if mode . lower ( ) in [ 'c' , 'r' ] : link_group = int ( group ) link_addr = Address ( addr ) for mem_addr in self : rec = self [ mem_addr ] if mode . lower ( ) == 'r' : mode_test = rec . control_flags . is_controller else : ...
def add_records ( self , domain , records ) : """Adds the specified DNS records to a domain . : param domain : the domain to add the records to : param records : the records to add"""
url = self . API_TEMPLATE + self . RECORDS . format ( domain = domain ) self . _patch ( url , json = records ) self . logger . debug ( 'Added records @ {}' . format ( records ) ) # If we didn ' t get any exceptions , return True to let the user know return True
def add_affect ( self , name , src , dest , val , condition = None ) : """adds how param ' src ' affects param ' dest ' to the list"""
self . affects . append ( ParamAffects ( name , src , dest , val , condition ) )