idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
25,400
def check_int ( val ) : r if not isinstance ( val , ( int , float , list , tuple , np . ndarray ) ) : raise TypeError ( 'Invalid input type.' ) if isinstance ( val , float ) : val = int ( val ) elif isinstance ( val , ( list , tuple ) ) : val = np . array ( val , dtype = int ) elif isinstance ( val , np . ndarray ) and...
r Check if input value is an int or a np . ndarray of ints if not convert .
25,401
def check_npndarray ( val , dtype = None , writeable = True , verbose = True ) : if not isinstance ( val , np . ndarray ) : raise TypeError ( 'Input is not a numpy array.' ) if ( ( not isinstance ( dtype , type ( None ) ) ) and ( not np . issubdtype ( val . dtype , dtype ) ) ) : raise TypeError ( 'The numpy array eleme...
Check if input object is a numpy array .
25,402
def positive ( data ) : r if not isinstance ( data , ( int , float , list , tuple , np . ndarray ) ) : raise TypeError ( 'Invalid data type, input must be `int`, `float`, ' '`list`, `tuple` or `np.ndarray`.' ) def pos_thresh ( data ) : return data * ( data > 0 ) def pos_recursive ( data ) : data = np . array ( data ) i...
r Positivity operator
25,403
def mean ( self ) : return np . dot ( np . array ( self . norm_scores ) , self . weights )
Compute a total score for each model over all the tests .
25,404
def T ( self ) : return ScoreMatrix ( self . tests , self . models , scores = self . values , weights = self . weights , transpose = True )
Get transpose of this ScoreMatrix .
25,405
def to_html ( self , show_mean = None , sortable = None , colorize = True , * args , ** kwargs ) : if show_mean is None : show_mean = self . show_mean if sortable is None : sortable = self . sortable df = self . copy ( ) if show_mean : df . insert ( 0 , 'Mean' , None ) df . loc [ : , 'Mean' ] = [ '%.3f' % self [ m ] . ...
Extend Pandas built in to_html method for rendering a DataFrame and use it to render a ScoreMatrix .
25,406
def rec_apply ( func , n ) : if n > 1 : rec_func = rec_apply ( func , n - 1 ) return lambda x : func ( rec_func ( x ) ) return func
Used to determine parent directory n levels up by repeatedly applying os . path . dirname
25,407
def printd ( * args , ** kwargs ) : global settings if settings [ 'PRINT_DEBUG_STATE' ] : print ( * args , ** kwargs ) return True return False
Print if PRINT_DEBUG_STATE is True
25,408
def assert_dimensionless ( value ) : if isinstance ( value , Quantity ) : value = value . simplified if value . dimensionality == Dimensionality ( { } ) : value = value . base . item ( ) else : raise TypeError ( "Score value %s must be dimensionless" % value ) return value
Tests for dimensionlessness of input . If input is dimensionless but expressed as a Quantity it returns the bare value . If it not it raised an error .
25,409
def import_all_modules ( package , skip = None , verbose = False , prefix = "" , depth = 0 ) : skip = [ ] if skip is None else skip for ff , modname , ispkg in pkgutil . walk_packages ( path = package . __path__ , prefix = prefix , onerror = lambda x : None ) : if ff . path not in package . __path__ [ 0 ] : continue if...
Recursively imports all subpackages modules and submodules of a given package . package should be an imported package not a string . skip is a list of modules or subpackages not to import .
25,410
def method_cache ( by = 'value' , method = 'run' ) : def decorate_ ( func ) : def decorate ( * args , ** kwargs ) : model = args [ 0 ] assert hasattr ( model , method ) , "Model must have a '%s' method." % method if func . __name__ == method : method_args = kwargs else : method_args = kwargs [ method ] if method in kwa...
A decorator used on any model method which calls the model s method method if that latter method has not been called using the current arguments or simply sets model attributes to match the run results if it has .
25,411
def convert_path ( cls , file ) : if isinstance ( file , str ) : return file elif isinstance ( file , list ) and all ( [ isinstance ( x , str ) for x in file ] ) : return "/" . join ( file ) else : print ( "Incorrect path specified" ) return - 1
Check to see if an extended path is given and convert appropriately
25,412
def get_path ( self , file ) : class_path = inspect . getfile ( self . __class__ ) parent_path = os . path . dirname ( class_path ) path = os . path . join ( parent_path , self . path , file ) return os . path . realpath ( path )
Get the full path of the notebook found in the directory specified by self . path .
25,413
def fix_display ( self ) : try : tkinter . Tk ( ) except ( tkinter . TclError , NameError ) : try : import matplotlib as mpl except ImportError : pass else : print ( "Setting matplotlib backend to Agg" ) mpl . use ( 'Agg' )
If this is being run on a headless system the Matplotlib backend must be changed to one that doesn t need a display .
25,414
def load_notebook ( self , name ) : with open ( self . get_path ( '%s.ipynb' % name ) ) as f : nb = nbformat . read ( f , as_version = 4 ) return nb , f
Loads a notebook file into memory .
25,415
def run_notebook ( self , nb , f ) : if PYTHON_MAJOR_VERSION == 3 : kernel_name = 'python3' elif PYTHON_MAJOR_VERSION == 2 : kernel_name = 'python2' else : raise Exception ( 'Only Python 2 and 3 are supported' ) ep = ExecutePreprocessor ( timeout = 600 , kernel_name = kernel_name ) try : ep . preprocess ( nb , { 'metad...
Runs a loaded notebook file .
25,416
def execute_notebook ( self , name ) : warnings . filterwarnings ( "ignore" , category = DeprecationWarning ) nb , f = self . load_notebook ( name ) self . run_notebook ( nb , f ) self . assertTrue ( True )
Loads and then runs a notebook file .
25,417
def convert_notebook ( self , name ) : exporter = nbconvert . exporters . python . PythonExporter ( ) relative_path = self . convert_path ( name ) file_path = self . get_path ( "%s.ipynb" % relative_path ) code = exporter . from_filename ( file_path ) [ 0 ] self . write_code ( name , code ) self . clean_code ( name , [...
Converts a notebook into a python file .
25,418
def convert_and_execute_notebook ( self , name ) : self . convert_notebook ( name ) code = self . read_code ( name ) exec ( code , globals ( ) )
Converts a notebook into a python file and then runs it .
25,419
def gen_file_path ( self , name ) : relative_path = self . convert_path ( name ) file_path = self . get_path ( "%s.ipynb" % relative_path ) parent_path = rec_apply ( os . path . dirname , self . gen_file_level ) ( file_path ) gen_file_name = name if isinstance ( name , str ) else name [ 1 ] gen_dir_path = self . get_pa...
Returns full path to generated files . Checks to see if directory exists where generated files are stored and creates one otherwise .
25,420
def read_code ( self , name ) : file_path = self . gen_file_path ( name ) with open ( file_path ) as f : code = f . read ( ) return code
Reads code from a python file called name
25,421
def clean_code ( self , name , forbidden ) : code = self . read_code ( name ) code = code . split ( '\n' ) new_code = [ ] for line in code : if [ bad for bad in forbidden if bad in line ] : pass else : allowed = [ 'time' , 'timeit' ] line = self . strip_line_magic ( line , allowed ) if isinstance ( line , list ) : line...
Remove lines containing items in forbidden from the code . Helpful for executing converted notebooks that still retain IPython magic commands .
25,422
def do_notebook ( self , name ) : CONVERT_NOTEBOOKS = int ( os . getenv ( 'CONVERT_NOTEBOOKS' , True ) ) s = StringIO ( ) if mock : out = unittest . mock . patch ( 'sys.stdout' , new = MockDevice ( s ) ) err = unittest . mock . patch ( 'sys.stderr' , new = MockDevice ( s ) ) self . _do_notebook ( name , CONVERT_NOTEBOO...
Run a notebook file after optionally converting it to a python file .
25,423
def _do_notebook ( self , name , convert_notebooks = False ) : if convert_notebooks : self . convert_and_execute_notebook ( name ) else : self . execute_notebook ( name )
Called by do_notebook to actually run the notebook .
25,424
def get_capabilities ( cls ) : capabilities = [ ] for _cls in cls . mro ( ) : if issubclass ( _cls , Capability ) and _cls is not Capability and not issubclass ( _cls , Model ) : capabilities . append ( _cls ) return capabilities
List the model s capabilities .
25,425
def failed_extra_capabilities ( self ) : failed = [ ] for capability , f_name in self . extra_capability_checks . items ( ) : f = getattr ( self , f_name ) instance_capable = f ( ) if not instance_capable : failed . append ( capability ) return failed
Check to see if instance passes its extra_capability_checks .
25,426
def describe ( self ) : result = "No description available" if self . description : result = "%s" % self . description else : if self . __doc__ : s = [ ] s += [ self . __doc__ . strip ( ) . replace ( '\n' , '' ) . replace ( ' ' , ' ' ) ] result = '\n' . join ( s ) return result
Describe the model .
25,427
def is_match ( self , match ) : result = False if self == match : result = True elif isinstance ( match , str ) and fnmatchcase ( self . name , match ) : result = True return result
Return whether this model is the same as match .
25,428
def main ( * args ) : parser = argparse . ArgumentParser ( ) parser . add_argument ( "action" , help = "create, check, run, make-nb, or run-nb" ) parser . add_argument ( "--directory" , "-dir" , default = os . getcwd ( ) , help = "path to directory with a .sciunit file" ) parser . add_argument ( "--stop" , "-s" , defau...
Launch the main routine .
25,429
def create ( file_path ) : if os . path . exists ( file_path ) : raise IOError ( "There is already a configuration file at %s" % file_path ) with open ( file_path , 'w' ) as f : config = configparser . ConfigParser ( ) config . add_section ( 'misc' ) config . set ( 'misc' , 'config-version' , '1.0' ) default_nb_name = ...
Create a default . sciunit config file if one does not already exist .
25,430
def parse ( file_path = None , show = False ) : if file_path is None : file_path = os . path . join ( os . getcwd ( ) , '.sciunit' ) if not os . path . exists ( file_path ) : raise IOError ( 'No .sciunit file was found at %s' % file_path ) config = configparser . RawConfigParser ( allow_no_value = True ) config . read ...
Parse a . sciunit config file .
25,431
def prep ( config = None , path = None ) : if config is None : config = parse ( ) if path is None : path = os . getcwd ( ) root = config . get ( 'root' , 'path' ) root = os . path . join ( path , root ) root = os . path . realpath ( root ) os . environ [ 'SCIDASH_HOME' ] = root if sys . path [ 0 ] != root : sys . path ...
Prepare to read the configuration information .
25,432
def run ( config , path = None , stop_on_error = True , just_tests = False ) : if path is None : path = os . getcwd ( ) prep ( config , path = path ) models = __import__ ( 'models' ) tests = __import__ ( 'tests' ) suites = __import__ ( 'suites' ) print ( '\n' ) for x in [ 'models' , 'tests' , 'suites' ] : module = __im...
Run sciunit tests for the given configuration .
25,433
def nb_name_from_path ( config , path ) : if path is None : path = os . getcwd ( ) root = config . get ( 'root' , 'path' ) root = os . path . join ( path , root ) root = os . path . realpath ( root ) default_nb_name = os . path . split ( os . path . realpath ( root ) ) [ 1 ] nb_name = config . get ( 'misc' , 'nb-name' ...
Get a notebook name from a path to a notebook
25,434
def make_nb ( config , path = None , stop_on_error = True , just_tests = False ) : root , nb_name = nb_name_from_path ( config , path ) clean = lambda varStr : re . sub ( '\W|^(?=\d)' , '_' , varStr ) name = clean ( nb_name ) mpl_style = config . get ( 'misc' , 'matplotlib' , fallback = 'inline' ) cells = [ new_markdow...
Create a Jupyter notebook sciunit tests for the given configuration .
25,435
def write_nb ( root , nb_name , cells ) : nb = new_notebook ( cells = cells , metadata = { 'language' : 'python' , } ) nb_path = os . path . join ( root , '%s.ipynb' % nb_name ) with codecs . open ( nb_path , encoding = 'utf-8' , mode = 'w' ) as nb_file : nbformat . write ( nb , nb_file , NB_VERSION ) print ( "Created ...
Write a jupyter notebook to disk .
25,436
def run_nb ( config , path = None ) : if path is None : path = os . getcwd ( ) root = config . get ( 'root' , 'path' ) root = os . path . join ( path , root ) nb_name = config . get ( 'misc' , 'nb-name' ) nb_path = os . path . join ( root , '%s.ipynb' % nb_name ) if not os . path . exists ( nb_path ) : print ( ( "No no...
Run a notebook file .
25,437
def add_code_cell ( cells , source ) : from nbformat . v4 . nbbase import new_code_cell n_code_cells = len ( [ c for c in cells if c [ 'cell_type' ] == 'code' ] ) cells . append ( new_code_cell ( source = source , execution_count = n_code_cells + 1 ) )
Add a code cell containing source to the notebook .
25,438
def cleanup ( config = None , path = None ) : if config is None : config = parse ( ) if path is None : path = os . getcwd ( ) root = config . get ( 'root' , 'path' ) root = os . path . join ( path , root ) if sys . path [ 0 ] == root : sys . path . remove ( root )
Cleanup by removing paths added during earlier in configuration .
25,439
def get_repo ( self , cached = True ) : module = sys . modules [ self . __module__ ] if hasattr ( self . __class__ , '_repo' ) and cached : repo = self . __class__ . _repo elif hasattr ( module , '__file__' ) : path = os . path . realpath ( module . __file__ ) try : repo = git . Repo ( path , search_parent_directories ...
Get a git repository object for this instance .
25,440
def get_remote ( self , remote = 'origin' ) : repo = self . get_repo ( ) if repo is not None : remotes = { r . name : r for r in repo . remotes } r = repo . remotes [ 0 ] if remote not in remotes else remotes [ remote ] else : r = None return r
Get a git remote object for this instance .
25,441
def get_remote_url ( self , remote = 'origin' , cached = True ) : if hasattr ( self . __class__ , '_remote_url' ) and cached : url = self . __class__ . _remote_url else : r = self . get_remote ( remote ) try : url = list ( r . urls ) [ 0 ] except GitCommandError as ex : if 'correct access rights' in str ( ex ) : cmd = ...
Get a git remote URL for this instance .
25,442
def _validate_iterable ( self , is_iterable , key , value ) : if is_iterable : try : iter ( value ) except TypeError : self . _error ( key , "Must be iterable (e.g. a list or array)" )
Validate fields with iterable key in schema set to True
25,443
def _validate_units ( self , has_units , key , value ) : if has_units : if isinstance ( self . test . units , dict ) : required_units = self . test . units [ key ] else : required_units = self . test . units if not isinstance ( value , pq . quantity . Quantity ) : self . _error ( key , "Must be a python quantity" ) if ...
Validate fields with units key in schema set to True .
25,444
def validate_quantity ( self , value ) : if not isinstance ( value , pq . quantity . Quantity ) : self . _error ( '%s' % value , "Must be a Python quantity." )
Validate that the value is of the Quantity type .
25,445
def compute ( cls , observation , prediction ) : assert isinstance ( observation , dict ) try : p_value = prediction [ 'mean' ] except ( TypeError , KeyError , IndexError ) : try : p_value = prediction [ 'value' ] except ( TypeError , IndexError ) : p_value = prediction o_mean = observation [ 'mean' ] o_std = observati...
Compute a z - score from an observation and a prediction .
25,446
def norm_score ( self ) : cdf = ( 1.0 + math . erf ( self . score / math . sqrt ( 2.0 ) ) ) / 2.0 return 1 - 2 * math . fabs ( 0.5 - cdf )
Return the normalized score .
25,447
def compute ( cls , observation , prediction ) : assert isinstance ( observation , dict ) assert isinstance ( prediction , dict ) p_mean = prediction [ 'mean' ] p_std = prediction [ 'std' ] o_mean = observation [ 'mean' ] o_std = observation [ 'std' ] try : p_n = prediction [ 'n' ] o_n = observation [ 'n' ] s = ( ( ( p...
Compute a Cohen s D from an observation and a prediction .
25,448
def compute ( cls , observation , prediction , key = None ) : assert isinstance ( observation , ( dict , float , int , pq . Quantity ) ) assert isinstance ( prediction , ( dict , float , int , pq . Quantity ) ) obs , pred = cls . extract_means_or_values ( observation , prediction , key = key ) value = pred / obs value ...
Compute a ratio from an observation and a prediction .
25,449
def compute_ssd ( cls , observation , prediction ) : value = ( ( observation - prediction ) ** 2 ) . sum ( ) score = FloatScore ( value ) return score
Compute sum - squared diff between observation and prediction .
25,450
def read_requirements ( ) : reqs_path = os . path . join ( '.' , 'requirements.txt' ) install_reqs = parse_requirements ( reqs_path , session = PipSession ( ) ) reqs = [ str ( ir . req ) for ir in install_reqs ] return reqs
parses requirements from requirements . txt
25,451
def register_backends ( vars ) : new_backends = { x . replace ( 'Backend' , '' ) : cls for x , cls in vars . items ( ) if inspect . isclass ( cls ) and issubclass ( cls , Backend ) } available_backends . update ( new_backends )
Register backends for use with models .
25,452
def init_backend ( self , * args , ** kwargs ) : self . model . attrs = { } self . use_memory_cache = kwargs . get ( 'use_memory_cache' , True ) if self . use_memory_cache : self . init_memory_cache ( ) self . use_disk_cache = kwargs . get ( 'use_disk_cache' , False ) if self . use_disk_cache : self . init_disk_cache (...
Initialize the backend .
25,453
def init_disk_cache ( self ) : try : path = self . disk_cache_location os . remove ( path ) except Exception : pass self . disk_cache_location = os . path . join ( tempfile . mkdtemp ( ) , 'cache' )
Initialize the on - disk version of the cache .
25,454
def get_memory_cache ( self , key = None ) : key = self . model . hash if key is None else key self . _results = self . memory_cache . get ( key ) return self . _results
Return result in memory cache for key key or None if not found .
25,455
def get_disk_cache ( self , key = None ) : key = self . model . hash if key is None else key if not getattr ( self , 'disk_cache_location' , False ) : self . init_disk_cache ( ) disk_cache = shelve . open ( self . disk_cache_location ) self . _results = disk_cache . get ( key ) disk_cache . close ( ) return self . _res...
Return result in disk cache for key key or None if not found .
25,456
def set_memory_cache ( self , results , key = None ) : key = self . model . hash if key is None else key self . memory_cache [ key ] = results
Store result in memory cache with key matching model state .
25,457
def set_disk_cache ( self , results , key = None ) : if not getattr ( self , 'disk_cache_location' , False ) : self . init_disk_cache ( ) disk_cache = shelve . open ( self . disk_cache_location ) key = self . model . hash if key is None else key disk_cache [ key ] = results disk_cache . close ( )
Store result in disk cache with key matching model state .
25,458
def backend_run ( self ) : key = self . model . hash if self . use_memory_cache and self . get_memory_cache ( key ) : return self . _results if self . use_disk_cache and self . get_disk_cache ( key ) : return self . _results results = self . _backend_run ( ) if self . use_memory_cache : self . set_memory_cache ( result...
Check for cached results ; then run the model if needed .
25,459
def save_results ( self , path = '.' ) : with open ( path , 'wb' ) as f : pickle . dump ( self . results , f )
Save results on disk .
25,460
def check ( cls , model , require_extra = False ) : class_capable = isinstance ( model , cls ) f_name = model . extra_capability_checks . get ( cls , None ) if model . extra_capability_checks is not None else False if f_name : f = getattr ( model , f_name ) instance_capable = f ( ) elif not require_extra : instance_cap...
Check whether the provided model has this capability .
25,461
def set_backend ( self , backend ) : if isinstance ( backend , str ) : name = backend args = [ ] kwargs = { } elif isinstance ( backend , ( tuple , list ) ) : name = '' args = [ ] kwargs = { } for i in range ( len ( backend ) ) : if i == 0 : name = backend [ i ] else : if isinstance ( backend [ i ] , dict ) : kwargs . ...
Set the simulation backend .
25,462
def color ( self , value = None ) : if value is None : value = self . norm_score rgb = Score . value_color ( value ) return rgb
Turn the score intp an RGB color tuple of three 8 - bit integers .
25,463
def extract_means_or_values ( cls , observation , prediction , key = None ) : obs_mv = cls . extract_mean_or_value ( observation , key ) pred_mv = cls . extract_mean_or_value ( prediction , key ) return obs_mv , pred_mv
Extracts the mean value or user - provided key from the observation and prediction dictionaries .
25,464
def extract_mean_or_value ( cls , obs_or_pred , key = None ) : result = None if not isinstance ( obs_or_pred , dict ) : result = obs_or_pred else : keys = ( [ key ] if key is not None else [ ] ) + [ 'mean' , 'value' ] for k in keys : if k in obs_or_pred : result = obs_or_pred [ k ] break if result is None : raise KeyEr...
Extracts the mean value or user - provided key from an observation or prediction dictionary .
25,465
def summary ( self ) : return "== Model %s did not complete test %s due to error '%s'. ==" % ( str ( self . model ) , str ( self . test ) , str ( self . score ) )
Summarize the performance of a model on a test .
25,466
def load ( self , draw_bbox = False , ** kwargs ) : im = Image . new ( 'RGBA' , self . img_size ) draw = None if draw_bbox : draw = ImageDraw . Draw ( im ) for sprite in self . images : data = sprite . load ( ) sprite_im = Image . open ( BytesIO ( data ) ) size = sprite . imgrect im . paste ( sprite_im , ( size [ 0 ] ,...
Makes the canvas . This could be far speedier if it copied raw pixels but that would take far too much time to write vs using Image inbuilts
25,467
def match_window ( in_data , offset ) : window_start = max ( offset - WINDOW_MASK , 0 ) for n in range ( MAX_LEN , THRESHOLD - 1 , - 1 ) : window_end = min ( offset + n , len ( in_data ) ) if window_end - offset < THRESHOLD : return None str_to_find = in_data [ offset : window_end ] idx = in_data . rfind ( str_to_find ...
Find the longest match for the string starting at offset in the preceeding data
25,468
def _merge_args_opts ( args_opts_dict , ** kwargs ) : merged = [ ] if not args_opts_dict : return merged for arg , opt in args_opts_dict . items ( ) : if not _is_sequence ( opt ) : opt = shlex . split ( opt or '' ) merged += opt if not arg : continue if 'add_input_option' in kwargs : merged . append ( '-i' ) merged . a...
Merge options with their corresponding arguments .
25,469
def run ( self , input_data = None , stdout = None , stderr = None ) : try : self . process = subprocess . Popen ( self . _cmd , stdin = subprocess . PIPE , stdout = stdout , stderr = stderr ) except OSError as e : if e . errno == errno . ENOENT : raise FFExecutableNotFoundError ( "Executable '{0}' not found" . format ...
Execute FFmpeg command line .
25,470
def _get_usage ( ctx ) : formatter = ctx . make_formatter ( ) pieces = ctx . command . collect_usage_pieces ( ctx ) formatter . write_usage ( ctx . command_path , ' ' . join ( pieces ) , prefix = '' ) return formatter . getvalue ( ) . rstrip ( '\n' )
Alternative non - prefixed version of get_usage .
25,471
def _get_help_record ( opt ) : def _write_opts ( opts ) : rv , _ = click . formatting . join_options ( opts ) if not opt . is_flag and not opt . count : rv += ' <{}>' . format ( opt . name ) return rv rv = [ _write_opts ( opt . opts ) ] if opt . secondary_opts : rv . append ( _write_opts ( opt . secondary_opts ) ) help...
Re - implementation of click . Opt . get_help_record .
25,472
def _format_description ( ctx ) : help_string = ctx . command . help or ctx . command . short_help if not help_string : return bar_enabled = False for line in statemachine . string2lines ( help_string , tab_width = 4 , convert_whitespace = True ) : if line == '\b' : bar_enabled = True continue if line == '' : bar_enabl...
Format the description for a given click . Command .
25,473
def _format_option ( opt ) : opt = _get_help_record ( opt ) yield '.. option:: {}' . format ( opt [ 0 ] ) if opt [ 1 ] : yield '' for line in statemachine . string2lines ( opt [ 1 ] , tab_width = 4 , convert_whitespace = True ) : yield _indent ( line )
Format the output for a click . Option .
25,474
def _format_options ( ctx ) : params = [ x for x in ctx . command . params if isinstance ( x , click . Option ) and not getattr ( x , 'hidden' , False ) ] for param in params : for line in _format_option ( param ) : yield line yield ''
Format all click . Option for a click . Command .
25,475
def _format_argument ( arg ) : yield '.. option:: {}' . format ( arg . human_readable_name ) yield '' yield _indent ( '{} argument{}' . format ( 'Required' if arg . required else 'Optional' , '(s)' if arg . nargs != 1 else '' ) )
Format the output of a click . Argument .
25,476
def _format_arguments ( ctx ) : params = [ x for x in ctx . command . params if isinstance ( x , click . Argument ) ] for param in params : for line in _format_argument ( param ) : yield line yield ''
Format all click . Argument for a click . Command .
25,477
def _format_envvar ( param ) : yield '.. envvar:: {}' . format ( param . envvar ) yield ' :noindex:' yield '' if isinstance ( param , click . Argument ) : param_ref = param . human_readable_name else : param_ref = param . opts [ 0 ] yield _indent ( 'Provide a default for :option:`{}`' . format ( param_ref ) )
Format the envvars of a click . Option or click . Argument .
25,478
def _format_envvars ( ctx ) : params = [ x for x in ctx . command . params if getattr ( x , 'envvar' ) ] for param in params : yield '.. _{command_name}-{param_name}-{envvar}:' . format ( command_name = ctx . command_path . replace ( ' ' , '-' ) , param_name = param . name , envvar = param . envvar , ) yield '' for lin...
Format all envvars for a click . Command .
25,479
def _format_subcommand ( command ) : yield '.. object:: {}' . format ( command . name ) if CLICK_VERSION < ( 7 , 0 ) : short_help = command . short_help else : short_help = command . get_short_help_str ( ) if short_help : yield '' for line in statemachine . string2lines ( short_help , tab_width = 4 , convert_whitespace...
Format a sub - command of a click . Command or click . Group .
25,480
def _filter_commands ( ctx , commands = None ) : lookup = getattr ( ctx . command , 'commands' , { } ) if not lookup and isinstance ( ctx . command , click . MultiCommand ) : lookup = _get_lazyload_commands ( ctx . command ) if commands is None : return sorted ( lookup . values ( ) , key = lambda item : item . name ) n...
Return list of used commands .
25,481
def _format_command ( ctx , show_nested , commands = None ) : if getattr ( ctx . command , 'hidden' , False ) : return for line in _format_description ( ctx ) : yield line yield '.. program:: {}' . format ( ctx . command_path ) for line in _format_usage ( ctx ) : yield line lines = list ( _format_options ( ctx ) ) if l...
Format the output of click . Command .
25,482
def _load_module ( self , module_path ) : module_path = str ( module_path ) try : module_name , attr_name = module_path . split ( ':' , 1 ) except ValueError : raise self . error ( '"{}" is not of format "module:parser"' . format ( module_path ) ) try : mod = __import__ ( module_name , globals ( ) , locals ( ) , [ attr...
Load the module .
25,483
def _show_annotation_box ( self , event ) : ax = event . artist . axes if self . display != 'multiple' : annotation = self . annotations [ ax ] elif event . mouseevent in self . annotations : annotation = self . annotations [ event . mouseevent ] else : annotation = self . annotate ( ax , ** self . _annotation_kwargs )...
Update an existing box or create an annotation box for an event .
25,484
def event_info ( self , event ) : def default_func ( event ) : return { } registry = { AxesImage : [ pick_info . image_props ] , PathCollection : [ pick_info . scatter_props , self . _contour_info , pick_info . collection_props ] , Line2D : [ pick_info . line_props , pick_info . errorbar_props ] , LineCollection : [ pi...
Get a dict of info for the artist selected by event .
25,485
def _formatter ( self , x = None , y = None , z = None , s = None , label = None , ** kwargs ) : def is_date ( axis ) : fmt = axis . get_major_formatter ( ) return ( isinstance ( fmt , mdates . DateFormatter ) or isinstance ( fmt , mdates . AutoDateFormatter ) ) def format_date ( num ) : if num is not None : return mda...
Default formatter function if no formatter kwarg is specified . Takes information about the pick event as a series of kwargs and returns the string to be displayed .
25,486
def _format_coord ( self , x , limits ) : if x is None : return None formatter = self . _mplformatter formatter . locs = np . linspace ( limits [ 0 ] , limits [ 1 ] , 7 ) formatter . _set_format ( * limits ) formatter . _set_orderOfMagnitude ( abs ( np . diff ( limits ) ) ) return formatter . pprint_val ( x )
Handles display - range - specific formatting for the x and y coords .
25,487
def _hide_box ( self , annotation ) : annotation . set_visible ( False ) if self . display == 'multiple' : annotation . axes . figure . texts . remove ( annotation ) lookup = dict ( ( self . annotations [ k ] , k ) for k in self . annotations ) del self . annotations [ lookup [ annotation ] ] annotation . figure . canv...
Remove a specific annotation box .
25,488
def enable ( self ) : def connect ( fig ) : if self . hover : event = 'motion_notify_event' else : event = 'button_press_event' cids = [ fig . canvas . mpl_connect ( event , self . _select ) ] try : proxy = fig . canvas . callbacks . BoundMethodProxy ( self ) fig . canvas . callbacks . callbacks [ event ] [ cids [ - 1 ...
Connects callbacks and makes artists pickable . If the datacursor has already been enabled this function has no effect .
25,489
def _increment_index ( self , di = 1 ) : if self . _last_event is None : return if not hasattr ( self . _last_event , 'ind' ) : return event = self . _last_event xy = pick_info . get_xy ( event . artist ) if xy is not None : x , y = xy i = ( event . ind [ 0 ] + di ) % len ( x ) event . ind = [ i ] event . mouseevent . ...
Move the most recently displayed annotation to the next item in the series if possible . If di is - 1 move it to the previous item .
25,490
def show_highlight ( self , artist ) : if artist in self . highlights : self . highlights [ artist ] . set_visible ( True ) else : self . highlights [ artist ] = self . create_highlight ( artist ) return self . highlights [ artist ]
Show or create a highlight for a givent artist .
25,491
def create_highlight ( self , artist ) : highlight = copy . copy ( artist ) highlight . set ( color = self . highlight_color , mec = self . highlight_color , lw = self . highlight_width , mew = self . highlight_width ) artist . axes . add_artist ( highlight ) return highlight
Create a new highlight for the given artist .
25,492
def _coords2index ( im , x , y , inverted = False ) : xmin , xmax , ymin , ymax = im . get_extent ( ) if im . origin == 'upper' : ymin , ymax = ymax , ymin data_extent = mtransforms . Bbox ( [ [ ymin , xmin ] , [ ymax , xmax ] ] ) array_extent = mtransforms . Bbox ( [ [ 0 , 0 ] , im . get_array ( ) . shape [ : 2 ] ] ) ...
Converts data coordinates to index coordinates of the array .
25,493
def _interleave ( a , b ) : b = np . column_stack ( [ b ] ) nx , ny = b . shape c = np . zeros ( ( nx + 1 , ny + 1 ) ) c [ : , 0 ] = a c [ : - 1 , 1 : ] = b return c . ravel ( ) [ : - ( c . shape [ 1 ] - 1 ) ]
Interleave arrays a and b ; b may have multiple columns and must be shorter by 1 .
25,494
def three_dim_props ( event ) : ax = event . artist . axes if ax . M is None : return { } xd , yd = event . mouseevent . xdata , event . mouseevent . ydata p = ( xd , yd ) edges = ax . tunit_edges ( ) ldists = [ ( mplot3d . proj3d . line2d_seg_dist ( p0 , p1 , p ) , i ) for i , ( p0 , p1 ) in enumerate ( edges ) ] ldis...
Get information for a pick event on a 3D artist .
25,495
def rectangle_props ( event ) : artist = event . artist width , height = artist . get_width ( ) , artist . get_height ( ) left , bottom = artist . xy right , top = left + width , bottom + height xcenter = left + 0.5 * width ycenter = bottom + 0.5 * height label = artist . get_label ( ) if label is None or label . start...
Returns the width height left and bottom of a rectangle artist .
25,496
def get_xy ( artist ) : xy = None if hasattr ( artist , 'get_offsets' ) : xy = artist . get_offsets ( ) . T elif hasattr ( artist , 'get_xydata' ) : xy = artist . get_xydata ( ) . T return xy
Attempts to get the x y data for individual items subitems of the artist . Returns None if this is not possible .
25,497
def datacursor ( artists = None , axes = None , ** kwargs ) : def plotted_artists ( ax ) : artists = ( ax . lines + ax . patches + ax . collections + ax . images + ax . containers ) return artists if axes is None : managers = pylab_helpers . Gcf . get_all_fig_managers ( ) figs = [ manager . canvas . figure for manager ...
Create an interactive data cursor for the specified artists or specified axes . The data cursor displays information about a selected artist in a popup annotation box .
25,498
def wrap_exception ( func : Callable ) -> Callable : try : from pygatt . backends . bgapi . exceptions import BGAPIError from pygatt . exceptions import NotConnectedError except ImportError : return func def _func_wrapper ( * args , ** kwargs ) : try : return func ( * args , ** kwargs ) except BGAPIError as exception :...
Decorator to wrap pygatt exceptions into BluetoothBackendException .
25,499
def write_handle ( self , handle : int , value : bytes ) : if not self . is_connected ( ) : raise BluetoothBackendException ( 'Not connected to device!' ) self . _device . char_write_handle ( handle , value , True ) return True
Write a handle to the device .