signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def remove_child ( self , child ) : '''Remove child from ` ` Node ` ` object Args : ` ` child ` ` ( ` ` Node ` ` ) : The child to remove'''
if not isinstance ( child , Node ) : raise TypeError ( "child must be a Node" ) try : self . children . remove ( child ) ; child . parent = None except : raise RuntimeError ( "Attempting to remove non-existent child" )
def convert_block_dicts_to_string ( self , block_1st2nd , block_1st , block_2nd , block_3rd ) : """Takes into account whether we need to output all codon positions ."""
out = "" # We need 1st and 2nd positions if self . codon_positions in [ 'ALL' , '1st-2nd' ] : for gene_code , seqs in block_1st2nd . items ( ) : out += '>{0}_1st-2nd\n----\n' . format ( gene_code ) for seq in seqs : out += seq elif self . codon_positions == '1st' : for gene_code , se...
def add ( self , component : Union [ Component , Sequence [ Component ] ] ) -> None : """Add a widget to the grid in the next available cell . Searches over columns then rows for available cells . Parameters components : bowtie . _ Component A Bowtie widget instance ."""
try : self [ Span ( * self . _available_cell ( ) ) ] = component except NoUnusedCellsError : span = list ( self . _spans . keys ( ) ) [ - 1 ] self . _spans [ span ] += component
def draw_no_data ( self ) : """Write the no data text to the svg"""
no_data = self . node ( self . graph . nodes [ 'text_overlay' ] , 'text' , x = self . graph . view . width / 2 , y = self . graph . view . height / 2 , class_ = 'no_data' ) no_data . text = self . graph . no_data_text
def itermovieshash ( self ) : """Iterate over movies hash stored in the database ."""
cur = self . _db . firstkey ( ) while cur is not None : yield cur cur = self . _db . nextkey ( cur )
def bsp_traverse_inverted_level_order ( node : tcod . bsp . BSP , callback : Callable [ [ tcod . bsp . BSP , Any ] , None ] , userData : Any = 0 , ) -> None : """Traverse this nodes hierarchy with a callback . . . deprecated : : 2.0 Use : any : ` BSP . inverted _ level _ order ` instead ."""
_bsp_traverse ( node . inverted_level_order ( ) , callback , userData )
def predict_topk ( self , dataset , output_type = "probability" , k = 3 , missing_value_action = 'auto' ) : """Return top - k predictions for the ` ` dataset ` ` , using the trained model . Predictions are returned as an SFrame with three columns : ` id ` , ` class ` , and ` probability ` , ` margin ` , or ` ra...
_check_categorical_option_type ( 'output_type' , output_type , [ 'rank' , 'margin' , 'probability' ] ) if missing_value_action == 'auto' : missing_value_action = _sl . select_default_missing_value_policy ( self , 'predict' ) # Low latency path if isinstance ( dataset , list ) : return self . __proxy__ . fast_pr...
def execute_locally ( self ) : """Runs the equivalent command locally in a blocking way ."""
# Make script file # self . make_script ( ) # Do it # with open ( self . kwargs [ 'out_file' ] , 'w' ) as handle : sh . python ( self . script_path , _out = handle , _err = handle )
def get_app_voice ( self , item ) : """App voice Returns the js menu compatible voice dict if the user can see it , None otherwise"""
if item . get ( 'name' , None ) is None : raise ImproperlyConfigured ( 'App menu voices must have a name key' ) if self . check_apps_permission ( [ item . get ( 'name' , None ) ] ) : children = [ ] if item . get ( 'models' , None ) is None : for name , model in self . apps_dict [ item . get ( 'name'...
def on_change ( self , server_description ) : """Process a new ServerDescription after an ismaster call completes ."""
# We do no I / O holding the lock . with self . _lock : # Monitors may continue working on ismaster calls for some time # after a call to Topology . close , so this method may be called at # any time . Ensure the topology is open before processing the # change . # Any monitored server was definitely in the topology des...
def escalate_incident ( self , incident , update_mask = None , subscriptions = None , tags = None , roles = None , artifacts = None , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , metadata = None , ) : """Escalates an incident . Example : >...
# Wrap the transport method to add retry and timeout logic . if "escalate_incident" not in self . _inner_api_calls : self . _inner_api_calls [ "escalate_incident" ] = google . api_core . gapic_v1 . method . wrap_method ( self . transport . escalate_incident , default_retry = self . _method_configs [ "EscalateIncide...
def InitPathInfos ( self , client_id , path_infos ) : """Initializes a collection of path info records for a client . Unlike ` WritePathInfo ` , this method clears stat and hash histories of paths associated with path info records . This method is intended to be used only in the data migration scripts . Arg...
self . ClearPathHistory ( client_id , path_infos ) self . WritePathInfos ( client_id , path_infos )
def run ( ) : # pylint : disable = too - many - branches """Main thread runner for all Duts . : return : Nothing"""
Dut . _logger . debug ( "Start DUT communication" , extra = { 'type' : '<->' } ) while Dut . _run : Dut . _sem . acquire ( ) try : dut = Dut . _signalled_duts . pop ( ) # Check for pending requests if dut . waiting_for_response is not None : item = dut . waiting_for_response ...
def plot ( self , dimension ) : """Plot barcode using matplotlib ."""
import matplotlib . pyplot as plt life_lines = self . get_life_lines ( dimension ) x , y = zip ( * life_lines ) plt . scatter ( x , y ) plt . xlabel ( "Birth" ) plt . ylabel ( "Death" ) if self . max_life is not None : plt . xlim ( [ 0 , self . max_life ] ) plt . title ( "Persistence Homology Dimension {}" . format...
def _make_tempy_tag ( self , tag , attrs , void ) : """Searches in tempy . tags for the correct tag to use , if does not exists uses the TempyFactory to create a custom tag ."""
tempy_tag_cls = getattr ( self . tempy_tags , tag . title ( ) , None ) if not tempy_tag_cls : unknow_maker = [ self . unknown_tag_maker , self . unknown_tag_maker . Void ] [ void ] tempy_tag_cls = unknow_maker [ tag ] attrs = { Tag . _TO_SPECIALS . get ( k , k ) : v or True for k , v in attrs } tempy_tag = temp...
def trans_history ( self , from_ = None , count = None , from_id = None , end_id = None , order = None , since = None , end = None ) : """Returns the history of transactions . To use this method you need a privilege of the info key . : param int or None from _ : transaction ID , from which the display starts ( ...
return self . _trade_api_call ( 'TransHistory' , from_ = from_ , count = count , from_id = from_id , end_id = end_id , order = order , since = since , end = end )
def validate ( retval , func , args ) : # type : ( int , Any , Tuple [ Any , Any ] ) - > Optional [ Tuple [ Any , Any ] ] """Validate the returned value of a Xlib or XRANDR function ."""
if retval != 0 and not ERROR . details : return args err = "{}() failed" . format ( func . __name__ ) details = { "retval" : retval , "args" : args } raise ScreenShotError ( err , details = details )
def qdii ( self , min_volume = 0 ) : """以字典形式返回QDII数据 : param min _ volume : 最小交易量 , 单位万元"""
# 添加当前的ctime self . __qdii_url = self . __qdii_url . format ( ctime = int ( time . time ( ) ) ) # 请求数据 rep = requests . get ( self . __qdii_url ) # 获取返回的json字符串 fundjson = json . loads ( rep . text ) # 格式化返回的json字符串 data = self . formatjisilujson ( fundjson ) data = { x : y for x , y in data . items ( ) if y [ "notes" ...
def split_conditional ( property ) : """If ' property ' is conditional property , returns condition and the property , e . g < variant > debug , < toolset > gcc : < inlining > full will become < variant > debug , < toolset > gcc < inlining > full . Otherwise , returns empty string ."""
assert isinstance ( property , basestring ) m = __re_split_conditional . match ( property ) if m : return ( m . group ( 1 ) , '<' + m . group ( 2 ) ) return None
def allowed_values ( self ) : """Return a list of allowed values ."""
if self . _allowed_values is None : self . _allowed_values = ValueList ( ) for val in self . scraper . _fetch_allowed_values ( self ) : if isinstance ( val , DimensionValue ) : self . _allowed_values . append ( val ) else : self . _allowed_values . append ( DimensionValue...
def _build_option_description ( k ) : """Builds a formatted description of a registered option and prints it ."""
o = _get_registered_option ( k ) d = _get_deprecated_option ( k ) buf = [ '{} ' . format ( k ) ] if o . doc : doc = '\n' . join ( o . doc . strip ( ) . splitlines ( ) ) else : doc = 'No description available.' buf . append ( doc ) if o : buf . append ( '\n [default: {}] [currently: {}]' . format ( o . de...
def _validate_unarmor ( self , certs , var_name ) : """Takes a list of byte strings or asn1crypto . x509 . Certificates objects , validates and loads them while unarmoring any PEM - encoded contents : param certs : A list of byte strings or asn1crypto . x509 . Certificate objects : param var _ name : A un...
output = [ ] for cert in certs : if isinstance ( cert , x509 . Certificate ) : output . append ( cert ) else : if not isinstance ( cert , byte_cls ) : raise TypeError ( pretty_message ( ''' %s must contain only byte strings or asn1crypt...
def ceiling_height ( self , value = 99999.0 ) : """Corresponds to IDD Field ` ceiling _ height ` This is the value for ceiling height in m . ( 77777 is unlimited ceiling height . 88888 is cirroform ceiling . ) It is not currently used in EnergyPlus calculations . Args : value ( float ) : value for IDD Fie...
if value is not None : try : value = float ( value ) except ValueError : raise ValueError ( 'value {} need to be of type float ' 'for field `ceiling_height`' . format ( value ) ) self . _ceiling_height = value
def is_transition_metal ( self ) : """True if element is a transition metal ."""
ns = list ( range ( 21 , 31 ) ) ns . extend ( list ( range ( 39 , 49 ) ) ) ns . append ( 57 ) ns . extend ( list ( range ( 72 , 81 ) ) ) ns . append ( 89 ) ns . extend ( list ( range ( 104 , 113 ) ) ) return self . Z in ns
def enrich_pubmed_citations ( manager , graph , group_size : Optional [ int ] = None , sleep_time : Optional [ int ] = None , ) -> Set [ str ] : """Overwrite all PubMed citations with values from NCBI ' s eUtils lookup service . Sets authors as list , so probably a good idea to run : func : ` pybel _ tools . muta...
pmids = get_pubmed_identifiers ( graph ) pmid_data , errors = get_citations_by_pmids ( manager , pmids = pmids , group_size = group_size , sleep_time = sleep_time ) for u , v , k in filter_edges ( graph , has_pubmed ) : pmid = graph [ u ] [ v ] [ k ] [ CITATION ] [ CITATION_REFERENCE ] . strip ( ) if pmid not i...
def get_branch_details ( repo : GithubRepository , branch : str ) -> Any : """References : https : / / developer . github . com / v3 / repos / branches / # get - branch"""
url = ( "https://api.github.com/repos/{}/{}/branches/{}" "?access_token={}" . format ( repo . organization , repo . name , branch , repo . access_token ) ) response = requests . get ( url ) if response . status_code != 200 : raise RuntimeError ( 'Failed to get branch details. Code: {}. Content: {}.' . format ( resp...
def set_file_path ( self , filePath ) : """Set the file path that needs to be locked . : Parameters : # . filePath ( None , path ) : The file that needs to be locked . When given and a lock is acquired , the file will be automatically opened for writing or reading depending on the given mode . If None is gi...
if filePath is not None : assert isinstance ( filePath , basestring ) , "filePath must be None or string" filePath = str ( filePath ) self . __filePath = filePath
def setProperty ( self , orgresource , protect , dummy = 7046 ) : """SetProperty Args : orgresource : File path protect : ' Y ' or ' N ' , 중요 표시 Returns : Integer number : # of version list False : Failed to get property"""
url = nurls [ 'setProperty' ] data = { 'userid' : self . user_id , 'useridx' : self . useridx , 'orgresource' : orgresource , 'protect' : protect , 'dummy' : dummy , } r = self . session . post ( url = url , data = data ) return resultManager ( r . text )
def save ( self , obj ) : """save an object : param obj : the object : return : the saved object"""
if obj not in self . session : self . session . add ( obj ) else : obj = self . session . merge ( obj ) self . session . flush ( ) self . session . refresh ( obj ) return obj
def frame_from_firmware ( self , firmware ) : '''extract information from firmware , return pretty string to user'''
# see Tools / scripts / generate - manifest for this map : frame_to_mavlink_dict = { "quad" : "QUADROTOR" , "hexa" : "HEXAROTOR" , "y6" : "ARDUPILOT_Y6" , "tri" : "TRICOPTER" , "octa" : "OCTOROTOR" , "octa-quad" : "ARDUPILOT_OCTAQUAD" , "heli" : "HELICOPTER" , "Plane" : "FIXED_WING" , "Tracker" : "ANTENNA_TRACKER" , "R...
def domain_urlize ( value ) : """Returns an HTML link to the supplied URL , but only using the domain as the text . Strips ' www . ' from the start of the domain , if present . e . g . if ` my _ url ` is ' http : / / www . example . org / foo / ' then : { { my _ url | domain _ urlize } } returns : < a hre...
parsed_uri = urlparse ( value ) domain = '{uri.netloc}' . format ( uri = parsed_uri ) if domain . startswith ( 'www.' ) : domain = domain [ 4 : ] return format_html ( '<a href="{}" rel="nofollow">{}</a>' , value , domain )
def mapstr_to_list ( mapstr ) : """Convert an ASCII map string with rows to a list of strings , 1 string per row ."""
maplist = [ ] with StringIO ( mapstr ) as infile : for row in infile : maplist . append ( row . strip ( ) ) return maplist
def _init_humidity ( self ) : """Internal . Initialises the humidity sensor via RTIMU"""
if not self . _humidity_init : self . _humidity_init = self . _humidity . humidityInit ( ) if not self . _humidity_init : raise OSError ( 'Humidity Init Failed' )
def get_precision ( self ) : """: returns : the ratio part of the dominant label for each unit . : rtype : 2D : class : ` numpy . ndarray `"""
assert self . classifier is not None , 'not calibrated' arr = np . zeros ( ( self . _som . nrows , self . _som . ncols ) ) for ij , ( lbl , p ) in self . classifier . items ( ) : arr [ ij ] = p return arr
def get_access_token ( tenant_id , application_id , application_secret ) : '''get an Azure access token using the adal library . Args : tenant _ id ( str ) : Tenant id of the user ' s account . application _ id ( str ) : Application id of a Service Principal account . application _ secret ( str ) : Applicat...
context = adal . AuthenticationContext ( get_auth_endpoint ( ) + tenant_id , api_version = None ) token_response = context . acquire_token_with_client_credentials ( get_resource_endpoint ( ) , application_id , application_secret ) return token_response . get ( 'accessToken' )
def unescape ( s , quote = False ) : """The opposite of the cgi . escape function . Replace escaped characters ' & amp ; ' , ' & lt ; ' and ' & gt ; ' with the corresponding regular characters . If the optional flag quote is true , the escaped quotation mark character ( ' & quot ; ' ) is also translated ."""
s = s . replace ( '&lt;' , '<' ) s = s . replace ( '&gt;' , '>' ) if quote : s = s . replace ( '&quot;' , '"' ) s = s . replace ( '&amp;' , '&' ) return s
def remove_empties ( variable ) : """Remove empty objects from the * variable * ' s attrs ."""
import h5py for key , val in variable . attrs . items ( ) : if isinstance ( val , h5py . _hl . base . Empty ) : variable . attrs . pop ( key ) return variable
def InferUserAndSubjectFromUrn ( self ) : """Infers user name and subject urn from self . urn ."""
_ , cron_str , cron_job_name , user , _ = self . urn . Split ( 5 ) if cron_str != "cron" : raise access_control . UnauthorizedAccess ( "Approval object has invalid urn %s." % self . urn , requested_access = self . token . requested_access ) return ( user , aff4 . ROOT_URN . Add ( "cron" ) . Add ( cron_job_name ) )
def get_forum ( self ) : """Returns the forum to consider ."""
if not hasattr ( self , 'forum' ) : self . forum = get_object_or_404 ( Forum , pk = self . kwargs [ 'pk' ] ) return self . forum
def radiance2tb ( self , rad ) : """Get the Tb from the radiance using the simple non - linear regression method . rad : Radiance in units = ' mW / m ^ 2 sr ^ - 1 ( cm ^ - 1 ) ^ - 1'"""
# Tb = C2 * νc / { α * log [ C1 * νc * * 3 / L + 1 ] } - β / α # C1 = 2 * h * c * * 2 and C2 = hc / k c_1 = 2 * H_PLANCK * C_SPEED ** 2 c_2 = H_PLANCK * C_SPEED / K_BOLTZMANN vc_ = SEVIRI [ self . bandname ] [ self . platform_name ] [ 0 ] # Multiply by 100 to get SI units ! vc_ *= 100.0 alpha = SEVIRI [ self . bandname...
def nvmlDeviceGetBridgeChipInfo ( handle ) : r"""* Get Bridge Chip Information for all the bridge chips on the board . * For all fully supported products . * Only applicable to multi - GPU products . * @ param device The identifier of the target device * @ param bridgeHierarchy Reference to the returned bri...
bridgeHierarchy = c_nvmlBridgeChipHierarchy_t ( ) fn = _nvmlGetFunctionPointer ( "nvmlDeviceGetBridgeChipInfo" ) ret = fn ( handle , byref ( bridgeHierarchy ) ) _nvmlCheckReturn ( ret ) return bytes_to_str ( bridgeHierarchy )
def cancel ( self ) : """Cancel the consumer and clean up resources associated with it . Consumers that are canceled are allowed to finish processing any messages before halting . Returns : defer . Deferred : A deferred that fires when the consumer has finished processing any message it was in the middle ...
# Remove it from protocol and factory so it doesn ' t restart later . try : del self . _protocol . _consumers [ self . queue ] except ( KeyError , AttributeError ) : pass try : del self . _protocol . factory . _consumers [ self . queue ] except ( KeyError , AttributeError ) : pass # Signal to the _ read...
def get_dip ( self ) : """Return the fault dip as the average dip over the mesh . The average dip is defined as the weighted mean inclination of all the mesh cells . See : meth : ` openquake . hazardlib . geo . mesh . RectangularMesh . get _ mean _ inclination _ and _ azimuth ` : returns : The average dip...
# uses the same approach as in simple fault surface if self . dip is None : mesh = self . mesh self . dip , self . strike = mesh . get_mean_inclination_and_azimuth ( ) return self . dip
def all_pkgs ( self ) : """Return a list of all packages ."""
if not self . packages : self . packages = self . get_pkg_list ( ) return self . packages
def format ( self , record ) : '''Format the log record to include exc _ info if the handler is enabled for a specific log level'''
formatted_record = super ( ExcInfoOnLogLevelFormatMixIn , self ) . format ( record ) exc_info_on_loglevel = getattr ( record , 'exc_info_on_loglevel' , None ) exc_info_on_loglevel_formatted = getattr ( record , 'exc_info_on_loglevel_formatted' , None ) if exc_info_on_loglevel is None and exc_info_on_loglevel_formatted ...
def parse_emails ( self , email_filename , index = 0 ) : """Generator function that parse and extract emails from the file ` email _ filename ` starting from the position ` index ` . Yield : An instance of ` mailbox . mboxMessage ` for each email in the file ."""
self . log ( "Parsing email dump: %s." % email_filename ) mbox = mailbox . mbox ( email_filename , factory = CustomMessage ) # Get each email from mbox file # The following implementation was used because the object # mbox does not support slicing . Converting the object to a # tuple ( as represented in the code down h...
def available_backups ( self ) : """The backups response contains what backups are available to be restored ."""
if not hasattr ( self , '_avail_backups' ) : result = self . _client . get ( "{}/backups" . format ( Instance . api_endpoint ) , model = self ) if not 'automatic' in result : raise UnexpectedResponseError ( 'Unexpected response loading available backups!' , json = result ) automatic = [ ] for a ...
def get_shell ( pid = None , max_depth = 6 ) : """Get the shell that the supplied pid or os . getpid ( ) is running in ."""
if not pid : pid = os . getpid ( ) processes = dict ( _iter_process ( ) ) def check_parent ( pid , lvl = 0 ) : ppid = processes [ pid ] . get ( 'parent_pid' ) shell_name = _get_executable ( processes . get ( ppid ) ) if shell_name in SHELL_NAMES : return ( shell_name , processes [ ppid ] [ 'exec...
def get_status_job ( self , id_job , hub = None , group = None , project = None , access_token = None , user_id = None ) : """Get the status about a job , by its id"""
if access_token : self . req . credential . set_token ( access_token ) if user_id : self . req . credential . set_user_id ( user_id ) if not self . check_credentials ( ) : respond = { } respond [ "status" ] = 'Error' respond [ "error" ] = "Not credentials valid" return respond if not id_job : ...
def stopwatch_now ( ) : """Get a timevalue for interval comparisons When possible it is a monotonic clock to prevent backwards time issues ."""
if six . PY2 : now = time . time ( ) else : now = time . monotonic ( ) return now
def load_plugins ( self ) : """Load external plugins . Custodian is intended to interact with internal and external systems that are not suitable for embedding into the custodian code base ."""
try : from pkg_resources import iter_entry_points except ImportError : return for ep in iter_entry_points ( group = "custodian.%s" % self . plugin_type ) : f = ep . load ( ) f ( )
def keys ( self , desc = None ) : '''numpy asarray does not copy data'''
res = asarray ( self . rc ( 'index' ) ) if desc == True : return reversed ( res ) else : return res
def sexagesimal ( sexathang , latlon , form = 'DDD' ) : """Arguments : sexathang : ( float ) , - 15.560615 ( negative = South ) , - 146.241122 ( negative = West ) # Apataki Carenage latlon : ( str ) ' lat ' | ' lon ' form : ( str ) , ' DDD ' | ' DMM ' | ' DMS ' , decimal Degrees , decimal Minutes , decimal Se...
cardinal = 'O' if not isinstance ( sexathang , float ) : sexathang = 'n/a' return sexathang if latlon == 'lon' : if sexathang > 0.0 : cardinal = 'E' if sexathang < 0.0 : cardinal = 'W' if latlon == 'lat' : if sexathang > 0.0 : cardinal = 'N' if sexathang < 0.0 : c...
def _expand_sources ( sources ) : '''Expands a user - provided specification of source files into a list of paths .'''
if sources is None : return [ ] if isinstance ( sources , six . string_types ) : sources = [ x . strip ( ) for x in sources . split ( ',' ) ] elif isinstance ( sources , ( float , six . integer_types ) ) : sources = [ six . text_type ( sources ) ] return [ path for source in sources for path in _glob ( sour...
def export_serving ( model_path ) : """Export trained model to use it in TensorFlow Serving or cloudML ."""
pred_config = PredictConfig ( session_init = get_model_loader ( model_path ) , model = InferenceOnlyModel ( ) , input_names = [ 'input_img_bytes' ] , output_names = [ 'prediction_img_bytes' ] ) ModelExporter ( pred_config ) . export_serving ( '/tmp/exported' )
def clear_cache ( m , files_processed ) : """Remove any files we may have uploaded from the cache ."""
for what , reason , url , path in files_processed : cp = m . doc . downloader . cache_path ( url ) if m . cache . exists ( cp ) : m . cache . remove ( cp )
def create_from_textgrid ( self , word_list ) : """Fills the ParsedResponse object with a list of TextGrid . Word objects originally from a . TextGrid file . : param list word _ list : List of TextGrid . Word objects corresponding to words / tokens in the subject response . Modifies : - self . timing _ includ...
self . timing_included = True for i , entry in enumerate ( word_list ) : self . unit_list . append ( Unit ( entry , format = "TextGrid" , type = self . type , index_in_timed_response = i ) ) # combine compound words , remove pluralizations , etc if self . type == "SEMANTIC" : self . lemmatize ( ) self . tok...
def logout ( self , command = 'exit' , note = None , echo = None , timeout = shutit_global . shutit_global_object . default_timeout , nonewline = False , loglevel = logging . DEBUG ) : """Logs the user out . Assumes that login has been called . If login has never been called , throw an error . @ param command :...
shutit_global . shutit_global_object . yield_to_draw ( ) shutit_pexpect_session = self . get_current_shutit_pexpect_session ( ) return shutit_pexpect_session . logout ( ShutItSendSpec ( shutit_pexpect_session , send = command , note = note , timeout = timeout , nonewline = nonewline , loglevel = loglevel , echo = echo ...
def _process_qtls_genetic_location ( self , raw , txid , common_name , limit = None ) : """This function processes Triples created : : param limit : : return :"""
aql_curie = self . files [ common_name + '_cm' ] [ 'curie' ] if self . test_mode : graph = self . testgraph else : graph = self . graph line_counter = 0 geno = Genotype ( graph ) model = Model ( graph ) eco_id = self . globaltt [ 'quantitative trait analysis evidence' ] taxon_curie = 'NCBITaxon:' + txid LOG . i...
def optimize ( self , start = None , n = 2 ) : """Run multidimensional scaling on this distance matrix . Args : start ( ` None ` or ` array - like ` ) : Starting coordinates . If ` start = None ` , random starting coordinates are used . If ` array - like ` must have shape [ ` m ` * ` n ` , ] . n ( ` int `...
self . n = n if start is None : start = np . random . rand ( self . m * self . n ) * 10 optim = minimize ( fun = self . _error_and_gradient , x0 = start , jac = True , method = 'L-BFGS-B' ) index = self . index if hasattr ( self , "index" ) else None return Projection . from_optimize_result ( result = optim , n = s...
def check_filters ( filters ) : """Execute range _ check for every element of an iterable . Parameters filters : iterable The collection of filters to check . Each element must be a two - element tuple of floats or ints . Returns The input as - is , or None if it evaluates to False . Raises ValueErr...
if not filters : return None try : return [ range_check ( f [ 0 ] , f [ 1 ] ) for f in filters ] except ValueError as err : raise ValueError ( "Error in --filter: " + py23_str ( err ) )
def _cancel_grpc ( operations_stub , operation_name ) : """Cancel an operation using a gRPC client . Args : operations _ stub ( google . longrunning . operations _ pb2 . OperationsStub ) : The gRPC operations stub . operation _ name ( str ) : The name of the operation ."""
request_pb = operations_pb2 . CancelOperationRequest ( name = operation_name ) operations_stub . CancelOperation ( request_pb )
def set_autosession ( self , value = None ) : """Turn autosession ( automatic committing after each modification call ) on / off . If value is None , only query the current value ( don ' t change anything ) ."""
if value is not None : self . rollback ( ) self . autosession = value return self . autosession
def start_capture ( self , * ports ) : """Start capture on ports . : param ports : list of ports to start capture on , if empty start on all ports ."""
IxeCapture . current_object = None IxeCaptureBuffer . current_object = None if not ports : ports = self . ports . values ( ) for port in ports : port . captureBuffer = None port_list = self . set_ports_list ( * ports ) self . api . call_rc ( 'ixStartCapture {}' . format ( port_list ) )
def _get_parent ( self ) : """: return : Remote origin as Proxy instance"""
_dir = os . path . dirname ( self . path ) if is_repo ( _dir ) : return Local ( _dir ) else : return None
def run ( self ) : """Run formula balance command"""
# Create a set of excluded reactions exclude = set ( self . _args . exclude ) count = 0 unbalanced = 0 unchecked = 0 for reaction , result in formula_balance ( self . _model ) : count += 1 if reaction . id in exclude or reaction . equation is None : continue if result is None : unchecked += ...
def r2deriv ( self , R , z , phi = 0. , t = 0. ) : """NAME : r2deriv PURPOSE : evaluate the second spherical radial derivative INPUT : R - Cylindrical Galactocentric radius ( can be Quantity ) z - vertical height ( can be Quantity ) phi - azimuth ( optional ; can be Quantity ) t - time ( optional ; ...
r = nu . sqrt ( R ** 2. + z ** 2. ) return ( self . R2deriv ( R , z , phi = phi , t = t , use_physical = False ) * R / r + self . Rzderiv ( R , z , phi = phi , t = t , use_physical = False ) * z / r ) * R / r + ( self . Rzderiv ( R , z , phi = phi , t = t , use_physical = False ) * R / r + self . z2deriv ( R , z , phi ...
def _encode_binary ( name , value , dummy0 , dummy1 ) : """Encode bson . binary . Binary ."""
subtype = value . subtype if subtype == 2 : value = _PACK_INT ( len ( value ) ) + value return b"\x05" + name + _PACK_LENGTH_SUBTYPE ( len ( value ) , subtype ) + value
def least_squares ( Cui , X , Y , regularization , num_threads = 0 ) : """For each user in Cui , calculate factors Xu for them using least squares on Y . Note : this is at least 10 times slower than the cython version included here ."""
users , n_factors = X . shape YtY = Y . T . dot ( Y ) for u in range ( users ) : X [ u ] = user_factor ( Y , YtY , Cui , u , regularization , n_factors )
def write ( self , originalPrefix , newPrefix = None ) : """Write project card to string . Args : originalPrefix ( str ) : Original name to give to files that follow the project naming convention ( e . g : prefix . gag ) . newPrefix ( str , optional ) : If new prefix is desired , pass in this parameter . De...
# Determine number of spaces between card and value for nice alignment numSpaces = max ( 2 , 25 - len ( self . name ) ) # Handle special case of booleans if self . value is None : line = '%s\n' % self . name else : if self . name == 'WMS' : line = '%s %s\n' % ( self . name , self . value ) elif newP...
def ensure_annotations ( resources , data ) : """Prepare any potentially missing annotations for downstream processing in a local directory ."""
transcript_gff = tz . get_in ( [ "rnaseq" , "transcripts" ] , resources ) if transcript_gff and utils . file_exists ( transcript_gff ) : out_dir = os . path . join ( tz . get_in ( [ "dirs" , "work" ] , data ) , "inputs" , "data" , "annotations" ) resources [ "rnaseq" ] [ "gene_bed" ] = gtf . gtf_to_bed ( transc...
def _update_ssl_params ( host ) : """Update the host ssl params ( port or scheme ) if needed . : param host : : return :"""
if host [ HostParsing . HOST ] and EsParser . _is_secure_connection_type ( host ) : host [ HostParsing . PORT ] = EsParser . SSL_DEFAULT_PORT host [ HostParsing . USE_SSL ] = True parsed_url = urlparse ( EsParser . _fix_host_prefix ( host [ HostParsing . HOST ] ) ) host [ HostParsing . HOST ] = parsed_u...
def section_names ( self , ordkey = "wall_time" ) : """Return the names of sections ordered by ordkey . For the time being , the values are taken from the first timer ."""
section_names = [ ] # FIXME this is not trivial for idx , timer in enumerate ( self . timers ( ) ) : if idx == 0 : section_names = [ s . name for s in timer . order_sections ( ordkey ) ] # check = section _ names # else : # new _ set = set ( [ s . name for s in timer . order _ sectio...
def request_finished ( key ) : """Remove finished Thread from queue . : param key : data source key"""
with event_lock : threads [ key ] = threads [ key ] [ 1 : ] if threads [ key ] : threads [ key ] [ 0 ] . run ( )
def listFileArray ( self ) : """API to list files in DBS . Either non - wildcarded logical _ file _ name , non - wildcarded dataset , non - wildcarded block _ name or non - wildcarded lfn list is required . The combination of a non - wildcarded dataset or block _ name with an wildcarded logical _ file _ name is...
ret = [ ] try : body = request . body . read ( ) if body : data = cjson . decode ( body ) data = validateJSONInputNoCopy ( "files" , data , True ) if 'sumOverLumi' in data and data [ 'sumOverLumi' ] == 1 : if ( 'logical_file_name' in data and isinstance ( data [ 'logical_file...
def time_wait ( predicate , timeout_seconds = 120 , sleep_seconds = 1 , ignore_exceptions = True , inverse_predicate = False , noisy = True , required_consecutive_success_count = 1 ) : """waits or spins for a predicate and returns the time of the wait . An exception in the function will be returned . A timeout ...
start = time_module . time ( ) wait_for ( predicate , timeout_seconds , sleep_seconds , ignore_exceptions , inverse_predicate , noisy , required_consecutive_success_count ) return elapse_time ( start )
def _parse_groupwise_input ( group_definitions , group_pairs , MDlogger , mname = '' ) : r"""For input of group type ( add _ group _ mindist ) , prepare the array of pairs of indices and groups so that : py : func : ` MinDistanceFeature ` can work This function will : - check the input types - sort the 1D a...
assert isinstance ( group_definitions , list ) , "group_definitions has to be of type list, not %s" % type ( group_definitions ) # Handle the special case of just one group if len ( group_definitions ) == 1 : group_pairs = np . array ( [ 0 , 0 ] , ndmin = 2 ) # Sort the elements within each group parsed_group_defin...
def find_frametype ( self , gpstime = None , frametype_match = None , host = None , port = None , return_all = False , allow_tape = True ) : """Find the containing frametype ( s ) for this ` Channel ` Parameters gpstime : ` int ` a reference GPS time at which to search for frame files frametype _ match : ` ...
return datafind . find_frametype ( self , gpstime = gpstime , frametype_match = frametype_match , host = host , port = port , return_all = return_all , allow_tape = allow_tape )
def cancel ( self ) : """Cancels the current lookup ."""
if self . _running : self . interrupt ( ) self . _running = False self . _cancelled = True self . loadingFinished . emit ( )
def derivative ( self , x ) : """Derivative of the product space operator . Parameters x : ` domain ` element The point to take the derivative in Returns adjoint : linear ` ProductSpaceOperator ` The derivative Examples > > > r3 = odl . rn ( 3) > > > pspace = odl . ProductSpace ( r3 , r3) > > > ...
# Lazy import to improve ` import odl ` time import scipy . sparse # Short circuit optimization if self . is_linear : return self deriv_ops = [ op . derivative ( x [ col ] ) for op , col in zip ( self . ops . data , self . ops . col ) ] data = np . empty ( len ( deriv_ops ) , dtype = object ) data [ : ] = deriv_ops...
def typechecked ( call_ : typing . Callable [ ... , T ] ) -> T : """A decorator to make a callable object checks its types . . code - block : : python from typing import Callable @ typechecked def foobar ( x : str ) - > bool : return x = = ' hello world ' @ typechecked def hello _ world ( foo : str , ...
@ functools . wraps ( call_ ) def decorator ( * args , ** kwargs ) : hints = typing . get_type_hints ( call_ ) check_arguments ( call_ , hints , * args , ** kwargs ) result = call_ ( * args , ** kwargs ) check_return ( call_ . __name__ , result , hints ) return result return decorator
def print_difftext ( text , other = None ) : """Args : text ( str ) : CommandLine : # python - m utool . util _ print - - test - print _ difftext # autopep8 ingest _ data . py - - diff | python - m utool . util _ print - - test - print _ difftext"""
if other is not None : # hack text = util_str . difftext ( text , other ) colortext = util_str . color_diff_text ( text ) try : print ( colortext ) except UnicodeEncodeError as ex : # NOQA import unicodedata colortext = unicodedata . normalize ( 'NFKD' , colortext ) . encode ( 'ascii' , 'ignore' ) p...
def _notify ( self , title , message , expected_action = None ) : """Notify user from external event"""
if self . editor is None : return inital_value = self . editor . save_on_focus_out self . editor . save_on_focus_out = False self . _flg_notify = True dlg_type = ( QtWidgets . QMessageBox . Yes | QtWidgets . QMessageBox . No ) expected_action = ( lambda * x : None ) if not expected_action else expected_action if ( ...
def complete_set ( self , cmd_param_text , full_cmd , * rest ) : """TODO : suggest the old value & the current version"""
complete_value = partial ( complete_values , [ "updated-value" ] ) complete_version = partial ( complete_values , [ str ( i ) for i in range ( 1 , 11 ) ] ) completers = [ self . _complete_path , complete_value , complete_version ] return complete ( completers , cmd_param_text , full_cmd , * rest )
def sync ( self , videoQuality , limit = None , unwatched = False , ** kwargs ) : """Add current Movie library section as sync item for specified device . See description of : func : ` plexapi . library . LibrarySection . search ( ) ` for details about filtering / sorting and : func : ` plexapi . library . Libr...
from plexapi . sync import Policy , MediaSettings kwargs [ 'mediaSettings' ] = MediaSettings . createVideo ( videoQuality ) kwargs [ 'policy' ] = Policy . create ( limit , unwatched ) return super ( MovieSection , self ) . sync ( ** kwargs )
def inverse ( self , z ) : """Inverse of the power transform link function Parameters ` z ` : array - like Value of the transformed mean parameters at ` p ` Returns ` p ` : array Mean parameters Notes g ^ ( - 1 ) ( z ` ) = ` z ` * * ( 1 / ` power ` )"""
p = np . power ( z , 1. / self . power ) return p
def update ( self , values , ** context ) : """Updates the model with the given dictionary of values . : param values : < dict > : param context : < orb . Context > : return : < int >"""
schema = self . schema ( ) column_updates = { } other_updates = { } for key , value in values . items ( ) : try : column_updates [ schema . column ( key ) ] = value except orb . errors . ColumnNotFound : other_updates [ key ] = value # update the columns in order for col in sorted ( column_updat...
def get_file_by_id ( self , file_id ) : """Gets the PBXFileReference to the given id : param file _ id : Identifier of the PBXFileReference to be retrieved . : return : A PBXFileReference if the id is found , None otherwise ."""
file_ref = self . objects [ file_id ] if not isinstance ( file_ref , PBXFileReference ) : return None return file_ref
def list_to_instance_list ( _self , _list , _Class ) : """Takes a list of resource dicts and returns a list of resource instances , defined by the _ Class param . : param _ self : Original resource calling the method : type _ self : core . MarvelObject : param _ list : List of dicts describing a Resource . ...
items = [ ] for item in _list : items . append ( _Class ( _self . marvel , item ) ) return items
async def on_raw_topic ( self , message ) : """TOPIC command ."""
setter , settermeta = self . _parse_user ( message . source ) target , topic = message . params self . _sync_user ( setter , settermeta ) # Update topic in our own channel list . if self . in_channel ( target ) : self . channels [ target ] [ 'topic' ] = topic self . channels [ target ] [ 'topic_by' ] = setter ...
def flag ( self , diagnostic , thresh = None ) : '''Returns indices of diagnostic that satisfy ( return True from ) the threshold predicate . Will use class - level default threshold if None provided . Args : diagnostic ( str ) : name of the diagnostic thresh ( func ) : threshold function ( boolean predic...
if thresh is None : thresh = self . defaults [ diagnostic ] result = self . results [ diagnostic ] if isinstance ( result , pd . DataFrame ) : if diagnostic == 'CorrelationMatrix' : result = result . copy ( ) np . fill_diagonal ( result . values , 0 ) return result . applymap ( thresh ) . su...
def swarm ( workingDir ) : """Runs a swarm in the giving working directory , assuming it was created by Menorah . : param workingDir : absolute or relative path to working directory created by Menorah"""
name = os . path . splitext ( os . path . basename ( workingDir ) ) [ 0 ] swarmDescriptionFile = os . path . join ( workingDir , "swarm_description.json" ) with open ( swarmDescriptionFile ) as swarmDesc : swarmDescription = json . loads ( swarmDesc . read ( ) ) print "==============================================...
def get_language_data ( self , qid , lang , lang_data_type ) : """get language data for specified qid : param qid : : param lang : language code : param lang _ data _ type : ' label ' , ' description ' or ' aliases ' : return : list of strings If nothing is found : If lang _ data _ type = = label : retu...
self . init_language_data ( lang , lang_data_type ) current_lang_data = self . loaded_langs [ lang ] [ lang_data_type ] all_lang_strings = current_lang_data . get ( qid , [ ] ) if not all_lang_strings and lang_data_type in { 'label' , 'description' } : all_lang_strings = [ '' ] return all_lang_strings
def delete_repo ( name , config_path = _DEFAULT_CONFIG_PATH , force = False ) : '''Remove a local package repository . : param str name : The name of the local repository . : param str config _ path : The path to the configuration file for the aptly instance . : param bool force : Whether to remove the reposi...
_validate_config ( config_path ) force = six . text_type ( bool ( force ) ) . lower ( ) current_repo = __salt__ [ 'aptly.get_repo' ] ( name = name , config_path = config_path ) if not current_repo : log . debug ( 'Repository already absent: %s' , name ) return True cmd = [ 'repo' , 'drop' , '-config={}' . forma...
def _get_fb_device ( self ) : """Internal . Finds the correct frame buffer device for the sense HAT and returns its / dev name ."""
device = None for fb in glob . glob ( '/sys/class/graphics/fb*' ) : name_file = os . path . join ( fb , 'name' ) if os . path . isfile ( name_file ) : with open ( name_file , 'r' ) as f : name = f . read ( ) if name . strip ( ) == self . SENSE_HAT_FB_NAME : fb_device = fb...
def _fit_transform_column ( self , table , metadata , transformer_name , table_name ) : """Transform a column from table using transformer and given parameters . Args : table ( pandas . DataFrame ) : Dataframe containing column to transform . metadata ( dict ) : Metadata for given column . transformer _ nam...
column_name = metadata [ 'name' ] content = { } columns = [ ] if self . missing and table [ column_name ] . isnull ( ) . any ( ) : null_transformer = transformers . NullTransformer ( metadata ) clean_column = null_transformer . fit_transform ( table [ column_name ] ) null_name = '?' + column_name column...
def get ( columns = None ) : """Get or create MetaData singleton ."""
if columns is None : columns = _DEFAULT_COLUMNS global _METADATA if not _METADATA : _METADATA = MetaData ( columns ) return _METADATA
def seen_tasks ( self , request , context ) : """Returns all seen task types ."""
_log_request ( request , context ) result = clearly_pb2 . SeenTasksMessage ( ) result . task_types . extend ( self . listener . memory . task_types ( ) ) return result
def siphash24 ( message , key = b'' , encoder = nacl . encoding . HexEncoder ) : """Computes a keyed MAC of ` ` message ` ` using the short - input - optimized siphash - 2-4 construction . : param message : The message to hash . : type message : bytes : param key : the message authentication key for the sip...
digest = _sip_hash ( message , key ) return encoder . encode ( digest )
def _get_offset ( self ) : """Subclasses may override this method ."""
sx , sxy , syx , sy , ox , oy = self . transformation return ( ox , oy )