idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
26,700 | def _check_kafka_disconnect ( self ) : for node_id in self . consumer . _client . _conns : conn = self . consumer . _client . _conns [ node_id ] if conn . state == ConnectionStates . DISCONNECTED or conn . state == ConnectionStates . DISCONNECTING : self . _spawn_kafka_connection_thread ( ) break | Checks the kafka connection is still valid |
26,701 | def _heartbeat_loop ( self ) : self . logger . debug ( "running main heartbeat thread" ) while not self . closed : time . sleep ( self . settings [ 'SLEEP_TIME' ] ) self . _report_self ( ) | A main run loop thread to do work |
26,702 | def _setup_redis ( self ) : if not self . closed : try : self . logger . debug ( "Creating redis connection to host " + str ( self . settings [ 'REDIS_HOST' ] ) ) self . redis_conn = redis . StrictRedis ( host = self . settings [ 'REDIS_HOST' ] , port = self . settings [ 'REDIS_PORT' ] , db = self . settings [ 'REDIS_D... | Returns a Redis Client |
26,703 | def _setup_kafka ( self ) : 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 . producer . close ( t... | Sets up kafka connections |
26,704 | def _create_consumer ( self ) : if not self . closed : try : self . logger . debug ( "Creating new kafka consumer using brokers: " + str ( self . settings [ 'KAFKA_HOSTS' ] ) + ' and topic ' + self . settings [ 'KAFKA_TOPIC_PREFIX' ] + ".outbound_firehose" ) return KafkaConsumer ( self . settings [ 'KAFKA_TOPIC_PREFIX'... | Tries to establing the Kafka consumer connection |
26,705 | def run ( self ) : self . logger . info ( "Running main flask method on port " + str ( self . settings [ 'FLASK_PORT' ] ) ) self . app . run ( host = '0.0.0.0' , port = self . settings [ 'FLASK_PORT' ] ) | Main flask run loop |
26,706 | def _create_ret_object ( self , status = SUCCESS , data = None , error = False , error_message = None , error_cause = None ) : ret = { } if status == self . FAILURE : ret [ 'status' ] = self . FAILURE else : ret [ 'status' ] = self . SUCCESS ret [ 'data' ] = data if error : ret [ 'error' ] = { } if error_message is not... | Create generic reponse objects . |
26,707 | def _close_thread ( self , thread , thread_name ) : if thread is not None and thread . isAlive ( ) : self . logger . debug ( "Waiting for {} thread to close" . format ( thread_name ) ) thread . join ( timeout = self . settings [ 'DAEMON_THREAD_JOIN_TIMEOUT' ] ) if thread . isAlive ( ) : self . logger . warn ( "{} daemo... | Closes daemon threads |
26,708 | def close ( self ) : self . logger . info ( "Closing Rest Service" ) self . closed = True self . _close_thread ( self . _redis_thread , "Redis setup" ) self . _close_thread ( self . _heartbeat_thread , "Heartbeat" ) self . _close_thread ( self . _kafka_thread , "Kafka setup" ) self . _close_thread ( self . _consumer_th... | Cleans up anything from the process |
26,709 | def _calculate_health ( self ) : if self . redis_connected and self . kafka_connected : return "GREEN" elif self . redis_connected or self . kafka_connected : return "YELLOW" else : return "RED" | Returns a string representation of the node health |
26,710 | def _feed_to_kafka ( self , json_item ) : @ MethodTimer . timeout ( self . settings [ 'KAFKA_FEED_TIMEOUT' ] , False ) def _feed ( json_item ) : try : self . logger . debug ( "Sending json to kafka at " + str ( self . settings [ 'KAFKA_PRODUCER_TOPIC' ] ) ) future = self . producer . send ( self . settings [ 'KAFKA_PRO... | Sends a request to Kafka |
26,711 | def _decorate_routes ( self ) : self . logger . debug ( "Decorating routes" ) self . app . add_url_rule ( '/<path:path>' , 'catch' , self . catch , methods = [ 'GET' , 'POST' ] , defaults = { 'path' : '' } ) self . app . add_url_rule ( '/' , 'index' , self . index , methods = [ 'POST' , 'GET' ] ) self . app . add_url_r... | Decorates the routes to use within the flask app |
26,712 | def poll ( self ) : if self . redis_connected : json_item = request . get_json ( ) result = None try : key = "rest:poll:{u}" . format ( u = json_item [ 'poll_id' ] ) result = self . redis_conn . get ( key ) if result is not None : result = json . loads ( result ) self . logger . debug ( "Found previous poll" ) self . r... | Retrieves older requests that may not make it back quick enough |
26,713 | def create_refresh_token ( identity , expires_delta = None , user_claims = None ) : jwt_manager = _get_jwt_manager ( ) return jwt_manager . _create_refresh_token ( identity , expires_delta , user_claims ) | Creates a new refresh token . |
26,714 | def is_token_revoked ( decoded_token ) : jti = decoded_token [ 'jti' ] try : token = TokenBlacklist . query . filter_by ( jti = jti ) . one ( ) return token . revoked except NoResultFound : return True | Checks if the given token is revoked or not . Because we are adding all the tokens that we create into this database if the token is not present in the database we are going to consider it revoked as we don t know where it was created . |
26,715 | def revoke_token ( token_id , user ) : try : token = TokenBlacklist . query . filter_by ( id = token_id , user_identity = user ) . one ( ) token . revoked = True db . session . commit ( ) except NoResultFound : raise TokenNotFound ( "Could not find the token {}" . format ( token_id ) ) | Revokes the given token . Raises a TokenNotFound error if the token does not exist in the database |
26,716 | def prune_database ( ) : now = datetime . now ( ) expired = TokenBlacklist . query . filter ( TokenBlacklist . expires < now ) . all ( ) for token in expired : db . session . delete ( token ) db . session . commit ( ) | Delete tokens that have expired from the database . |
26,717 | def verify_jwt_in_request ( ) : if request . method not in config . exempt_methods : jwt_data = _decode_jwt_from_request ( request_type = 'access' ) ctx_stack . top . jwt = jwt_data verify_token_claims ( jwt_data ) _load_user ( jwt_data [ config . identity_claim_key ] ) | Ensure that the requester has a valid access token . This does not check the freshness of the access token . Raises an appropiate exception there is no token or if the token is invalid . |
26,718 | def verify_fresh_jwt_in_request ( ) : if request . method not in config . exempt_methods : jwt_data = _decode_jwt_from_request ( request_type = 'access' ) ctx_stack . top . jwt = jwt_data fresh = jwt_data [ 'fresh' ] if isinstance ( fresh , bool ) : if not fresh : raise FreshTokenRequired ( 'Fresh token required' ) els... | Ensure that the requester has a valid and fresh access token . Raises an appropiate exception if there is no token the token is invalid or the token is not marked as fresh . |
26,719 | def jwt_optional ( fn ) : @ wraps ( fn ) def wrapper ( * args , ** kwargs ) : verify_jwt_in_request_optional ( ) return fn ( * args , ** kwargs ) return wrapper | A decorator to optionally protect a Flask endpoint |
26,720 | def load_precise_model ( model_name : str ) -> Any : if not model_name . endswith ( '.net' ) : print ( 'Warning: Unknown model type, ' , model_name ) inject_params ( model_name ) return load_keras ( ) . models . load_model ( model_name ) | Loads a Keras model from file handling custom loss function |
26,721 | def create_model ( model_name : Optional [ str ] , params : ModelParams ) -> 'Sequential' : if model_name and isfile ( model_name ) : print ( 'Loading from ' + model_name + '...' ) model = load_precise_model ( model_name ) else : from keras . layers . core import Dense from keras . layers . recurrent import GRU from ke... | Load or create a precise model |
26,722 | def layer_with ( self , sample : np . ndarray , value : int ) -> np . ndarray : b = np . full ( ( 2 , len ( sample ) ) , value , dtype = float ) b [ 0 ] = sample return b | Create an identical 2d array where the second row is filled with value |
26,723 | def generate_wakeword_pieces ( self , volume ) : while True : target = 1 if random ( ) > 0.5 else 0 it = self . pos_files_it if target else self . neg_files_it sample_file = next ( it ) yield self . layer_with ( self . normalize_volume_to ( load_audio ( sample_file ) , volume ) , target ) yield self . layer_with ( np .... | Generates chunks of audio that represent the wakeword stream |
26,724 | def chunk_audio_pieces ( self , pieces , chunk_size ) : left_over = np . array ( [ ] ) for piece in pieces : if left_over . size == 0 : combined = piece else : combined = np . concatenate ( [ left_over , piece ] , axis = - 1 ) for chunk in chunk_audio ( combined . T , chunk_size ) : yield chunk . T left_over = piece [ ... | Convert chunks of audio into a series of equally sized pieces |
26,725 | def calc_volume ( self , sample : np . ndarray ) : return sqrt ( np . mean ( np . square ( sample ) ) ) | Find the RMS of the audio |
26,726 | def max_run_length ( x : np . ndarray , val : int ) : if x . size == 0 : return 0 else : y = np . array ( x [ 1 : ] != x [ : - 1 ] ) i = np . append ( np . where ( y ) , len ( x ) - 1 ) run_lengths = np . diff ( np . append ( - 1 , i ) ) run_length_values = x [ i ] return max ( [ rl for rl , v in zip ( run_lengths , ru... | Finds the maximum continuous length of the given value in the sequence |
26,727 | def samples_to_batches ( samples : Iterable , batch_size : int ) : it = iter ( samples ) while True : with suppress ( StopIteration ) : batch_in , batch_out = [ ] , [ ] for i in range ( batch_size ) : sample_in , sample_out = next ( it ) batch_in . append ( sample_in ) batch_out . append ( sample_out ) if not batch_in ... | Chunk a series of network inputs and outputs into larger batches |
26,728 | def run ( self ) : _ , test_data = self . data . load ( train = False , test = True ) try : self . model . fit_generator ( self . samples_to_batches ( self . generate_samples ( ) , self . args . batch_size ) , steps_per_epoch = self . args . steps_per_epoch , epochs = self . epoch + self . args . epochs , validation_da... | Train the model on randomly generated batches |
26,729 | def from_both ( cls , tags_file : str , tags_folder : str , folder : str ) -> 'TrainData' : return cls . from_tags ( tags_file , tags_folder ) + cls . from_folder ( folder ) | Load data from both a database and a structured folder |
26,730 | def load_inhibit ( self , train = True , test = True ) -> tuple : def loader ( kws : list , nkws : list ) : from precise . params import pr inputs = np . empty ( ( 0 , pr . n_features , pr . feature_size ) ) outputs = np . zeros ( ( len ( kws ) , 1 ) ) for f in kws : if not isfile ( f ) : continue new_vec = load_vector... | Generate data with inhibitory inputs created from wake word samples |
26,731 | def parse_args ( parser : ArgumentParser ) -> Any : extra_usage = add_to_parser ( parser , extra_usage ) args = parser . parse_args ( ) args . tags_folder = args . tags_folder . format ( folder = args . folder ) return args | Return parsed args from parser adding options for train data inputs |
26,732 | def vectorize_raw ( audio : np . ndarray ) -> np . ndarray : if len ( audio ) == 0 : raise InvalidAudio ( 'Cannot vectorize empty audio!' ) return vectorizers [ pr . vectorizer ] ( audio ) | Turns audio into feature vectors without clipping for length |
26,733 | def vectorize_inhibit ( audio : np . ndarray ) -> np . ndarray : def samp ( x ) : return int ( pr . sample_rate * x ) inputs = [ ] for offset in range ( samp ( inhibit_t ) , samp ( inhibit_dist_t ) , samp ( inhibit_hop_t ) ) : if len ( audio ) - offset < samp ( pr . buffer_t / 2. ) : break inputs . append ( vectorize (... | Returns an array of inputs generated from the wake word audio that shouldn t cause an activation |
26,734 | def update ( self , prob ) : chunk_activated = prob > 1.0 - self . sensitivity if chunk_activated or self . activation < 0 : self . activation += 1 has_activated = self . activation > self . trigger_level if has_activated or chunk_activated and self . activation < 0 : self . activation = - ( 8 * 2048 ) // self . chunk_... | Returns whether the new prediction caused an activation |
26,735 | def start ( self ) : if self . stream is None : from pyaudio import PyAudio , paInt16 self . pa = PyAudio ( ) self . stream = self . pa . open ( 16000 , 1 , paInt16 , True , frames_per_buffer = self . chunk_size ) self . _wrap_stream_read ( self . stream ) self . engine . start ( ) self . running = True self . is_pause... | Start listening from stream |
26,736 | def stop ( self ) : if self . thread : self . running = False if isinstance ( self . stream , ReadWriteStream ) : self . stream . write ( b'\0' * self . chunk_size ) self . thread . join ( ) self . thread = None self . engine . stop ( ) if self . pa : self . pa . terminate ( ) self . stream . stop_stream ( ) self . str... | Stop listening and close stream |
26,737 | def _handle_predictions ( self ) : while self . running : chunk = self . stream . read ( self . chunk_size ) if self . is_paused : continue prob = self . engine . get_prediction ( chunk ) self . on_prediction ( prob ) if self . detector . update ( prob ) : self . on_activation ( ) | Continuously check Precise process output |
26,738 | def calc_filenames ( self , is_correct : bool , actual_output : bool , threshold = 0.5 ) -> list : return [ filename for output , target , filename in zip ( self . outputs , self . targets , self . filenames ) if ( ( output > threshold ) == bool ( target ) ) == is_correct and actual_output == bool ( output > threshold ... | Find a list of files with the given classification |
26,739 | def get_thresholds ( points = 100 , power = 3 ) -> list : return [ ( i / ( points + 1 ) ) ** power for i in range ( 1 , points + 1 ) ] | Run a function with a series of thresholds between 0 and 1 |
26,740 | def load_for ( self , model : str ) -> Tuple [ list , list ] : inject_params ( model ) if self . prev_cache != pr . vectorization_md5_hash ( ) : self . prev_cache = pr . vectorization_md5_hash ( ) self . data = self . loader ( ) return self . data | Injects the model parameters reloading if they changed and returning the data |
26,741 | def buffer_to_audio ( buffer : bytes ) -> np . ndarray : return np . fromstring ( buffer , dtype = '<i2' ) . astype ( np . float32 , order = 'C' ) / 32768.0 | Convert a raw mono audio byte string to numpy array of floats |
26,742 | def find_wavs ( folder : str ) -> Tuple [ List [ str ] , List [ str ] ] : return ( glob_all ( join ( folder , 'wake-word' ) , '*.wav' ) , glob_all ( join ( folder , 'not-wake-word' ) , '*.wav' ) ) | Finds wake - word and not - wake - word wavs in folder |
26,743 | def convert ( model_path : str , out_file : str ) : print ( 'Converting' , model_path , 'to' , out_file , '...' ) import tensorflow as tf from precise . model import load_precise_model from keras import backend as K out_dir , filename = split ( out_file ) out_dir = out_dir or '.' os . makedirs ( out_dir , exist_ok = Tr... | Converts an HD5F file from Keras to a . pb for use with TensorFlow |
26,744 | def inject_params ( model_name : str ) -> ListenerParams : params_file = model_name + '.params' try : with open ( params_file ) as f : pr . __dict__ . update ( compatibility_params , ** json . load ( f ) ) except ( OSError , ValueError , TypeError ) : if isfile ( model_name ) : print ( 'Warning: Failed to load paramete... | Set the global listener params to a saved model |
26,745 | def save_params ( model_name : str ) : with open ( model_name + '.params' , 'w' ) as f : json . dump ( pr . __dict__ , f ) | Save current global listener params to a file |
26,746 | def retrain ( self ) : folder = TrainData . from_folder ( self . args . folder ) train_data , test_data = folder . load ( True , not self . args . no_validation ) train_data = TrainData . merge ( train_data , self . sampled_data ) test_data = TrainData . merge ( test_data , self . test ) train_inputs , train_outputs = ... | Train for a session pulling in any new data from the filesystem |
26,747 | def train_on_audio ( self , fn : str ) : save_test = random ( ) > 0.8 audio = load_audio ( fn ) num_chunks = len ( audio ) // self . args . chunk_size self . listener . clear ( ) for i , chunk in enumerate ( chunk_audio ( audio , self . args . chunk_size ) ) : print ( '\r' + str ( i * 100. / num_chunks ) + '%' , end = ... | Run through a single audio file |
26,748 | def run ( self ) : for fn in glob_all ( self . args . random_data_folder , '*.wav' ) : if fn in self . trained_fns : print ( 'Skipping ' + fn + '...' ) continue print ( 'Starting file ' + fn + '...' ) self . train_on_audio ( fn ) print ( '\r100% ' ) self . trained_fns . append ( fn ) save_trained_fns ( ... | Begin reading through audio files saving false activations and retraining when necessary |
26,749 | def predict ( self , inputs : np . ndarray ) -> np . ndarray : return self . sess . run ( self . out_var , { self . inp_var : inputs } ) | Run on multiple inputs |
26,750 | def satoshi_to_currency ( num , currency ) : return '{:f}' . format ( Decimal ( num / Decimal ( EXCHANGE_RATES [ currency ] ( ) ) ) . quantize ( Decimal ( '0.' + '0' * CURRENCY_PRECISION [ currency ] ) , rounding = ROUND_DOWN ) . normalize ( ) ) | Converts a given number of satoshi to another currency as a formatted string rounded down to the proper number of decimal places . |
26,751 | def get_balance ( cls , address ) : for api_call in cls . GET_BALANCE_MAIN : try : return api_call ( address ) except cls . IGNORED_ERRORS : pass raise ConnectionError ( 'All APIs are unreachable.' ) | Gets the balance of an address in satoshi . |
26,752 | def get_transactions ( cls , address ) : for api_call in cls . GET_TRANSACTIONS_MAIN : try : return api_call ( address ) except cls . IGNORED_ERRORS : pass raise ConnectionError ( 'All APIs are unreachable.' ) | Gets the ID of all transactions related to an address . |
26,753 | def get_unspent ( cls , address ) : for api_call in cls . GET_UNSPENT_MAIN : try : return api_call ( address ) except cls . IGNORED_ERRORS : pass raise ConnectionError ( 'All APIs are unreachable.' ) | Gets all unspent transaction outputs belonging to an address . |
26,754 | def broadcast_tx ( cls , tx_hex ) : success = None for api_call in cls . BROADCAST_TX_MAIN : try : success = api_call ( tx_hex ) if not success : continue return except cls . IGNORED_ERRORS : pass if success is False : raise ConnectionError ( 'Transaction broadcast failed, or ' 'Unspents were already used.' ) raise Con... | Broadcasts a transaction to the blockchain . |
26,755 | def calculate_preimages ( tx_obj , inputs_parameters ) : input_count = int_to_varint ( len ( tx_obj . TxIn ) ) output_count = int_to_varint ( len ( tx_obj . TxOut ) ) output_block = b'' . join ( [ bytes ( o ) for o in tx_obj . TxOut ] ) hashPrevouts = double_sha256 ( b'' . join ( [ i . txid + i . txindex for i in tx_ob... | Calculates preimages for provided transaction structure and input values . |
26,756 | def verify ( self , signature , data ) : return self . _pk . public_key . verify ( signature , data ) | Verifies some data was signed by this private key . |
26,757 | def get_transactions ( self ) : self . transactions [ : ] = NetworkAPI . get_transactions ( self . address ) if self . segwit_address : self . transactions += NetworkAPI . get_transactions ( self . segwit_address ) return self . transactions | Fetches transaction history . |
26,758 | def address ( self ) : if self . _address is None : self . _address = multisig_to_address ( self . public_keys , self . m , version = self . version ) return self . _address | The public address you share with others to receive funds . |
26,759 | def bech32_polymod ( values ) : generator = [ 0x3b6a57b2 , 0x26508e6d , 0x1ea119fa , 0x3d4233dd , 0x2a1462b3 ] chk = 1 for value in values : top = chk >> 25 chk = ( chk & 0x1ffffff ) << 5 ^ value for i in range ( 5 ) : chk ^= generator [ i ] if ( ( top >> i ) & 1 ) else 0 return chk | Internal function that computes the Bech32 checksum . |
26,760 | def bech32_hrp_expand ( hrp ) : return [ ord ( x ) >> 5 for x in hrp ] + [ 0 ] + [ ord ( x ) & 31 for x in hrp ] | Expand the HRP into values for checksum computation . |
26,761 | def bech32_create_checksum ( hrp , data ) : values = bech32_hrp_expand ( hrp ) + data polymod = bech32_polymod ( values + [ 0 , 0 , 0 , 0 , 0 , 0 ] ) ^ 1 return [ ( polymod >> 5 * ( 5 - i ) ) & 31 for i in range ( 6 ) ] | Compute the checksum values given HRP and data . |
26,762 | def bech32_encode ( hrp , data ) : combined = data + bech32_create_checksum ( hrp , data ) return hrp + '1' + '' . join ( [ CHARSET [ d ] for d in combined ] ) | Compute a Bech32 string given HRP and data values . |
26,763 | def convertbits ( data , frombits , tobits , pad = True ) : acc = 0 bits = 0 ret = [ ] maxv = ( 1 << tobits ) - 1 max_acc = ( 1 << ( frombits + tobits - 1 ) ) - 1 for value in data : if value < 0 or ( value >> frombits ) : return None acc = ( ( acc << frombits ) | value ) & max_acc bits += frombits while bits >= tobits... | General power - of - 2 base conversion . |
26,764 | def decode ( addr ) : hrpgot , data = bech32_decode ( addr ) if hrpgot not in BECH32_VERSION_SET : return ( None , None ) decoded = convertbits ( data [ 1 : ] , 5 , 8 , False ) if decoded is None or len ( decoded ) < 2 or len ( decoded ) > 40 : return ( None , None ) if data [ 0 ] > 16 : return ( None , None ) if data ... | Decode a segwit address . |
26,765 | def _run ( method , cmd , cwd = None , shell = True , universal_newlines = True , stderr = STDOUT ) : if not cmd : error_msg = 'Passed empty text or list' raise AttributeError ( error_msg ) if isinstance ( cmd , six . string_types ) : cmd = str ( cmd ) if shell : if isinstance ( cmd , list ) : cmd = ' ' . join ( cmd ) ... | Internal wrapper for call amd check_output |
26,766 | def call ( cmd , shell = True , cwd = None , universal_newlines = True , stderr = STDOUT ) : return Shell . _run ( call , cmd , shell = shell , cwd = cwd , stderr = stderr , universal_newlines = universal_newlines ) | Just execute a specific command . |
26,767 | def get_logger ( name , level = 0 ) : level = 0 if not isinstance ( level , int ) else level level = 0 if level < 0 else level level = 4 if level > 4 else level console = logging . StreamHandler ( ) level = [ logging . NOTSET , logging . ERROR , logging . WARN , logging . INFO , logging . DEBUG ] [ level ] console . se... | Setup a logging instance |
26,768 | def indent ( self , text , n_indents = 1 , skipping = False ) : lines = text . splitlines ( ) space = self . TEMPLATES . get ( self . target_language ) . get ( 'indent' , ' ' ) if len ( lines ) == 1 : if skipping : return text . strip ( ) return n_indents * space + text . strip ( ) indented_lines = [ ] for idx , line i... | Indent text with single spaces . |
26,769 | def temp ( self , name , templates = None , n_indents = None , skipping = False ) : if templates is None : templates = self . TEMPLATES . get ( self . target_language ) keys = name . split ( '.' ) key = keys . pop ( 0 ) . lower ( ) template = templates . get ( key , None ) if template is not None : if isinstance ( temp... | Get specific template of chosen programming language . |
26,770 | def read_sklearn_version ( ) : from sklearn import __version__ as sklearn_ver sklearn_ver = str ( sklearn_ver ) . split ( '.' ) sklearn_ver = [ int ( v ) for v in sklearn_ver ] major , minor = sklearn_ver [ 0 ] , sklearn_ver [ 1 ] patch = sklearn_ver [ 2 ] if len ( sklearn_ver ) >= 3 else 0 return major , minor , patch | Determine the installed version of sklearn |
26,771 | def _platform_is_windows ( platform = sys . platform ) : matched = platform in ( 'cygwin' , 'win32' , 'win64' ) if matched : error_msg = "Windows isn't supported yet" raise OSError ( error_msg ) return matched | Is the current OS a Windows? |
26,772 | def check_deps ( deps ) : if not isinstance ( deps , list ) : deps = [ deps ] checks = list ( Environment . has_apps ( deps ) ) if not all ( checks ) : for name , available in list ( dict ( zip ( deps , checks ) ) . items ( ) ) : if not available : error_msg = "The required application/dependency '{0}'" " isn't availab... | check whether specific requirements are available . |
26,773 | def create_tree ( self ) : feature_indices = [ ] for i in self . estimator . tree_ . feature : n_features = self . n_features if self . n_features > 1 or ( self . n_features == 1 and i >= 0 ) : feature_indices . append ( [ str ( j ) for j in range ( n_features ) ] [ i ] ) indentation = 1 if self . target_language in [ ... | Parse and build the tree branches . |
26,774 | def _get_intercepts ( self ) : temp_arr = self . temp ( 'arr' ) for layer in self . intercepts : inter = ', ' . join ( [ self . repr ( b ) for b in layer ] ) yield temp_arr . format ( inter ) | Concatenate all intercepts of the classifier . |
26,775 | def create_embedded_meth ( self ) : fns = [ ] for idx , estimator in enumerate ( self . estimators ) : tree = self . create_single_method ( idx , estimator ) fns . append ( tree ) fns = '\n' . join ( fns ) fn_names = '' if self . target_language in [ 'c' , 'java' ] : fn_names = [ ] temp_method_calls = self . temp ( 'em... | Build the estimator methods or functions . |
26,776 | def _classifiers ( self ) : classifiers = ( AdaBoostClassifier , BernoulliNB , DecisionTreeClassifier , ExtraTreesClassifier , GaussianNB , KNeighborsClassifier , LinearSVC , NuSVC , RandomForestClassifier , SVC , ) if self . sklearn_ver [ : 2 ] >= ( 0 , 18 ) : from sklearn . neural_network . multilayer_perceptron impo... | Get a set of supported classifiers . |
26,777 | def _regressors ( self ) : regressors = ( ) if self . sklearn_ver [ : 2 ] >= ( 0 , 18 ) : from sklearn . neural_network . multilayer_perceptron import MLPRegressor regressors += ( MLPRegressor , ) return regressors | Get a set of supported regressors . |
26,778 | def predict ( self , X , class_name = None , method_name = None , tnp_dir = 'tmp' , keep_tmp_dir = False , num_format = lambda x : str ( x ) ) : if class_name is None : class_name = self . estimator_name if method_name is None : method_name = self . target_method if not self . _tested_dependencies : self . _test_depend... | Predict using the transpiled model . |
26,779 | def integrity_score ( self , X , method = 'predict' , normalize = True , num_format = lambda x : str ( x ) ) : X = np . array ( X ) if not X . ndim > 1 : X = np . array ( [ X ] ) method = str ( method ) . strip ( ) . lower ( ) if method not in [ 'predict' , 'predict_proba' ] : error = "The given method '{}' isn't suppo... | Compute the accuracy of the ported classifier . |
26,780 | def _get_filename ( class_name , language ) : name = str ( class_name ) . strip ( ) lang = str ( language ) if language in [ 'java' , 'php' ] : name = "" . join ( [ name [ 0 ] . upper ( ) + name [ 1 : ] ] ) suffix = { 'c' : 'c' , 'java' : 'java' , 'js' : 'js' , 'go' : 'go' , 'php' : 'php' , 'ruby' : 'rb' } suffix = suf... | Generate the specific filename . |
26,781 | def _get_commands ( filename , class_name , language ) : cname = str ( class_name ) fname = str ( filename ) lang = str ( language ) comp_vars = { 'c' : 'gcc {} -lm -o {}' . format ( fname , cname ) , 'java' : 'javac {}' . format ( fname ) , 'go' : 'go build -o {} {}.go' . format ( cname , cname ) } comp_cmd = comp_var... | Generate the related compilation and execution commands . |
26,782 | def _get_metadata_for_region ( region_code ) : country_calling_code = country_code_for_region ( region_code ) main_country = region_code_for_country_code ( country_calling_code ) return PhoneMetadata . metadata_for_region ( main_country , _EMPTY_METADATA ) | The metadata needed by this class is the same for all regions sharing the same country calling code . Therefore we return the metadata for main region for this country calling code . |
26,783 | def _maybe_create_new_template ( self ) : ii = 0 while ii < len ( self . _possible_formats ) : number_format = self . _possible_formats [ ii ] pattern = number_format . pattern if self . _current_formatting_pattern == pattern : return False if self . _create_formatting_template ( number_format ) : self . _current_forma... | Returns True if a new template is created as opposed to reusing the existing template . |
26,784 | def _get_formatting_template ( self , number_pattern , number_format ) : longest_phone_number = unicod ( "999999999999999" ) number_re = re . compile ( number_pattern ) m = number_re . search ( longest_phone_number ) a_phone_number = m . group ( 0 ) if len ( a_phone_number ) < len ( self . _national_number ) : return U... | Gets a formatting template which can be used to efficiently format a partial number where digits are added one by one . |
26,785 | def input_digit ( self , next_char , remember_position = False ) : self . _accrued_input += next_char if remember_position : self . _original_position = len ( self . _accrued_input ) if not self . _is_digit_or_leading_plus_sign ( next_char ) : self . _able_to_format = False self . _input_has_formatting = True else : ne... | Formats a phone number on - the - fly as each digit is entered . |
26,786 | def _attempt_to_format_accrued_digits ( self ) : for number_format in self . _possible_formats : num_re = re . compile ( number_format . pattern ) if fullmatch ( num_re , self . _national_number ) : if number_format . national_prefix_formatting_rule is None : self . _should_add_space_after_national_prefix = False else ... | Checks to see if there is an exact pattern match for these digits . If so we should use this instead of any other formatting template whose leadingDigitsPattern also matches the input . |
26,787 | def _attempt_to_choose_formatting_pattern ( self ) : if len ( self . _national_number ) >= _MIN_LEADING_DIGITS_LENGTH : self . _get_available_formats ( self . _national_number ) formatted_number = self . _attempt_to_format_accrued_digits ( ) if len ( formatted_number ) > 0 : return formatted_number if self . _maybe_cre... | Attempts to set the formatting template and returns a string which contains the formatted version of the digits entered so far . |
26,788 | def _input_accrued_national_number ( self ) : length_of_national_number = len ( self . _national_number ) if length_of_national_number > 0 : temp_national_number = U_EMPTY_STRING for ii in range ( length_of_national_number ) : temp_national_number = self . _input_digit_helper ( self . _national_number [ ii ] ) if self ... | Invokes input_digit_helper on each digit of the national number accrued and returns a formatted string in the end . |
26,789 | def _is_nanpa_number_with_national_prefix ( self ) : return ( self . _current_metadata . country_code == 1 and self . _national_number [ 0 ] == '1' and self . _national_number [ 1 ] != '0' and self . _national_number [ 1 ] != '1' ) | Returns true if the current country is a NANPA country and the national number begins with the national prefix . |
26,790 | def _attempt_to_extract_idd ( self ) : international_prefix = re . compile ( unicod ( "\\" ) + _PLUS_SIGN + unicod ( "|" ) + ( self . _current_metadata . international_prefix or U_EMPTY_STRING ) ) idd_match = international_prefix . match ( self . _accrued_input_without_formatting ) if idd_match : self . _is_complete_nu... | Extracts IDD and plus sign to self . _prefix_before_national_number when they are available and places the remaining input into _national_number . |
26,791 | def _attempt_to_extract_ccc ( self ) : if len ( self . _national_number ) == 0 : return False country_code , number_without_ccc = _extract_country_code ( self . _national_number ) if country_code == 0 : return False self . _national_number = number_without_ccc new_region_code = region_code_for_country_code ( country_co... | Extracts the country calling code from the beginning of _national_number to _prefix_before_national_number when they are available and places the remaining input into _national_number . |
26,792 | def country_name_for_number ( numobj , lang , script = None , region = None ) : region_codes = region_codes_for_country_code ( numobj . country_code ) if len ( region_codes ) == 1 : return _region_display_name ( region_codes [ 0 ] , lang , script , region ) else : region_where_number_is_valid = u ( "ZZ" ) for region_co... | Returns the customary display name in the given langauge for the given territory the given PhoneNumber object is from . If it could be from many territories nothing is returned . |
26,793 | def description_for_valid_number ( numobj , lang , script = None , region = None ) : number_region = region_code_for_number ( numobj ) if region is None or region == number_region : mobile_token = country_mobile_token ( numobj . country_code ) national_number = national_significant_number ( numobj ) if mobile_token != ... | Return a text description of a PhoneNumber object in the language provided . |
26,794 | def description_for_number ( numobj , lang , script = None , region = None ) : ntype = number_type ( numobj ) if ntype == PhoneNumberType . UNKNOWN : return "" elif not is_number_type_geographical ( ntype , numobj . country_code ) : return country_name_for_number ( numobj , lang , script , region ) return description_f... | Return a text description of a PhoneNumber object for the given language . |
26,795 | def _find_lang ( langdict , lang , script , region ) : full_locale = _full_locale ( lang , script , region ) if ( full_locale in _LOCALE_NORMALIZATION_MAP and _LOCALE_NORMALIZATION_MAP [ full_locale ] in langdict ) : return langdict [ _LOCALE_NORMALIZATION_MAP [ full_locale ] ] if full_locale in langdict : return langd... | Return the entry in the dictionary for the given language information . |
26,796 | def _prefix_description_for_number ( data , longest_prefix , numobj , lang , script = None , region = None ) : e164_num = format_number ( numobj , PhoneNumberFormat . E164 ) if not e164_num . startswith ( U_PLUS ) : raise Exception ( "Expect E164 number to start with +" ) for prefix_len in range ( longest_prefix , 0 , ... | Return a text description of a PhoneNumber for the given language . |
26,797 | def merge_from ( self , other ) : if other . pattern is not None : self . pattern = other . pattern if other . format is not None : self . format = other . format self . leading_digits_pattern . extend ( other . leading_digits_pattern ) if other . national_prefix_formatting_rule is not None : self . national_prefix_for... | Merge information from another NumberFormat object into this one . |
26,798 | def merge_from ( self , other ) : if other . national_number_pattern is not None : self . national_number_pattern = other . national_number_pattern if other . example_number is not None : self . example_number = other . example_number | Merge information from another PhoneNumberDesc object into this one . |
26,799 | def load_all ( kls ) : for region_code , loader in list ( kls . _region_available . items ( ) ) : if loader is not None : loader ( region_code ) kls . _region_available [ region_code ] = None for country_code , loader in list ( kls . _country_code_available . items ( ) ) : if loader is not None : loader ( country_code ... | Force immediate load of all metadata |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.