signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _zfs_image_create ( vm_name , pool , disk_name , hostname_property_name , sparse_volume , disk_size , disk_image_name ) : '''Clones an existing image , or creates a new one . When cloning an image , disk _ image _ name refers to the source of the clone . If not specified , disk _ size is used for creating ...
if not disk_image_name and not disk_size : raise CommandExecutionError ( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' . format ( disk_name ) ) if not pool : raise CommandExecutionError ( 'Unable to create new disk {0}, please specify' ' the disk pool name' . forma...
def fit_predict ( self , data , labels , unkown = None ) : """Fit and classify data efficiently . : param data : sparse input matrix ( ideal dtype is ` numpy . float32 ` ) : type data : : class : ` scipy . sparse . csr _ matrix ` : param labels : the labels associated with data : type labels : iterable : ...
self . fit ( data , labels ) return self . _predict_from_bmus ( self . _bmus , unkown )
def validate ( style , value , vectorized = True ) : """Validates a style and associated value . Arguments style : str The style to validate ( e . g . ' color ' , ' size ' or ' marker ' ) value : The style value to validate vectorized : bool Whether validator should allow vectorized setting Returns ...
validator = get_validator ( style ) if validator is None : return None if isinstance ( value , ( np . ndarray , list ) ) and vectorized : return all ( validator ( v ) for v in value ) try : valid = validator ( value ) return False if valid == False else True except : return False
def _onClassAttribute ( self , name , line , pos , absPosition , level ) : """Memorizes a class attribute"""
# A class must be on the top of the stack attributes = self . objectsStack [ level ] . classAttributes for item in attributes : if item . name == name : return attributes . append ( ClassAttribute ( name , line , pos , absPosition ) )
def flatten ( nested ) : """Return a flatten version of the nested argument"""
flat_return = list ( ) def __inner_flat ( nested , flat ) : for i in nested : __inner_flat ( i , flat ) if isinstance ( i , list ) else flat . append ( i ) return flat __inner_flat ( nested , flat_return ) return flat_return
def glover_time_derivative ( tr , oversampling = 50 , time_length = 32. , onset = 0. ) : """Implementation of the Glover time derivative hrf ( dhrf ) model Parameters tr : float scan repeat time , in seconds oversampling : int , temporal oversampling factor , optional time _ length : float , hrf kerne...
do = .1 dhrf = 1. / do * ( glover_hrf ( tr , oversampling , time_length , onset ) - glover_hrf ( tr , oversampling , time_length , onset + do ) ) return dhrf
def get_encoded_text ( container , xpath ) : """Return text for element at xpath in the container xml if it is there . Parameters container : xml . etree . ElementTree . Element The element to be searched in . xpath : str The path to be looked for . Returns result : str"""
try : return "" . join ( container . find ( xpath , ns ) . itertext ( ) ) except AttributeError : return None
def sils_cut ( T , f , c , d , h , conshdlr ) : """solve _ sils - - solve the lot sizing problem with cutting planes - start with a relaxed model - used lazy constraints to elimitate fractional setup variables with cutting planes Parameters : - T : number of periods - P : set of products - f [ t ] : set...
Ts = range ( 1 , T + 1 ) model = sils ( T , f , c , d , h ) y , x , I = model . data # relax integer variables for t in Ts : model . chgVarType ( y [ t ] , "C" ) model . addVar ( vtype = "B" , name = "fake" ) # for making the problem MIP # compute D [ i , j ] = sum _ { t = i } ^ j d [ t ] D = { } for t in Ts : ...
def safely_encode ( unicode_or_str , encoding = 'utf-8' ) : '''Encodes < unicode > into byte < str > . Replaces any non utf8 chars'''
if isinstance ( unicode_or_str , unicode ) : rstr = unicode_or_str . encode ( encoding , 'replace' ) elif isinstance ( unicode_or_str , str ) : rstr = unicode_or_str else : raise Exception ( u'Not of type unicode or str' ) return rstr
def run ( cls , command , cwd = "." , ** kwargs ) : """Make a subprocess call , collect its output and returncode . Returns CommandResult instance as ValueObject ."""
assert isinstance ( command , six . string_types ) command_result = CommandResult ( ) command_result . command = command use_shell = cls . USE_SHELL if "shell" in kwargs : use_shell = kwargs . pop ( "shell" ) # - - BUILD COMMAND ARGS : if six . PY2 and isinstance ( command , six . text_type ) : # - - PREPARE - FOR ...
def register_callbacks ( self , on_create , on_modify , on_delete ) : """Register callbacks for file creation , modification , and deletion"""
self . on_create = on_create self . on_modify = on_modify self . on_delete = on_delete
def _generate_download_google_link ( link ) : """Brief Function that returns a direct download link of a file stored inside a Google Drive Repository . Description Generally a link from a Google Drive file is only for viewing purposes . If the user wants to download the file it can be done with Google Dri...
# Get file id . if "id=" not in link : # Split link into segments ( split character - - > / ) split_link = link . split ( "/" ) file_id = split_link [ - 2 ] else : # Split link into segments ( split string - - > " id = " ) split_link = link . split ( "id=" ) file_id = split_link [ - 1 ] return "https://...
def virtual_media ( self ) : """Property to provide reference to ` VirtualMediaCollection ` instance . It is calculated once when the first time it is queried . On refresh , this property gets reset ."""
return virtual_media . VirtualMediaCollection ( self . _conn , utils . get_subresource_path_by ( self , 'VirtualMedia' ) , redfish_version = self . redfish_version )
def set_void_declension ( self , number_type , case_type ) : """> > > decl = DeclinableOneGender ( " armr " , Gender . masculine ) > > > decl . declension > > > decl . set _ void _ declension ( Number , Case ) > > > decl . declension : param number _ type : : param case _ type : : return :"""
self . declension = [ ] for i , a_number in enumerate ( number_type ) : self . declension . append ( [ ] ) for _ in case_type : self . declension [ i ] . append ( "" )
def lookup_field ( key , lookup_type = None , placeholder = None , html_class = "div" , select_type = "strapselect" , mapping = "uuid" ) : """Generates a lookup field for form definitions"""
if lookup_type is None : lookup_type = key if placeholder is None : placeholder = "Select a " + lookup_type result = { 'key' : key , 'htmlClass' : html_class , 'type' : select_type , 'placeholder' : placeholder , 'options' : { "type" : lookup_type , "asyncCallback" : "$ctrl.getFormData" , "map" : { 'valueProper...
def transform_non_affine ( self , s ) : """Apply transformation to a Nx1 numpy array . Parameters s : array Data to be transformed in display scale units . Return array or masked array Transformed data , in data value units ."""
T = self . _T M = self . _M W = self . _W p = self . _p # Calculate x return T * 10 ** ( - ( M - W ) ) * ( 10 ** ( s - W ) - ( p ** 2 ) * 10 ** ( - ( s - W ) / p ) + p ** 2 - 1 )
def get_histories_fix_params ( self , exp , rep , tag , ** kwargs ) : """this function uses get _ history ( . . ) but returns all histories where the subexperiments match the additional kwargs arguments . if alpha = 1.0, beta = 0.01 is given , then only those experiment histories are returned , as a list ."""
subexps = self . get_exps ( exp ) tagvalues = [ re . sub ( "0+$" , '0' , '%s%f' % ( k , kwargs [ k ] ) ) for k in kwargs ] histories = [ self . get_history ( se , rep , tag ) for se in subexps if all ( map ( lambda tv : tv in se , tagvalues ) ) ] params = [ self . get_params ( se ) for se in subexps if all ( map ( lamb...
def map ( self , mapper : Callable [ [ Any ] , Any ] ) -> 'List' : """Map a function over a List ."""
try : ret = List . from_iterable ( [ mapper ( x ) for x in self ] ) except TypeError : ret = List . from_iterable ( [ partial ( mapper , x ) for x in self ] ) return ret
def get_func ( func , aliasing , implementations ) : """Return the key of a found implementation or the func itself"""
try : func_str = aliasing [ func ] except KeyError : if callable ( func ) : return func else : if func_str in implementations : return func_str if func_str . startswith ( 'nan' ) and func_str [ 3 : ] in funcs_no_separate_nan : raise ValueError ( "%s does not have a nan-version" ....
def update ( self , function ) : """Atomically apply function to the value , and return the old and new values ."""
with self . lock : oldValue = self . value self . value = function ( oldValue ) return oldValue , self . value
def format_price ( self , price ) : """Formats the price with the set decimal mark and currency"""
# ensure we have a float price = api . to_float ( price , default = 0.0 ) dm = self . get_decimal_mark ( ) cur = self . get_currency_symbol ( ) price = "%s %.2f" % ( cur , price ) return price . replace ( "." , dm )
def on_remembered_identifiers_failure ( self , exc , subject_context ) : """Called when an exception is thrown while trying to retrieve identifier . The default implementation logs a debug message and forgets ( ' unremembers ' ) the problem identity by calling forget _ identity ( subject _ context ) and then ...
msg = ( "There was a failure while trying to retrieve remembered " "identifier. This could be due to a configuration problem or " "corrupted identifier. This could also be due to a recently " "changed encryption key. The remembered identity will be " "forgotten and not used for this request. " , exc ) logger . debug...
def convert_level ( self , record ) : """Converts a logging level into a logbook level ."""
level = record . levelno if level >= logging . CRITICAL : return levels . CRITICAL if level >= logging . ERROR : return levels . ERROR if level >= logging . WARNING : return levels . WARNING if level >= logging . INFO : return levels . INFO return levels . DEBUG
def create_from_position ( cls , skydir , config , ** kwargs ) : """Create an ROIModel instance centered on a sky direction . Parameters skydir : ` ~ astropy . coordinates . SkyCoord ` Sky direction on which the ROI will be centered . config : dict Model configuration dictionary ."""
coordsys = kwargs . pop ( 'coordsys' , 'CEL' ) roi = cls ( config , skydir = skydir , coordsys = coordsys , ** kwargs ) return roi
def crawl_up ( arg ) : # type : ( str ) - > Tuple [ str , str ] """Given a . py [ i ] filename , return ( root directory , module ) . We crawl up the path until we find a directory without _ _ init _ _ . py [ i ] , or until we run out of path components ."""
dir , mod = os . path . split ( arg ) mod = strip_py ( mod ) or mod while dir and get_init_file ( dir ) : dir , base = os . path . split ( dir ) if not base : break if mod == '__init__' or not mod : mod = base else : mod = base + '.' + mod return dir , mod
def describe_autocomplete ( self , service , operation , param ) : """Describe operation and args needed for server side completion . : type service : str : param service : The AWS service name . : type operation : str : param operation : The AWS operation name . : type param : str : param param : The n...
service_index = self . _index [ service ] LOG . debug ( service_index ) if param not in service_index . get ( 'operations' , { } ) . get ( operation , { } ) : LOG . debug ( "param not in index: %s" , param ) return None p = service_index [ 'operations' ] [ operation ] [ param ] resource_name = p [ 'resourceName...
def p_functioncall ( self , p ) : 'functioncall : identifier LPAREN func _ args RPAREN'
p [ 0 ] = FunctionCall ( p [ 1 ] , p [ 3 ] , lineno = p . lineno ( 1 ) ) p . set_lineno ( 0 , p . lineno ( 1 ) )
def load_churn ( ) : """Load and return the churn dataset ( classification ) . The bank marketing is a easily transformable example - dependent cost - sensitive classification dataset . Returns data : Bunch Dictionary - like object , the interesting attributes are : ' data ' , the data to learn , ' target...
module_path = dirname ( __file__ ) raw_data = pd . read_csv ( join ( module_path , 'data' , 'churn_tv_subscriptions.csv.gz' ) , delimiter = ',' , compression = 'gzip' ) descr = open ( join ( module_path , 'descr' , 'churn_tv_subscriptions.rst' ) ) . read ( ) target = raw_data [ 'target' ] . values . astype ( np . int )...
def open ( self , name , mode = 'rb' ) : """Retrieves the specified file from storage ."""
self . request = urlopen ( self . url ) if self . algorithm : self . hash = hashlib . new ( self . algorithm ) return self
def _sample_point ( self , sample = None ) : """Returns a dict that represents the sample point assigned to the sample specified Keys : obj , id , title , url"""
samplepoint = sample . getSamplePoint ( ) if sample else None data = { } if samplepoint : data = { 'obj' : samplepoint , 'id' : samplepoint . id , 'title' : samplepoint . Title ( ) , 'url' : samplepoint . absolute_url ( ) } return data
def write_response ( self , response ) : """Writes response content synchronously to the transport ."""
if self . _response_timeout_handler : self . _response_timeout_handler . cancel ( ) self . _response_timeout_handler = None try : keep_alive = self . keep_alive self . transport . write ( response . output ( self . request . version , keep_alive , self . keep_alive_timeout ) ) self . log_response ( ...
def find_mice ( self , direction , mechanism , purviews = False ) : """Return the | MIC | or | MIE | for a mechanism . Args : direction ( Direction ) : : | CAUSE | or | EFFECT | . mechanism ( tuple [ int ] ) : The mechanism to be tested for irreducibility . Keyword Args : purviews ( tuple [ int ] ) : Op...
purviews = self . potential_purviews ( direction , mechanism , purviews ) if not purviews : max_mip = _null_ria ( direction , mechanism , ( ) ) else : max_mip = max ( self . find_mip ( direction , mechanism , purview ) for purview in purviews ) if direction == Direction . CAUSE : return MaximallyIrreducible...
def message ( self , message : types . Message ) : """Select target message : param message : : return :"""
setattr ( self , 'from_chat_id' , message . chat . id ) setattr ( self , 'message_id' , message . message_id ) return self
def flush ( self ) : """Wait until history is read but no more than 10 cycles in case a browser session is closed ."""
i = 0 while self . _frame_data . is_dirty and i < 10 : i += 1 time . sleep ( 0.1 )
def get_all_tags ( self , filters = None ) : """Retrieve all the metadata tags associated with your account . : type filters : dict : param filters : Optional filters that can be used to limit the results returned . Filters are provided in the form of a dictionary consisting of filter names as the key and...
params = { } if filters : self . build_filter_params ( params , filters ) return self . get_list ( 'DescribeTags' , params , [ ( 'item' , Tag ) ] , verb = 'POST' )
def get_office ( self , row , division ) : """Gets the Office object for the given row of election results . Depends on knowing the division of the row of election results ."""
AT_LARGE_STATES = [ "AK" , "DE" , "MT" , "ND" , "SD" , "VT" , "WY" ] if division . level . name not in [ geography . DivisionLevel . STATE , geography . DivisionLevel . COUNTRY , ] : state = division . parent else : state = division if row [ "officename" ] == "President" : return government . Office . objec...
def query ( self , * args , ** kwargs ) : """Returns a new QuerySet instance with the args ANDed to the existing set ."""
clone = self . _clone ( ) queries = [ ] from pyes . query import Query if args : for f in args : if isinstance ( f , Query ) : queries . append ( f ) else : raise TypeError ( 'Only Query objects can be passed as argument' ) for field , value in kwargs . items ( ) : if val...
def getFooter ( ) : """return a header string with command line options and timestamp ."""
return "# job finished in %i seconds at %s -- %s -- %s" % ( time . time ( ) - global_starting_time , time . asctime ( time . localtime ( time . time ( ) ) ) , " " . join ( map ( lambda x : "%5.2f" % x , os . times ( ) [ : 4 ] ) ) , global_id )
def hot_answers ( self ) : """获取话题下热门的回答 : return : 话题下的热门动态中的回答 , 按热门度顺序返回生成器 : rtype : Question . Iterable"""
from . question import Question from . author import Author from . answer import Answer hot_questions_url = Topic_Hot_Questions_Url . format ( self . id ) params = { 'start' : 0 , '_xsrf' : self . xsrf } res = self . _session . get ( hot_questions_url ) soup = BeautifulSoup ( res . content ) while True : answers_di...
def fix_text_escapes ( self , txt : str , quote_char : str ) -> str : """Fix the various text escapes"""
def _subf ( matchobj ) : return matchobj . group ( 0 ) . translate ( self . re_trans_table ) if quote_char : txt = re . sub ( r'\\' + quote_char , quote_char , txt ) return re . sub ( r'\\.' , _subf , txt , flags = re . MULTILINE + re . DOTALL + re . UNICODE )
def oem ( self , command , timeout_ms = None , info_cb = DEFAULT_MESSAGE_CALLBACK ) : """Executes an OEM command on the device . Args : command : The command to execute , such as ' poweroff ' or ' bootconfig read ' . timeout _ ms : Optional timeout in milliseconds to wait for a response . info _ cb : See Do...
return self . _simple_command ( 'oem %s' % command , timeout_ms = timeout_ms , info_cb = info_cb )
def find_threshold ( errors , z_range = ( 0 , 10 ) ) : """Find the ideal threshold . The ideal threshold is the one that minimizes the z _ cost function ."""
mean = errors . mean ( ) std = errors . std ( ) min_z , max_z = z_range best_z = min_z best_cost = np . inf for z in range ( min_z , max_z ) : best = fmin ( z_cost , z , args = ( errors , mean , std ) , full_output = True , disp = False ) z , cost = best [ 0 : 2 ] if cost < best_cost : best_z = z [ ...
def _split_incoming_queries_into_batches ( self , sources , searchParams = False ) : """* split incoming queries into batches * * * Key Arguments : * * - ` ` sources ` ` - - sources to split into batches - ` ` searchParams ` ` - - search params associated with batches * * Return : * * - ` ` theseBatches `...
self . log . info ( 'starting the ``_split_incoming_queries_into_batches`` method' ) batchSize = 180 total = len ( sources ) batches = int ( total / batchSize ) + 1 start = 0 end = 0 theseBatches = [ ] theseBatchParams = [ ] for i in range ( batches ) : end = end + batchSize start = i * batchSize thisBatch ...
def _pfp__set_packer ( self , pack_type , packer = None , pack = None , unpack = None , func_call_info = None ) : """Set the packer / pack / unpack functions for this field , as well as the pack type . : pack _ type : The data type of the packed data : packer : A function that can handle packing and unpacking...
self . _pfp__pack_type = pack_type self . _pfp__unpack = unpack self . _pfp__pack = pack self . _pfp__packer = packer self . _pfp__pack_func_call_info = func_call_info
def solve ( self , b ) : """LUx = b : Ly = b Ux = y"""
# b = self . permute _ vec ( b ) y = [ ] for bri in range ( self . N ) : # block row index for li in range ( self . n ) : # local row index s = 0.0 for lci in range ( li ) : # local column index s += self . lu [ bri ] [ li , lci ] * y [ bri * self . n + lci ] for di in range ( 1 ...
def disable_hit ( self , hit_id , response_groups = None ) : """Remove a HIT from the Mechanical Turk marketplace , approves all submitted assignments that have not already been approved or rejected , and disposes of the HIT and all assignment data . Assignments for the HIT that have already been submitted , ...
params = { 'HITId' : hit_id , } # Handle optional response groups argument if response_groups : self . build_list_params ( params , response_groups , 'ResponseGroup' ) return self . _process_request ( 'DisableHIT' , params )
def next_frame_sampling_stochastic ( ) : """Basic 2 - frame conv model with stochastic tower ."""
hparams = basic_deterministic_params . next_frame_sampling ( ) hparams . stochastic_model = True hparams . add_hparam ( "latent_channels" , 1 ) hparams . add_hparam ( "latent_std_min" , - 5.0 ) hparams . add_hparam ( "num_iterations_1st_stage" , 15000 ) hparams . add_hparam ( "num_iterations_2nd_stage" , 15000 ) hparam...
def recursive_copy ( source , dest ) : '''Recursively copy the source directory to the destination , leaving files with the source does not explicitly overwrite . ( identical to cp - r on a unix machine )'''
for root , _ , files in salt . utils . path . os_walk ( source ) : path_from_source = root . replace ( source , '' ) . lstrip ( os . sep ) target_directory = os . path . join ( dest , path_from_source ) if not os . path . exists ( target_directory ) : os . makedirs ( target_directory ) for name ...
def get ( self ) : """API endpoint to get validators set . Return : A JSON string containing the validator set of the current node ."""
pool = current_app . config [ 'bigchain_pool' ] with pool ( ) as bigchain : validators = bigchain . get_validators ( ) return validators
def _simsearch_to_simresult ( self , sim_resp : Dict , method : SimAlgorithm ) -> SimResult : """Convert owlsim json to SimResult object : param sim _ resp : owlsim response from search _ by _ attribute _ set ( ) : param method : SimAlgorithm : return : SimResult object"""
sim_ids = get_nodes_from_ids ( sim_resp [ 'query_IRIs' ] ) sim_resp [ 'results' ] = OwlSim2Api . _rank_results ( sim_resp [ 'results' ] , method ) # get id type map : ids = [ result [ 'j' ] [ 'id' ] for result in sim_resp [ 'results' ] ] id_type_map = get_id_type_map ( ids ) matches = [ ] for result in sim_resp [ 'resu...
def get_all_file_report_pages ( self , query ) : """Get File Report ( All Pages ) . : param query : a VirusTotal Intelligence search string in accordance with the file search documentation . : return : All JSON responses appended together ."""
responses = [ ] next_page , response = self . get_hashes_from_search ( self , query ) responses . append ( _return_response_and_status_code ( response ) ) while next_page : next_page , response = self . get_hashes_from_search ( query , next_page ) responses . append ( _return_response_and_status_code ( response...
def get_decoder ( encoding , flexible = False ) : """RETURN FUNCTION TO PERFORM DECODE : param encoding : STRING OF THE ENCODING : param flexible : True IF YOU WISH TO TRY OUR BEST , AND KEEP GOING : return : FUNCTION"""
if encoding == None : def no_decode ( v ) : return v return no_decode elif flexible : def do_decode1 ( v ) : return v . decode ( encoding , 'ignore' ) return do_decode1 else : def do_decode2 ( v ) : return v . decode ( encoding ) return do_decode2
def _kcpassword ( password ) : '''Internal function for obfuscating the password used for AutoLogin This is later written as the contents of the ` ` / etc / kcpassword ` ` file . . versionadded : : 2017.7.3 Adapted from : https : / / github . com / timsutton / osx - vm - templates / blob / master / scripts ...
# The magic 11 bytes - these are just repeated # 0x7D 0x89 0x52 0x23 0xD2 0xBC 0xDD 0xEA 0xA3 0xB9 0x1F key = [ 125 , 137 , 82 , 35 , 210 , 188 , 221 , 234 , 163 , 185 , 31 ] key_len = len ( key ) # Convert each character to a byte password = list ( map ( ord , password ) ) # pad password length out to an even multiple...
def acquire ( self , blocking = True , timeout = None ) : """Acquire the lock . If * blocking * is true ( the default ) , then this will block until the lock can be acquired . The * timeout * parameter specifies an optional timeout in seconds . The return value is a boolean indicating whether the lock was a...
hub = get_hub ( ) try : # switcher . _ _ call _ _ needs to be synchronized with a lock IF it can # be called from different threads . This is the case here because # this method may be called from multiple threads and the callbacks # are run in the calling thread . So pass it our _ lock . with switch_back ( timeout...
def listTemplates ( data = { } ) : """Fetch existing Templates details . Args : ` data ` : dictionary containing the value of page number and per - page value Returns : Dictionary containing paging _ info and command _ templates details"""
conn = Qubole . agent ( ) url_path = Template . rest_entity_path page_attr = [ ] if "page" in data and data [ "page" ] is not None : page_attr . append ( "page=%s" % data [ "page" ] ) if "per_page" in data and data [ "per_page" ] is not None : page_attr . append ( "per_page=%s" % data [ "per_page" ] ) if page_a...
def en004 ( self , value = None ) : """Corresponds to IDD Field ` en004 ` mean coincident dry - bulb temperature to Enthalpy corresponding to 0.4 % annual cumulative frequency of occurrence Args : value ( float ) : value for IDD Field ` en004 ` Unit : kJ / kg if ` value ` is None it will not be checked ...
if value is not None : try : value = float ( value ) except ValueError : raise ValueError ( 'value {} need to be of type float ' 'for field `en004`' . format ( value ) ) self . _en004 = value
def help_center_articles_search ( self , category = None , label_names = None , locale = None , query = None , section = None , updated_after = None , updated_before = None , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / help _ center / search # search - articles"
api_path = "/api/v2/help_center/articles/search.json" api_query = { } if "query" in kwargs . keys ( ) : api_query . update ( kwargs [ "query" ] ) del kwargs [ "query" ] if category : api_query . update ( { "category" : category , } ) if label_names : api_query . update ( { "label_names" : label_names , ...
def get_cached ( self , link , default = None ) : '''Retrieves a cached navigator from the id _ map . Either a Link object or a bare uri string may be passed in .'''
if hasattr ( link , 'uri' ) : return self . id_map . get ( link . uri , default ) else : return self . id_map . get ( link , default )
def phyper_at_fpr ( fg_vals , bg_vals , fpr = 0.01 ) : """Computes the hypergeometric p - value at a specific FPR ( default 1 % ) . Parameters fg _ vals : array _ like The list of values for the positive set . bg _ vals : array _ like The list of values for the negative set . fpr : float , optional Th...
fg_vals = np . array ( fg_vals ) s = scoreatpercentile ( bg_vals , 100 - fpr * 100 ) table = [ [ sum ( fg_vals >= s ) , sum ( bg_vals >= s ) ] , [ sum ( fg_vals < s ) , sum ( bg_vals < s ) ] , ] return fisher_exact ( table , alternative = "greater" ) [ 1 ]
def mix ( self , repetitions = 1 , volume = None , location = None , rate = 1.0 ) : """Mix a volume of liquid ( in microliters / uL ) using this pipette Notes If no ` location ` is passed , the pipette will mix from it ' s current position . If no ` volume ` is passed , ` mix ` will default to it ' s ` max ...
if not self . tip_attached : log . warning ( "Cannot mix without a tip attached." ) if volume is None : volume = self . max_volume if not location and self . previous_placeable : location = self . previous_placeable do_publish ( self . broker , commands . mix , self . mix , 'before' , self , None , None , r...
def get_all_fields ( self ) : """Get all aviable fields"""
return { name : { 'name' : name , 'label' : field [ 'label' ] , } for name , field in self . get_model_config ( ) . get_list_fields ( ) . items ( ) }
def get_coord_line_number ( self , coord ) : """return the one - indexed line number given the coordinates"""
if coord [ 0 ] in self . _coords : if coord [ 1 ] in self . _coords [ coord [ 0 ] ] : return self . _coords [ coord [ 0 ] ] [ coord [ 1 ] ] return None
def concate_extension ( * extensions , name ) : """Concatenate extensions Notes The method assumes that the first index is the name of the stressor / impact / input type . To provide a consistent naming this is renamed to ' indicator ' if they differ . All other index names ( ' compartments ' , . . . ) ar...
if type ( extensions [ 0 ] ) is tuple or type ( extensions [ 0 ] ) is list : extensions = extensions [ 0 ] # check if fd extensions is present in one of the given extensions FY_present = False SY_present = False SFY_columns = None for ext in extensions : if 'FY' in ext . get_DataFrame ( data = False ) : ...
def _reattach_linked_hdds ( self ) : """Reattach linked cloned hard disks ."""
hdd_info_file = os . path . join ( self . working_dir , self . _vmname , "hdd_info.json" ) try : with open ( hdd_info_file , "r" , encoding = "utf-8" ) as f : hdd_table = json . load ( f ) except ( ValueError , OSError ) as e : # The VM has never be started return for hdd_info in hdd_table : hdd_fil...
def of ( fixture_classes : Iterable [ type ] , context : Union [ None , 'torment.TestContext' ] = None ) -> Iterable [ 'torment.fixtures.Fixture' ] : '''Obtain all Fixture objects of the provided classes . * * Parameters * * : ` ` fixture _ classes ` ` : classes inheriting from ` ` torment . fixtures . Fixture ...
classes = list ( copy . copy ( fixture_classes ) ) fixtures = [ ] # type : Iterable [ torment . fixtures . Fixture ] while len ( classes ) : current = classes . pop ( ) subclasses = current . __subclasses__ ( ) if len ( subclasses ) : classes . extend ( subclasses ) elif current not in fixture_c...
def _qnwsimp1 ( n , a , b ) : """Compute univariate Simpson quadrature nodes and weights Parameters n : int The number of nodes a : int The lower endpoint b : int The upper endpoint Returns nodes : np . ndarray ( dtype = float ) An n element array of nodes nodes : np . ndarray ( dtype = float ...
if n % 2 == 0 : print ( "WARNING qnwsimp: n must be an odd integer. Increasing by 1" ) n += 1 nodes = np . linspace ( a , b , n ) dx = nodes [ 1 ] - nodes [ 0 ] weights = np . kron ( np . ones ( ( n + 1 ) // 2 ) , np . array ( [ 2.0 , 4.0 ] ) ) weights = weights [ : n ] weights [ 0 ] = weights [ - 1 ] = 1 weigh...
def get_curve_name ( self , ecdh = False ) : """Return correct curve name for device operations ."""
if ecdh : return formats . get_ecdh_curve_name ( self . curve_name ) else : return self . curve_name
def _report ( self , action , key_mapper = mappers . _report_key_mapper ) : '''Return the dictionary of * * kwargs with the correct datums attribute names and data types for the top level of the report , and return the nested levels separately .'''
_top_level = [ k for k , v in self . report . items ( ) if not isinstance ( v , dict ) ] _nested_level = [ k for k , v in self . report . items ( ) if isinstance ( v , dict ) ] top_level_dict = { } nested_levels_dict = { } for key in _top_level : try : if key == 'date' or key == 'timestamp' : it...
def sample_forward_transitions ( self , batch_size , batch_info , forward_steps : int , discount_factor : float ) -> Transitions : """Sample transitions from replay buffer with _ forward steps _ . That is , instead of getting a transition s _ t - > s _ t + 1 with reward r , get a transition s _ t - > s _ t + n ...
indexes = self . backend . sample_batch_transitions ( batch_size , forward_steps = forward_steps ) transition_tensors = self . backend . get_transitions_forward_steps ( indexes , forward_steps = forward_steps , discount_factor = discount_factor ) return Trajectories ( num_steps = batch_size , num_envs = self . backend ...
def mousePressEvent ( self , event ) : """Reimplement Qt method"""
if event . button ( ) != Qt . LeftButton : QTableView . mousePressEvent ( self , event ) return index_clicked = self . indexAt ( event . pos ( ) ) if index_clicked . isValid ( ) : if index_clicked == self . currentIndex ( ) and index_clicked in self . selectedIndexes ( ) : self . clearSelection ( ) ...
def all_downstreams ( self , node , graph = None ) : """Returns a list of all nodes ultimately downstream of the given node in the dependency graph , in topological order ."""
if graph is None : graph = self . graph nodes = [ node ] nodes_seen = set ( ) i = 0 while i < len ( nodes ) : downstreams = self . downstream ( nodes [ i ] , graph ) for downstream_node in downstreams : if downstream_node not in nodes_seen : nodes_seen . add ( downstream_node ) ...
def missing_inds ( x , format_data = True ) : """Returns indices of missing data This function is useful to identify rows of your array that contain missing data or nans . The returned indices can be used to remove the rows with missing data , or label the missing data points that are interpolated using PPC...
if format_data : x = formatter ( x , ppca = False ) inds = [ ] for arr in x : if np . argwhere ( np . isnan ( arr ) ) . size is 0 : inds . append ( None ) else : inds . append ( np . argwhere ( np . isnan ( arr ) ) [ : , 0 ] ) if len ( inds ) > 1 : return inds else : return inds [ 0 ...
def set_naxispath ( self , naxispath ) : """Choose a slice out of multidimensional data ."""
revnaxis = list ( naxispath ) revnaxis . reverse ( ) # construct slice view and extract it view = tuple ( revnaxis + [ slice ( None ) , slice ( None ) ] ) data = self . get_mddata ( ) [ view ] if len ( data . shape ) != 2 : raise ImageError ( "naxispath does not lead to a 2D slice: {}" . format ( naxispath ) ) self...
def networkMultiLevel ( self , * modes , nodeCount = True , edgeWeight = True , stemmer = None , edgeAttribute = None , nodeAttribute = None , _networkTypeString = 'n-level network' ) : """Creates a network of the objects found by any number of tags _ modes _ , with edges between all co - occurring values . IF you ...
stemCheck = False if stemmer is not None : if isinstance ( stemmer , collections . abc . Callable ) : stemCheck = True else : raise TagError ( "stemmer must be callable, e.g. a function or class with a __call__ method." ) count = 0 progArgs = ( 0 , "Starting to make a {} from {}" . format ( _net...
def show_system_monitor_output_switch_status_switch_ip ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) show_system_monitor = ET . Element ( "show_system_monitor" ) config = show_system_monitor output = ET . SubElement ( show_system_monitor , "output" ) switch_status = ET . SubElement ( output , "switch-status" ) switch_ip = ET . SubElement ( switch_status , "switch-ip" ) switch_ip . te...
def into_buffer ( self , buf , offset ) : """Produce a framed / packed SBP message into the provided buffer and offset ."""
self . payload = containerize ( exclude_fields ( self ) ) self . parser = MsgEphemerisGPSDepF . _parser self . stream_payload . reset ( buf , offset ) return self . pack_into ( buf , offset , self . _build_payload )
def update_display ( cb , pool , params , plane , qwertz ) : """Draws everything . : param cb : Cursebox instance . : type cb : cursebox . Cursebox : param params : Current application parameters . : type params : params . Params : param plane : Plane containing the current Mandelbrot values . : type pl...
cb . clear ( ) draw_panel ( cb , pool , params , plane ) update_position ( params ) # Update Mandelbrot - space coordinates before drawing them draw_menu ( cb , params , qwertz ) cb . refresh ( )
def calculate_bell_number ( index : int ) -> int : """A function to compute nth Bell number . A bell number is number that counts the number of ways to partition a set . > > > calculate _ bell _ number ( 2) > > > calculate _ bell _ number ( 3) > > > calculate _ bell _ number ( 4) 15"""
bell_matrix = [ [ 0 for _ in range ( index + 1 ) ] for _ in range ( index + 1 ) ] bell_matrix [ 0 ] [ 0 ] = 1 for i in range ( 1 , index + 1 ) : bell_matrix [ i ] [ 0 ] = bell_matrix [ i - 1 ] [ i - 1 ] for j in range ( 1 , i + 1 ) : bell_matrix [ i ] [ j ] = bell_matrix [ i - 1 ] [ j - 1 ] + bell_matri...
def autocorrelation ( signal ) : """The ` correlation < https : / / en . wikipedia . org / wiki / Autocorrelation # Estimation > ` _ of a signal with a delayed copy of itself . : param signal : A 1 - dimensional array or list ( the signal ) . : type signal : array : return : The autocorrelated signal . : rt...
signal = np . array ( signal ) n = len ( signal ) variance = signal . var ( ) signal -= signal . mean ( ) r = np . correlate ( signal , signal , mode = 'full' ) [ - n : ] result = r / ( variance * ( np . arange ( n , 0 , - 1 ) ) ) return np . array ( result )
async def ensure_closed ( self ) : """Send quit command and then close socket connection"""
if self . _writer is None : # connection has been closed return send_data = struct . pack ( '<i' , 1 ) + int2byte ( COMMAND . COM_QUIT ) self . _writer . write ( send_data ) await self . _writer . drain ( ) self . close ( )
async def api_call ( self , path , body = None , full_url = False ) : """Make the actual call to the HMIP server . Throws ` HmipWrongHttpStatusError ` or ` HmipConnectionError ` if connection has failed or response is not correct ."""
result = None if not full_url : path = self . full_url ( path ) for i in range ( self . _restCallRequestCounter ) : try : with async_timeout . timeout ( self . _restCallTimout , loop = self . _loop ) : result = await self . _websession . post ( path , data = body , headers = self . headers )...
def _set_color ( self , context , r , g , b , a ) : """the alpha has to changed based on the parent , so that happens at the time of drawing"""
if a < 1 : context . set_source_rgba ( r , g , b , a ) else : context . set_source_rgb ( r , g , b )
def user_update ( user_id = None , name = None , email = None , enabled = None , tenant = None , profile = None , project = None , description = None , ** connection_args ) : '''Update a user ' s information ( keystone user - update ) The following fields may be updated : name , email , enabled , tenant . Becau...
kstone = auth ( profile , ** connection_args ) if not user_id : for user in kstone . users . list ( ) : if user . name == name : user_id = user . id break if not user_id : return { 'Error' : 'Unable to resolve user id' } user = kstone . users . get ( user_id ) # Keep prev...
def _update_partition_in_create ( self , tenant_id , tenant_name ) : """Function to update a partition ."""
in_subnet_dict = self . get_in_ip_addr ( tenant_id ) # self . _ update _ partition ( tenant _ name , in _ ip ) # Need more generic thinking on this one TODO ( padkrish ) next_hop = str ( netaddr . IPAddress ( in_subnet_dict . get ( 'subnet' ) ) + 2 ) self . _update_partition_srvc_node_ip ( tenant_name , next_hop )
def serialize_job_ids ( self , job_ids ) : """Returns job _ ids serialized for storage in Redis"""
if len ( job_ids ) == 0 or self . use_large_ids : return job_ids elif isinstance ( job_ids [ 0 ] , ObjectId ) : return [ x . binary for x in job_ids ] else : return [ bytes . fromhex ( str ( x ) ) for x in job_ids ]
def __trim_grave_accent ( self , href ) : """Trim grave accents manually ( because BeautifulSoup doesn " t support it ) . Args : href ( str ) : The BeautifulSoup href value . Returns : str : The BeautifulSoup href value without grave accents ."""
if href . startswith ( "`" ) : href = href [ 1 : ] if href . endswith ( "`" ) : href = href [ : - 1 ] return href
def chain_update ( self , block , receipts ) : """Handles both " sawtooth / block - commit " Events and " identity / update " Events . For " sawtooth / block - commit " , the last _ block _ num is updated or a fork is detected . For " identity / update " , the corresponding cache entry will be updated ."""
block_events = BlockEventExtractor ( block ) . extract ( [ EventSubscription ( event_type = "sawtooth/block-commit" ) ] ) receipt_events = ReceiptEventExtractor ( receipts ) . extract ( [ EventSubscription ( event_type = "identity/update" ) ] ) for event in block_events : forked = self . _handle_block_commit ( even...
def read_strain_losc ( ifo , start_time , end_time ) : """Get the strain data from the LOSC data Parameters ifo : str The name of the IFO to read data for . Ex . ' H1 ' , ' L1 ' , ' V1' start _ time : int The gps time in GPS seconds end _ time : int The end time in GPS seconds Returns ts : TimeSer...
channel = _get_channel ( start_time ) return read_frame_losc ( '%s:%s' % ( ifo , channel ) , start_time , end_time )
def n_sections ( neurites , neurite_type = NeuriteType . all , iterator_type = Tree . ipreorder ) : '''Number of sections in a collection of neurites'''
return sum ( 1 for _ in iter_sections ( neurites , iterator_type = iterator_type , neurite_filter = is_type ( neurite_type ) ) )
def chunks ( seq , num ) : """Separate ` seq ` ( ` np . array ` ) into ` num ` series of as - near - as possible equal length values . : param seq : Sequence to split : type seq : np . array : param num : Number of parts to split sequence into : type num : int : return : np . array of split parts"""
avg = len ( seq ) / float ( num ) out = [ ] last = 0.0 while last < len ( seq ) : out . append ( seq [ int ( last ) : int ( last + avg ) ] ) last += avg return np . array ( out )
def parse_form_action_url ( html , parser = None ) : """Parse < form action = " ( . + ) " > url : param html : str : raw html text : param parser : bs4 . BeautifulSoup : html parser : return : url str : for example : / login . php ? act = security _ check & to = & hash = 12346"""
if parser is None : parser = bs4 . BeautifulSoup ( html , 'html.parser' ) forms = parser . find_all ( 'form' ) if not forms : raise VkParseError ( 'Action form is not found in the html \n%s' % html ) if len ( forms ) > 1 : raise VkParseError ( 'Find more than 1 forms to handle:\n%s' , forms ) form = forms [...
def list_directories ( dir_pathname , recursive = True , topdown = True , followlinks = False ) : """Enlists all the directories using their absolute paths within the specified directory , optionally recursively . : param dir _ pathname : The directory to traverse . : param recursive : ` ` True ` ` for wa...
for root , dirnames , filenames in walk ( dir_pathname , recursive , topdown , followlinks ) : for dirname in dirnames : yield absolute_path ( os . path . join ( root , dirname ) )
def _fork_and_supervise_child ( cls ) : """Fork a child and then watch the process group until there are no processes in it ."""
pid = os . fork ( ) if pid == 0 : # Fork again but orphan the child this time so we ' ll have # the original parent and the second child which is orphaned # so we don ' t have to worry about it becoming a zombie cls . _orphan_this_process ( ) return # Since this process is not going to exit , we need to call # ...
def make_graph_pydot ( self , recs , nodecolor , edgecolor , dpi , draw_parents = True , draw_children = True ) : """draw AMIGO style network , lineage containing one query record ."""
import pydot G = pydot . Dot ( graph_type = 'digraph' , dpi = "{}" . format ( dpi ) ) # Directed Graph edgeset = set ( ) usr_ids = [ rec . id for rec in recs ] for rec in recs : if draw_parents : edgeset . update ( rec . get_all_parent_edges ( ) ) if draw_children : edgeset . update ( rec . get_...
def _add_merged_attributes ( node , all_recipes , all_roles ) : """Merges attributes from cookbooks , node and roles Chef Attribute precedence : http : / / docs . opscode . com / essentials _ cookbook _ attribute _ files . html # attribute - precedence LittleChef implements , in precedence order : - Cookboo...
# Get cookbooks from extended recipes attributes = { } for recipe in node [ 'recipes' ] : # Find this recipe found = False for r in all_recipes : if recipe == r [ 'name' ] : found = True for attr in r [ 'attributes' ] : if r [ 'attributes' ] [ attr ] . get ( 'type...
def check_views ( view_set , max_views = 3 ) : """Ensures valid view / dimensions are selected ."""
if not isinstance ( view_set , Iterable ) : view_set = tuple ( [ view_set , ] ) if len ( view_set ) > max_views : raise ValueError ( 'Can only have {} views' . format ( max_views ) ) return [ check_int ( view , 'view' , min_value = 0 , max_value = max_views - 1 ) for view in view_set ]
def train ( self , data , ** kwargs ) : """Calculate the standard deviations and means in the training data"""
self . data = data for i in xrange ( 0 , data . shape [ 1 ] ) : column_mean = np . mean ( data . icol ( i ) ) column_stdev = np . std ( data . icol ( i ) ) # Have to do + = or " list " type will fail ( ie with append ) self . column_means += [ column_mean ] self . column_stdevs += [ column_stdev ] s...
def run ( cls , version = None ) : """Test runner method ; is called by parent class defined in suite . py . : param version : B2G version string to test against : return : bool PASS / FAIL status"""
try : dumper = certdump ( ) versions = dumper . nssversion_via_marionette ( ) except Exception as e : # TODO : too broad exception cls . log_status ( 'FAIL' , 'Failed to gather information from the device via Marionette: %s' % e ) return False if version is None : cls . log_status ( 'FAIL' , 'NSS ve...
def _read2bit ( d , l , offset = False ) : """Read DNA from a 2bit file where each base is encoded in 2bit (4 bases per byte ) . Parameters l : tuple Location tuple Returns list Array of base chars"""
s = l . start - 1 ret = bytearray ( [ 0 ] * l . length ) if offset : bi = s // 4 else : bi = 0 for i in range ( 0 , l . length ) : block = s % 4 if block == 0 : v = ( d [ bi ] >> 6 ) elif block == 1 : v = ( d [ bi ] >> 4 ) elif block == 2 : v = ( d [ bi ] >> 2 ) else ...
def any_embedded_linux ( self ) : """Check whether the current board is any embedded Linux device ."""
return self . any_raspberry_pi or self . any_beaglebone or self . any_orange_pi or self . any_giant_board or self . any_jetson_board