signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _set_many ( self , i , j , x ) : """Sets value at each ( i , j ) to x Here ( i , j ) index major and minor respectively , and must not contain duplicate entries ."""
i , j , M , N = self . _prepare_indices ( i , j ) n_samples = len ( x ) offsets = np . empty ( n_samples , dtype = self . indices . dtype ) ret = _sparsetools . csr_sample_offsets ( M , N , self . indptr , self . indices , n_samples , i , j , offsets ) if ret == 1 : # rinse and repeat self . sum_duplicates ( ) ...
def _image_summary ( self , tf_name , images , step = None ) : """Log a list of images . References : https : / / github . com / yunjey / pytorch - tutorial / blob / master / tutorials / 04 - utils / tensorboard / logger . py # L22 Example : > > > tf _ name = ' foo ' > > > value = ( [ 0 , 1 , 2 , 3 , 4 , ...
img_summaries = [ ] for i , img in enumerate ( images ) : # Write the image to a string try : s = StringIO ( ) except : s = BytesIO ( ) scipy . misc . toimage ( img ) . save ( s , format = "png" ) # Create an Image object img_sum = summary_pb2 . Summary . Image ( encoded_image_string...
def subset_gctoo ( gctoo , row_bool = None , col_bool = None , rid = None , cid = None , ridx = None , cidx = None , exclude_rid = None , exclude_cid = None ) : """Extract a subset of data from a GCToo object in a variety of ways . The order of rows and columns will be preserved . Args : gctoo ( GCToo object ...
assert sum ( [ ( rid is not None ) , ( row_bool is not None ) , ( ridx is not None ) ] ) <= 1 , ( "Only one of rid, row_bool, and ridx can be provided." ) assert sum ( [ ( cid is not None ) , ( col_bool is not None ) , ( cidx is not None ) ] ) <= 1 , ( "Only one of cid, col_bool, and cidx can be provided." ) # Figure o...
def _create_simulator_trial_result ( self , params : study . ParamResolver , measurements : Dict [ str , np . ndarray ] , final_simulator_state : Any ) -> 'SimulationTrialResult' : """This method can be overridden to creation of a trial result . Args : params : The ParamResolver for this trial . measurements ...
return SimulationTrialResult ( params = params , measurements = measurements , final_simulator_state = final_simulator_state )
def _alephResultToDict ( dom ) : """Convert part of non - nested XML to : py : class : ` dict ` . Args : dom ( HTMLElement tree ) : pre - parsed XML ( see dhtmlparser ) . Returns : dict : with python data"""
result = { } for i in dom . childs : if not i . isOpeningTag ( ) : continue keyword = i . getTagName ( ) . strip ( ) value = _tryConvertToInt ( i . getContent ( ) . strip ( ) ) # if there are multiple tags with same keyword , add values into # array , instead of rewriting existing value at g...
def _addr_hooked_or_syscall ( self , addr ) : """Check whether the address belongs to a hook or a syscall . : param int addr : The address to check . : return : True if the address is hooked or belongs to a syscall . False otherwise . : rtype : bool"""
return self . project . is_hooked ( addr ) or self . project . simos . is_syscall_addr ( addr )
def set_time ( self , time ) : '''Update the length of the buffer in seconds : param time : number of seconds : return : self'''
self . length = int ( time * self . sample_rate ) return self
def get_tx_fee ( tx_hex , config_path = None , bitcoind_opts = None , bitcoind_client = None ) : """Get the tx fee for a tx Return the fee on success Return None on error"""
tx_fee_per_byte = get_tx_fee_per_byte ( config_path = config_path , bitcoind_opts = bitcoind_opts , bitcoind_client = bitcoind_client ) if tx_fee_per_byte is None : return None return calculate_tx_fee ( tx_hex , tx_fee_per_byte )
def run ( self ) : """If the connection drops , then run _ forever will terminate and a reconnection attempt will be made ."""
while True : self . connect_lock . acquire ( ) if self . stopped ( ) : return self . __connect ( ) self . connect_lock . release ( ) self . ws . run_forever ( )
def email_address ( self , email_address ) : """Sets the email _ address of this OrderFulfillmentRecipient . The email address of the fulfillment recipient . If provided , overrides the value from customer profile indicated by customer _ id . : param email _ address : The email _ address of this OrderFulfillmen...
if email_address is None : raise ValueError ( "Invalid value for `email_address`, must not be `None`" ) if len ( email_address ) > 255 : raise ValueError ( "Invalid value for `email_address`, length must be less than `255`" ) self . _email_address = email_address
def codes_get_api_version ( ) : """Get the API version . Returns the version of the API as a string in the format " major . minor . revision " ."""
ver = lib . codes_get_api_version ( ) patch = ver % 100 ver = ver // 100 minor = ver % 100 major = ver // 100 return "%d.%d.%d" % ( major , minor , patch )
def alter_partitions ( self , db_name , tbl_name , new_parts ) : """Parameters : - db _ name - tbl _ name - new _ parts"""
self . send_alter_partitions ( db_name , tbl_name , new_parts ) self . recv_alter_partitions ( )
def clean_ret_type ( ret_type ) : """Clean the erraneous parsed return type ."""
ret_type = get_printable ( ret_type ) . strip ( ) if ret_type == 'LRESULT LRESULT' : ret_type = 'LRESULT' for bad in [ 'DECLSPEC_NORETURN' , 'NTSYSCALLAPI' , '__kernel_entry' , '__analysis_noreturn' , '_Post_equals_last_error_' , '_Maybe_raises_SEH_exception_' , '_CRT_STDIO_INLINE' , '_ACRTIMP' ] : if bad in re...
def add_chain_info ( data_api , data_setters , chain_index ) : """Add the data for a whole chain . : param data _ api the data api from where to get the data : param data _ setters the class to push the data to : param chain _ index the index for this chain"""
chain_id = data_api . chain_id_list [ chain_index ] chain_name = data_api . chain_name_list [ chain_index ] num_groups = data_api . groups_per_chain [ chain_index ] data_setters . set_chain_info ( chain_id , chain_name , num_groups ) next_ind = data_api . group_counter + num_groups last_ind = data_api . group_counter f...
def remove_xml_element_file ( name , path ) : """Remove XML elements from a single file"""
ET . register_namespace ( "" , "http://soap.sforce.com/2006/04/metadata" ) tree = elementtree_parse_file ( path ) tree = remove_xml_element ( name , tree ) return tree . write ( path , encoding = UTF8 , xml_declaration = True )
def read_config ( ctx , param , config_path ) : """Callback that is used whenever - - config is passed ."""
if sys . argv [ 1 ] == 'init' : return cfg = ctx . ensure_object ( Config ) if config_path is None : config_path = path . join ( sys . path [ 0 ] , 'v2ex_config.json' ) if not path . exists ( config_path ) : sys . exit ( "Can't find config file at {0}.\nPlease read " "https://github.com/lord63/v2ex_daily_mi...
def run ( self , manager ) : """Run this query and returns the resulting BEL graph . : param manager : A cache manager : rtype : Optional [ pybel . BELGraph ]"""
universe = self . _get_universe ( manager ) graph = self . seeding . run ( universe ) return self . pipeline . run ( graph , universe = universe )
def get_data_flow_m ( self , data_flow_id ) : """Searches and return the data flow model with the given in the given container state model : param data _ flow _ id : The data flow id to be searched : return : The model of the data flow or None if it is not found"""
for data_flow_m in self . data_flows : if data_flow_m . data_flow . data_flow_id == data_flow_id : return data_flow_m return None
def token_gen_call ( username , password ) : """Authenticate and return a token"""
secret_key = 'super-secret-key-please-change' mockusername = 'User2' mockpassword = 'Mypassword' if mockpassword == password and mockusername == username : # This is an example . Don ' t do that . return { "token" : jwt . encode ( { 'user' : username , 'data' : 'mydata' } , secret_key , algorithm = 'HS256' ) } retu...
def _pipeline_present_with_definition ( name , expected_pipeline_objects , expected_parameter_objects , expected_parameter_values , region , key , keyid , profile ) : '''Return true if the pipeline exists and the definition matches . name The name of the pipeline . expected _ pipeline _ objects Pipeline obj...
result_pipeline_id = __salt__ [ 'boto_datapipeline.pipeline_id_from_name' ] ( name , region = region , key = key , keyid = keyid , profile = profile , ) if 'error' in result_pipeline_id : return False , { } pipeline_id = result_pipeline_id [ 'result' ] pipeline_definition_result = __salt__ [ 'boto_datapipeline.get_...
from typing import List import math def compute_prime_factors ( num : int ) -> List [ int ] : """Returns the sorted list of prime factors for the given positive integer . Each prime factor is listed as many times as it appears in the factorization . The input number must be the multiplication result of all fact...
factors = [ ] divisor = 2 while divisor <= math . isqrt ( num ) + 1 : if num % divisor : divisor += 1 else : num //= divisor factors . append ( divisor ) if num > 1 : factors . append ( num ) return factors
def Conduction ( self , dt , flx1 , bc , temp2 , flx2 ) : """Solve the conductance of heat based on of the element layers . arg : flx1 : net heat flux on surface bc : boundary condition parameter ( 1 or 2) temp2 : deep soil temperature ( ave of air temperature ) flx2 : surface flux ( sum of absorbed , emi...
t = self . layerTemp # vector of layer temperatures ( K ) hc = self . layerVolHeat # vector of layer volumetric heat ( J m - 3 K - 1) tc = self . layerThermalCond # vector of layer thermal conductivities ( W m - 1 K - 1) d = self . layerThickness # vector of layer thicknesses ( m ) # flx1 : net heat flux on surface # b...
def sync_map_items ( self ) : """Access the sync _ map _ items : returns : twilio . rest . sync . v1 . service . sync _ map . sync _ map _ item . SyncMapItemList : rtype : twilio . rest . sync . v1 . service . sync _ map . sync _ map _ item . SyncMapItemList"""
if self . _sync_map_items is None : self . _sync_map_items = SyncMapItemList ( self . _version , service_sid = self . _solution [ 'service_sid' ] , map_sid = self . _solution [ 'sid' ] , ) return self . _sync_map_items
def get_extended_attribute ( value ) : """[ CFWS ] 1 * extended _ attrtext [ CFWS ] This is like the non - extended version except we allow % characters , so that we can pick up an encoded value as a single string ."""
# XXX : should we have an ExtendedAttribute TokenList ? attribute = Attribute ( ) if value and value [ 0 ] in CFWS_LEADER : token , value = get_cfws ( value ) attribute . append ( token ) if value and value [ 0 ] in EXTENDED_ATTRIBUTE_ENDS : raise errors . HeaderParseError ( "expected token but found '{}'" ...
def cli_script_main ( cli_args ) : """A command line interface to basic bitmath operations ."""
choices = ALL_UNIT_TYPES parser = argparse . ArgumentParser ( description = 'Converts from one type of size to another.' ) parser . add_argument ( '--from-stdin' , default = False , action = 'store_true' , help = 'Reads number from stdin rather than the cli' ) parser . add_argument ( '-f' , '--from' , choices = choices...
def _pipeline_cell ( args , cell_body ) : """Implements the BigQuery cell magic used to validate , execute or deploy BQ pipelines . The supported syntax is : % % bigquery pipeline [ - q | - - sql < query identifier > ] < other args > < action > [ < YAML or JSON cell _ body or inline SQL > ] Args : args : ...
if args [ 'action' ] == 'deploy' : raise Exception ( 'Deploying a pipeline is not yet supported' ) env = { } for key , value in datalab . utils . commands . notebook_environment ( ) . items ( ) : if isinstance ( value , datalab . bigquery . _udf . UDF ) : env [ key ] = value query = _get_query_argument ...
def auth ( self , value ) : """Sets any non - user authentication information associated with the request , such as an authentication token ."""
self . _auth = value self . _request . auth = value
def import_locations ( self , kml_file ) : """Import KML data files . ` ` import _ locations ( ) ` ` returns a dictionary with keys containing the section title , and values consisting of : class : ` Placemark ` objects . It expects data files in KML format , as specified in ` KML Reference ` _ , which is X...
self . _kml_file = kml_file data = utils . prepare_xml_read ( kml_file , objectify = True ) for place in data . Document . Placemark : name = place . name . text coords = place . Point . coordinates . text if coords is None : logging . info ( 'No coordinates found for %r entry' % name ) cont...
def optional_else ( self , node , last ) : """Create op _ pos for optional else"""
if node . orelse : min_first_max_last ( node , node . orelse [ - 1 ] ) if 'else' in self . operators : position = ( node . orelse [ 0 ] . first_line , node . orelse [ 0 ] . first_col ) _ , efirst = self . operators [ 'else' ] . find_previous ( position ) if efirst and efirst > last : ...
def overextends ( parser , token ) : """Extended version of Django ' s ` ` extends ` ` tag that allows circular inheritance to occur , eg a template can both be overridden and extended at once ."""
bits = token . split_contents ( ) if len ( bits ) != 2 : raise TemplateSyntaxError ( "'%s' takes one argument" % bits [ 0 ] ) parent_name = parser . compile_filter ( bits [ 1 ] ) nodelist = parser . parse ( ) if nodelist . get_nodes_by_type ( ExtendsNode ) : raise TemplateSyntaxError ( "'%s' cannot appear more ...
def _gcs_list_buckets ( project , pattern ) : """List all Google Cloud Storage buckets that match a pattern ."""
data = [ { 'Bucket' : 'gs://' + bucket . name , 'Created' : bucket . metadata . created_on } for bucket in google . datalab . storage . Buckets ( _make_context ( project ) ) if fnmatch . fnmatch ( bucket . name , pattern ) ] return google . datalab . utils . commands . render_dictionary ( data , [ 'Bucket' , 'Created' ...
def view_activation_map ( self , data_vector = None , data_index = None , activation_map = None , figsize = None , colormap = cm . Spectral_r , colorbar = False , bestmatches = False , bestmatchcolors = None , labels = None , zoom = None , filename = None ) : """Plot the activation map of a given data instance or a...
if data_vector is None and data_index is None : raise Exception ( "Either specify a vector to see its activation " "or give an index of the training data instances" ) if data_vector is not None and data_index is not None : raise Exception ( "You cannot specify both a data vector and the " "index of a training d...
def conv_stride2_multistep ( x , nbr_steps , output_filters , name = None , reuse = None ) : """Use a strided convolution to downsample x by 2 , ` nbr _ steps ` times . We use stride and filter size 2 to avoid the checkerboard problem of deconvs . As detailed in http : / / distill . pub / 2016 / deconv - checke...
with tf . variable_scope ( name , default_name = "conv_stride2_multistep" , values = [ x ] , reuse = reuse ) : if nbr_steps == 0 : out = conv ( x , output_filters , ( 1 , 1 ) ) return out , [ out ] hidden_layers = [ x ] for i in range ( nbr_steps ) : hidden_layers . append ( conv ( h...
def draw ( self , ** kwargs ) : """Draws the heatmap of the ranking matrix of variables ."""
# Set the axes aspect to be equal self . ax . set_aspect ( "equal" ) # Generate a mask for the upper triangle mask = np . zeros_like ( self . ranks_ , dtype = np . bool ) mask [ np . triu_indices_from ( mask ) ] = True # Draw the heatmap # TODO : Move mesh to a property so the colorbar can be finalized data = np . ma ....
def setModel ( self , model ) : """Sets the model this view represents . : qtdoc : ` Re - implemented < QAbstractItemView . setModel > ` : param model : model to set : type model : : class : ` QStimulusModel < sparkle . gui . stim . stimulus _ model . QStimulusModel > `"""
super ( StimulusView , self ) . setModel ( model ) self . setSelectionModel ( ComponentSelectionModel ( model ) ) # initialize nested list to appropriate size self . _rects = [ [ None ] * self . model ( ) . columnCountForRow ( x ) for x in range ( self . model ( ) . rowCount ( ) ) ] self . _viewIsDirty = True self . _c...
def _init_model ( self ) : """Composes all layers of 3D CNN ."""
model = Sequential ( ) model . add ( Conv3D ( input_shape = [ self . time_delay ] + list ( self . image_size ) + [ self . channels ] , filters = self . filters , kernel_size = self . kernel_size , activation = 'relu' , data_format = 'channels_last' ) ) model . add ( Conv3D ( filters = self . filters , kernel_size = sel...
def repair ( self , x , copy_if_changed = True , copy_always = False ) : """projects infeasible values on the domain bound , might be overwritten by derived class"""
if copy_always : x = array ( x , copy = True ) copy = False else : copy = copy_if_changed if self . bounds is None : return x for ib in [ 0 , 1 ] : if self . bounds [ ib ] is None : continue for i in rglen ( x ) : idx = min ( [ i , len ( self . bounds [ ib ] ) - 1 ] ) if ...
def message ( message , name = None ) : """Convenience decorator that applies [ ` Msg ( ) ` ] ( # msg ) to a callable . ` ` ` python from good import Schema , message @ message ( u ' Need a number ' ) def intify ( v ) : return int ( v ) : param message : Error message to use instead : type message : u...
def decorator ( func ) : wf = update_wrapper ( Msg ( func , message ) , func ) if name : wf . name = name return wf return decorator
def init_app ( self , app , decorators = None ) : """Initialize the app with Swagger plugin"""
self . decorators = decorators or self . decorators self . app = app self . load_config ( app ) # self . load _ apispec ( app ) if self . template_file is not None : self . template = self . load_swagger_file ( self . template_file ) self . register_views ( app ) self . add_headers ( app ) if self . parse : if ...
def records ( self ) : """Returns the record set for the current settings of this browser . : return < orb . RecordSet >"""
if ( self . isGroupingActive ( ) ) : self . _records . setGroupBy ( self . currentGrouping ( ) ) else : self . _records . setGroupBy ( None ) return self . _records
def run ( self , graph , universe = None ) : """Run the contained protocol on a seed graph . : param pybel . BELGraph graph : The seed BEL graph : param pybel . BELGraph universe : Allows just - in - time setting of the universe in case it wasn ' t set before . Defaults to the given network . : return : The...
self . universe = universe or graph . copy ( ) return self . _run_helper ( graph . copy ( ) , self . protocol )
def limit_weights ( weights , limit = 0.1 ) : """Limits weights and redistributes excedent amount proportionally . ex : - weights are { a : 0.7 , b : 0.2 , c : 0.1} - call with limit = 0.5 - excess 0.2 in a is ditributed to b and c proportionally . - result is { a : 0.5 , b : 0.33 , c : 0.167} Args ...
if 1.0 / limit > len ( weights ) : raise ValueError ( 'invalid limit -> 1 / limit must be <= len(weights)' ) if isinstance ( weights , dict ) : weights = pd . Series ( weights ) if np . round ( weights . sum ( ) , 1 ) != 1.0 : raise ValueError ( 'Expecting weights (that sum to 1) - sum is %s' % weights . su...
def main ( ) : """Main function to run command"""
configParser = FileParser ( ) logging . config . dictConfig ( configParser . load_from_file ( os . path . join ( os . path . dirname ( os . path . dirname ( __file__ ) ) , 'settings' , 'logging.yml' ) ) ) ApiDoc ( ) . main ( )
def get_app_ticket ( self , app_id ) : """Get app ownership ticket : param app _ id : app id : type app _ id : : class : ` int ` : return : ` CMsgClientGetAppOwnershipTicketResponse < https : / / github . com / ValvePython / steam / blob / 39627fe883feeed2206016bacd92cf0e4580ead6 / protobufs / steammessages _...
return self . send_job_and_wait ( MsgProto ( EMsg . ClientGetAppOwnershipTicket ) , { 'app_id' : app_id } , timeout = 15 )
def start ( self ) : '''Take the messages from the queue , inspect and identify the operating system , then queue the message correspondingly .'''
# metric counters napalm_logs_server_messages_received = Counter ( "napalm_logs_server_messages_received" , "Count of messages received from listener processes" ) napalm_logs_server_skipped_buffered_messages = Counter ( 'napalm_logs_server_skipped_buffered_messages' , 'Count of messages skipped as they were already buf...
def fix_spelling ( words , join = True , joinstring = ' ' ) : """Simple function for quickly correcting misspelled words . Parameters words : list of str or str Either a list of pretokenized words or a string . In case of a string , it will be splitted using default behaviour of string . split ( ) function ...
return Vabamorf . instance ( ) . fix_spelling ( words , join , joinstring )
def _update_record ( self , identifier , rtype = None , name = None , content = None ) : """Updates a record . Name changes are allowed , but the record identifier will change"""
if identifier is not None : if name is not None : records = self . _list_records_internal ( identifier = identifier ) if len ( records ) == 1 and records [ 0 ] [ 'name' ] != self . _full_name ( name ) : # API does not allow us to update name directly self . _update_record_with_name ( rec...
def init_associations ( self , fin_anno , taxids = None ) : """Read annotation file . Store annotation data in a list of namedtuples ."""
nts = [ ] if fin_anno is None : return nts tic = timeit . default_timer ( ) lnum = - 1 line = "\t" * len ( self . flds ) try : with open ( fin_anno ) as ifstrm : category2ns = { 'Process' : 'BP' , 'Function' : 'MF' , 'Component' : 'CC' } ntobj = cx . namedtuple ( 'ntanno' , self . flds ) ...
def LSTM ( nO , nI ) : """Create an LSTM layer . Args : number out , number in"""
weights = LSTM_weights ( nO , nI ) gates = LSTM_gates ( weights . ops ) return Recurrent ( RNN_step ( weights , gates ) )
def distance ( self , method = 'haversine' ) : """Calculate distances between locations in segments . Args : method ( str ) : Method used to calculate distance Returns : list of list of float : Groups of distance between points in segments"""
distances = [ ] for segment in self : if len ( segment ) < 2 : distances . append ( [ ] ) else : distances . append ( segment . distance ( method ) ) return distances
def construct ( key_data , algorithm = None ) : """Construct a Key object for the given algorithm with the given key _ data ."""
# Allow for pulling the algorithm off of the passed in jwk . if not algorithm and isinstance ( key_data , dict ) : algorithm = key_data . get ( 'alg' , None ) if not algorithm : raise JWKError ( 'Unable to find a algorithm for key: %s' % key_data ) key_class = get_key ( algorithm ) if not key_class : raise ...
def ssm_create_association ( name = None , kwargs = None , instance_id = None , call = None ) : '''Associates the specified SSM document with the specified instance http : / / docs . aws . amazon . com / ssm / latest / APIReference / API _ CreateAssociation . html CLI Examples : . . code - block : : bash sa...
if call != 'action' : raise SaltCloudSystemExit ( 'The ssm_create_association action must be called with ' '-a or --action.' ) if not kwargs : kwargs = { } if 'instance_id' in kwargs : instance_id = kwargs [ 'instance_id' ] if name and not instance_id : instance_id = _get_node ( name ) [ 'instanceId' ] ...
def as_bel ( self ) -> str : """Return this fusion range as a BEL string ."""
return '{reference}.{start}_{stop}' . format ( reference = self [ FUSION_REFERENCE ] , start = self [ FUSION_START ] , stop = self [ FUSION_STOP ] , )
def anonymous_required ( function ) : """Redirect to user profile if user is already logged - in"""
def wrapper ( * args , ** kwargs ) : if args [ 0 ] . user . is_authenticated ( ) : url = settings . ANONYMOUS_REQUIRED_REDIRECT_URL return HttpResponseRedirect ( reverse ( url ) ) return function ( * args , ** kwargs ) return wrapper
def queue_callback ( self , session , block_id , data ) : """Queues up a callback event to occur for a session with the given payload data . Will block if the queue is full . : param session : the session with a defined callback function to call . : param block _ id : the block _ id of the message received . ...
self . _queue . put ( ( session , block_id , data ) )
def exception_handler ( exceptionObj ) : """Function that takes exception Object ( < Byte > , < str > ) as a parameter and returns the error message < str >"""
try : if isinstance ( exceptionObj , Exception ) and hasattr ( exceptionObj , 'args' ) : if not ( hasattr ( exceptionObj , 'message' or hasattr ( exceptionObj , 'msg' ) ) ) : if len ( exceptionObj . args ) >= 1 : if type ( exceptionObj . args [ 0 ] ) == type ( b'' ) : ...
def get_subtree ( self , name ) : # noqa : D302 r"""Get all node names in a sub - tree . : param name : Sub - tree root node name : type name : : ref : ` NodeName ` : rtype : list of : ref : ` NodeName ` : raises : * RuntimeError ( Argument \ ` name \ ` is not valid ) * RuntimeError ( Node * [ name ] * ...
if self . _validate_node_name ( name ) : raise RuntimeError ( "Argument `name` is not valid" ) self . _node_in_tree ( name ) return self . _get_subtree ( name )
def create ( gandi , resource , flags , algorithm , public_key ) : """Create DNSSEC key ."""
result = gandi . dnssec . create ( resource , flags , algorithm , public_key ) return result
def parse ( cls , fptr , offset , length ) : """Parse JPX free box . Parameters f : file Open file object . offset : int Start position of box in bytes . length : int Length of the box in bytes . Returns FreeBox Instance of the current free box ."""
# Must seek to end of box . nbytes = offset + length - fptr . tell ( ) fptr . read ( nbytes ) return cls ( length = length , offset = offset )
def create_response_signature ( self , string_message , zone ) : """Basic helper function to keep code clean for defining a response message signature"""
zz = '' if zone is not None : zz = hex ( int ( zone ) - 1 ) . replace ( '0x' , '' ) # RNET requires zone value to be zero based string_message = string_message . replace ( '@zz' , zz ) # Replace zone parameter return string_message
def turn_off ( self , effect = EFFECT_SUDDEN , transition_time = MIN_TRANSITION_TIME ) : """This method is used to switch off the smart LED ( software managed off ) . : param effect : if the change is made suddenly or smoothly : param transition _ time : in case the change is made smoothly , time in ms that cha...
# Check bulb state if self . is_off ( ) : return else : # Input validation schema = Schema ( { 'effect' : Any ( self . EFFECT_SUDDEN , self . EFFECT_SMOOTH ) , 'transition_time' : All ( int , Range ( min = 30 ) ) } ) schema ( { 'effect' : effect , 'transition_time' : transition_time } ) # Send command ...
def GuardedTFile ( * args , ** kwargs ) : """Factory function that lazily creates the guarded TFile class , and creates and returns an instance with all passed * args * and * kwargs * . This is required as we do not want to import ROOT in the global scope ."""
global guarded_tfile_cls if not guarded_tfile_cls : import ROOT class GuardedTFile ( ROOT . TFile ) : def __enter__ ( self ) : return self def __exit__ ( self , exc_type , exc_value , traceback ) : if self . IsOpen ( ) : self . Close ( ) guarded_tfile_...
def append_num_column ( self , text : str , index : int ) : """Add value to the output row , width based on index"""
width = self . columns [ index ] [ "width" ] return f"{text:>{width}}"
def _set_intf_isis ( self , v , load = False ) : """Setter method for intf _ isis , mapped from YANG variable / routing _ system / interface / ve / intf _ isis ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ intf _ isis is considered as a private method ...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = intf_isis . intf_isis , is_container = 'container' , presence = True , yang_name = "intf-isis" , rest_name = "" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , e...
def _setup_kafka ( self ) : """Sets up kafka connections"""
# close older connections if self . consumer is not None : self . logger . debug ( "Closing existing kafka consumer" ) self . consumer . close ( ) self . consumer = None if self . producer is not None : self . logger . debug ( "Closing existing kafka producer" ) self . producer . flush ( ) self ...
def lrem ( self , name , count , value ) : """Remove the first ` ` count ` ` occurrences of elements equal to ` ` value ` ` from the list stored at ` ` name ` ` . The count argument influences the operation in the following ways : count > 0 : Remove elements equal to value moving from head to tail . count <...
return self . execute_command ( 'LREM' , name , count , value )
def _asyncio_open_serial_windows ( path ) : """Open a windows named pipe : returns : An IO like object"""
try : yield from wait_for_named_pipe_creation ( path ) except asyncio . TimeoutError : raise NodeError ( 'Pipe file "{}" is missing' . format ( path ) ) return WindowsPipe ( path )
def put_many ( self , type : Type [ T ] , items : Iterable [ T ] , context : PipelineContext = None ) -> None : """Puts multiple objects of the same type into the data sink . Args : type : The type of the objects being inserted . items : The objects to be inserted . context : The context of the insertion ( ...
pass
def new_signal ( celf , path , iface , name ) : "creates a new DBUS . MESSAGE _ TYPE _ SIGNAL message ."
result = dbus . dbus_message_new_signal ( path . encode ( ) , iface . encode ( ) , name . encode ( ) ) if result == None : raise CallFailed ( "dbus_message_new_signal" ) # end if return celf ( result )
def sort_and_translate ( nums ) : """This function sorts the integers in the input array that are between 1 and 9 inclusive , in descending order , then replaces each digit with its corresponding name from " One " to " Nine " . If the input array is empty , the function returns an empty array . If there are...
number_word_mapping = { 1 : "One" , 2 : "Two" , 3 : "Three" , 4 : "Four" , 5 : "Five" , 6 : "Six" , 7 : "Seven" , 8 : "Eight" , 9 : "Nine" , } # Sort and reverse the array : nums . sort ( ) nums . reverse ( ) # Create a new array to store the words : words = [ ] # Convert the digits to words : for num in nums : if ...
def cmd ( send , msg , args ) : """Reports the difference between now and some specified time . Syntax : { command } < time >"""
parser = arguments . ArgParser ( args [ 'config' ] ) parser . add_argument ( 'date' , nargs = '*' , action = arguments . DateParser ) try : cmdargs = parser . parse_args ( msg ) except arguments . ArgumentException as e : send ( str ( e ) ) return if not cmdargs . date : send ( "Time until when?" ) ...
def _build_mask_ds ( mask , mask_offset ) : """Build the mask dataset to indicate which element to skip . Args : mask : ` tf . Tensor ` , binary mask to apply to all following elements . This mask should have a length 100. mask _ offset : ` tf . Tensor ` , Integer specifying from how much the mask should ...
mask_ds = tf . data . Dataset . from_tensor_slices ( mask ) mask_ds = mask_ds . repeat ( ) mask_ds = mask_ds . skip ( mask_offset ) return mask_ds
def load_folder_content ( folder_path ) : """load api / testcases / testsuites definitions from folder . Args : folder _ path ( str ) : api / testcases / testsuites files folder . Returns : dict : api definition mapping . " tests / api / basic . yml " : [ { " api " : { " def " : " api _ login " , " requ...
items_mapping = { } for file_path in load_folder_files ( folder_path ) : items_mapping [ file_path ] = load_file ( file_path ) return items_mapping
def first_run ( self , known_block_number ) : """Blocking call to update the local state , if necessary ."""
assert self . callbacks , 'callbacks not set' latest_block = self . chain . get_block ( block_identifier = 'latest' ) log . debug ( 'Alarm task first run' , known_block_number = known_block_number , latest_block_number = latest_block [ 'number' ] , latest_gas_limit = latest_block [ 'gasLimit' ] , latest_block_hash = to...
def render_template ( template_name : str , ** kwargs ) : """Renders the template file with the given filename from within Cauldron ' s template environment folder . : param template _ name : The filename of the template to render . Any path elements should be relative to Cauldron ' s root template folder ....
return get_environment ( ) . get_template ( template_name ) . render ( cauldron_template_uid = make_template_uid ( ) , ** kwargs )
def imagetransformer_base_10l_8h_big_uncond_dr03_dan_64 ( ) : """big 1d model for unconditional generation on imagenet ."""
hparams = imagetransformer_base_10l_8h_big_cond_dr03_dan ( ) hparams . unconditional = True hparams . max_length = 14000 hparams . batch_size = 1 hparams . img_len = 64 hparams . layer_prepostprocess_dropout = 0.1 return hparams
def show_dropped ( self ) : """Show dropped files"""
ctx = _find_context ( self . broker ) if ctx and ctx . all_files : ds = self . broker . get_by_type ( datasource ) vals = [ ] for v in ds . values ( ) : if isinstance ( v , list ) : vals . extend ( d . path for d in v ) else : vals . append ( v . path ) dropped = ...
def checkArgs ( args ) : """Checks the arguments and options . : param args : an object containing the options of the program . : type args : argparse . Namespace : returns : ` ` True ` ` if everything was OK . If there is a problem with an option , an exception is raised using the : py : class : ` Progra...
# Checking the input file if not os . path . isfile ( args . problematic_samples ) : msg = "{}: no such file" . format ( args . problematic_samples ) raise ProgramError ( msg ) # Checking the raw directory if not os . path . isdir ( args . raw_dir ) : msg = "{}: no such directory" . format ( args . raw_dir ...
def addLeadingToGroups ( self , proteinIds , groupIds ) : """Add one or multiple leading proteins to one or multiple protein groups . : param proteinIds : a proteinId or a list of proteinIds , a proteinId must be a string . : param groupIds : a groupId or a list of groupIds , a groupId must be a string ."...
for groupId in AUX . toList ( groupIds ) : self . groups [ groupId ] . addLeadingProteins ( proteinIds ) self . _addProteinIdsToGroupMapping ( proteinIds , groupId )
def create ( self , * fields , ** kw ) : """Create a new base with specified field names A keyword argument mode can be specified ; it is used if a file with the base name already exists - if mode = ' open ' : open the existing base , ignore the fields - if mode = ' override ' : erase the existing base and ...
mode = kw . get ( "mode" , None ) if self . _table_exists ( ) : if mode == "override" : self . cursor . execute ( "DROP TABLE %s" % self . name ) elif mode == "open" : return self . open ( ) else : raise IOError , "Base %s already exists" % self . name self . fields = [ f [ 0 ] for f...
def set_location ( self , time , latitude , longitude ) : '''Sets the location for the query . Parameters time : datetime or DatetimeIndex Time range of the query .'''
if isinstance ( time , datetime . datetime ) : tzinfo = time . tzinfo else : tzinfo = time . tz if tzinfo is None : self . location = Location ( latitude , longitude ) else : self . location = Location ( latitude , longitude , tz = tzinfo )
def validate_index ( self , index ) : """Check that a linear index of a square is within board ' s bounds ."""
if index < 0 or index >= self . size : raise ForbiddenIndex ( "Linear index {} not in {}x{} board." . format ( index , self . length , self . height ) )
def handleFlaskPostRequest ( flaskRequest , endpoint ) : """Handles the specified flask request for one of the POST URLS Invokes the specified endpoint to generate a response ."""
if flaskRequest . method == "POST" : return handleHttpPost ( flaskRequest , endpoint ) elif flaskRequest . method == "OPTIONS" : return handleHttpOptions ( ) else : raise exceptions . MethodNotAllowedException ( )
def _encode_telegram_base64 ( string ) : """Inverse for ` _ decode _ telegram _ base64 ` ."""
try : return base64 . urlsafe_b64encode ( string ) . rstrip ( b'=' ) . decode ( 'ascii' ) except ( binascii . Error , ValueError , TypeError ) : return None
def parse_lines ( log_parsers , fileinp ) : """parse lines from the fileinput and send them to the log _ parsers"""
while 1 : logentry = fileinp . readline ( ) if not logentry : break elif not logentry . rstrip ( ) : continue # skip newlines processed = False for lp in log_parsers : if lp . grok ( logentry ) : processed = True if not processed : # error : none of the lo...
def turn_to_angle ( self , speed , angle_target_degrees , brake = True , block = True ) : """Rotate in place to ` angle _ target _ degrees ` at ` speed `"""
assert self . odometry_thread_id , "odometry_start() must be called to track robot coordinates" # Make both target and current angles positive numbers between 0 and 360 if angle_target_degrees < 0 : angle_target_degrees += 360 angle_current_degrees = math . degrees ( self . theta ) if angle_current_degrees < 0 : ...
def tuples_to_coll ( cls , generator , coerce = False ) : """* required virtual method * This class method , part of the sub - class API , converts a generator of ` ` ( K , V ) ` ` tuples ( the * tuple protocol * ) to one of the underlying collection type ."""
if cls != Collection : raise exc . CollectionDefinitionError ( property = 'tuples_to_coll' , coll = 'Collection' , )
def _all_filenames ( self ) : """Return a list of absolute cache filenames"""
try : return [ os . path . join ( self . cache_dir , filename ) for filename in os . listdir ( self . cache_dir ) ] except ( FileNotFoundError , OSError ) : return [ ]
def _write_single_sample ( self , sample ) : """: type sample : Sample"""
bytes = sample . extras . get ( "responseHeadersSize" , 0 ) + 2 + sample . extras . get ( "responseBodySize" , 0 ) message = sample . error_msg if not message : message = sample . extras . get ( "responseMessage" ) if not message : for sample in sample . subsamples : if sample . error_msg : ...
def z_axis_rotation ( theta ) : """Generates a 3x3 rotation matrix for a rotation of angle theta about the z axis . Parameters theta : float amount to rotate , in radians Returns : obj : ` numpy . ndarray ` of float A random 3x3 rotation matrix ."""
R = np . array ( [ [ np . cos ( theta ) , - np . sin ( theta ) , 0 ] , [ np . sin ( theta ) , np . cos ( theta ) , 0 ] , [ 0 , 0 , 1 ] ] ) return R
def assign_issue ( self , issue , assignee ) : """Assign an issue to a user . None will set it to unassigned . - 1 will set it to Automatic . : param issue : the issue ID or key to assign : type issue : int or str : param assignee : the user to assign the issue to : type assignee : str : rtype : bool"""
url = self . _options [ 'server' ] + '/rest/api/latest/issue/' + str ( issue ) + '/assignee' payload = { 'name' : assignee } r = self . _session . put ( url , data = json . dumps ( payload ) ) raise_on_error ( r ) return True
def exam_reliability_by_datetime ( datetime_axis , datetime_new_axis , reliable_distance ) : """A datetime - version that takes datetime object list as x _ axis reliable _ distance equals to the time difference in seconds ."""
numeric_datetime_axis = [ totimestamp ( a_datetime ) for a_datetime in datetime_axis ] numeric_datetime_new_axis = [ totimestamp ( a_datetime ) for a_datetime in datetime_new_axis ] return exam_reliability ( numeric_datetime_axis , numeric_datetime_new_axis , reliable_distance , precision = 0 )
def to_full_path ( cls , path ) : """: return : string with a full repository - relative path which can be used to initialize a Reference instance , for instance by using ` ` Reference . from _ path ` `"""
if isinstance ( path , SymbolicReference ) : path = path . path full_ref_path = path if not cls . _common_path_default : return full_ref_path if not path . startswith ( cls . _common_path_default + "/" ) : full_ref_path = '%s/%s' % ( cls . _common_path_default , path ) return full_ref_path
def interpn ( * args , ** kw ) : """Interpolation on N - D . ai = interpn ( x , y , z , . . . , a , xi , yi , zi , . . . ) where the arrays x , y , z , . . . define a rectangular grid and a . shape = = ( len ( x ) , len ( y ) , len ( z ) , . . . ) are the values interpolate at xi , yi , zi , . . ."""
method = kw . pop ( 'method' , 'cubic' ) if kw : raise ValueError ( "Unknown arguments: " % kw . keys ( ) ) nd = ( len ( args ) - 1 ) // 2 if len ( args ) != 2 * nd + 1 : raise ValueError ( "Wrong number of arguments" ) q = args [ : nd ] qi = args [ nd + 1 : ] a = args [ nd ] for j in range ( nd ) : # print q [...
def cum_returns ( returns , starting_value = 0 , out = None ) : """Compute cumulative returns from simple returns . Parameters returns : pd . Series , np . ndarray , or pd . DataFrame Returns of the strategy as a percentage , noncumulative . - Time series with decimal returns . - Example : : 2015-07-16 ...
if len ( returns ) < 1 : return returns . copy ( ) nanmask = np . isnan ( returns ) if np . any ( nanmask ) : returns = returns . copy ( ) returns [ nanmask ] = 0 allocated_output = out is None if allocated_output : out = np . empty_like ( returns ) np . add ( returns , 1 , out = out ) out . cumprod ( a...
def set_expected_action ( self , expected_response_action ) : """Expected outcome of the transaction ( ' APPROVED ' or ' DECLINED ' )"""
if expected_response_action . upper ( ) not in [ 'APPROVED' , 'APPROVE' , 'DECLINED' , 'DECLINE' ] : return False self . expected_response_action = expected_response_action . upper ( ) return True
def init_app ( self , app ) : """Setup scoped sesssion creation and teardown for the passed ` ` app ` ` . : param app : a : class : ` ~ flask . Flask ` application"""
app . scoped_session = self @ app . teardown_appcontext def remove_scoped_session ( * args , ** kwargs ) : # pylint : disable = missing - docstring , unused - argument , unused - variable app . scoped_session . remove ( )
def _subs ( self , substitutions , default , simplify ) : """Return an expression where all subterms equal to a key expression are substituted by the corresponding value expression using a mapping of : { expr - > expr to substitute . }"""
# track the new list of unchanged args or replaced args through # a substitution new_arguments = [ ] changed_something = False # shortcut for basic logic True or False if self is self . TRUE or self is self . FALSE : return self # if the expression has no elements , e . g . is empty , do not apply # substitions if ...
def intervalTreesFromList ( inElements , verbose = False , openEnded = False ) : """build a dictionary , indexed by chrom name , of interval trees for each chrom . : param inElements : list of genomic intervals . Members of the list must have chrom , start and end fields ; no other restrictions . : param verb...
elements = { } if verbose : totalLines = len ( inElements ) pind = ProgressIndicator ( totalToDo = totalLines , messagePrefix = "completed" , messageSuffix = "of parsing" ) for element in inElements : if element . chrom not in elements : elements [ element . chrom ] = [ ] elements [ element . ch...
def GetValue ( self ) : '''Positionals have no associated options _ string , so only the supplied arguments are returned . The order is assumed to be the same as the order of declaration in the client code Returns " argument _ value "'''
self . AssertInitialization ( 'Positional' ) if str ( self . _widget . GetValue ( ) ) == EMPTY : return None return self . _widget . GetValue ( )