signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def data ( self ) : """Embedded file content , or empty if kind is ` external ` or ` alias `"""
if self . kind == 'data' : return self . _data . data else : with self . open ( ) as f : return f . read ( )
def method_name_exist ( self , meth_name ) : """Check if there is already a meth _ name method in the current class It is useful before allowing to rename a method to check name does not already exist ."""
methods = self . current_class . get_methods ( ) for m in methods : if m . name == meth_name : return True return False
def handler ( param ) : """Decorator that associates a handler to an event class This decorator works for both methods and functions . Since it only registers the callable object and returns it without evaluating it . The name param should be informed in a dotted notation and should contain two informations...
if isinstance ( param , basestring ) : return lambda f : _register_handler ( param , f ) else : core . HANDLER_METHOD_REGISTRY . append ( param ) return param
def on_message ( self , msg ) : '''When a message with an already known traversal _ id is received , we try to build a duplication message and send it in to a protocol dependent recipient . This is used in contracts traversing the graph , when the contract has reached again the same shard . This message is ...
self . log ( 'Received message: %r' , msg ) # Check if it isn ' t expired message time_left = time . left ( msg . expiration_time ) if time_left < 0 : self . log ( 'Throwing away expired message. Time left: %s, ' 'msg_class: %r' , time_left , msg . get_msg_class ( ) ) return False # Check for duplicated message...
def wiki_delete ( self , page_id ) : """Delete a specific page wiki ( Requires login ) ( UNTESTED ) ( Builder + ) . Parameters : page _ id ( int ) :"""
return self . _get ( 'wiki_pages/{0}.json' . format ( page_id ) , auth = True , method = 'DELETE' )
def replace_in_dirs ( version ) : """Look through dirs and run replace _ in _ files in each ."""
print ( color ( "Upgrading directory-components dependency in all repos..." , fg = 'blue' , style = 'bold' ) ) for dirname in Utils . dirs : replace = "directory-components=={}" . format ( version ) replace_in_files ( dirname , replace ) done ( version )
def relocate_digits ( str_input ) : """This function relocates all numbers in a string to the end of the string . Args : str _ input : A string containing alphanumeric characters . Returns : The input string with all numbers moved to the end of the string . Examples : > > > relocate _ digits ( ' I1love1...
non_digit_chars = '' digit_chars = '' for char in str_input : if char . isdigit ( ) : digit_chars += char else : non_digit_chars += char return non_digit_chars + digit_chars
def modifydocs ( a , b , desc = '' ) : """Convenience function for writing documentation . For a class method ` a ` that is essentially a wrapper for an outside function ` b ` , rope in the docstring from ` b ` and append to that of ` a ` . Also modify the docstring of ` a ` to get the indentation right . W...
newdoc = a . func_doc . replace ( '\t\t' , '\t' ) newdoc += "Documentation from " + desc + ":\n" + b . func_doc return newdoc
def on_error ( self , content ) : """In case of error , conf [ ' error ' ] is checked for policy name . It can be ' ignore ' , or ' notify ' ( default ) . Ignore policy replaces content with None , Notify policy passes content through ."""
error_policy = self . conf . get ( 'error' , 'notify' ) if error_policy == 'ignore' : if content : logger . error ( "Ignoring error in %s" , repr ( content ) [ : 60 ] ) return None elif error_policy == 'notify' : logger . debug ( "Notifying on error" ) return content else : logger . warning ...
def add_inputs ( self , rawtx , wifs , change_address = None , fee = 10000 , dont_sign = False ) : """Add sufficient inputs from given < wifs > to cover < rawtx > outputs and < fee > . If no < change _ address > is given , change will be sent to first wif ."""
tx = deserialize . tx ( rawtx ) keys = deserialize . keys ( self . testnet , wifs ) fee = deserialize . positive_integer ( fee ) if change_address is not None : change_address = deserialize . address ( self . testnet , change_address ) tx = control . add_inputs ( self . service , self . testnet , tx , keys , change...
def _ascii_tree ( self , indent : str , no_types : bool , val_count : bool ) -> str : """Return the receiver ' s subtree as ASCII art ."""
def suffix ( sn ) : return f" {{{sn.val_count}}}\n" if val_count else "\n" if not self . children : return "" cs = [ ] for c in self . children : cs . extend ( c . _flatten ( ) ) cs . sort ( key = lambda x : x . qual_name ) res = "" for c in cs [ : - 1 ] : res += ( indent + c . _tree_line ( no_types ) +...
def bfs ( self , root = None , display = None , priority = 'L' ) : '''API : bfs ( self , root = None , display = None , priority = ' L ' , order = ' in ' ) Description : Searches tree starting from node named root using breadth - first strategy if root argument is provided . Starts search from root node of ...
if root == None : root = self . root self . traverse ( root , display , Queue ( ) , priority )
def __view_to_intervals ( self , data_and_metadata : DataAndMetadata . DataAndMetadata , intervals : typing . List [ typing . Tuple [ float , float ] ] ) -> None : """Change the view to encompass the channels and data represented by the given intervals ."""
left = None right = None for interval in intervals : left = min ( left , interval [ 0 ] ) if left is not None else interval [ 0 ] right = max ( right , interval [ 1 ] ) if right is not None else interval [ 1 ] left = left if left is not None else 0.0 right = right if right is not None else 1.0 left_channel = in...
def _get_max_sigma ( self , R ) : """Calculate maximum sigma of scanner RAS coordinates Parameters R : 2D array , with shape [ n _ voxel , n _ dim ] The coordinate matrix of fMRI data from one subject Returns max _ sigma : float The maximum sigma of scanner coordinates ."""
max_sigma = 2.0 * math . pow ( np . nanmax ( np . std ( R , axis = 0 ) ) , 2 ) return max_sigma
def send ( self , tids , session , ** kwargs ) : '''taobao . topats . delivery . send 异步批量物流发货api 使用指南 : http : / / open . taobao . com / dev / index . php / ATS % E4 % BD % BF % E7%94 % A8 % E6%8C % 87 % E5%8D % 97 - 1 . 提供异步批量物流发货功能 - 2 . 一次最多发货40个订单 - 3 . 提交任务会进行初步任务校验 , 如果成功会返回任务号和创建时间 , 如果失败就报错 - 4 ....
request = TOPRequest ( 'taobao.postage.add' ) request [ 'tids' ] = tids for k , v in kwargs . iteritems ( ) : if k not in ( 'company_codes' , 'out_sids' , 'seller_name' , 'seller_area_id' , 'seller_address' , 'seller_zip' , 'seller_phone' , 'seller_mobile' , 'order_types' , 'memos' ) and v == None : continu...
def _normalize_day ( year , month , day ) : """Coerce the day of the month to an internal value that may or may not match the " public " value . With the exception of the last three days of every month , all days are stored as - is . The last three days are instead stored as - 1 ( the last ) , - 2 ( first f...
if year < MIN_YEAR or year > MAX_YEAR : raise ValueError ( "Year out of range (%d..%d)" % ( MIN_YEAR , MAX_YEAR ) ) if month < 1 or month > 12 : raise ValueError ( "Month out of range (1..12)" ) days_in_month = DAYS_IN_MONTH [ ( year , month ) ] if day in ( days_in_month , - 1 ) : return year , month , - 1 ...
def pcklof ( filename ) : """Load a binary PCK file for use by the readers . Return the handle of the loaded file which is used by other PCK routines to refer to the file . http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / pcklof _ c . html : param filename : Name of the file t...
filename = stypes . stringToCharP ( filename ) handle = ctypes . c_int ( ) libspice . pcklof_c ( filename , ctypes . byref ( handle ) ) return handle . value
def read_certificate ( self , certificate_name ) : '''a method to retrieve the details about a server certificate : param certificate _ name : string with name of server certificate : return : dictionary with certificate details'''
title = '%s.read_certificate' % self . __class__ . __name__ # validate inputs input_fields = { 'certificate_name' : certificate_name } for key , value in input_fields . items ( ) : object_title = '%s(%s=%s)' % ( title , key , str ( value ) ) self . fields . validate ( value , '.%s' % key , object_title ) # veri...
def _get_pants_target_alias ( self , pants_target_type ) : """Returns the pants target alias for the given target"""
if pants_target_type in self . target_aliases_map : return self . target_aliases_map . get ( pants_target_type ) else : return "{}.{}" . format ( pants_target_type . __module__ , pants_target_type . __name__ )
def reset ( self ) : """factory reset"""
print '%s call reset' % self . port try : self . _sendline ( 'factoryreset' ) self . _read ( ) except Exception , e : ModuleHelper . WriteIntoDebugLogger ( "reset() Error: " + str ( e ) )
def get_sngl_chisqs ( self , instruments = None ) : """Get the single - detector \ chi ^ 2 for each row in the table ."""
if len ( self ) and instruments is None : instruments = map ( str , instrument_set_from_ifos ( self [ 0 ] . ifos ) ) elif instruments is None : instruments = [ ] return dict ( ( ifo , self . get_sngl_chisq ( ifo ) ) for ifo in instruments )
def decrypt ( self , key , data , mode , padding ) : # pylint : disable = unused - argument , no - self - use """Decrypt data using the supplied values . : param bytes key : Loaded decryption key : param bytes data : IV prepended to encrypted data : param JavaMode mode : Decryption mode to use ( not used by :...
if hasattr ( key , "public_bytes" ) : raise NotImplementedError ( '"decrypt" is not supported by public keys' ) try : return key . decrypt ( data , padding . build ( ) ) except Exception : error_message = "Decryption failed" _LOGGER . exception ( error_message ) raise DecryptionError ( error_message...
def entrez_batch_webhistory ( record , expected , batchsize , * fnargs , ** fnkwargs ) : """Recovers the Entrez data from a prior NCBI webhistory search , in batches of defined size , using Efetch . Returns all results as a list . - record : Entrez webhistory record - expected : number of expected search retu...
results = [ ] for start in range ( 0 , expected , batchsize ) : batch_handle = entrez_retry ( Entrez . efetch , retstart = start , retmax = batchsize , webenv = record [ "WebEnv" ] , query_key = record [ "QueryKey" ] , * fnargs , ** fnkwargs ) batch_record = Entrez . read ( batch_handle , validate = False ) ...
def frequency_from_polarizations ( h_plus , h_cross ) : """Return gravitational wave frequency Return the gravitation - wave frequency as a function of time from the h _ plus and h _ cross polarizations of the waveform . It is 1 bin shorter than the input vectors and the sample times are advanced half a bin...
phase = phase_from_polarizations ( h_plus , h_cross ) freq = numpy . diff ( phase ) / ( 2 * lal . PI * phase . delta_t ) start_time = phase . start_time + phase . delta_t / 2 return TimeSeries ( freq . astype ( real_same_precision_as ( h_plus ) ) , delta_t = phase . delta_t , epoch = start_time )
def get_sources ( self , skydir = None , distance = None , cuts = None , minmax_ts = None , minmax_npred = None , exclude = None , square = False , coordsys = 'CEL' , names = None ) : """Retrieve list of source objects satisfying the following selections : * Angular separation from ` ` skydir ` ` or ROI center ...
if skydir is None : skydir = self . skydir if exclude is None : exclude = [ ] rsrc , srcs = self . get_sources_by_position ( skydir , distance , square = square , coordsys = coordsys ) o = [ ] for s in srcs + self . diffuse_sources : if names and s . name not in names : continue if s . name in e...
def _checkMissingParams ( self , template , ** kwargs ) : """Check the missing parameters for rendering from the template file"""
parameters = self . listFields ( template ) self . _findMissingParams ( parameters , ** kwargs )
def _evaluate ( self , x , y ) : '''Returns the level of the interpolated function at each value in x , y . Only called internally by HARKinterpolator2D . _ _ call _ _ ( etc ) .'''
x_pos , y_pos = self . findSector ( x , y ) alpha , beta = self . findCoords ( x , y , x_pos , y_pos ) # Calculate the function at each point using bilinear interpolation f = ( ( 1 - alpha ) * ( 1 - beta ) * self . f_values [ x_pos , y_pos ] + ( 1 - alpha ) * beta * self . f_values [ x_pos , y_pos + 1 ] + alpha * ( 1 -...
def get_draft_entries ( number = 5 , template = 'zinnia/tags/entries_draft.html' ) : """Return the last draft entries ."""
return { 'template' : template , 'entries' : Entry . objects . filter ( status = DRAFT ) [ : number ] }
def control_system_state_send ( self , time_usec , x_acc , y_acc , z_acc , x_vel , y_vel , z_vel , x_pos , y_pos , z_pos , airspeed , vel_variance , pos_variance , q , roll_rate , pitch_rate , yaw_rate , force_mavlink1 = False ) : '''The smoothed , monotonic system state used to feed the control loops of the syst...
return self . send ( self . control_system_state_encode ( time_usec , x_acc , y_acc , z_acc , x_vel , y_vel , z_vel , x_pos , y_pos , z_pos , airspeed , vel_variance , pos_variance , q , roll_rate , pitch_rate , yaw_rate ) , force_mavlink1 = force_mavlink1 )
def is_port_profile_created ( self , vlan_id , device_id ) : """Indicates if port profile has been created on UCS Manager ."""
entry = self . session . query ( ucsm_model . PortProfile ) . filter_by ( vlan_id = vlan_id , device_id = device_id ) . first ( ) return entry and entry . created_on_ucs
def relative_point ( self , bearing_to_point , distance ) : '''Return a waypoint at a location described relative to the current point : param bearing _ to _ point : Relative bearing from the current waypoint : type bearing _ to _ point : Bearing : param distance : Distance from the current waypoint : type ...
bearing = math . radians ( 360 - bearing_to_point ) rad_distance = ( distance / EARTH_RADIUS ) lat1 = ( self . lat_radians ) lon1 = ( self . long_radians ) lat3 = math . asin ( math . sin ( lat1 ) * math . cos ( rad_distance ) + math . cos ( lat1 ) * math . sin ( rad_distance ) * math . cos ( bearing ) ) lon3 = lon1 + ...
def _get_parselypage ( self , body ) : """extract the parsely - page meta content from a page"""
parser = ParselyPageParser ( ) ret = None try : parser . feed ( body ) except HTMLParseError : pass # ignore and hope we got ppage if parser . ppage is None : return ret = parser . ppage if ret : ret = { parser . original_unescape ( k ) : parser . original_unescape ( v ) for k , v in iteritems ( ret...
def _train_model ( self , train_set , train_labels , validation_set , validation_labels ) : """Train the model . : param train _ set : training set : param train _ labels : training labels : param validation _ set : validation set : param validation _ labels : validation labels : return : self"""
shuff = list ( zip ( train_set , train_labels ) ) pbar = tqdm ( range ( self . num_epochs ) ) for i in pbar : np . random . shuffle ( list ( shuff ) ) batches = [ _ for _ in utilities . gen_batches ( shuff , self . batch_size ) ] for batch in batches : x_batch , y_batch = zip ( * batch ) sel...
def head ( self , item ) : """Makes a HEAD request on a specific item ."""
uri = "/%s/%s" % ( self . uri_base , utils . get_id ( item ) ) return self . _head ( uri )
def authorize_with_service_account ( self , email , scope , callback_url , state = None ) : """Attempts to authorize the email with impersonation from a service account : param string email : the email address to impersonate : param string callback _ url : URL to callback with the OAuth code . : param string ...
params = { 'email' : email , 'scope' : scope , 'callback_url' : callback_url } if state is not None : params [ 'state' ] = state self . request_handler . post ( endpoint = "service_account_authorizations" , data = params ) None
def publish ( self , name , data , userList ) : """Publish data"""
# Publish data to all room users self . broadcast ( userList , { "name" : name , "data" : SockJSDefaultHandler . _parser . encode ( data ) } )
def p_expression_minus ( self , p ) : 'expression : expression MINUS expression'
p [ 0 ] = Minus ( p [ 1 ] , p [ 3 ] , lineno = p . lineno ( 1 ) ) p . set_lineno ( 0 , p . lineno ( 1 ) )
def describe_node ( self , node ) : """return node , node data , outgoing edges , incoming edges for node"""
incoming , outgoing , data = self . nodes [ node ] return node , data , outgoing , incoming
def _mouseDown ( x , y , button ) : """Send the mouse down event to Windows by calling the mouse _ event ( ) win32 function . Args : x ( int ) : The x position of the mouse event . y ( int ) : The y position of the mouse event . button ( str ) : The mouse button , either ' left ' , ' middle ' , or ' right...
if button == 'left' : try : _sendMouseEvent ( MOUSEEVENTF_LEFTDOWN , x , y ) except ( PermissionError , OSError ) : # TODO : We need to figure out how to prevent these errors , see https : / / github . com / asweigart / pyautogui / issues / 60 pass elif button == 'middle' : try : _se...
def _call_salt_command ( self , fun , args , kwargs , assertion_section = None ) : '''Generic call of salt Caller command'''
value = False try : if args and kwargs : value = self . salt_lc . cmd ( fun , * args , ** kwargs ) elif args and not kwargs : value = self . salt_lc . cmd ( fun , * args ) elif not args and kwargs : value = self . salt_lc . cmd ( fun , ** kwargs ) else : value = self . sa...
def get_privkey_address ( privkey_info , blockchain = 'bitcoin' , ** blockchain_opts ) : """Get the address from a private key bundle"""
if blockchain == 'bitcoin' : return btc_get_privkey_address ( privkey_info , ** blockchain_opts ) else : raise ValueError ( 'Unknown blockchain "{}"' . format ( blockchain ) )
def _generate_examples ( self , filepath ) : """This function returns the examples in the raw ( text ) form ."""
logging . info ( "generating examples from = %s" , filepath ) with tf . io . gfile . GFile ( filepath ) as f : squad = json . load ( f ) for article in squad [ "data" ] : if "title" in article : title = article [ "title" ] . strip ( ) else : title = "" for paragra...
def main ( argv : Optional [ Sequence [ str ] ] = None ) -> None : """Parse arguments and process the homework assignment ."""
parser = ArgumentParser ( description = "Convert Jupyter Notebook assignments to PDFs" ) parser . add_argument ( "--hw" , type = int , required = True , help = "Homework number to convert" , dest = "hw_num" , ) parser . add_argument ( "-p" , "--problems" , type = int , help = "Problem numbers to convert" , dest = "prob...
def resample ( self , data , cache_dir = None , mask_area = None , ** kwargs ) : """Resample ` data ` by calling ` precompute ` and ` compute ` methods . Only certain resampling classes may use ` cache _ dir ` and the ` mask ` provided when ` mask _ area ` is True . The return value of calling the ` precomput...
# default is to mask areas for SwathDefinitions if mask_area is None and isinstance ( self . source_geo_def , SwathDefinition ) : mask_area = True if mask_area : if isinstance ( self . source_geo_def , SwathDefinition ) : geo_dims = self . source_geo_def . lons . dims else : geo_dims = ( 'y'...
def apply_repulsion ( repulsion , nodes , barnes_hut_optimize = False , region = None , barnes_hut_theta = 1.2 ) : """Iterate through the nodes or edges and apply the forces directly to the node objects ."""
if not barnes_hut_optimize : for i in range ( 0 , len ( nodes ) ) : for j in range ( 0 , i ) : repulsion . apply_node_to_node ( nodes [ i ] , nodes [ j ] ) else : for i in range ( 0 , len ( nodes ) ) : region . apply_force ( nodes [ i ] , repulsion , barnes_hut_theta )
def capture ( self , instance_id , name , additional_disks = False , notes = None ) : """Capture one or all disks from a VS to a SoftLayer image . Parameters set to None will be ignored and not attempted to be updated . : param integer instance _ id : the instance ID to edit : param string name : name assigne...
vsi = self . client . call ( 'Virtual_Guest' , 'getObject' , id = instance_id , mask = """id, blockDevices[id,device,mountType, diskImage[id,metadataFlag,type[keyName]]]""" ) disks_to_capture = [ ] for block_device in vsi [ 'blockDevices' ] : # We never want metadata disks if utils . lookup ...
def array_controllers ( self ) : """This property gets the list of instances for array controllers This property gets the list of instances for array controllers : returns : a list of instances of array controllers ."""
return array_controller . HPEArrayControllerCollection ( self . _conn , utils . get_subresource_path_by ( self , [ 'Links' , 'ArrayControllers' ] ) , redfish_version = self . redfish_version )
def _transform_row_wrapper ( self , row ) : """Transforms a single source row . : param dict [ str | str ] row : The source row ."""
self . _count_total += 1 try : # Transform the naturals keys in line to technical keys . in_row = copy . copy ( row ) out_row = { } park_info , ignore_info = self . _transform_row ( in_row , out_row ) except Exception as e : # Log the exception . self . _handle_exception ( row , e ) # Keep track of ...
def get_account_holds ( self , account_id , ** kwargs ) : """Get holds on an account . This method returns a generator which may make multiple HTTP requests while iterating through it . Holds are placed on an account for active orders or pending withdraw requests . As an order is filled , the hold amount ...
endpoint = '/accounts/{}/holds' . format ( account_id ) return self . _send_paginated_message ( endpoint , params = kwargs )
def observer ( names_or_instance , names = None , func = None , change_only = False ) : """Specify a callback function that will fire on Property value change Observer functions on a HasProperties class fire after the observed Property or Properties have been changed ( unlike validator functions that fire on ...
mode = 'observe_change' if change_only else 'observe_set' if names is None and func is None : return Observer ( names_or_instance , mode ) obs = Observer ( names , mode ) ( func ) _set_listener ( names_or_instance , obs ) return obs
def remove_storage_controller ( self , name ) : """Removes a storage controller from the machine with all devices attached to it . in name of type str raises : class : ` VBoxErrorObjectNotFound ` A storage controller with given name doesn ' t exist . raises : class : ` VBoxErrorNotSupported ` Medium forma...
if not isinstance ( name , basestring ) : raise TypeError ( "name can only be an instance of type basestring" ) self . _call ( "removeStorageController" , in_p = [ name ] )
def sign_assertion_using_xmlsec ( self , statement , ** kwargs ) : """Deprecated function . See sign _ assertion ( ) ."""
return self . sign_statement ( statement , class_name ( saml . Assertion ( ) ) , ** kwargs )
def transfer_session_cookies_to_driver ( self , domain = None ) : """Copies the Session ' s cookies into the webdriver Using the ' domain ' parameter we choose the cookies we wish to transfer , we only transfer the cookies which belong to that domain . The domain defaults to our last visited site if not provi...
if not domain and self . _last_requests_url : domain = tldextract . extract ( self . _last_requests_url ) . registered_domain elif not domain and not self . _last_requests_url : raise Exception ( 'Trying to transfer cookies to selenium without specifying a domain ' 'and without having visited any page in the cu...
def get_fasta_record ( fasta_file , transcript_name ) : """Return a single transcript from a valid fasta file as a record . record [ transcript _ name ] = sequence Keyword arguments : fasta _ file - - FASTA format file of the transcriptome transcript _ name - - Name of the transcript as in the FASTA header"...
with open_pysam_file ( fname = fasta_file , ftype = 'fasta' ) as f : sequence = f . fetch ( transcript_name ) return { transcript_name : sequence }
def is_subnet_present ( self , subnet_addr ) : """Returns if a subnet is present ."""
try : subnet_list = self . neutronclient . list_subnets ( body = { } ) subnet_dat = subnet_list . get ( 'subnets' ) for sub in subnet_dat : if sub . get ( 'cidr' ) == subnet_addr : return True return False except Exception as exc : LOG . error ( "Failed to list subnet %(sub)s, Ex...
def get ( method , hmc , uri , uri_parms , logon_required ) : """Operation : List Logical Partitions of CPC ( empty result in DPM mode ."""
cpc_oid = uri_parms [ 0 ] query_str = uri_parms [ 1 ] try : cpc = hmc . cpcs . lookup_by_oid ( cpc_oid ) except KeyError : raise InvalidResourceError ( method , uri ) result_lpars = [ ] if not cpc . dpm_enabled : filter_args = parse_query_parms ( method , uri , query_str ) for lpar in cpc . lpars . list...
def publish ( func ) : """publish the return value of this function as a message from this endpoint"""
@ wraps ( func ) def wrapper ( self , * args , ** kwargs ) : # outgoing payload = func ( self , * args , ** kwargs ) payload . pop ( 'self' , None ) self . _publish ( func . __name__ , payload ) return None wrapper . is_publish = True return wrapper
def tagmask ( self , tags ) : """: returns : a boolean array with True where the assets has tags"""
mask = numpy . zeros ( len ( tags ) , bool ) for t , tag in enumerate ( tags ) : tagname , tagvalue = tag . split ( '=' ) mask [ t ] = self . tagvalue ( tagname ) == tagvalue return mask
def condition_to_lambda ( condition , default = False ) : """Translates an integer , set , list or function into a lambda that checks if state ' s current basic block matches some condition . : param condition : An integer , set , list or lambda to convert to a lambda . : param default : The default return va...
if condition is None : condition_function = lambda state : default static_addrs = set ( ) elif isinstance ( condition , int ) : return condition_to_lambda ( ( condition , ) ) elif isinstance ( condition , ( tuple , set , list ) ) : static_addrs = set ( condition ) def condition_function ( state ) : ...
def get_attribute_data ( doc ) : """Helper function : parse attribute data from a wiki html doc Args : doc ( document parsed with lxml . html ) : parsed wiki page Returns : dict : attributes values and listed links , format ` ` { < key > : { ' value ' : < value > , ' link ' : < link > } } ` ` ; only the f...
attributes = dict ( ) for attribute_node in doc . xpath ( "//div[contains(@class, 'pi-data ')]" ) : # label node node = attribute_node . xpath ( ".//*[contains(@class, 'pi-data-label')]" ) [ 0 ] label = " " . join ( node . itertext ( ) ) . strip ( ) # value node node = attribute_node . xpath ( ".//*[con...
def diff_op ( self ) : """The diffusion operator calculated from the data"""
if self . graph is not None : if isinstance ( self . graph , graphtools . graphs . LandmarkGraph ) : diff_op = self . graph . landmark_op else : diff_op = self . graph . diff_op if sparse . issparse ( diff_op ) : diff_op = diff_op . toarray ( ) return diff_op else : raise Not...
def letter_scales ( counts ) : """Convert letter counts to frequencies , sorted increasing ."""
try : scale = 1.0 / sum ( counts . values ( ) ) except ZeroDivisionError : # This logo is all gaps , nothing can be done return [ ] freqs = [ ( aa , cnt * scale ) for aa , cnt in counts . iteritems ( ) if cnt ] freqs . sort ( key = lambda pair : pair [ 1 ] ) return freqs
def update_subscription ( self , * , subscription_id , credit_card_token ) : """Update information associated with the specified subscription . At the moment it is only possible to update the token of the credit card to which the charge of the subscription is made . Args : subscription _ id : Identification o...
payload = { "creditCardToken" : credit_card_token } fmt = 'subscriptions/{}' . format ( subscription_id ) return self . client . _put ( self . url + fmt , json = payload , headers = self . get_headers ( ) )
def get_accounts ( self , username = None ) : """Get a list of accounts owned by the user . Parameters username : string The name of the user . Note : This is only required on the sandbox , on production systems your access token will identify you . See more : http : / / developer . oanda . com / rest...
url = "{0}/{1}/accounts" . format ( self . domain , self . API_VERSION ) params = { "username" : username } try : return self . _Client__call ( uri = url , params = params , method = "get" ) except RequestException : return False except AssertionError : return False
def do_rm ( self , line ) : "rm [ : tablename ] [ ! fieldname : expectedvalue ] [ - v ] { haskkey [ rangekey ] }"
table , line = self . get_table_params ( line ) expected , line = self . get_expected ( line ) args = self . getargs ( line ) if "-v" in args : ret = "ALL_OLD" args . remove ( "-v" ) else : ret = None hkey = self . get_typed_key_value ( table , args [ 0 ] , True ) rkey = self . get_typed_key_value ( table ,...
def _check_compatible_with ( self , other : Union [ Period , Timestamp , Timedelta , NaTType ] , ) -> None : """Verify that ` self ` and ` other ` are compatible . * DatetimeArray verifies that the timezones ( if any ) match * PeriodArray verifies that the freq matches * Timedelta has no verification In eac...
raise AbstractMethodError ( self )
def _rpc_response_callback ( self , channel , method_frame , header_frame , body ) : """Internal callback used by consume ( ) Parameters channel : object Channel from which the callback originated method _ frame : dict Information about the message header _ frame : dict Headers of the message body :...
self . logger . debug ( "Received RPC response with correlation_id: {0}" . format ( header_frame . correlation_id ) ) if header_frame . correlation_id in self . responses : self . responses [ header_frame . correlation_id ] = { "method_frame" : method_frame , "header_frame" : header_frame , "body" : body } channel ...
def __add_annotation_tier ( self , docgraph , body , annotation_layer ) : """adds a span - based annotation layer as a < tier > to the Exmaralda < body > . Parameter docgraph : DiscourseDocumentGraph the document graph from which the chains will be extracted body : etree . _ Element an etree representatio...
layer_cat = annotation_layer . split ( ':' ) [ - 1 ] temp_tier = self . E ( 'tier' , { 'id' : "TIE{}" . format ( self . tier_count ) , 'category' : layer_cat , 'type' : "t" , 'display-name' : "[{}]" . format ( annotation_layer ) } ) self . tier_count += 1 for node_id in select_nodes_by_layer ( docgraph , annotation_lay...
def wind_components ( speed , wdir ) : r"""Calculate the U , V wind vector components from the speed and direction . Parameters speed : array _ like The wind speed ( magnitude ) wdir : array _ like The wind direction , specified as the direction from which the wind is blowing ( 0-2 pi radians or 0-360 d...
wdir = _check_radians ( wdir , max_radians = 4 * np . pi ) u = - speed * np . sin ( wdir ) v = - speed * np . cos ( wdir ) return u , v
def escapeForIRI ( xri ) : """Escape things that need to be escaped when transforming to an IRI ."""
xri = xri . replace ( '%' , '%25' ) xri = _xref_re . sub ( _escape_xref , xri ) return xri
def run_migrations_offline ( ) : """Run migrations in ' offline ' mode . This configures the context with just a URL and not an Engine , though an Engine is acceptable here as well . By skipping the Engine creation we don ' t even need a DBAPI to be available . Calls to context . execute ( ) here emit the...
url = config . get_main_option ( "sqlalchemy.url" ) context . configure ( url = url , target_metadata = target_metadata , literal_binds = True ) with context . begin_transaction ( ) : context . run_migrations ( )
def _cache_offsets ( self , up_to_index = None , verbose = True ) : """Cache all event offsets ."""
if not up_to_index : if verbose : self . print ( "Caching event file offsets, this may take a bit." ) self . blob_file . seek ( 0 , 0 ) self . event_offsets = [ ] if not self . raw_header : self . event_offsets . append ( 0 ) else : self . blob_file . seek ( self . event_offsets [ - ...
def _tie_correct ( sample ) : """Returns the tie correction value for U . See : https : / / docs . scipy . org / doc / scipy / reference / generated / scipy . stats . tiecorrect . html"""
tc = 0 n = sum ( sample . values ( ) ) if n < 2 : return 1.0 # Avoid a ` ` ZeroDivisionError ` ` . for k in sorted ( sample . keys ( ) ) : tc += math . pow ( sample [ k ] , 3 ) - sample [ k ] tc = 1 - tc / ( math . pow ( n , 3 ) - n ) return tc
def get_entries ( path ) : """Return sorted lists of directories and files in the given path ."""
dirs , files = [ ] , [ ] for entry in os . listdir ( path ) : # Categorize entry as directory or file . if os . path . isdir ( os . path . join ( path , entry ) ) : dirs . append ( entry ) else : files . append ( entry ) dirs . sort ( ) files . sort ( ) return dirs , files
def remove_file ( self , name ) : """Remove cur _ dir / name ."""
self . check_write ( name ) path = os . path . join ( self . cur_dir , name ) os . remove ( path )
def set_scope ( self , include = None , exclude = None ) : """Sets ` scope ` , the " start point " for the audit . Args : include : A list of css selectors specifying the elements that contain the portion of the page that should be audited . Defaults to auditing the entire document . exclude : This arg is...
if include : self . scope = u"document.querySelector(\"{}\")" . format ( u', ' . join ( include ) ) else : self . scope = "null" if exclude is not None : raise NotImplementedError ( "The argument `exclude` has not been implemented in " "AxsAuditConfig.set_scope method." )
def _resume ( self ) : # type : ( Descriptor ) - > int """Resume a download , if possible : param Descriptor self : this : rtype : int or None : return : verified download offset"""
if self . _resume_mgr is None or self . _offset > 0 : return None # check if path exists in resume db rr = self . _resume_mgr . get_record ( self . _dst_ase ) if rr is None : logger . debug ( 'no resume record for {}' . format ( self . _dst_ase . path ) ) return None # ensure lengths are the same if rr . le...
def reinforce_branches_voltage ( grid , crit_branches , grid_level = 'MV' ) : # TODO : finish docstring """Reinforce MV or LV grid by installing a new branch / line type Parameters grid : GridDing0 Grid identifier . crit _ branches : : any : ` list ` of : obj : ` int ` List of critical branches . # TODO :...
# load cable data , file _ names and parameter branch_parameters = grid . network . static_data [ '{gridlevel}_cables' . format ( gridlevel = grid_level ) ] branch_parameters = branch_parameters [ branch_parameters [ 'U_n' ] == grid . v_level ] . sort_values ( 'I_max_th' ) branch_ctr = 0 for branch in crit_branches : ...
def nltides_gw_phase_diff_isco ( f_low , f0 , amplitude , n , m1 , m2 ) : """Calculate the gravitational - wave phase shift bwtween f _ low and f _ isco due to non - linear tides . Parameters f _ low : float Frequency from which to compute phase . If the other arguments are passed as numpy arrays then the...
f0 , amplitude , n , m1 , m2 , input_is_array = ensurearray ( f0 , amplitude , n , m1 , m2 ) f_low = numpy . zeros ( m1 . shape ) + f_low phi_l = nltides_gw_phase_difference ( f_low , f0 , amplitude , n , m1 , m2 ) f_isco = f_schwarzchild_isco ( m1 + m2 ) phi_i = nltides_gw_phase_difference ( f_isco , f0 , amplitude , ...
def init_completer ( self ) : """Initialize the completion machinery . This creates a completer that provides the completions that are IPython specific . We use this to supplement PyDev ' s core code completions ."""
# PyDev uses its own completer and custom hooks so that it uses # most completions from PyDev ' s core completer which provides # extra information . # See getCompletions for where the two sets of results are merged if IPythonRelease . _version_major >= 6 : self . Completer = self . _new_completer_600 ( ) elif IPyt...
def exists ( self , digest ) : """Check file existence in fsdb Returns : True if file exists under this instance of fsdb , false otherwise"""
if not isinstance ( digest , string_types ) : raise TypeError ( "digest must be a string" ) return os . path . isfile ( self . get_file_path ( digest ) )
def connect_container_to_network ( self , container , net_id , ipv4_address = None , ipv6_address = None , aliases = None , links = None , link_local_ips = None ) : """Connect a container to a network . Args : container ( str ) : container - id / name to be connected to the network net _ id ( str ) : network ...
data = { "Container" : container , "EndpointConfig" : self . create_endpoint_config ( aliases = aliases , links = links , ipv4_address = ipv4_address , ipv6_address = ipv6_address , link_local_ips = link_local_ips ) , } url = self . _url ( "/networks/{0}/connect" , net_id ) res = self . _post_json ( url , data = data )...
def read_yaml_file ( self , file_name ) : """Parses a YAML file into a matrix . : param file _ name : name of the YAML file : return : a matrix with the file ' s contents"""
with open ( os . path . join ( self . __path ( ) , os . path . basename ( file_name ) ) , 'rt' ) as yamlfile : return yaml . load ( yamlfile )
def add_device ( ) : """Add a device via HTTP POST . POST JSON in the following format : : " device _ id " : " < your _ device _ id > " , " host " : " < address > : < port > " , " adbkey " : " < path to the adbkey file > " """
req = request . get_json ( ) success = False if 'device_id' in req and 'host' in req : success = add ( req [ 'device_id' ] , req [ 'host' ] , req . get ( 'adbkey' , '' ) , req . get ( 'adb_server_ip' , '' ) , req . get ( 'adb_server_port' , 5037 ) ) return jsonify ( success = success )
def next_position ( self , pos ) : """returns the next position in depth - first order"""
candidate = None if pos is not None : candidate = self . first_child_position ( pos ) if candidate is None : candidate = self . next_sibling_position ( pos ) if candidate is None : candidate = self . _next_of_kin ( pos ) return candidate
def disable_cors ( self ) : """Switches CORS off . : returns : CORS status in JSON format"""
return self . update_cors_configuration ( enable_cors = False , allow_credentials = False , origins = [ ] , overwrite_origins = True )
def prep_search_string ( cls , search_string , match_substrings ) : """Prepares search string as a proper whoosh search string . : param search _ string : The search string which should be prepared . : param match _ substrings : ` ` True ` ` if you want to match substrings , ` ` False ` ` otherwise ."""
if sys . version < '3' and not isinstance ( search_string , unicode ) : search_string = search_string . decode ( 'utf-8' ) s = search_string . strip ( ) # we don ' t want stars from user s = s . replace ( '*' , '' ) if len ( s ) < _get_config ( cls ) [ 'search_string_min_len' ] : raise ValueError ( 'Search stri...
def input ( self , filter_fn , prompt ) : """Prompt user until valid input is received . RejectWarning is raised if a KeyboardInterrupt is caught ."""
while True : try : return filter_fn ( raw_input ( prompt ) ) except InvalidInputError as e : if e . message : self . show ( 'ERROR: ' + e . message ) except KeyboardInterrupt : raise RejectWarning
def access_time ( self ) : """dfdatetime . Filetime : access time or None if not set ."""
timestamp = self . _fsntfs_attribute . get_access_time_as_integer ( ) return dfdatetime_filetime . Filetime ( timestamp = timestamp )
async def _sasl_respond ( self ) : """Respond to SASL challenge with response ."""
# Formulate a response . if self . _sasl_client : try : response = self . _sasl_client . process ( self . _sasl_challenge ) except puresasl . SASLError : response = None if response is None : self . logger . warning ( 'SASL challenge processing failed: aborting SASL authentication.' ...
def get_loci_fasta ( loci , out_fa , ref ) : """get fasta from precursor"""
if not find_cmd ( "bedtools" ) : raise ValueError ( "Not bedtools installed" ) with make_temp_directory ( ) as temp : bed_file = os . path . join ( temp , "file.bed" ) for nc , loci in loci . iteritems ( ) : for l in loci : with open ( bed_file , 'w' ) as bed_handle : log...
def forward ( self , inputs , lengths ) : """Execute the encoder . : param inputs : tensor with indices from the vocabulary : param lengths : vector with sequence lengths ( excluding padding ) returns : tensor with encoded sequences"""
x = self . embedder ( inputs ) # bidirectional layer x = self . dropout ( x ) x = pack_padded_sequence ( x , lengths . cpu ( ) . numpy ( ) , batch_first = self . batch_first ) x , _ = self . rnn_layers [ 0 ] ( x ) x , _ = pad_packed_sequence ( x , batch_first = self . batch_first ) # 1st unidirectional layer x = self ....
def stop ( self ) : """Clears all members"""
# Exit the loop with self . _lock : self . _stop_event . set ( ) self . _shell_event . clear ( ) if self . _context is not None : # Unregister from events self . _context . remove_service_listener ( self ) # Release the shell self . clear_shell ( ) self . _context = None
def __configure_interior ( self , * args ) : """Private function to configure the interior Frame . : param args : Tkinter event"""
# Resize the canvas scrollregion to fit the entire frame ( size_x , size_y ) = ( self . interior . winfo_reqwidth ( ) , self . interior . winfo_reqheight ( ) ) self . _canvas . config ( scrollregion = "0 0 {0} {1}" . format ( size_x , size_y ) ) if self . interior . winfo_reqwidth ( ) is not self . _canvas . winfo_widt...
def _start_message_fetcher ( self ) : """Start the message fetcher ( called from coroutine )"""
Global . LOGGER . debug ( 'starting the message fetcher' ) event_loop = asyncio . get_event_loop ( ) try : Global . LOGGER . debug ( 'entering event loop for message fetcher coroutine' ) event_loop . run_until_complete ( self . message_fetcher_coroutine ( event_loop ) ) finally : Global . LOGGER . debug ( '...
def request ( self , url , * , method = 'GET' , headers = None , data = None , result_callback = None ) : """Perform request . : param str url : request URL . : param str method : request method . : param dict headers : request headers . : param object data : request data . : param object - > object resul...
url = self . _make_full_url ( url ) self . _log . debug ( 'Performing %s request to %s' , method , url ) return self . _request ( url , method = method , headers = headers , data = data , result_callback = result_callback )
def namedb_get_value_hash_txids ( cur , value_hash ) : """Get the list of txs that sent this value hash , ordered by block and vtxindex"""
query = 'SELECT txid FROM history WHERE value_hash = ? ORDER BY block_id,vtxindex;' args = ( value_hash , ) rows = namedb_query_execute ( cur , query , args ) txids = [ ] for r in rows : # present txid = str ( r [ 'txid' ] ) txids . append ( txid ) return txids
def classify ( self , dataset , max_neighbors = 10 , radius = None , verbose = True ) : """Return the predicted class for each observation in * dataset * . This prediction is made based on the closest neighbors stored in the nearest neighbors classifier model . Parameters dataset : SFrame Dataset of new o...
# # Validate the query ' dataset ' . Note that the ' max _ neighbors ' and # ' radius ' parameters are validated by the nearest neighbor model ' s # query method . _raise_error_if_not_sframe ( dataset , "dataset" ) _raise_error_if_sframe_empty ( dataset , "dataset" ) n_query = dataset . num_rows ( ) # # Validate neighb...
def _set_email_list ( self , v , load = False ) : """Setter method for email _ list , mapped from YANG variable / rbridge _ id / maps / email / email _ list ( list ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ email _ list is considered as a private method . Backe...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = YANGListType ( "email" , email_list . email_list , yang_name = "email-list" , rest_name = "email-list" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_helper , yang_keys = 'email' ,...
def migrate_data ( self , data , from_state ) : """Migrate data objects . : param data : Queryset containing all data objects that need to be migrated : param from _ state : Database model state"""
for instance in data : if instance . status == 'ER' : continue container = getattr ( instance , self . schema_type , { } ) schema = container . pop ( self . field [ - 1 ] ) container [ self . new_field ] = schema setattr ( instance , self . schema_type , container ) instance . save ( )