idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
36,500
def after_epoch ( self , epoch_data : EpochData , ** kwargs ) -> None : self . _save_stats ( epoch_data ) super ( ) . after_epoch ( epoch_data = epoch_data , ** kwargs )
Compute the specified aggregations and save them to the given epoch data .
36,501
def from_file ( filepath : str ) : trace = TrainingTrace ( ) trace . _trace = load_config ( filepath ) return trace
Load training trace from the given filepath .
36,502
def after_epoch ( self , epoch_id : int , epoch_data : EpochData ) : if self . _stream not in epoch_data : raise KeyError ( 'The hook could not determine whether the threshold was exceeded as the stream `{}`' 'was not found in the epoch data' . format ( self . _stream ) ) if self . _variable not in epoch_data [ self . ...
Check termination conditions .
36,503
def train ( config_path : str , cl_arguments : Iterable [ str ] , output_root : str ) -> None : config = None try : config_path = find_config ( config_path ) config = load_config ( config_file = config_path , additional_args = cl_arguments ) validate_config ( config ) logging . debug ( '\tLoaded config: %s' , config ) ...
Load config and start the training .
36,504
def evaluate ( model_path : str , stream_name : str , config_path : Optional [ str ] , cl_arguments : Iterable [ str ] , output_root : str ) -> None : config = None try : model_dir = path . dirname ( model_path ) if not path . isdir ( model_path ) else model_path config_path = find_config ( model_dir if config_path is ...
Evaluate the given model on the specified data stream .
36,505
def predict ( config_path : str , restore_from : Optional [ str ] , cl_arguments : Iterable [ str ] , output_root : str ) -> None : config = None try : config_path = find_config ( config_path ) restore_from = restore_from or path . dirname ( config_path ) config = load_config ( config_file = config_path , additional_ar...
Run prediction from the specified config path .
36,506
def _create_epoch_data ( self , streams : Optional [ Iterable [ str ] ] = None ) -> EpochData : if streams is None : streams = [ self . _train_stream_name ] + self . _extra_streams return OrderedDict ( [ ( stream_name , OrderedDict ( ) ) for stream_name in streams ] )
Create empty epoch data double dict .
36,507
def _check_sources ( self , batch : Dict [ str , object ] ) -> None : unused_sources = [ source for source in batch . keys ( ) if source not in self . _model . input_names ] missing_sources = [ source for source in self . _model . input_names if source not in batch . keys ( ) ] if unused_sources : if self . _on_unused_...
Check for unused and missing sources .
36,508
def train_by_stream ( self , stream : StreamWrapper ) -> None : self . _run_epoch ( stream = stream , train = True )
Train the model with the given stream .
36,509
def evaluate_stream ( self , stream : StreamWrapper ) -> None : self . _run_epoch ( stream = stream , train = False )
Evaluate the given stream .
36,510
def _run_zeroth_epoch ( self , streams : Iterable [ str ] ) -> None : for stream_name in streams : with self . get_stream ( stream_name ) as stream : self . evaluate_stream ( stream ) epoch_data = self . _create_epoch_data ( streams ) for hook in self . _hooks : hook . after_epoch ( epoch_id = 0 , epoch_data = epoch_da...
Run zeroth epoch on the specified streams .
36,511
def run_training ( self , trace : Optional [ TrainingTrace ] = None ) -> None : for stream_name in [ self . _train_stream_name ] + self . _extra_streams : self . get_stream ( stream_name ) def training ( ) : logging . debug ( 'Training started' ) self . _epochs_done = 0 if not self . _skip_zeroth_epoch : logging . info...
Run the main loop in the training mode .
36,512
def run_evaluation ( self , stream_name : str ) -> None : def prediction ( ) : logging . info ( 'Running prediction' ) self . _run_zeroth_epoch ( [ stream_name ] ) logging . info ( 'Prediction done\n\n' ) self . _try_run ( prediction )
Run the main loop with the given stream in the prediction mode .
36,513
def major_vote ( all_votes : Iterable [ Iterable [ Hashable ] ] ) -> Iterable [ Hashable ] : return [ Counter ( votes ) . most_common ( ) [ 0 ] [ 0 ] for votes in zip ( * all_votes ) ]
For the given iterable of object iterations return an iterable of the most common object at each position of the inner iterations .
36,514
def _load_models ( self ) -> None : if self . _models is None : logging . info ( 'Loading %d models' , len ( self . _model_paths ) ) def load_model ( model_path : str ) : logging . debug ( '\tloading %s' , model_path ) if path . isdir ( model_path ) : model_path = path . join ( model_path , CXF_CONFIG_FILE ) config = l...
Maybe load all the models to be assembled together and save them to the self . _models attribute .
36,515
def run ( self , batch : Batch , train : bool = False , stream : StreamWrapper = None ) -> Batch : if train : raise ValueError ( 'Ensemble model cannot be trained.' ) self . _load_models ( ) batch_outputs = [ model . run ( batch , False , stream ) for model in self . _models ] aggregated = { } for output_name in self ....
Run feed - forward pass with the given batch using all the models aggregate and return the results .
36,516
def get_attribute ( module_name : str , attribute_name : str ) : assert isinstance ( module_name , str ) assert isinstance ( attribute_name , str ) _module = importlib . import_module ( module_name ) return getattr ( _module , attribute_name )
Get the specified module attribute . It most cases it will be a class or function .
36,517
def create_object ( module_name : str , class_name : str , args : Iterable = ( ) , kwargs : Dict [ str , Any ] = _EMPTY_DICT ) : return get_attribute ( module_name , class_name ) ( * args , ** kwargs )
Create an object instance of the given class from the given module . Args and kwargs are passed to the constructor .
36,518
def list_submodules ( module_name : str ) -> List [ str ] : _module = importlib . import_module ( module_name ) return [ module_name + '.' + submodule_name for _ , submodule_name , _ in pkgutil . iter_modules ( _module . __path__ ) ]
List full names of all the submodules in the given module .
36,519
def find_class_module ( module_name : str , class_name : str ) -> Tuple [ List [ str ] , List [ Tuple [ str , Exception ] ] ] : matched_submodules = [ ] erroneous_submodules = [ ] for submodule_name in list_submodules ( module_name ) : try : submodule = importlib . import_module ( submodule_name ) if hasattr ( submodul...
Find sub - modules of the given module that contain the given class .
36,520
def get_class_module ( module_name : str , class_name : str ) -> Optional [ str ] : matched_modules , erroneous_modules = find_class_module ( module_name , class_name ) for submodule , error in erroneous_modules : logging . warning ( 'Could not inspect sub-module `%s` due to `%s` ' 'when searching for `%s` in sub-modul...
Get a sub - module of the given module which has the given class .
36,521
def _get_stream ( self ) -> Iterator : if self . _stream is None : self . _stream = iter ( self . _get_stream_fn ( ) ) return self . _stream
Possibly create and return raw dataset stream iterator .
36,522
def _enqueue_batches ( self , stop_event : Event ) -> None : while True : self . _stream = self . _get_stream ( ) while True : with self . _semaphore : pass time . sleep ( CXF_BUFFER_SLEEP ) try : batch = next ( self . _stream ) except StopIteration : break self . _queue . put ( batch ) self . _batch_count += 1 if stop...
Enqueue all the stream batches . If specified stop after epoch_size batches .
36,523
def _dequeue_batch ( self ) -> Optional [ Batch ] : if self . _enqueueing_thread is None : raise ValueError ( 'StreamWrapper `{}` with buffer of size `{}` was used outside with-resource environment.' . format ( self . _name , self . _buffer_size ) ) if not self . _enqueueing_thread . is_alive ( ) and self . _queue . em...
Return a single batch from queue or None signaling epoch end .
36,524
def _next_batch ( self ) -> Optional [ Batch ] : if self . _epoch_limit_reached ( ) : self . _batch_count = 0 return None try : batch = next ( self . _get_stream ( ) ) self . _batch_count += 1 return batch except StopIteration : self . _stream = None if self . _epoch_size > 0 : batch = next ( self . _get_stream ( ) ) s...
Return a single batch or None signaling epoch end .
36,525
def _start_thread ( self ) : self . _stopping_event = Event ( ) self . _enqueueing_thread = Thread ( target = self . _enqueue_batches , args = ( self . _stopping_event , ) ) self . _enqueueing_thread . start ( )
Start an enqueueing thread .
36,526
def _stop_thread ( self ) : self . _stopping_event . set ( ) queue_content = [ ] try : while True : queue_content . append ( self . _queue . get_nowait ( ) ) except Empty : pass self . _enqueueing_thread . join ( ) try : queue_content . append ( self . _queue . get_nowait ( ) ) except Empty : pass self . _queue = Queue...
Stop the enqueueing thread . Keep the queue content and stream state .
36,527
def _after_n_epoch ( self , epoch_id : int , ** _ ) -> None : SaveEvery . save_model ( model = self . _model , name_suffix = str ( epoch_id ) , on_failure = self . _on_save_failure )
Save the model every n_epochs epoch .
36,528
def save_model ( model : AbstractModel , name_suffix : str , on_failure : str ) -> None : try : logging . debug ( 'Saving the model' ) save_path = model . save ( name_suffix ) logging . info ( 'Model saved to: %s' , save_path ) except Exception as ex : if on_failure == 'error' : raise IOError ( 'Failed to save the mode...
Save the given model with the given name_suffix . On failure take the specified action .
36,529
def _get_value ( self , epoch_data : EpochData ) -> float : if self . _stream_name not in epoch_data : raise KeyError ( 'Stream `{}` was not found in the epoch data.\nAvailable streams are `{}`.' . format ( self . _stream_name , epoch_data . keys ( ) ) ) stream_data = epoch_data [ self . _stream_name ] if self . _varia...
Retrieve the value of the monitored variable from the given epoch data .
36,530
def _is_value_better ( self , new_value : float ) -> bool : if self . _best_value is None : return True if self . _condition == 'min' : return new_value < self . _best_value if self . _condition == 'max' : return new_value > self . _best_value
Test if the new value is better than the best so far .
36,531
def after_epoch ( self , epoch_data : EpochData , ** _ ) -> None : new_value = self . _get_value ( epoch_data ) if self . _is_value_better ( new_value ) : self . _best_value = new_value SaveEvery . save_model ( model = self . _model , name_suffix = self . _OUTPUT_NAME , on_failure = self . _on_save_failure )
Save the model if the new value of the monitored variable is better than the best value so far .
36,532
def print_progress_bar ( done : int , total : int , prefix : str = '' , suffix : str = '' ) -> None : percent = '{0:.1f}' . format ( 100 * ( done / float ( total ) ) ) base_len = shutil . get_terminal_size ( ) . columns - 7 - len ( prefix ) - len ( suffix ) base_len = min ( [ base_len , 50 ] ) min_length = base_len - 1...
Print a progressbar with the given prefix and suffix without newline at the end .
36,533
def after_epoch ( self , ** _ ) -> None : if not self . _total_batch_count_saved : self . _total_batch_count = self . _current_batch_count . copy ( ) self . _total_batch_count_saved = True self . _current_batch_count . clear ( ) self . _current_stream_start = None self . _current_stream_name = None erase_line ( )
Reset progress counters . Save total_batch_count after the 1st epoch .
36,534
def after_epoch_profile ( self , epoch_id , profile : TimeProfile , train_stream_name : str , extra_streams : Iterable [ str ] ) -> None : read_data_total = 0 eval_total = 0 train_total = sum ( profile . get ( 'eval_batch_{}' . format ( train_stream_name ) , [ ] ) ) hooks_total = sum ( profile . get ( 'after_epoch_hook...
Summarize and log the given epoch profile .
36,535
def confusion_matrix ( expected : np . ndarray , predicted : np . ndarray , num_classes : int ) -> np . ndarray : assert np . issubclass_ ( expected . dtype . type , np . integer ) , " Classes' indices must be integers" assert np . issubclass_ ( predicted . dtype . type , np . integer ) , " Classes' indices must be int...
Calculate and return confusion matrix for the predicted and expected labels
36,536
def _build_grid_search_commands ( script : str , params : typing . Iterable [ str ] ) -> typing . Iterable [ typing . List [ str ] ] : param_space = OrderedDict ( ) for arg in params : assert '=' in arg name = arg [ : arg . index ( '=' ) ] options = arg [ arg . index ( '=' ) + 1 : ] options = ast . literal_eval ( optio...
Build all grid search parameter configurations .
36,537
def grid_search ( script : str , params : typing . Iterable [ str ] , dry_run : bool = False ) -> None : commands = _build_grid_search_commands ( script = script , params = params ) if dry_run : logging . warning ( 'Dry run' ) for command in commands : logging . info ( command ) else : for command in commands : try : c...
Build all grid search parameter configurations and optionally run them .
36,538
def stream_info ( self ) -> None : stream_names = [ stream_name for stream_name in dir ( self ) if 'stream' in stream_name and stream_name != 'stream_info' ] logging . info ( 'Found %s stream candidates: %s' , len ( stream_names ) , stream_names ) for stream_name in stream_names : try : stream_fn = getattr ( self , str...
Check and report source names dtypes and shapes of all the streams available .
36,539
def find_config ( config_path : str ) -> str : if path . isdir ( config_path ) : config_path = path . join ( config_path , CXF_CONFIG_FILE ) assert path . exists ( config_path ) , '`{}` does not exist' . format ( config_path ) return config_path
Derive configuration file path from the given path and check its existence .
36,540
def fallback ( message : str , ex : Exception ) -> None : logging . error ( '%s' , message ) logging . exception ( '%s' , ex ) sys . exit ( 1 )
Fallback procedure when a cli command fails .
36,541
def _configure_dataset ( self , data_root : str = None , download_urls : Iterable [ str ] = None , ** kwargs ) -> None : self . _data_root = data_root self . _download_urls = download_urls
Save the passed values and use them as a default property implementation .
36,542
def resume ( config_path : str , restore_from : Optional [ str ] , cl_arguments : Iterable [ str ] , output_root : str ) -> None : config = None try : config_path = find_config ( config_path ) restore_from = restore_from or path . dirname ( config_path ) config = load_config ( config_file = config_path , additional_arg...
Load config from the directory specified and start the training .
36,543
def after_epoch_profile ( self , epoch_id : int , profile : TimeProfile , train_stream_name : str , extra_streams : Iterable [ str ] ) -> None : pass
After epoch profile event .
36,544
def load_yaml ( yaml_file : str ) -> Any : with open ( yaml_file , 'r' ) as file : return ruamel . yaml . load ( file , ruamel . yaml . RoundTripLoader )
Load YAML from file .
36,545
def yaml_to_file ( data : Mapping , output_dir : str , name : str ) -> str : dumped_config_f = path . join ( output_dir , name ) with open ( dumped_config_f , 'w' ) as file : yaml . dump ( data , file , Dumper = ruamel . yaml . RoundTripDumper ) return dumped_config_f
Save the given object to the given path in YAML .
36,546
def yaml_to_str ( data : Mapping ) -> str : return yaml . dump ( data , Dumper = ruamel . yaml . RoundTripDumper )
Return the given given config as YAML str .
36,547
def reload ( data : Any ) -> Any : return yaml . load ( yaml . dump ( data , Dumper = ruamel . yaml . RoundTripDumper ) , Loader = ruamel . yaml . RoundTripLoader )
Dump and load yaml data . This is useful to avoid many anchor parsing bugs . When you edit a yaml config reload it to make sure the changes are propagated to anchor expansions .
36,548
def _is_nan ( self , variable : str , data ) -> bool : if isinstance ( data , np . ndarray ) or isinstance ( data , list ) : return any ( np . isnan ( data ) ) or ( self . _stop_on_inf and any ( np . isinf ( data ) ) ) elif np . isscalar ( data ) : return np . isnan ( data ) or ( self . _stop_on_inf and np . isinf ( da...
Recursively search passed data and find NaNs .
36,549
def _check_nan ( self , epoch_data : EpochData ) -> None : for stream_name in epoch_data . keys ( ) : stream_data = epoch_data [ stream_name ] variables = self . _variables if self . _variables is not None else stream_data . keys ( ) for variable in variables : if variable not in stream_data : raise KeyError ( 'Variabl...
Raise an exception when some of the monitored data is NaN .
36,550
def after_epoch ( self , epoch_data : EpochData , ** kwargs ) -> None : if self . _after_epoch : self . _check_nan ( epoch_data )
If initialized to check after each epoch stop the training once the epoch data contains a monitored variable equal to NaN .
36,551
def after_batch ( self , stream_name : str , batch_data ) -> None : if self . _after_batch : self . _check_nan ( { stream_name : batch_data } )
If initialized to check after each batch stop the training once the batch data contains a monitored variable equal to NaN .
36,552
def after_epoch ( self , epoch_id : int , ** kwargs ) -> None : if epoch_id % self . _n_epochs == 0 : self . _after_n_epoch ( epoch_id = epoch_id , ** kwargs )
Call _after_n_epoch method every n_epochs epoch .
36,553
def humanize_filesize ( filesize : int ) -> Tuple [ str , str ] : for unit in [ '' , 'K' , 'M' , 'G' , 'T' , 'P' , 'E' , 'Z' ] : if filesize < 1024.0 : return '{:3.1f}' . format ( filesize ) , unit + 'B' filesize /= 1024.0
Return human readable pair of size and unit from the given filesize in bytes .
36,554
def is_train_dir ( dir_ : str ) -> bool : return path . exists ( path . join ( dir_ , CXF_CONFIG_FILE ) ) and path . exists ( path . join ( dir_ , CXF_TRACE_FILE ) ) and path . exists ( path . join ( dir_ , CXF_LOG_FILE ) )
Test if the given dir contains training artifacts .
36,555
def _print_trainings_long ( trainings : Iterable [ Tuple [ str , dict , TrainingTrace ] ] ) -> None : long_table = [ ] for train_dir , config , trace in trainings : start_datetime , end_datetime = trace [ TrainingTraceKeys . TRAIN_BEGIN ] , trace [ TrainingTraceKeys . TRAIN_END ] if start_datetime : age = format_timede...
Print a plain table with the details of the given trainings .
36,556
def _ls_print_listing ( dir_ : str , recursive : bool , all_ : bool , long : bool ) -> List [ Tuple [ str , dict , TrainingTrace ] ] : all_trainings = [ ] for root_dir , train_dirs in walk_train_dirs ( dir_ ) : if train_dirs : if recursive : print ( root_dir + ':' ) trainings = [ ( train_dir , load_config ( path . join...
Print names of the train dirs contained in the given dir .
36,557
def _ls_print_summary ( all_trainings : List [ Tuple [ str , dict , TrainingTrace ] ] ) -> None : counts_by_name = defaultdict ( int ) counts_by_classes = defaultdict ( int ) for _ , config , _ in all_trainings : counts_by_name [ get_model_name ( config ) ] += 1 counts_by_classes [ get_classes ( config ) ] += 1 print_b...
Print trainings summary . In particular print tables summarizing the number of trainings with - particular model names - particular combinations of models and datasets
36,558
def list_train_dirs ( dir_ : str , recursive : bool , all_ : bool , long : bool , verbose : bool ) -> None : if verbose : long = True if dir_ == CXF_DEFAULT_LOG_DIR and not path . exists ( CXF_DEFAULT_LOG_DIR ) : print ( 'The default log directory `{}` does not exist.\n' 'Consider specifying the directory to be listed ...
List training dirs contained in the given dir with options and outputs similar to the regular ls command . The function is accessible through cxflow CLI cxflow ls .
36,559
def after_batch ( self , stream_name : str , batch_data : Batch ) : for variable in self . _variables : if variable in batch_data : value = batch_data [ variable ] if not hasattr ( value , '__iter__' ) : raise TypeError ( 'Variable `{}` to be accumulated is not iterable.' . format ( variable ) ) self . _accumulator [ s...
Extend the accumulated variables with the given batch data .
36,560
def invoke_dataset_method ( config_path : str , method_name : str , output_root : str , cl_arguments : Iterable [ str ] ) -> None : config = dataset = method = output_dir = None try : config_path = find_config ( config_path ) config = load_config ( config_file = config_path , additional_args = cl_arguments ) assert 'da...
Create the specified dataset and invoke its specified method .
36,561
def _signal_handler ( self , * _ ) -> None : if self . _num_signals == 0 : logging . warning ( 'Interrupt signal caught - training will be terminated' ) logging . warning ( 'Another interrupt signal will terminate the program immediately' ) self . _num_signals += 1 else : logging . error ( 'Another interrupt signal cau...
On the first signal increase the self . _num_signals counter . Call sys . exit on any subsequent signal .
36,562
def create_output_dir ( config : dict , output_root : str , default_model_name : str = 'Unnamed' ) -> str : logging . info ( 'Creating output dir' ) model_name = default_model_name if 'name' not in config [ 'model' ] : logging . warning ( '\tmodel.name not found in config, defaulting to: %s' , model_name ) else : model...
Create output_dir under the given output_root and - dump the given config to YAML file under this dir - register a file logger logging to a file under this dir
36,563
def create_dataset ( config : dict , output_dir : Optional [ str ] = None ) -> AbstractDataset : logging . info ( 'Creating dataset' ) dataset_config = make_simple ( config ) [ 'dataset' ] assert 'class' in dataset_config , '`dataset.class` not present in the config' dataset_module , dataset_class = parse_fully_qualifi...
Create a dataset object according to the given config .
36,564
def create_model ( config : dict , output_dir : Optional [ str ] , dataset : AbstractDataset , restore_from : Optional [ str ] = None ) -> AbstractModel : logging . info ( 'Creating a model' ) model_config = config [ 'model' ] model_config = dict ( model_config . items ( ) ) assert 'class' in model_config , '`model.cla...
Create a model object either from scratch of from the checkpoint in resume_dir .
36,565
def _prune_subdirs ( dir_ : str ) -> None : for logdir in [ path . join ( dir_ , f ) for f in listdir ( dir_ ) if is_train_dir ( path . join ( dir_ , f ) ) ] : for subdir in [ path . join ( logdir , f ) for f in listdir ( logdir ) if path . isdir ( path . join ( logdir , f ) ) ] : _safe_rmtree ( subdir )
Delete all subdirs in training log dirs .
36,566
def _prune ( dir_ : str , epochs : int ) -> None : for logdir in [ path . join ( dir_ , f ) for f in listdir ( dir_ ) if path . isdir ( path . join ( dir_ , f ) ) ] : if not is_train_dir ( logdir ) : _safe_rmtree ( logdir ) else : trace_path = path . join ( logdir , CXF_TRACE_FILE ) try : epochs_done = TrainingTrace . ...
Delete all training dirs with incomplete training artifacts or with less than specified epochs done .
36,567
def prune_train_dirs ( dir_ : str , epochs : int , subdirs : bool ) -> None : if dir_ == CXF_DEFAULT_LOG_DIR and not path . exists ( CXF_DEFAULT_LOG_DIR ) : print ( 'The default log directory `{}` does not exist.\n' 'Consider specifying the directory to be listed as an argument.' . format ( CXF_DEFAULT_LOG_DIR ) ) quit...
Prune training log dirs contained in the given dir . The function is accessible through cxflow CLI cxflow prune .
36,568
def output_names ( self ) -> Iterable [ str ] : self . _load_models ( ) return chain . from_iterable ( map ( lambda m : m . output_names , self . _models ) )
List of model output names .
36,569
def run ( self , batch : Batch , train : bool = False , stream : StreamWrapper = None ) -> Batch : if train : raise ValueError ( 'Ensemble model cannot be trained.' ) self . _load_models ( ) current_batch = dict ( copy . deepcopy ( batch ) ) for model in self . _models : current_batch . update ( model . run ( current_b...
Run all the models in - order and return accumulated outputs .
36,570
def _log_variables ( self , epoch_data : EpochData ) : for stream_name in epoch_data . keys ( ) : stream_data = epoch_data [ stream_name ] variables = self . _variables if self . _variables is not None else stream_data . keys ( ) for variable in variables : if variable not in stream_data : raise KeyError ( 'Variable `{...
Log variables from the epoch data .
36,571
def get_reference_end_from_cigar ( reference_start , cigar ) : reference_end = reference_start for i in xrange ( len ( cigar ) ) : k , n = cigar [ i ] if k in ( 0 , 2 , 3 , 7 , 8 ) : reference_end += n return reference_end
This returns the coordinate just past the last aligned base . This matches the behavior of pysam s reference_end method
36,572
def set_order_by_clip ( self , a , b ) : if self . is_left_clip ( a . cigar ) : self . query_left = b self . query_right = a else : self . query_left = a self . query_right = b
Determine which SplitPiece is the leftmost based on the side of the longest clipping operation
36,573
def _is_streaming_request ( self ) : arg2 = self . argstreams [ 1 ] arg3 = self . argstreams [ 2 ] return not ( isinstance ( arg2 , InMemStream ) and isinstance ( arg3 , InMemStream ) and ( ( arg2 . auto_close and arg3 . auto_close ) or ( arg2 . state == StreamState . completed and arg3 . state == StreamState . complet...
check request is stream request or not
36,574
def should_retry_on_error ( self , error ) : if self . is_streaming_request : return False retry_flag = self . headers . get ( 're' , retry . DEFAULT ) if retry_flag == retry . NEVER : return False if isinstance ( error , StreamClosedError ) : return True if error . code in [ ErrorCode . bad_request , ErrorCode . cance...
rules for retry
36,575
def client_for ( service , service_module , thrift_service_name = None ) : assert service_module , 'service_module is required' service = service or '' if not thrift_service_name : thrift_service_name = service_module . __name__ . rsplit ( '.' , 1 ) [ - 1 ] method_names = get_service_methods ( service_module . Iface ) ...
Build a synchronous client class for the given Thrift service .
36,576
def generate_method ( method_name ) : def call ( self , * args , ** kwargs ) : if not self . threadloop . is_ready ( ) : self . threadloop . start ( ) return self . threadloop . submit ( getattr ( self . async_thrift , method_name ) , * args , ** kwargs ) return call
Generate a method for a given Thrift service .
36,577
def read_full ( stream ) : assert stream , "stream is required" chunks = [ ] chunk = yield stream . read ( ) while chunk : chunks . append ( chunk ) chunk = yield stream . read ( ) raise tornado . gen . Return ( b'' . join ( chunks ) )
Read the full contents of the given stream into memory .
36,578
def maybe_stream ( s ) : if isinstance ( s , Stream ) : return s if s is None : stream = InMemStream ( ) stream . close ( ) return stream if isinstance ( s , unicode ) : s = s . encode ( 'utf-8' ) if isinstance ( s , bytearray ) : s = bytes ( s ) if isinstance ( s , bytes ) : stream = InMemStream ( s ) stream . close (...
Ensure that the given argument is a stream .
36,579
def build_raw_error_message ( protocol_exception ) : message = ErrorMessage ( id = protocol_exception . id , code = protocol_exception . code , tracing = protocol_exception . tracing , description = protocol_exception . description , ) return message
build protocol level error message based on Error object
36,580
def build_raw_request_message ( self , request , args , is_completed = False ) : request . flags = FlagsType . none if is_completed else FlagsType . fragment if request . state == StreamState . init : message = CallRequestMessage ( flags = request . flags , ttl = request . ttl * 1000 , tracing = request . tracing , ser...
build protocol level message based on request and args .
36,581
def build_raw_response_message ( self , response , args , is_completed = False ) : response . flags = FlagsType . none if is_completed else FlagsType . fragment if response . state == StreamState . init : message = CallResponseMessage ( flags = response . flags , code = response . code , tracing = response . tracing , ...
build protocol level message based on response and args .
36,582
def build_request ( self , message ) : args = self . prepare_args ( message ) req = Request ( flags = message . flags , ttl = message . ttl / 1000.0 , tracing = message . tracing , service = message . service , headers = message . headers , checksum = message . checksum , argstreams = args , id = message . id , ) retur...
Build inbound request object from protocol level message info .
36,583
def build_response ( self , message ) : args = self . prepare_args ( message ) res = Response ( flags = message . flags , code = message . code , headers = message . headers , checksum = message . checksum , argstreams = args , id = message . id , ) return res
Build response object from protocol level message info
36,584
def build ( self , message ) : context = None if message . message_type in [ Types . CALL_REQ , Types . CALL_RES ] : self . verify_message ( message ) context = self . build_context ( message ) if message . flags == common . FlagsType . fragment : self . message_buffer [ message . id ] = context num = 0 for i , arg in ...
buffer all the streaming messages based on the message id . Reconstruct all fragments together .
36,585
def fragment ( self , message ) : if message . message_type in [ Types . CALL_RES , Types . CALL_REQ , Types . CALL_REQ_CONTINUE , Types . CALL_RES_CONTINUE ] : rw = RW [ message . message_type ] payload_space = ( common . MAX_PAYLOAD_SIZE - rw . length_no_args ( message ) ) fragment_msg = message . fragment ( payload_...
Fragment message based on max payload size
36,586
def verify_message ( self , message ) : if verify_checksum ( message , self . in_checksum . get ( message . id , 0 ) , ) : self . in_checksum [ message . id ] = message . checksum [ 1 ] if message . flags == FlagsType . none : self . in_checksum . pop ( message . id ) else : self . in_checksum . pop ( message . id , No...
Verify the checksum of the message .
36,587
def chain ( * rws ) : assert rws is not None if len ( rws ) == 1 and isinstance ( rws [ 0 ] , list ) : rws = rws [ 0 ] return ChainReadWriter ( rws )
Build a ReadWriter from the given list of ReadWriters .
36,588
def take ( self , stream , num ) : s = stream . read ( num ) slen = len ( s ) if slen != num : raise ReadError ( "Expected %d bytes but got %d bytes." % ( num , slen ) ) return s
Read the given number of bytes from the stream .
36,589
def get_service_methods ( iface ) : methods = inspect . getmembers ( iface , predicate = inspect . ismethod ) return set ( name for ( name , method ) in methods if not name . startswith ( '__' ) )
Get a list of methods defined in the interface for a Thrift service .
36,590
def deprecate ( message ) : warnings . simplefilter ( 'default' ) warnings . warn ( message , category = DeprecationWarning ) warnings . resetwarnings ( )
Loudly prints warning .
36,591
def deprecated ( message ) : def decorator ( fn ) : @ functools . wraps ( fn ) def new_fn ( * args , ** kwargs ) : deprecate ( message ) return fn ( * args , ** kwargs ) return new_fn return decorator
Warn every time a fn is called .
36,592
def load ( path , service = None , hostport = None , module_name = None ) : if not path . endswith ( '.thrift' ) : service , path = path , service module = thriftrw . load ( path = path , name = module_name ) return TChannelThriftModule ( service , module , hostport )
Loads the Thrift file at the specified path .
36,593
def interface_ip ( interface ) : sock = socket . socket ( socket . AF_INET , socket . SOCK_DGRAM ) return socket . inet_ntoa ( fcntl . ioctl ( sock . fileno ( ) , 0x8915 , struct . pack ( '256s' , interface [ : 15 ] ) ) [ 20 : 24 ] )
Determine the IP assigned to us by the given network interface .
36,594
def client_for ( service , service_module , thrift_service_name = None ) : assert service_module , 'service_module is required' service = service or '' if not thrift_service_name : thrift_service_name = service_module . __name__ . rsplit ( '.' , 1 ) [ - 1 ] method_names = get_service_methods ( service_module . Iface ) ...
Build a client class for the given Thrift service .
36,595
def generate_method ( service_module , service_name , method_name ) : assert service_module assert service_name assert method_name args_type = getattr ( service_module , method_name + '_args' ) result_type = getattr ( service_module , method_name + '_result' , None ) serializer = ThriftSerializer ( result_type ) if res...
Generate a method for the given Thrift service .
36,596
def connect ( self ) : if self . connections : future = gen . Future ( ) future . set_result ( self . connections [ 0 ] ) return future if self . _connecting : return self . _connecting conn_future = self . _connecting = self . connection_class . outgoing ( hostport = self . hostport , process_name = self . tchannel . ...
Get a connection to this peer .
36,597
def register_outgoing_conn ( self , conn ) : assert conn , "conn is required" conn . set_outbound_pending_change_callback ( self . _on_conn_change ) self . connections . append ( conn ) self . _set_on_close_cb ( conn ) self . _on_conn_change ( )
Add outgoing connection into the heap .
36,598
def register_incoming_conn ( self , conn ) : assert conn , "conn is required" conn . set_outbound_pending_change_callback ( self . _on_conn_change ) self . connections . appendleft ( conn ) self . _set_on_close_cb ( conn ) self . _on_conn_change ( )
Add incoming connection into the heap .
36,599
def outgoing_connections ( self ) : return list ( dropwhile ( lambda c : c . direction != OUTGOING , self . connections ) )
Returns a list of all outgoing connections for this peer .