signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def n_to_c ( self , var_n ) : """Given a parsed n . variant , return a c . variant on the specified transcript using the specified alignment method ( default is " transcript " indicating a self alignment ) . : param hgvs . sequencevariant . SequenceVariant var _ n : a variant object : returns : variant obje...
if not ( var_n . type == "n" ) : raise HGVSInvalidVariantError ( "Expected n. variant; got " + str ( var_n ) ) if self . _validator : self . _validator . validate ( var_n ) var_n . fill_ref ( self . hdp ) tm = self . _fetch_AlignmentMapper ( tx_ac = var_n . ac , alt_ac = var_n . ac , alt_aln_method = "transcrip...
def update_resource ( self , resource , filename , change = None ) : """Update resource from uri to filename on local system . Update means three things : 1 . GET resources 2 . set mtime in local time to be equal to timestamp in UTC ( should perhaps or at least warn if different from LastModified from the G...
path = os . path . dirname ( filename ) distutils . dir_util . mkpath ( path ) num_updated = 0 if ( self . dryrun ) : self . logger . info ( "dryrun: would GET %s --> %s" % ( resource . uri , filename ) ) else : # 1 . GET for try_i in range ( 1 , self . tries + 1 ) : try : r = requests . get...
def real_time_statistics ( self ) : """Access the real _ time _ statistics : returns : twilio . rest . taskrouter . v1 . workspace . workspace _ real _ time _ statistics . WorkspaceRealTimeStatisticsList : rtype : twilio . rest . taskrouter . v1 . workspace . workspace _ real _ time _ statistics . WorkspaceReal...
if self . _real_time_statistics is None : self . _real_time_statistics = WorkspaceRealTimeStatisticsList ( self . _version , workspace_sid = self . _solution [ 'sid' ] , ) return self . _real_time_statistics
def _configure_send ( self , request , ** kwargs ) : # type : ( ClientRequest , Any ) - > Dict [ str , str ] """Configure the kwargs to use with requests . See " send " for kwargs details . : param ClientRequest request : The request object to be sent . : returns : The requests . Session . request kwargs : ...
requests_kwargs = { } # type : Any session = kwargs . pop ( 'session' , self . session ) # If custom session was not create here if session is not self . session : self . _init_session ( session ) session . max_redirects = int ( self . config . redirect_policy ( ) ) session . trust_env = bool ( self . config . prox...
def get_items ( self , repository_id , project = None , scope_path = None , recursion_level = None , include_content_metadata = None , latest_processed_change = None , download = None , include_links = None , version_descriptor = None ) : """GetItems . [ Preview API ] Get Item Metadata and / or Content for a coll...
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) if repository_id is not None : route_values [ 'repositoryId' ] = self . _serialize . url ( 'repository_id' , repository_id , 'str' ) query_parameters = { } if scope_path is not None :...
def stop ( self , timeout = 15 ) : """Stop the subprocess . Keyword Arguments * * timeout * * Time in seconds to wait for a process and its children to exit ."""
pp = self . pid if pp : try : kill_process_nicely ( pp , timeout = timeout ) except psutil . NoSuchProcess : pass
def to_networkx ( self , labels = None , edge_labels = False ) : """Get a networkx representation of the binary search tree ."""
import networkx as nx graph = nx . DiGraph ( ) for node in self . _traverse_nodes ( ) : u = node . key graph . add_node ( u ) # Minor redundancy # Set node properties graph . nodes [ u ] [ 'value' ] = node . value if labels is not None : label = ',' . join ( [ str ( getattr ( node , k ) ...
def modify_instance_attribute ( self , instance_id , attribute , value ) : """Changes an attribute of an instance : type instance _ id : string : param instance _ id : The instance id you wish to change : type attribute : string : param attribute : The attribute you wish to change . * AttributeName - Expe...
# Allow a bool to be passed in for value of disableApiTermination if attribute == 'disableApiTermination' : if isinstance ( value , bool ) : if value : value = 'true' else : value = 'false' params = { 'InstanceId' : instance_id , 'Attribute' : attribute , 'Value' : value } re...
def query_neighbors ( self , nodes : List [ Node ] ) -> List [ Edge ] : """Get all edges incident to any of the given nodes ."""
return self . session . query ( Edge ) . filter ( self . _edge_one_node ( nodes ) ) . all ( )
def get_changeset ( args ) : """Dump the changeset objects as JSON , reading the provided bundle YAML . The YAML can be provided either from stdin or by passing a file path as first argument ."""
# Parse the arguments . parser = argparse . ArgumentParser ( description = get_changeset . __doc__ ) parser . add_argument ( 'infile' , nargs = '?' , type = argparse . FileType ( 'r' ) , default = sys . stdin , help = 'path to the bundle YAML file' ) parser . add_argument ( '--version' , action = 'version' , version = ...
def render ( self , renderer = None , ** kwargs ) : """Render the navigational item using a renderer . : param renderer : An object implementing the : class : ` ~ . Renderer ` interface . : return : A markupsafe string with the rendered result ."""
return Markup ( get_renderer ( current_app , renderer ) ( ** kwargs ) . visit ( self ) )
def search_for_devices_by_serial_number ( self , sn ) : """Returns a list of device objects that match the serial number in param ' sn ' . This will match partial serial numbers ."""
import re sn_search = re . compile ( sn ) matches = [ ] for dev_o in self . get_all_devices_in_portal ( ) : # print ( " Checking { 0 } " . format ( dev _ o [ ' sn ' ] ) ) try : if sn_search . match ( dev_o [ 'sn' ] ) : matches . append ( dev_o ) except TypeError as err : print ( "Pro...
def _loglikelihood ( self , y , mu , weights = None , rescale_y = True ) : """compute the log - likelihood of the dataset using the current model Parameters y : array - like of shape ( n , ) containing target values mu : array - like of shape ( n _ samples , ) expected value of the targets given the model...
if rescale_y : y = np . round ( y * weights ) . astype ( 'int' ) return self . distribution . log_pdf ( y = y , mu = mu , weights = weights ) . sum ( )
def retrieve_ocsps ( self , cert , issuer ) : """: param cert : An asn1crypto . x509 . Certificate object : param issuer : An asn1crypto . x509 . Certificate object of cert ' s issuer : return : A list of asn1crypto . ocsp . OCSPResponse objects"""
if not self . _allow_fetching : return self . _ocsps if cert . issuer_serial not in self . _fetched_ocsps : try : ocsp_response = ocsp_client . fetch ( cert , issuer , ** self . _ocsp_fetch_params ) self . _fetched_ocsps [ cert . issuer_serial ] = [ ocsp_response ] # Responses can contai...
def endline_handle ( self , original , loc , tokens ) : """Add line number information to end of line ."""
internal_assert ( len ( tokens ) == 1 , "invalid endline tokens" , tokens ) lines = tokens [ 0 ] . splitlines ( True ) if self . minify : lines = lines [ 0 ] out = [ ] ln = lineno ( loc , original ) for endline in lines : out . append ( self . wrap_line_number ( self . adjust ( ln ) ) + endline ) ln += 1 re...
def start_transports ( self ) : """start thread transports ."""
self . transport = Transport ( self . queue , self . batch_size , self . batch_interval , self . session_factory ) thread = threading . Thread ( target = self . transport . loop ) self . threads . append ( thread ) thread . daemon = True thread . start ( )
def _represent_undefined ( self , data ) : """Raises flag for objects that cannot be represented"""
raise RepresenterError ( _format ( "Cannot represent an object: {0!A} of type: {1}; " "yaml_representers: {2!A}, " "yaml_multi_representers: {3!A}" , data , type ( data ) , self . yaml_representers . keys ( ) , self . yaml_multi_representers . keys ( ) ) )
def ensure_open ( f , mode = 'r' ) : r"""Return a file pointer using gzip . open if filename ends with . gz otherwise open ( ) TODO : try to read a gzip rather than relying on gz extension , likewise for zip and other formats TODO : monkey patch the file so that . write _ bytes = . write and . write writes both...
fin = f if isinstance ( f , basestring ) : if len ( f ) <= MAX_LEN_FILEPATH : f = find_filepath ( f ) or f if f and ( not hasattr ( f , 'seek' ) or not hasattr ( f , 'readlines' ) ) : if f . lower ( ) . endswith ( '.gz' ) : return gzip . open ( f , mode = mode ) ...
def ip_address ( ) : """Get the IP address used for public connections ."""
s = socket . socket ( socket . AF_INET , socket . SOCK_DGRAM ) # 8.8.8.8 is the google public DNS s . connect ( ( "8.8.8.8" , 53 ) ) ip = s . getsockname ( ) [ 0 ] s . close ( ) return ip
def fromTerm ( cls , term ) : """Create a functor from a Term or term handle ."""
if isinstance ( term , Term ) : term = term . handle elif not isinstance ( term , ( c_void_p , int ) ) : raise ArgumentTypeError ( ( str ( Term ) , str ( int ) ) , str ( type ( term ) ) ) f = functor_t ( ) if PL_get_functor ( term , byref ( f ) ) : # get args args = [ ] arity = PL_functor_arity ( f . va...
def vprintf ( self , alevel , format , * args ) : '''A verbosity - aware printf .'''
if self . _verbosity and self . _verbosity >= alevel : sys . stdout . write ( format % args )
def pop_row ( self , idr = None , tags = False ) : """Pops a row , default the last"""
idr = idr if idr is not None else len ( self . body ) - 1 row = self . body . pop ( idr ) return row if tags else [ cell . childs [ 0 ] for cell in row ]
def _get_host_ref ( service_instance , host , host_name = None ) : '''Helper function that returns a host object either from the host location or the host _ name . If host _ name is provided , that is the host _ object that will be returned . The function will first search for hosts by DNS Name . If no hosts ar...
search_index = salt . utils . vmware . get_inventory ( service_instance ) . searchIndex # First , try to find the host reference by DNS Name . if host_name : host_ref = search_index . FindByDnsName ( dnsName = host_name , vmSearch = False ) else : host_ref = search_index . FindByDnsName ( dnsName = host , vmSea...
def map_vnics ( vm ) : """maps the vnic on the vm by name : param vm : virtual machine : return : dictionary : { ' vnic _ name ' : vnic }"""
return { device . deviceInfo . label : device for device in vm . config . hardware . device if isinstance ( device , vim . vm . device . VirtualEthernetCard ) }
def _filter_packages ( self ) : """Run the package filtering plugins and remove any packages from the packages _ to _ sync that match any filters . - Logging of action will be done within the check _ match methods"""
global LOG_PLUGINS filter_plugins = filter_project_plugins ( ) if not filter_plugins : if LOG_PLUGINS : logger . info ( "No project filters are enabled. Skipping filtering" ) LOG_PLUGINS = False return # Make a copy of self . packages _ to _ sync keys # as we may delete packages during iteration...
def _notify_single_item ( self , item ) : """Route inbound items to individual channels"""
# channels that this individual item has already triggered # ( dont want to trigger them again ) triggered_channels = set ( ) for key_set in self . watch_keys : # only pluck keys if they exist plucked = { key_name : item [ key_name ] for key_name in key_set if key_name in item } route_keys = expand_dict_as_keys...
def write ( self , bucket , rows ) : """https : / / github . com / frictionlessdata / tableschema - pandas - py # storage"""
# Prepare descriptor = self . describe ( bucket ) new_data_frame = self . __mapper . convert_descriptor_and_rows ( descriptor , rows ) # Just set new DataFrame if current is empty if self . __dataframes [ bucket ] . size == 0 : self . __dataframes [ bucket ] = new_data_frame # Append new data frame to the old one s...
def register_channel ( model_class , search_fields = ( ) ) : """Register channel for model : param model _ class : model to register channel for : param search _ fields : : return :"""
if len ( search_fields ) == 0 : search_fields = get_fields_with_icontains_filter ( model_class ) channel_class = type ( model_class . __name__ + "LookupChannel" , ( AutoLookupChannelBase , ) , { "model" : model_class , "dynamical_search_fields" : search_fields , } ) channel_name = class_name_to_low_case ( model_cla...
def classify ( self , text = u'' ) : """Predicts the Language of a given text . : param text : Unicode text to be classified ."""
text = self . lm . normalize ( text ) tokenz = LM . tokenize ( text , mode = 'c' ) result = self . lm . calculate ( doc_terms = tokenz ) # print ' Karbasa : ' , self . karbasa ( result ) if self . unk and self . lm . karbasa ( result ) < self . min_karbasa : lang = 'unk' else : lang = result [ 'calc_id' ] retur...
def resolve_structure ( self , fc , ct ) : """Resolve structure specifications ."""
if self . debug : print ( "++++++++ Resolving structure of (%s) with %s" % ( fc , ct ) ) for w in ct . structure . withs : try : if w . instance == 'parent' or w . instance == 'this' : w2 = With ( w . instance , w . as_ ) else : w2 = With ( fc . paths [ w . instance ] . v...
def addAnswers ( self , answers , callback = None , errback = None , ** kwargs ) : """Add answers to the record . : param answers : answers structure . See the class note on answer format ."""
if not self . data : raise RecordException ( 'record not loaded' ) orig_answers = self . data [ 'answers' ] new_answers = self . _rest . _getAnswersForBody ( answers ) orig_answers . extend ( new_answers ) return self . update ( answers = orig_answers , callback = callback , errback = errback , ** kwargs )
def _create_cadvisor_prometheus_instance ( self , instance ) : """Create a copy of the instance and set default values . This is so the base class can create a scraper _ config with the proper values ."""
cadvisor_instance = deepcopy ( instance ) cadvisor_instance . update ( { 'namespace' : self . NAMESPACE , # We need to specify a prometheus _ url so the base class can use it as the key for our config _ map , # we specify a dummy url that will be replaced in the ` check ( ) ` function . We append it with " cadvisor " #...
def _set_view ( self ) : """Assign a view to current graph"""
if self . logarithmic : view_class = PolarLogView else : view_class = PolarView self . view = view_class ( self . width - self . margin_box . x , self . height - self . margin_box . y , self . _box )
def wait_for_any_log ( nodes , pattern , timeout , filename = 'system.log' , marks = None ) : """Look for a pattern in the system . log of any in a given list of nodes . @ param nodes The list of nodes whose logs to scan @ param pattern The target pattern @ param timeout How long to wait for the pattern . N...
if marks is None : marks = { } for _ in range ( timeout ) : for node in nodes : found = node . grep_log ( pattern , filename = filename , from_mark = marks . get ( node , None ) ) if found : return node time . sleep ( 1 ) raise TimeoutError ( time . strftime ( "%d %b %Y %H:%M:%S"...
def tx_max ( tasmax , freq = 'YS' ) : r"""Highest max temperature The maximum value of daily maximum temperature . Parameters tasmax : xarray . DataArray Maximum daily temperature [ ° C ] or [ K ] freq : str , optional Resampling frequency Returns xarray . DataArray Maximum value of daily maximum ...
return tasmax . resample ( time = freq ) . max ( dim = 'time' , keep_attrs = True )
def laplace ( affinity_matrix , shi_malik_type = False ) : """Converts affinity matrix into normalised graph Laplacian , for spectral clustering . ( At least ) two forms exist : L = ( D ^ - 0.5 ) . A . ( D ^ - 0.5 ) - default L = ( D ^ - 1 ) . A - ` Shi - Malik ` type , from Shi Malik paper"""
diagonal = affinity_matrix . sum ( axis = 1 ) - affinity_matrix . diagonal ( ) zeros = diagonal <= 1e-10 diagonal [ zeros ] = 1 if ( diagonal <= 1e-10 ) . any ( ) : # arbitrarily small value raise ZeroDivisionError if shi_malik_type : inv_d = np . diag ( 1 / diagonal ) return inv_d . dot ( affinity_matrix )...
def block ( self , * args , ** kwargs ) : """Call the wrapped function , and wait for the result in a blocking fashion Returns the result of the function call . : param args : : param kwargs : : return : result of function call"""
LOG . debug ( '%s on %s (awaitable %s async %s provider %s)' , 'blocking' , self . _func , self . _is_awaitable , self . _is_asyncio_provider , self . _concurrency_provider ) if self . _deferable : raise RuntimeError ( 'Already activated this call by deferring it' ) with self . _lock : if not hasattr ( self , '...
def arith_prog_term ( a , n , d ) : """Function to compute the n - th term of an Arithmetic Progression ( AP ) . The n - th term " Tn " of an AP where " a " is the first term , and " d " the common difference , is computed using the formula : Tn = a + ( n - 1 ) * d Examples : arith _ prog _ term ( 1 , 5 , 2...
term = ( a + ( ( n - 1 ) * d ) ) return term
def auto_labels ( df ) : """Transforms atomic system information into well - formatted labels . Parameters df : Pandas DataFrame . Returns labels : list of system labels ."""
systems = list ( df . system ) facets = list ( df . facet ) systems_labels = [ w . replace ( '_' , '\ ' ) for w in systems ] systems_labels = [ sub ( w ) for w in systems_labels ] systems_labels = [ w . replace ( '}$$_{' , '' ) for w in systems_labels ] systems_labels = [ w . replace ( '$' , '' ) for w in systems_label...
def match_string ( pattern , search_string ) : '''Match a pattern in a string'''
rexobj = REX ( pattern , None ) rexpatstr = reformat_pattern ( pattern ) # print " rexpatstr : " , rexpatstr rexpat = re . compile ( rexpatstr ) rexobj . rex_patternstr = rexpatstr rexobj . rex_pattern = rexpat line_count = 1 for line in search_string . splitlines ( ) : line = line . strip ( ) mobj = rexpat . m...
def print_summary ( self ) -> None : """Prints the tasks ' timing summary ."""
print ( "Tasks execution time summary:" ) for mon_task in self . _monitor_tasks : print ( "%s:\t%.4f (sec)" % ( mon_task . task_name , mon_task . total_time ) )
def _get_model_fitting ( self , mf_id ) : """Retreive model fitting with identifier ' mf _ id ' from the list of model fitting objects stored in self . model _ fitting"""
for model_fitting in self . model_fittings : if model_fitting . activity . id == mf_id : return model_fitting raise Exception ( "Model fitting activity with id: " + str ( mf_id ) + " not found." )
def cli ( env ) : """Server order options for a given chassis ."""
hardware_manager = hardware . HardwareManager ( env . client ) options = hardware_manager . get_create_options ( ) tables = [ ] # Datacenters dc_table = formatting . Table ( [ 'datacenter' , 'value' ] ) dc_table . sortby = 'value' for location in options [ 'locations' ] : dc_table . add_row ( [ location [ 'name' ] ...
def get_driver_class ( provider ) : """Return the driver class : param provider : str - provider name : return :"""
if "." in provider : parts = provider . split ( '.' ) kls = parts . pop ( ) path = '.' . join ( parts ) module = import_module ( path ) if not hasattr ( module , kls ) : raise ImportError ( '{0} provider not found at {1}' . format ( kls , path ) ) driver = getattr ( module , kls ) else :...
def vn_free_ar ( call = None , kwargs = None ) : '''Frees a reserved address range from a virtual network . . . versionadded : : 2016.3.0 vn _ id The ID of the virtual network from which to free an address range . Can be used instead of ` ` vn _ name ` ` . vn _ name The name of the virtual network from ...
if call != 'function' : raise SaltCloudSystemExit ( 'The vn_free_ar function must be called with -f or --function.' ) if kwargs is None : kwargs = { } vn_id = kwargs . get ( 'vn_id' , None ) vn_name = kwargs . get ( 'vn_name' , None ) ar_id = kwargs . get ( 'ar_id' , None ) if ar_id is None : raise SaltClou...
def callback ( self , filename , lines , ** kwargs ) : """publishes lines one by one to the given topic"""
timestamp = self . get_timestamp ( ** kwargs ) if kwargs . get ( 'timestamp' , False ) : del kwargs [ 'timestamp' ] for line in lines : try : import warnings with warnings . catch_warnings ( ) : warnings . simplefilter ( 'error' ) # produce message if self . _...
def join ( self , other , on = None , how = 'left' , lsuffix = None , rsuffix = None , algorithm = 'merge' , is_on_sorted = True , is_on_unique = True ) : """Database - like join this DataFrame with the other DataFrame . Currently assumes the ` on ` columns are sorted and the on - column ( s ) values are unique !...
check_type ( lsuffix , str ) check_type ( rsuffix , str ) self_names = self . _gather_column_names ( ) other_names = other . _gather_column_names ( ) common_names = set ( self_names ) . intersection ( set ( other_names ) ) if len ( common_names ) > 0 and lsuffix is None and rsuffix is None : raise ValueError ( 'Col...
def get_trust ( self ) : """Gets the ` ` Trust ` ` for this authorization . return : ( osid . authentication . process . Trust ) - the ` ` Trust ` ` raise : IllegalState - ` ` has _ trust ( ) ` ` is ` ` false ` ` raise : OperationFailed - unable to complete request * compliance : mandatory - - This method m...
# Implemented from template for osid . resource . Resource . get _ avatar _ template if not bool ( self . _my_map [ 'trustId' ] ) : raise errors . IllegalState ( 'this Authorization has no trust' ) mgr = self . _get_provider_manager ( 'AUTHENTICATION.PROCESS' ) if not mgr . supports_trust_lookup ( ) : raise err...
def showSegmentation ( segmentation , voxelsize_mm = np . ones ( [ 3 , 1 ] ) , degrad = 4 , label = 1 , smoothing = True ) : """Funkce vrací trojrozměrné porobné jako data [ ' segmentation ' ] v data [ ' slab ' ] je popsáno , co která hodnota znamená"""
labels = [ ] segmentation = segmentation [ : : degrad , : : degrad , : : degrad ] # import pdb ; pdb . set _ trace ( ) mesh_data = seg2fem . gen_mesh_from_voxels_mc ( segmentation , voxelsize_mm * degrad ) if smoothing : mesh_data . coors = seg2fem . smooth_mesh ( mesh_data ) else : mesh_data = seg2fem . gen_me...
def get_params ( self ) : """Get parameters from this object"""
params = super ( ) . get_params ( ) params . update ( { 'knn' : self . knn , 'decay' : self . decay , 'bandwidth' : self . bandwidth , 'bandwidth_scale' : self . bandwidth_scale , 'distance' : self . distance , 'thresh' : self . thresh , 'n_jobs' : self . n_jobs , 'random_state' : self . random_state , 'verbose' : self...
def queue_get_stoppable ( self , q ) : """Take obj from queue , but will give up when the thread is stopped"""
while not self . stopped ( ) : try : return q . get ( timeout = 5 ) except queue . Empty : pass
def safe_mult ( a , b ) : """safe version of multiply"""
if isinstance ( a , str ) and isinstance ( b , int ) and len ( a ) * b > MAX_STR_LEN : raise RuntimeError ( "String length exceeded, max string length is {}" . format ( MAX_STR_LEN ) ) return a * b
def get_github_login ( self , user , rol , commit_hash , repo ) : """rol : author or committer"""
login = None try : login = self . github_logins [ user ] except KeyError : # Get the login from github API GITHUB_API_URL = "https://api.github.com" commit_url = GITHUB_API_URL + "/repos/%s/commits/%s" % ( repo , commit_hash ) headers = { 'Authorization' : 'token ' + self . github_token } r = self ....
def listen ( self , topic , timeout = 1 , limit = 1 ) : """Listen to a topic and return a list of message payloads received within the specified time . Requires an async Subscribe to have been called previously . ` topic ` topic to listen to ` timeout ` duration to listen ` limit ` the max number of payload...
if not self . _subscribed : logger . warn ( 'Cannot listen when not subscribed to a topic' ) return [ ] if topic not in self . _messages : logger . warn ( 'Cannot listen when not subscribed to topic: %s' % topic ) return [ ] # If enough messages have already been gathered , return them if limit != 0 and...
def add ( self , artifact_type : ArtifactType , src_path : str , dst_path : str = None ) : """Add an artifact of type ` artifact _ type ` at ` src _ path ` . ` src _ path ` should be the path of the file relative to project root . ` dst _ path ` , if given , is the desired path of the artifact in dependent ta...
if dst_path is None : dst_path = src_path other_src_path = self . _artifacts [ artifact_type ] . setdefault ( dst_path , src_path ) if src_path != other_src_path : raise RuntimeError ( '{} artifact with dest path {} exists with different src ' 'path: {} != {}' . format ( artifact_type , dst_path , src_path , ot...
def prep_connection ( self , creds = None , keyspace = None , node_auto_discovery = True ) : """Do login and set _ keyspace tasks as necessary , and also check this node ' s idea of the Cassandra ring . Expects that our connection is alive . Return a Deferred that will fire with the ring information , or be ...
d = defer . succeed ( None ) if creds is not None : d . addCallback ( lambda _ : self . my_login ( creds ) ) if keyspace is not None : d . addCallback ( lambda _ : self . my_set_keyspace ( keyspace ) ) if node_auto_discovery : d . addCallback ( lambda _ : self . my_describe_ring ( keyspace ) ) return d
def compute ( self , inputs , outputs ) : """Run one iteration of TemporalPoolerRegion ' s compute . Note that if the reset signal is True ( 1 ) we assume this iteration represents the * end * of a sequence . The output will contain the pooled representation to this point and any history will then be reset . ...
resetSignal = False if 'resetIn' in inputs : if len ( inputs [ 'resetIn' ] ) != 1 : raise Exception ( "resetIn has invalid length" ) if inputs [ 'resetIn' ] [ 0 ] != 0 : resetSignal = True outputs [ "mostActiveCells" ] [ : ] = numpy . zeros ( self . _columnCount , dtype = GetNTAReal ( ) ) if sel...
def decompressBlocks ( self , startBlock , endBlock ) : '''This is mostly a helper function to get BWT range , but I wanted it to be a separate thing for use possibly in decompression @ param startBlock - the index of the start block we will decode @ param endBlock - the index of the final block we will decod...
expectedIndex = startBlock * self . binSize trueIndex = np . sum ( self . partialFM [ startBlock ] ) - self . offsetSum dist = expectedIndex - trueIndex # find the end of the region of interest startRange = self . refFM [ startBlock ] if endBlock >= self . refFM . shape [ 0 ] - 1 : endRange = self . bwt . shape [ 0...
def fetchable_partitions ( self ) : """Return set of TopicPartitions that should be Fetched ."""
fetchable = set ( ) for partition , state in six . iteritems ( self . assignment ) : if state . is_fetchable ( ) : fetchable . add ( partition ) return fetchable
def attention_bias_local_2d_block ( mesh , h_dim , w_dim , memory_h_dim , memory_w_dim , dtype = tf . int32 ) : """Bias for attention for local blocks where attention to right is disallowed . Create the bias matrix by using two separate masks , one for the memory part which doesn ' t overlap with the query and ...
memory_height = mtf . Dimension ( memory_h_dim . name , h_dim . size ) memory_width = mtf . Dimension ( memory_w_dim . name , w_dim . size ) mask_top_visible = mtf . zeros ( mesh , [ h_dim , memory_height ] , dtype = dtype ) mask_left_visible = mtf . zeros ( mesh , [ w_dim , memory_width ] , dtype = dtype ) mask_query ...
def show_as_root_until_keypress ( self , w , key , afterwards = None ) : """Replaces root widget by given : class : ` urwid . Widget ` and makes the UI ignore all further commands apart from cursor movement . If later on ` key ` is pressed , the old root widget is reset , callable ` afterwards ` is called and...
self . mainloop . widget = w self . _unlock_key = key self . _unlock_callback = afterwards self . _locked = True
def check_param_ranges ( num_bins , num_groups , num_values , trim_outliers , trim_percentile ) : """Ensuring the parameters are in valid ranges ."""
if num_bins < minimum_num_bins : raise ValueError ( 'Too few bins! The number of bins must be >= 5' ) if num_values < num_groups : raise ValueError ( 'Insufficient number of values in features (< number of nodes), or invalid membership!' ) if trim_outliers : if trim_percentile < 0 or trim_percentile >= 100 ...
def apply ( self , func , ** kwargs ) : """apply the function to my values ; return a block if we are not one"""
with np . errstate ( all = 'ignore' ) : result = func ( self . values , ** kwargs ) if not isinstance ( result , Block ) : result = self . make_block ( values = _block_shape ( result , ndim = self . ndim ) ) return result
def install_custom_css ( destdir , cssfile , resource = PKGNAME ) : """Add the kernel CSS to custom . css"""
ensure_dir_exists ( destdir ) custom = os . path . join ( destdir , 'custom.css' ) prefix = css_frame_prefix ( resource ) # Check if custom . css already includes it . If so , let ' s remove it first exists = False if os . path . exists ( custom ) : with io . open ( custom ) as f : for line in f : ...
def select_with_main_images ( self , limit = None , ** kwargs ) : '''Select all objects with filters passed as kwargs . For each object it ' s main image instance is accessible as ` ` object . main _ image ` ` . Results can be limited using ` ` limit ` ` parameter . Selection is performed using only 2 or 3 sq...
objects = self . get_query_set ( ) . filter ( ** kwargs ) [ : limit ] self . image_model_class . injector . inject_to ( objects , 'main_image' , is_main = True ) return objects
def query ( searchstr , outformat = FORMAT_BIBTEX , allresults = False ) : """Query google scholar . This method queries google scholar and returns a list of citations . Parameters searchstr : str the query outformat : int , optional the output format of the citations . Default is bibtex . allresults ...
logger . debug ( "Query: {sstring}" . format ( sstring = searchstr ) ) searchstr = '/scholar?q=' + quote ( searchstr ) url = GOOGLE_SCHOLAR_URL + searchstr header = HEADERS header [ 'Cookie' ] = "GSP=CF=%d" % outformat request = Request ( url , headers = header ) response = urlopen ( request ) html = response . read ( ...
def help ( subcommand = None ) : """Print help for subcommands . Prints the help text for the specified subcommand . If subcommand is not specified , prints one - line summaries for every command ."""
if not subcommand : print ( "blurb version" , __version__ ) print ( ) print ( "Management tool for CPython Misc/NEWS and Misc/NEWS.d entries." ) print ( ) print ( "Usage:" ) print ( " blurb [subcommand] [options...]" ) print ( ) # print list of subcommands summaries = [ ] long...
async def get ( self , key , param = None , extend_herd_timeout = None ) : """Use key or identity generate from key and param to get cached content and expire time . Compare expire time with time . now ( ) , return None and set cache with extended timeout if cache is expired , else , return unpacked content...
identity = self . _gen_identity ( key , param ) res = await self . client . get ( identity ) if res : res , timeout = self . _unpack ( res ) now = int ( time . time ( ) ) if timeout <= now : extend_timeout = extend_herd_timeout or self . extend_herd_timeout expected_expired_ts = now + extend...
def main ( ) : '''Example code , showing the instantiation of a ChebiEntity , a call to get _ name ( ) , get _ outgoings ( ) and the calling of a number of methods of the returned Relation objects .'''
chebi_entity = ChebiEntity ( 15903 ) print ( chebi_entity . get_name ( ) ) for outgoing in chebi_entity . get_outgoings ( ) : target_chebi_entity = ChebiEntity ( outgoing . get_target_chebi_id ( ) ) print ( outgoing . get_type ( ) + '\t' + target_chebi_entity . get_name ( ) )
def _prepare_insert ( self , tmpl , record_class , field_names , placeholder_for_id = False ) : """With transaction isolation level of " read committed " this should generate records with a contiguous sequence of integer IDs , assumes an indexed ID column , the database - side SQL max function , the insert - ...
field_names = list ( field_names ) if hasattr ( record_class , 'application_name' ) and 'application_name' not in field_names : field_names . append ( 'application_name' ) if hasattr ( record_class , 'pipeline_id' ) and 'pipeline_id' not in field_names : field_names . append ( 'pipeline_id' ) if hasattr ( recor...
def get_active_title ( ) : '''returns the window title of the active window'''
if os . name == 'posix' : cmd = [ 'xdotool' , 'getactivewindow' , 'getwindowname' ] proc = subprocess . Popen ( cmd , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) title = proc . communicate ( ) [ 0 ] . decode ( 'utf-8' ) else : raise NotImplementedError return title
def as_dataframe ( self , fillna = True , subjects = None ) : """Return association set as pandas DataFrame Each row is a subject ( e . g . gene ) Each column is the inferred class used to describe the subject"""
entries = [ ] selected_subjects = self . subjects if subjects is not None : selected_subjects = subjects for s in selected_subjects : vmap = { } for c in self . inferred_types ( s ) : vmap [ c ] = 1 entries . append ( vmap ) logging . debug ( "Creating DataFrame" ) df = pd . DataFrame ( entries ...
def _set_secondary_path ( self , v , load = False ) : """Setter method for secondary _ path , mapped from YANG variable / mpls _ config / router / mpls / mpls _ cmds _ holder / lsp / secondary _ path ( list ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ secondary _ p...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = YANGListType ( "secpath_name" , secondary_path . secondary_path , yang_name = "secondary-path" , rest_name = "secondary-path" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_helper ...
def on_invite ( self , connection , event ) : """Got an invitation to a channel"""
sender = self . get_nick ( event . source ) invited = self . get_nick ( event . target ) channel = event . arguments [ 0 ] if invited == self . _nickname : logging . info ( "! I am invited to %s by %s" , channel , sender ) connection . join ( channel ) else : logging . info ( ">> %s invited %s to %s" , send...
def fnmatches ( entry , * pattern_list ) : """returns true if entry matches any of the glob patterns , false otherwise"""
for pattern in pattern_list : if pattern and fnmatch ( entry , pattern ) : return True return False
def add_new ( self , command ) : """Add a new entry to the queue ."""
self . queue [ self . next_key ] = command self . queue [ self . next_key ] [ 'status' ] = 'queued' self . queue [ self . next_key ] [ 'returncode' ] = '' self . queue [ self . next_key ] [ 'stdout' ] = '' self . queue [ self . next_key ] [ 'stderr' ] = '' self . queue [ self . next_key ] [ 'start' ] = '' self . queue ...
def transform ( self , Xs ) : """Transports source samples Xs onto target ones Xt Parameters Xs : array - like , shape ( n _ source _ samples , n _ features ) The training input samples . Returns transp _ Xs : array - like , shape ( n _ source _ samples , n _ features ) The transport source samples ."""
# check the necessary inputs parameters are here if check_params ( Xs = Xs ) : if np . array_equal ( self . xs_ , Xs ) : # perform standard barycentric mapping transp = self . coupling_ / np . sum ( self . coupling_ , 1 ) [ : , None ] # set nans to 0 transp [ ~ np . isfinite ( transp ) ] = 0...
def register_nonzero_counter ( network , stats ) : """Register forward hooks to count the number of nonzero floating points values from all the tensors used by the given network during inference . : param network : The network to attach the counter : param stats : Dictionary holding the counter ."""
if hasattr ( network , "__counter_nonzero__" ) : raise ValueError ( "nonzero counter was already registered for this network" ) if not isinstance ( stats , dict ) : raise ValueError ( "stats must be a dictionary" ) network . __counter_nonzero__ = stats handles = [ ] for name , module in network . named_modules ...
def writeChunk ( self , stream , filename , chunkIdx = None ) : """Streams an uploaded chunk to a file . : param stream : the binary stream that contains the file . : param filename : the name of the file . : param chunkIdx : optional chunk index ( for writing to a tmp dir ) : return : no of bytes written o...
import io more = True outputFileName = filename if chunkIdx is None else filename + '.' + str ( chunkIdx ) outputDir = self . _uploadDir if chunkIdx is None else self . _tmpDir chunkFilePath = os . path . join ( outputDir , outputFileName ) if os . path . exists ( chunkFilePath ) and os . path . isfile ( chunkFilePath ...
def disable ( name , stop = False , ** kwargs ) : '''Don ' t start service ` ` name ` ` at boot Returns ` ` True ` ` if operation is successful name the service ' s name stop if True , also stops the service CLI Example : . . code - block : : bash salt ' * ' service . disable < name > [ stop = True ...
# non - existent as registrered service if not enabled ( name ) : return False # down _ file : file that prevent sv autostart svc_realpath = _get_svc_path ( name ) [ 0 ] down_file = os . path . join ( svc_realpath , 'down' ) if stop : stop ( name ) if not os . path . exists ( down_file ) : try : sal...
def ExecutePackage ( self , package_id , parameters = { } ) : """Execute an existing Bluerprint package on the server . https : / / t3n . zendesk . com / entries / 59727040 - Execute - Package Requires package ID , currently only available by browsing control and browsing for the package itself . The UUID par...
return ( clc . v2 . Requests ( clc . v2 . API . Call ( 'POST' , 'operations/%s/servers/executePackage' % ( self . alias ) , json . dumps ( { 'servers' : [ self . id ] , 'package' : { 'packageId' : package_id , 'parameters' : parameters } } ) , session = self . session ) , alias = self . alias , session = self . session...
def _cursorLeft ( self ) : """Handles " cursor left " events"""
if self . cursorPos > 0 : self . cursorPos -= 1 sys . stdout . write ( console . CURSOR_LEFT ) sys . stdout . flush ( )
def laplacian_calculation ( mesh , equal_weight = True ) : """Calculate a sparse matrix for laplacian operations . Parameters mesh : trimesh . Trimesh Input geometry equal _ weight : bool If True , all neighbors will be considered equally If False , all neightbors will be weighted by inverse distance ...
# get the vertex neighbors from the cache neighbors = mesh . vertex_neighbors # avoid hitting crc checks in loops vertices = mesh . vertices . view ( np . ndarray ) # stack neighbors to 1D arrays col = np . concatenate ( neighbors ) row = np . concatenate ( [ [ i ] * len ( n ) for i , n in enumerate ( neighbors ) ] ) i...
def evaluate ( data_eval , model , nsp_loss , mlm_loss , vocab_size , ctx , log_interval , dtype ) : """Evaluation function ."""
mlm_metric = MaskedAccuracy ( ) nsp_metric = MaskedAccuracy ( ) mlm_metric . reset ( ) nsp_metric . reset ( ) eval_begin_time = time . time ( ) begin_time = time . time ( ) step_num = 0 running_mlm_loss = running_nsp_loss = 0 total_mlm_loss = total_nsp_loss = 0 running_num_tks = 0 for _ , dataloader in enumerate ( data...
def get_env_macros ( self , data ) : """Get all environment macros from data For each object in data : : * Fetch all macros in object . _ _ class _ _ . macros * Fetch all customs macros in o . custom : param data : data to get macro : type data : : return : dict with macro name as key and macro value as...
env = { } for obj in data : cls = obj . __class__ macros = cls . macros for macro in macros : if macro . startswith ( "USER" ) : continue prop = macros [ macro ] value = self . _get_value_from_element ( obj , prop ) env [ '%s%s' % ( self . env_prefix , macro ) ] =...
def add_showanswer ( self , showanswer ) : """stub"""
if showanswer is None : raise NullArgument ( 'showanswer cannot be None' ) if not self . my_osid_object_form . _is_valid_string ( showanswer , self . get_showanswer_metadata ( ) ) : raise InvalidArgument ( 'showanswer' ) self . my_osid_object_form . _my_map [ 'showanswer' ] = showanswer
def get_stp_mst_detail_output_cist_port_configured_path_cost ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_stp_mst_detail = ET . Element ( "get_stp_mst_detail" ) config = get_stp_mst_detail output = ET . SubElement ( get_stp_mst_detail , "output" ) cist = ET . SubElement ( output , "cist" ) port = ET . SubElement ( cist , "port" ) configured_path_cost = ET . SubElement ( port , "config...
def model_to_owl ( model , fname ) : """Save a BioPAX model object as an OWL file . Parameters model : org . biopax . paxtools . model . Model A BioPAX model object ( java object ) . fname : str The name of the OWL file to save the model in ."""
io_class = autoclass ( 'org.biopax.paxtools.io.SimpleIOHandler' ) io = io_class ( autoclass ( 'org.biopax.paxtools.model.BioPAXLevel' ) . L3 ) try : fileOS = autoclass ( 'java.io.FileOutputStream' ) ( fname ) except JavaException : logger . error ( 'Could not open data file %s' % fname ) return l3_factory =...
def dof ( self ) : """Returns the DoF of the robot ( with grippers ) ."""
dof = self . mujoco_robot . dof if self . has_gripper_left : dof += self . gripper_left . dof if self . has_gripper_right : dof += self . gripper_right . dof return dof
def load_cache ( ) : """Load cache from the disk . Return : set : Deserialized data from disk ."""
if not os . path . exists ( settings . DUP_FILTER_FILE ) : return set ( ) with open ( settings . DUP_FILTER_FILE ) as f : return set ( json . loads ( f . read ( ) ) )
def _subscription_thread ( self , endpoint ) : """Thread Method , running the connection for each endpoint . : param endpoint : : return :"""
try : conn = create_connection ( self . addr + endpoint , timeout = 5 ) except WebSocketTimeoutException : self . restart_q . put ( endpoint ) return while self . threads_running [ endpoint ] : try : msg = conn . recv ( ) except WebSocketTimeoutException : self . _controller_q . put ...
def add_custom_options ( parser ) : """Adds custom options to a parser . : param parser : the parser to which to add options . : type parser : argparse . ArgumentParser"""
parser . add_argument ( "--outliers-of" , type = str , metavar = "POP" , default = "CEU" , choices = [ "CEU" , "YRI" , "JPT-CHB" ] , help = ( "Finds the outliers of this population. " "[default: %(default)s]" ) ) parser . add_argument ( "--multiplier" , type = float , metavar = "FLOAT" , default = 1.9 , help = ( "To fi...
def success_response ( self , method_resp , ** kw ) : """Make a standard " success " response , which contains some ancilliary data . Also , detect if this node is too far behind the Bitcoin blockchain , and if so , convert this into an error message ."""
resp = { 'status' : True , 'indexing' : config . is_indexing ( self . working_dir ) , 'lastblock' : virtualchain_hooks . get_last_block ( self . working_dir ) , } resp . update ( kw ) resp . update ( method_resp ) if self . is_stale ( ) : # our state is stale resp [ 'stale' ] = True resp [ 'warning' ] = 'Daemon...
def count ( self , func ) : """Counts the number of elements in the sequence which satisfy the predicate func . > > > seq ( [ - 1 , - 2 , 1 , 2 ] ) . count ( lambda x : x > 0) : param func : predicate to count elements on : return : count of elements that satisfy predicate"""
n = 0 for element in self : if func ( element ) : n += 1 return n
def getInterval ( self , alpha ) : """Evaluate the interval corresponding to a C . L . of ( 1 - alpha ) % . Parameters alpha : limit confidence level ."""
dlnl = twosided_cl_to_dlnl ( 1.0 - alpha ) lo_lim = self . getDeltaLogLike ( dlnl , upper = False ) hi_lim = self . getDeltaLogLike ( dlnl , upper = True ) return ( lo_lim , hi_lim )
def _exclude_ss_bonded_cysteines ( self ) : """Pre - compute ss bonds to discard cystines for H - adding ."""
ss_bonds = self . nh_structure . search_ss_bonds ( ) for cys_pair in ss_bonds : cys1 , cys2 = cys_pair cys1 . resname = 'CYX' cys2 . resname = 'CYX'
def guess_payload_class ( self , payload ) : """the type of the payload encapsulation is given be the outer TZSP layers attribute encapsulation _ protocol # noqa : E501"""
under_layer = self . underlayer tzsp_header = None while under_layer : if isinstance ( under_layer , TZSP ) : tzsp_header = under_layer break under_layer = under_layer . underlayer if tzsp_header : return tzsp_header . get_encapsulated_payload_class ( ) else : raise TZSPStructureExceptio...
def check_entry ( self , entries , * args , ** kwargs ) : """With a list of entries , check each entry against every other"""
verbosity = kwargs . get ( 'verbosity' , 1 ) user_total_overlaps = 0 user = '' for index_a , entry_a in enumerate ( entries ) : # Show the name the first time through if index_a == 0 : if args and verbosity >= 1 or verbosity >= 2 : self . show_name ( entry_a . user ) user = entry_a ....
def reqNewsArticle ( self , providerCode : str , articleId : str , newsArticleOptions : List [ TagValue ] = None ) -> NewsArticle : """Get the body of a news article . This method is blocking . https : / / interactivebrokers . github . io / tws - api / news . html Args : providerCode : Code indicating news ...
return self . _run ( self . reqNewsArticleAsync ( providerCode , articleId , newsArticleOptions ) )
def _get_first_urn ( self , urn ) : """Provisional route for GetFirstUrn request : param urn : URN to filter the resource : param inv : Inventory Identifier : return : GetFirstUrn response"""
urn = URN ( urn ) subreference = None textId = urn . upTo ( URN . NO_PASSAGE ) if urn . reference is not None : subreference = str ( urn . reference ) firstId = self . resolver . getTextualNode ( textId = textId , subreference = subreference ) . firstId r = render_template ( "cts/GetFirstUrn.xml" , firstId = firstI...