idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
35,300 | def get_compiler_path ( ) : given_binary = os . environ . get ( 'SOLC_BINARY' ) if given_binary : return given_binary for path in os . getenv ( 'PATH' , '' ) . split ( os . pathsep ) : path = path . strip ( '"' ) executable_path = os . path . join ( path , BINARY ) if os . path . isfile ( executable_path ) and os . acc... | Return the path to the solc compiler . |
35,301 | def solc_arguments ( libraries = None , combined = 'bin,abi' , optimize = True , extra_args = None ) : args = [ '--combined-json' , combined , ] def str_of ( address ) : try : return address . decode ( 'utf8' ) except AttributeError : return address if optimize : args . append ( '--optimize' ) if extra_args : try : arg... | Build the arguments to call the solc binary . |
35,302 | def solc_parse_output ( compiler_output ) : result = yaml . safe_load ( compiler_output ) [ 'contracts' ] if 'bin' in tuple ( result . values ( ) ) [ 0 ] : for value in result . values ( ) : value [ 'bin_hex' ] = value [ 'bin' ] try : value [ 'bin' ] = decode_hex ( value [ 'bin_hex' ] ) except ( TypeError , ValueError ... | Parses the compiler output . |
35,303 | def compiler_version ( ) : version_info = subprocess . check_output ( [ 'solc' , '--version' ] ) match = re . search ( b'^Version: ([0-9a-z.-]+)/' , version_info , re . MULTILINE ) if match : return match . group ( 1 ) | Return the version of the installed solc . |
35,304 | def solidity_names ( code ) : names = [ ] in_string = None backslash = False comment = None for pos , char in enumerate ( code ) : if in_string : if not backslash and in_string == char : in_string = None backslash = False if char == '\\' : backslash = True else : backslash = False elif comment == '//' : if char in ( '\... | Return the library and contract names in order of appearence . |
35,305 | def compile_file ( filepath , libraries = None , combined = 'bin,abi' , optimize = True , extra_args = None ) : workdir , filename = os . path . split ( filepath ) args = solc_arguments ( libraries = libraries , combined = combined , optimize = optimize , extra_args = extra_args ) args . insert ( 0 , get_compiler_path ... | Return the compile contract code . |
35,306 | def solidity_get_contract_key ( all_contracts , filepath , contract_name ) : if contract_name in all_contracts : return contract_name else : if filepath is None : filename = '<stdin>' else : _ , filename = os . path . split ( filepath ) contract_key = filename + ":" + contract_name return contract_key if contract_key i... | A backwards compatible method of getting the key to the all_contracts dictionary for a particular contract |
35,307 | def compile ( cls , code , path = None , libraries = None , contract_name = '' , extra_args = None ) : result = cls . _code_or_path ( code , path , contract_name , libraries , 'bin' , extra_args ) return result [ 'bin' ] | Return the binary of last contract in code . |
35,308 | def combined ( cls , code , path = None , extra_args = None ) : if code and path : raise ValueError ( 'sourcecode and path are mutually exclusive.' ) if path : contracts = compile_file ( path , extra_args = extra_args ) with open ( path ) as handler : code = handler . read ( ) elif code : contracts = compile_code ( cod... | Compile combined - json with abi bin devdoc userdoc . |
35,309 | def compile_rich ( cls , code , path = None , extra_args = None ) : return { contract_name : { 'code' : '0x' + contract . get ( 'bin_hex' ) , 'info' : { 'abiDefinition' : contract . get ( 'abi' ) , 'compilerVersion' : cls . compiler_version ( ) , 'developerDoc' : contract . get ( 'devdoc' ) , 'language' : 'Solidity' , ... | full format as returned by jsonrpc |
35,310 | def validate_uncles ( state , block ) : if utils . sha3 ( rlp . encode ( block . uncles ) ) != block . header . uncles_hash : raise VerificationFailed ( "Uncle hash mismatch" ) if len ( block . uncles ) > state . config [ 'MAX_UNCLES' ] : raise VerificationFailed ( "Too many uncles" ) for uncle in block . uncles : if u... | Validate the uncles of this block . |
35,311 | def finalize ( state , block ) : if state . is_METROPOLIS ( ) : br = state . config [ 'BYZANTIUM_BLOCK_REWARD' ] nr = state . config [ 'BYZANTIUM_NEPHEW_REWARD' ] else : br = state . config [ 'BLOCK_REWARD' ] nr = state . config [ 'NEPHEW_REWARD' ] delta = int ( br + nr * len ( block . uncles ) ) state . delta_balance ... | Apply rewards and commit . |
35,312 | def ensure_new_style_deprecation ( cli_ctx , kwargs , object_type ) : deprecate_info = kwargs . get ( 'deprecate_info' , None ) if isinstance ( deprecate_info , Deprecated ) : deprecate_info . object_type = object_type elif isinstance ( deprecate_info , STRING_TYPES ) : deprecate_info = Deprecated ( cli_ctx , redirect ... | Helper method to make the previous string - based deprecate_info kwarg work with the new style . |
35,313 | def _version_less_than_or_equal_to ( self , v1 , v2 ) : from distutils . version import LooseVersion return LooseVersion ( v1 ) <= LooseVersion ( v2 ) | Returns true if v1 < = v2 . |
35,314 | def prompt_choice_list ( msg , a_list , default = 1 , help_string = None ) : verify_is_a_tty ( ) options = '\n' . join ( [ ' [{}] {}{}' . format ( i + 1 , x [ 'name' ] if isinstance ( x , dict ) and 'name' in x else x , ' - ' + x [ 'desc' ] if isinstance ( x , dict ) and 'desc' in x else '' ) for i , x in enumerate ( a... | Prompt user to select from a list of possible choices . |
35,315 | def _add_argument ( obj , arg ) : argparse_options = { name : value for name , value in arg . options . items ( ) if name in ARGPARSE_SUPPORTED_KWARGS } if arg . options_list : scrubbed_options_list = [ ] for item in arg . options_list : if isinstance ( item , Deprecated ) : if item . expired ( ) : continue class _Depr... | Only pass valid argparse kwargs to argparse . ArgumentParser . add_argument |
35,316 | def load_command_table ( self , command_loader ) : cmd_tbl = command_loader . command_table grp_tbl = command_loader . command_group_table if not cmd_tbl : raise ValueError ( 'The command table is empty. At least one command is required.' ) if not self . subparsers : sp = self . add_subparsers ( dest = '_command' ) sp ... | Process the command table and load it into the parser |
35,317 | def _get_subparser ( self , path , group_table = None ) : group_table = group_table or { } for length in range ( 0 , len ( path ) ) : parent_path = path [ : length ] parent_subparser = self . subparsers . get ( tuple ( parent_path ) , None ) if not parent_subparser : command_group = group_table . get ( ' ' . join ( par... | For each part of the path walk down the tree of subparsers creating new ones if one doesn t already exist . |
35,318 | def parse_args ( self , args = None , namespace = None ) : self . _expand_prefixed_files ( args ) return super ( CLICommandParser , self ) . parse_args ( args ) | Overrides argparse . ArgumentParser . parse_args |
35,319 | def extract_full_summary_from_signature ( operation ) : lines = inspect . getdoc ( operation ) regex = r'\s*(:param)\s+(.+?)\s*:(.*)' summary = '' if lines : match = re . search ( regex , lines ) summary = lines [ : match . regs [ 0 ] [ 0 ] ] if match else lines summary = summary . replace ( '\n' , ' ' ) . replace ( '\... | Extract the summary from the docstring of the command . |
35,320 | def get_runtime_version ( self ) : import platform version_info = '\n\n' version_info += 'Python ({}) {}' . format ( platform . system ( ) , sys . version ) version_info += '\n\n' version_info += 'Python location \'{}\'' . format ( sys . executable ) version_info += '\n' return version_info | Get the runtime information . |
35,321 | def show_version ( self ) : version_info = self . get_cli_version ( ) version_info += self . get_runtime_version ( ) print ( version_info , file = self . out_file ) | Print version information to the out file . |
35,322 | def unregister_event ( self , event_name , handler ) : try : self . _event_handlers [ event_name ] . remove ( handler ) except ValueError : pass | Unregister a callable that will be called when event is raised . |
35,323 | def raise_event ( self , event_name , ** kwargs ) : handlers = list ( self . _event_handlers [ event_name ] ) logger . debug ( 'Event: %s %s' , event_name , handlers ) for func in handlers : func ( self , ** kwargs ) | Raise an event . Calls each handler in turn with kwargs |
35,324 | def exception_handler ( self , ex ) : if isinstance ( ex , CLIError ) : logger . error ( ex ) else : logger . exception ( ex ) return 1 | The default exception handler |
35,325 | def invoke ( self , args , initial_invocation_data = None , out_file = None ) : from . util import CommandResultItem if not isinstance ( args , ( list , tuple ) ) : raise TypeError ( 'args should be a list or tuple.' ) exit_code = 0 try : args = self . completion . get_completion_args ( ) or args out_file = out_file or... | Invoke a command . |
35,326 | def get_logger ( module_name = None ) : if module_name : logger_name = '{}.{}' . format ( CLI_LOGGER_NAME , module_name ) else : logger_name = CLI_LOGGER_NAME return logging . getLogger ( logger_name ) | Get the logger for a module . If no module name is given the current CLI logger is returned . |
35,327 | def configure ( self , args ) : verbose_level = self . _determine_verbose_level ( args ) log_level_config = self . console_log_configs [ verbose_level ] root_logger = logging . getLogger ( ) cli_logger = logging . getLogger ( CLI_LOGGER_NAME ) root_logger . setLevel ( logging . DEBUG ) cli_logger . setLevel ( logging .... | Configure the loggers with the appropriate log level etc . |
35,328 | def _determine_verbose_level ( self , args ) : verbose_level = 0 for arg in args : if arg == CLILogging . VERBOSE_FLAG : verbose_level += 1 elif arg == CLILogging . DEBUG_FLAG : verbose_level += 2 return min ( verbose_level , len ( self . console_log_configs ) - 1 ) | Get verbose level by reading the arguments . |
35,329 | def enum_choice_list ( data ) : if not data : return { } try : choices = [ x . value for x in data ] except AttributeError : choices = data def _type ( value ) : return next ( ( x for x in choices if x . lower ( ) == value . lower ( ) ) , value ) if value else value params = { 'choices' : CaseInsensitiveList ( choices ... | Creates the argparse choices and type kwargs for a supplied enum type or list of strings |
35,330 | def register_cli_argument ( self , scope , dest , argtype , ** kwargs ) : argument = CLIArgumentType ( overrides = argtype , ** kwargs ) self . arguments [ scope ] [ dest ] = argument | Add an argument to the argument registry |
35,331 | def get_cli_argument ( self , command , name ) : parts = command . split ( ) result = CLIArgumentType ( ) for index in range ( 0 , len ( parts ) + 1 ) : probe = ' ' . join ( parts [ 0 : index ] ) override = self . arguments . get ( probe , { } ) . get ( name , None ) if override : result . update ( override ) return re... | Get the argument for the command after applying the scope hierarchy |
35,332 | def argument ( self , argument_dest , arg_type = None , ** kwargs ) : self . _check_stale ( ) if not self . _applicable ( ) : return deprecate_action = self . _handle_deprecations ( argument_dest , ** kwargs ) if deprecate_action : kwargs [ 'action' ] = deprecate_action self . command_loader . argument_registry . regis... | Register an argument for the given command scope using a knack . arguments . CLIArgumentType |
35,333 | def positional ( self , argument_dest , arg_type = None , ** kwargs ) : self . _check_stale ( ) if not self . _applicable ( ) : return if self . command_scope not in self . command_loader . command_table : raise ValueError ( "command authoring error: positional argument '{}' cannot be registered to a group-level " "sco... | Register a positional argument for the given command scope using a knack . arguments . CLIArgumentType |
35,334 | def extra ( self , argument_dest , ** kwargs ) : self . _check_stale ( ) if not self . _applicable ( ) : return if self . command_scope in self . command_loader . command_group_table : raise ValueError ( "command authoring error: extra argument '{}' cannot be registered to a group-level " "scope '{}'. It must be regist... | Register extra parameters for the given command . Typically used to augment auto - command built commands to add more parameters than the specific SDK method introspected . |
35,335 | def load_command_table ( self , args ) : self . cli_ctx . raise_event ( EVENT_CMDLOADER_LOAD_COMMAND_TABLE , cmd_tbl = self . command_table ) return OrderedDict ( self . command_table ) | Load commands into the command table |
35,336 | def load_arguments ( self , command ) : from knack . arguments import ArgumentsContext self . cli_ctx . raise_event ( EVENT_CMDLOADER_LOAD_ARGUMENTS , cmd_tbl = self . command_table , command = command ) try : self . command_table [ command ] . load_arguments ( ) except KeyError : return with ArgumentsContext ( self , ... | Load the arguments for the specified command |
35,337 | def create_command ( self , name , operation , ** kwargs ) : if not isinstance ( operation , six . string_types ) : raise ValueError ( "Operation must be a string. Got '{}'" . format ( operation ) ) name = ' ' . join ( name . split ( ) ) client_factory = kwargs . get ( 'client_factory' , None ) def _command_handler ( c... | Constructs the command object that can then be added to the command table |
35,338 | def _get_op_handler ( operation ) : try : mod_to_import , attr_path = operation . split ( '#' ) op = import_module ( mod_to_import ) for part in attr_path . split ( '.' ) : op = getattr ( op , part ) if isinstance ( op , types . FunctionType ) : return op return six . get_method_function ( op ) except ( ValueError , At... | Import and load the operation handler |
35,339 | def command ( self , name , handler_name , ** kwargs ) : import copy command_name = '{} {}' . format ( self . group_name , name ) if self . group_name else name command_kwargs = copy . deepcopy ( self . group_kwargs ) command_kwargs . update ( kwargs ) command_kwargs [ 'deprecate_info' ] = kwargs . get ( 'deprecate_inf... | Register a command into the command table |
35,340 | def _rudimentary_get_command ( self , args ) : nouns = [ ] command_names = self . commands_loader . command_table . keys ( ) for arg in args : if arg and arg [ 0 ] != '-' : nouns . append ( arg ) else : break def _find_args ( args ) : search = ' ' . join ( args ) . lower ( ) return next ( ( x for x in command_names if ... | Rudimentary parsing to get the command |
35,341 | def execute ( self , args ) : import colorama self . cli_ctx . raise_event ( EVENT_INVOKER_PRE_CMD_TBL_CREATE , args = args ) cmd_tbl = self . commands_loader . load_command_table ( args ) command = self . _rudimentary_get_command ( args ) self . cli_ctx . invocation . data [ 'command_string' ] = command self . command... | Executes the command invocation |
35,342 | def get_completion_args ( self , is_completion = False , comp_line = None ) : is_completion = is_completion or os . environ . get ( ARGCOMPLETE_ENV_NAME ) comp_line = comp_line or os . environ . get ( 'COMP_LINE' ) return comp_line . split ( ) [ 1 : ] if is_completion and comp_line else None | Get the args that will be used to tab completion if completion is active . |
35,343 | def out ( self , obj , formatter = None , out_file = None ) : if not isinstance ( obj , CommandResultItem ) : raise TypeError ( 'Expected {} got {}' . format ( CommandResultItem . __name__ , type ( obj ) ) ) import platform import colorama if platform . system ( ) == 'Windows' : out_file = colorama . AnsiToWin32 ( out_... | Produces the output using the command result . The method does not return a result as the output is written straight to the output file . |
35,344 | def update_status_with_media ( self , ** params ) : warnings . warn ( 'This method is deprecated. You should use Twython.upload_media instead.' , TwythonDeprecationWarning , stacklevel = 2 ) return self . post ( 'statuses/update_with_media' , params = params ) | Updates the authenticating user s current status and attaches media for upload . In other words it creates a Tweet with a picture attached . |
35,345 | def create_metadata ( self , ** params ) : params = json . dumps ( params ) return self . post ( "https://upload.twitter.com/1.1/media/metadata/create.json" , params = params ) | Adds metadata to a media element such as image descriptions for visually impaired . |
35,346 | def _get_error_message ( self , response ) : error_message = 'An error occurred processing your request.' try : content = response . json ( ) error_message = content [ 'errors' ] [ 0 ] [ 'message' ] except TypeError : error_message = content [ 'errors' ] except ValueError : pass except ( KeyError , IndexError ) : pass ... | Parse and return the first error message |
35,347 | def request ( self , endpoint , method = 'GET' , params = None , version = '1.1' , json_encoded = False ) : if endpoint . startswith ( 'http://' ) : raise TwythonError ( 'api.twitter.com is restricted to SSL/TLS traffic.' ) if endpoint . startswith ( 'https://' ) : url = endpoint else : url = '%s/%s.json' % ( self . ap... | Return dict of response received from Twitter s API |
35,348 | def get_lastfunction_header ( self , header , default_return_value = None ) : if self . _last_call is None : raise TwythonError ( 'This function must be called after an API call. \ It delivers header information.' ) return self . _last_call [ 'headers' ] . get ( header , default_return_val... | Returns a specific header from the last API call This will return None if the header is not present |
35,349 | def get_authentication_tokens ( self , callback_url = None , force_login = False , screen_name = '' ) : if self . oauth_version != 1 : raise TwythonError ( 'This method can only be called when your \ OAuth version is 1.0.' ) request_args = { } if callback_url : request_args [ 'oauth_callba... | Returns a dict including an authorization URL auth_url to direct a user to |
35,350 | def obtain_access_token ( self ) : if self . oauth_version != 2 : raise TwythonError ( 'This method can only be called when your \ OAuth version is 2.0.' ) data = { 'grant_type' : 'client_credentials' } basic_auth = HTTPBasicAuth ( self . app_key , self . app_secret ) try : response = self... | Returns an OAuth 2 access token to make OAuth 2 authenticated read - only calls . |
35,351 | def construct_api_url ( api_url , ** params ) : querystring = [ ] params , _ = _transparent_params ( params or { } ) params = requests . utils . to_key_val_list ( params ) for ( k , v ) in params : querystring . append ( '%s=%s' % ( Twython . encode ( k ) , quote_plus ( Twython . encode ( v ) ) ) ) return '%s?%s' % ( a... | Construct a Twitter API url encoded with parameters |
35,352 | def cursor ( self , function , return_pages = False , ** params ) : if not callable ( function ) : raise TypeError ( '.cursor() takes a Twython function as its first \ argument. Did you provide the result of a \ function call?' ) if not hasattr ( function , 'iter_mo... | Returns a generator for results that match a specified query . |
35,353 | def _request ( self , url , method = 'GET' , params = None ) : self . connected = True retry_counter = 0 method = method . lower ( ) func = getattr ( self . client , method ) params , _ = _transparent_params ( params ) def _send ( retry_counter ) : requests_args = { } for k , v in self . client_args . items ( ) : if k ... | Internal stream request handling |
35,354 | def optimize ( self ) : with open ( LIBRARIES_FILE , 'r' ) as f : libs_data = json . load ( f ) for alg , libs_names in libs_data . items ( ) : libs = self . get_libs ( alg ) if not libs : continue self . libs [ alg ] = [ lib for lib in libs if [ lib . module_name , lib . func_name ] in libs_names ] self . libs [ alg ]... | Sort algorithm implementations by speed . |
35,355 | def clone ( self ) : obj = self . __class__ ( ) obj . libs = deepcopy ( self . libs ) return obj | Clone library manager prototype |
35,356 | def normalized_distance ( self , * sequences ) : return float ( self . distance ( * sequences ) ) / self . maximum ( * sequences ) | Get distance from 0 to 1 |
35,357 | def external_answer ( self , * sequences ) : if not getattr ( self , 'external' , False ) : return if hasattr ( self , 'test_func' ) and self . test_func is not self . _ident : return libs = libraries . get_libs ( self . __class__ . __name__ ) for lib in libs : if not lib . check_conditions ( self , * sequences ) : con... | Try to get answer from known external libraries . |
35,358 | def _ident ( * elements ) : try : return len ( set ( elements ) ) == 1 except TypeError : for e1 , e2 in zip ( elements , elements [ 1 : ] ) : if e1 != e2 : return False return True | Return True if all sequences are equal . |
35,359 | def _get_sequences ( self , * sequences ) : if not self . qval : return [ s . split ( ) for s in sequences ] if self . qval == 1 : return sequences return [ find_ngrams ( s , self . qval ) for s in sequences ] | Prepare sequences . |
35,360 | def _get_counters ( self , * sequences ) : if all ( isinstance ( s , Counter ) for s in sequences ) : return sequences return [ Counter ( s ) for s in self . _get_sequences ( * sequences ) ] | Prepare sequences and convert it to Counters . |
35,361 | def _count_counters ( self , counter ) : if getattr ( self , 'as_set' , False ) : return len ( set ( counter ) ) else : return sum ( counter . values ( ) ) | Return all elements count from Counter |
35,362 | def make_inst2 ( ) : I , d = multidict ( { 1 : 45 , 2 : 20 , 3 : 30 , 4 : 30 } ) J , M = multidict ( { 1 : 35 , 2 : 50 , 3 : 40 } ) c = { ( 1 , 1 ) : 8 , ( 1 , 2 ) : 9 , ( 1 , 3 ) : 14 , ( 2 , 1 ) : 6 , ( 2 , 2 ) : 12 , ( 2 , 3 ) : 9 , ( 3 , 1 ) : 10 , ( 3 , 2 ) : 13 , ( 3 , 3 ) : 16 , ( 4 , 1 ) : 9 , ( 4 , 2 ) : 7 , (... | creates example data set 2 |
35,363 | def addCuts ( self , checkonly ) : cutsadded = False edges = [ ] x = self . model . data for ( i , j ) in x : if self . model . getVal ( x [ i , j ] ) > .5 : if i != V [ 0 ] and j != V [ 0 ] : edges . append ( ( i , j ) ) G = networkx . Graph ( ) G . add_edges_from ( edges ) Components = list ( networkx . connected_com... | add cuts if necessary and return whether model is feasible |
35,364 | def distCEIL2D ( x1 , y1 , x2 , y2 ) : xdiff = x2 - x1 ydiff = y2 - y1 return int ( math . ceil ( math . sqrt ( xdiff * xdiff + ydiff * ydiff ) ) ) | returns smallest integer not less than the distance of two points |
35,365 | def read_atsplib ( filename ) : "basic function for reading a ATSP problem on the TSPLIB format" "NOTE: only works for explicit matrices" if filename [ - 3 : ] == ".gz" : f = gzip . open ( filename , 'r' ) data = f . readlines ( ) else : f = open ( filename , 'r' ) data = f . readlines ( ) for line in data : if line . ... | basic function for reading a ATSP problem on the TSPLIB format |
35,366 | def multidict ( D ) : keys = list ( D . keys ( ) ) if len ( keys ) == 0 : return [ [ ] ] try : N = len ( D [ keys [ 0 ] ] ) islist = True except : N = 1 islist = False dlist = [ dict ( ) for d in range ( N ) ] for k in keys : if islist : for i in range ( N ) : dlist [ i ] [ k ] = D [ k ] [ i ] else : dlist [ 0 ] [ k ] ... | creates a multidictionary |
35,367 | def register_plugin_module ( mod ) : for k , v in load_plugins_from_module ( mod ) . items ( ) : if k : if isinstance ( k , ( list , tuple ) ) : k = k [ 0 ] global_registry [ k ] = v | Find plugins in given module |
35,368 | def register_plugin_dir ( path ) : import glob for f in glob . glob ( path + '/*.py' ) : for k , v in load_plugins_from_module ( f ) . items ( ) : if k : global_registry [ k ] = v | Find plugins in given directory |
35,369 | def describe ( self ) : desc = { 'name' : self . name , 'description' : self . description , 'type' : self . type or 'unknown' , } for attr in [ 'min' , 'max' , 'allowed' , 'default' ] : v = getattr ( self , attr ) if v is not None : desc [ attr ] = v return desc | Information about this parameter |
35,370 | def validate ( self , value ) : if self . type is not None : value = coerce ( self . type , value ) if self . min is not None and value < self . min : raise ValueError ( '%s=%s is less than %s' % ( self . name , value , self . min ) ) if self . max is not None and value > self . max : raise ValueError ( '%s=%s is great... | Does value meet parameter requirements? |
35,371 | def describe ( self ) : if isinstance ( self . _plugin , list ) : pl = [ p . name for p in self . _plugin ] elif isinstance ( self . _plugin , dict ) : pl = { k : classname ( v ) for k , v in self . _plugin . items ( ) } else : pl = self . _plugin if isinstance ( self . _plugin , str ) else self . _plugin . name return... | Basic information about this entry |
35,372 | def get ( self , ** user_parameters ) : plugin , open_args = self . _create_open_args ( user_parameters ) data_source = plugin ( ** open_args ) data_source . catalog_object = self . _catalog data_source . name = self . name data_source . description = self . _description data_source . cat = self . _catalog return data_... | Instantiate the DataSource for the given parameters |
35,373 | def _load ( self , reload = False ) : if self . autoreload or reload : options = self . storage_options or { } if hasattr ( self . path , 'path' ) or hasattr ( self . path , 'read' ) : file_open = self . path self . path = make_path_posix ( getattr ( self . path , 'path' , getattr ( self . path , 'name' , 'file' ) ) ) ... | Load text of fcatalog file and pass to parse |
35,374 | def parse ( self , text ) : self . text = text data = yaml_load ( self . text ) if data is None : raise exceptions . CatalogException ( 'No YAML data in file' ) context = dict ( root = self . _dir ) result = CatalogParser ( data , context = context , getenv = self . getenv , getshell = self . getshell ) if result . err... | Create entries from catalog text |
35,375 | def name_from_path ( self ) : name = os . path . splitext ( os . path . basename ( self . path ) ) [ 0 ] if name == 'catalog' : name = os . path . basename ( os . path . dirname ( self . path ) ) return name . replace ( '.' , '_' ) | If catalog is named catalog take name from parent directory |
35,376 | def get ( self ) : head = self . request . headers name = self . get_argument ( 'name' ) if self . auth . allow_connect ( head ) : if 'source_id' in head : cat = self . _cache . get ( head [ 'source_id' ] ) else : cat = self . _catalog try : source = cat [ name ] except KeyError : msg = 'No such entry' raise tornado . ... | Access one source s info . |
35,377 | def preprocess ( cls , cat ) : if isinstance ( cat , str ) : cat = intake . open_catalog ( cat ) return cat | Function to run on each cat input |
35,378 | def expand_nested ( self , cats ) : down = '│' right = '└──' def get_children ( parent ) : return [ e ( ) for e in parent . _entries . values ( ) if e . _container == 'catalog' ] if len ( cats ) == 0 : return cat = cats [ 0 ] old = list ( self . options . items ( ) ) name = next ( k for k , v in old if v == cat ) index... | Populate widget with nested catalogs |
35,379 | def collapse_nested ( self , cats , max_nestedness = 10 ) : children = [ ] removed = set ( ) nestedness = max_nestedness old = list ( self . widget . options . values ( ) ) nested = [ cat for cat in old if getattr ( cat , 'cat' ) is not None ] parents = { cat . cat for cat in nested } parents_to_remove = cats while len... | Collapse any items that are nested under cats . max_nestedness acts as a fail - safe to prevent infinite looping . |
35,380 | def remove_selected ( self , * args ) : self . collapse_nested ( self . selected ) self . remove ( self . selected ) | Remove the selected catalog - allow the passing of arbitrary args so that buttons work . Also remove any nested catalogs . |
35,381 | def add ( self , key , source ) : from intake . catalog . local import LocalCatalogEntry try : with self . fs . open ( self . path , 'rb' ) as f : data = yaml . safe_load ( f ) except IOError : data = { 'sources' : { } } ds = source . _yaml ( ) [ 'sources' ] [ source . name ] data [ 'sources' ] [ key ] = ds with self .... | Add the persisted source to the store under the given key |
35,382 | def get_tok ( self , source ) : if isinstance ( source , str ) : return source if isinstance ( source , CatalogEntry ) : return source . _metadata . get ( 'original_tok' , source . _tok ) if isinstance ( source , DataSource ) : return source . metadata . get ( 'original_tok' , source . _tok ) raise IndexError | Get string token from object |
35,383 | def remove ( self , source , delfiles = True ) : source = self . get_tok ( source ) with self . fs . open ( self . path , 'rb' ) as f : data = yaml . safe_load ( f . read ( ) . decode ( ) ) data [ 'sources' ] . pop ( source , None ) with self . fs . open ( self . path , 'wb' ) as fo : fo . write ( yaml . dump ( data , ... | Remove a dataset from the persist store |
35,384 | def backtrack ( self , source ) : key = self . get_tok ( source ) s = self [ key ] ( ) meta = s . metadata [ 'original_source' ] cls = meta [ 'cls' ] args = meta [ 'args' ] kwargs = meta [ 'kwargs' ] cls = import_name ( cls ) sout = cls ( * args , ** kwargs ) sout . metadata = s . metadata [ 'original_metadata' ] sout ... | Given a unique key in the store recreate original source |
35,385 | def refresh ( self , key ) : s0 = self [ key ] s = self . backtrack ( key ) s . persist ( ** s0 . metadata [ 'persist_kwargs' ] ) | Recreate and re - persist the source for the given unique ID |
35,386 | def cats ( self , cats ) : sources = [ ] for cat in coerce_to_list ( cats ) : sources . extend ( [ entry for entry in cat . _entries . values ( ) if entry . _container != 'catalog' ] ) self . items = sources | Set sources from a list of cats |
35,387 | def main ( argv = None ) : from intake . cli . bootstrap import main as _main return _main ( 'Intake Catalog CLI' , subcommands . all , argv or sys . argv ) | Execute the intake command line program . |
35,388 | def _load_metadata ( self ) : if self . _schema is None : self . _schema = self . _get_schema ( ) self . datashape = self . _schema . datashape self . dtype = self . _schema . dtype self . shape = self . _schema . shape self . npartitions = self . _schema . npartitions self . metadata . update ( self . _schema . extra_... | load metadata only if needed |
35,389 | def yaml ( self , with_plugin = False ) : from yaml import dump data = self . _yaml ( with_plugin = with_plugin ) return dump ( data , default_flow_style = False ) | Return YAML representation of this data - source |
35,390 | def discover ( self ) : self . _load_metadata ( ) return dict ( datashape = self . datashape , dtype = self . dtype , shape = self . shape , npartitions = self . npartitions , metadata = self . metadata ) | Open resource and populate the source attributes . |
35,391 | def read_chunked ( self ) : self . _load_metadata ( ) for i in range ( self . npartitions ) : yield self . _get_partition ( i ) | Return iterator over container fragments of data source |
35,392 | def read_partition ( self , i ) : self . _load_metadata ( ) if i < 0 or i >= self . npartitions : raise IndexError ( '%d is out of range' % i ) return self . _get_partition ( i ) | Return a part of the data corresponding to i - th partition . |
35,393 | def plot ( self ) : try : from hvplot import hvPlot except ImportError : raise ImportError ( "The intake plotting API requires hvplot." "hvplot may be installed with:\n\n" "`conda install -c pyviz hvplot` or " "`pip install hvplot`." ) metadata = self . metadata . get ( 'plot' , { } ) fields = self . metadata . get ( '... | Returns a hvPlot object to provide a high - level plotting API . |
35,394 | def persist ( self , ttl = None , ** kwargs ) : from . . container import container_map from . . container . persist import PersistStore import time if 'original_tok' in self . metadata : raise ValueError ( 'Cannot persist a source taken from the persist ' 'store' ) method = container_map [ self . container ] . _persis... | Save data from this source to local persistent storage |
35,395 | def export ( self , path , ** kwargs ) : from . . container import container_map import time method = container_map [ self . container ] . _persist out = method ( self , path = path , ** kwargs ) out . description = self . description metadata = { 'timestamp' : time . time ( ) , 'original_metadata' : self . metadata , ... | Save this data for sharing with other people |
35,396 | def load_user_catalog ( ) : cat_dir = user_data_dir ( ) if not os . path . isdir ( cat_dir ) : return Catalog ( ) else : return YAMLFilesCatalog ( cat_dir ) | Return a catalog for the platform - specific user Intake directory |
35,397 | def load_global_catalog ( ) : cat_dir = global_data_dir ( ) if not os . path . isdir ( cat_dir ) : return Catalog ( ) else : return YAMLFilesCatalog ( cat_dir ) | Return a catalog for the environment - specific Intake directory |
35,398 | def global_data_dir ( ) : prefix = False if VIRTUALENV_VAR in os . environ : prefix = os . environ [ VIRTUALENV_VAR ] elif CONDA_VAR in os . environ : prefix = sys . prefix elif which ( 'conda' ) : prefix = conda_prefix ( ) if prefix : return make_path_posix ( os . path . join ( prefix , 'share' , 'intake' ) ) else : r... | Return the global Intake catalog dir for the current environment |
35,399 | def load_combo_catalog ( ) : user_dir = user_data_dir ( ) global_dir = global_data_dir ( ) desc = 'Generated from data packages found on your intake search path' cat_dirs = [ ] if os . path . isdir ( user_dir ) : cat_dirs . append ( user_dir + '/*.yaml' ) cat_dirs . append ( user_dir + '/*.yml' ) if os . path . isdir (... | Load a union of the user and global catalogs for convenience |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.