idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
20,600 | def deleteEdge ( self , edge , waitForSync = False ) : url = "%s/edge/%s" % ( self . URL , edge . _id ) r = self . connection . session . delete ( url , params = { 'waitForSync' : waitForSync } ) if r . status_code == 200 or r . status_code == 202 : return True raise DeletionError ( "Unable to delete edge, %s" % edge .... | removes an edge from the graph |
20,601 | def delete ( self , _key ) : "removes a document from the cache" try : doc = self . cacheStore [ _key ] doc . prev . nextDoc = doc . nextDoc doc . nextDoc . prev = doc . prev del ( self . cacheStore [ _key ] ) except KeyError : raise KeyError ( "Document with _key %s is not available in cache" % _key ) | removes a document from the cache |
20,602 | def getChain ( self ) : "returns a list of keys representing the chain of documents" l = [ ] h = self . head while h : l . append ( h . _key ) h = h . nextDoc return l | returns a list of keys representing the chain of documents |
20,603 | def validate ( self , value ) : for v in self . validators : v . validate ( value ) return True | checks the validity of value given the lits of validators |
20,604 | def getCollectionClass ( cls , name ) : try : return cls . collectionClasses [ name ] except KeyError : raise KeyError ( "There is no Collection Class of type: '%s'; currently supported values: [%s]" % ( name , ', ' . join ( getCollectionClasses ( ) . keys ( ) ) ) ) | Return the class object of a collection given its name |
20,605 | def isDocumentCollection ( cls , name ) : try : col = cls . getCollectionClass ( name ) return issubclass ( col , Collection ) except KeyError : return False | return true or false wether name is the name of a document collection . |
20,606 | def isEdgeCollection ( cls , name ) : try : col = cls . getCollectionClass ( name ) return issubclass ( col , Edges ) except KeyError : return False | return true or false wether name is the name of an edge collection . |
20,607 | def getIndexes ( self ) : url = "%s/index" % self . database . URL r = self . connection . session . get ( url , params = { "collection" : self . name } ) data = r . json ( ) for ind in data [ "indexes" ] : self . indexes [ ind [ "type" ] ] [ ind [ "id" ] ] = Index ( collection = self , infos = ind ) return self . inde... | Fills self . indexes with all the indexes associates with the collection and returns it |
20,608 | def delete ( self ) : r = self . connection . session . delete ( self . URL ) data = r . json ( ) if not r . status_code == 200 or data [ "error" ] : raise DeletionError ( data [ "errorMessage" ] , data ) | deletes the collection from the database |
20,609 | def createDocument ( self , initDict = None ) : if initDict is not None : return self . createDocument_ ( initDict ) else : if self . _validation [ "on_load" ] : self . _validation [ "on_load" ] = False return self . createDocument_ ( self . defaultDocument ) self . _validation [ "on_load" ] = True else : return self .... | create and returns a document populated with the defaults or with the values in initDict |
20,610 | def createDocument_ ( self , initDict = None ) : "create and returns a completely empty document or one populated with initDict" if initDict is None : initV = { } else : initV = initDict return self . documentClass ( self , initV ) | create and returns a completely empty document or one populated with initDict |
20,611 | def ensureHashIndex ( self , fields , unique = False , sparse = True , deduplicate = False ) : data = { "type" : "hash" , "fields" : fields , "unique" : unique , "sparse" : sparse , "deduplicate" : deduplicate } ind = Index ( self , creationData = data ) self . indexes [ "hash" ] [ ind . infos [ "id" ] ] = ind return i... | Creates a hash index if it does not already exist and returns it |
20,612 | def ensureGeoIndex ( self , fields ) : data = { "type" : "geo" , "fields" : fields , } ind = Index ( self , creationData = data ) self . indexes [ "geo" ] [ ind . infos [ "id" ] ] = ind return ind | Creates a geo index if it does not already exist and returns it |
20,613 | def ensureFulltextIndex ( self , fields , minLength = None ) : data = { "type" : "fulltext" , "fields" : fields , } if minLength is not None : data [ "minLength" ] = minLength ind = Index ( self , creationData = data ) self . indexes [ "fulltext" ] [ ind . infos [ "id" ] ] = ind return ind | Creates a fulltext index if it does not already exist and returns it |
20,614 | def validatePrivate ( self , field , value ) : if field not in self . arangoPrivates : raise ValueError ( "%s is not a private field of collection %s" % ( field , self ) ) if field in self . _fields : self . _fields [ field ] . validate ( value ) return True | validate a private field value |
20,615 | def simpleQuery ( self , queryType , rawResults = False , ** queryArgs ) : return SimpleQuery ( self , queryType , rawResults , ** queryArgs ) | General interface for simple queries . queryType can be something like all by - example etc ... everything is in the arango doc . If rawResults the query will return dictionaries instead of Document objetcs . |
20,616 | def action ( self , method , action , ** params ) : fct = getattr ( self . connection . session , method . lower ( ) ) r = fct ( self . URL + "/" + action , params = params ) return r . json ( ) | a generic fct for interacting everything that doesn t have an assigned fct |
20,617 | def bulkSave ( self , docs , onDuplicate = "error" , ** params ) : payload = [ ] for d in docs : if type ( d ) is dict : payload . append ( json . dumps ( d , default = str ) ) else : try : payload . append ( d . toJson ( ) ) except Exception as e : payload . append ( json . dumps ( d . getStore ( ) , default = str ) )... | Parameter docs must be either an iterrable of documents or dictionnaries . This function will return the number of documents created and updated and will raise an UpdateError exception if there s at least one error . params are any parameters from arango s documentation |
20,618 | def getEdges ( self , vertex , inEdges = True , outEdges = True , rawResults = False ) : if isinstance ( vertex , Document ) : vId = vertex . _id elif ( type ( vertex ) is str ) or ( type ( vertex ) is bytes ) : vId = vertex else : raise ValueError ( "Vertex is neither a Document nor a String" ) params = { "vertex" : v... | returns in out or both edges liked to a given document . vertex can be either a Document object or a string for an _id . If rawResults a arango results will be return as fetched if false will return a liste of Edge objects |
20,619 | def reloadCollections ( self ) : "reloads the collection list." r = self . connection . session . get ( self . collectionsURL ) data = r . json ( ) if r . status_code == 200 : self . collections = { } for colData in data [ "result" ] : colName = colData [ 'name' ] if colData [ 'isSystem' ] : colObj = COL . SystemCollec... | reloads the collection list . |
20,620 | def reloadGraphs ( self ) : "reloads the graph list" r = self . connection . session . get ( self . graphsURL ) data = r . json ( ) if r . status_code == 200 : self . graphs = { } for graphData in data [ "graphs" ] : try : self . graphs [ graphData [ "_key" ] ] = GR . getGraphClass ( graphData [ "_key" ] ) ( self , gra... | reloads the graph list |
20,621 | def createGraph ( self , name , createCollections = True , isSmart = False , numberOfShards = None , smartGraphAttribute = None ) : def _checkCollectionList ( lst ) : for colName in lst : if not COL . isCollection ( colName ) : raise ValueError ( "'%s' is not a defined Collection" % colName ) graphClass = GR . getGraph... | Creates a graph and returns it . name must be the name of a class inheriting from Graph . Checks will be performed to make sure that every collection mentionned in the edges definition exist . Raises a ValueError in case of a non - existing collection . |
20,622 | def validateAQLQuery ( self , query , bindVars = None , options = None ) : "returns the server answer is the query is valid. Raises an AQLQueryError if not" if bindVars is None : bindVars = { } if options is None : options = { } payload = { 'query' : query , 'bindVars' : bindVars , 'options' : options } r = self . conn... | returns the server answer is the query is valid . Raises an AQLQueryError if not |
20,623 | def transaction ( self , collections , action , waitForSync = False , lockTimeout = None , params = None ) : payload = { "collections" : collections , "action" : action , "waitForSync" : waitForSync } if lockTimeout is not None : payload [ "lockTimeout" ] = lockTimeout if params is not None : payload [ "params" ] = par... | Execute a server - side transaction |
20,624 | def getPatches ( self ) : if not self . mustValidate : return self . getStore ( ) res = { } res . update ( self . patchStore ) for k , v in self . subStores . items ( ) : res [ k ] = v . getPatches ( ) return res | get patches as a dictionary |
20,625 | def getStore ( self ) : res = { } res . update ( self . store ) for k , v in self . subStores . items ( ) : res [ k ] = v . getStore ( ) return res | get the inner store as dictionary |
20,626 | def validateField ( self , field ) : if field not in self . validators and not self . collection . _validation [ 'allow_foreign_fields' ] : raise SchemaViolation ( self . collection . __class__ , field ) if field in self . store : if isinstance ( self . store [ field ] , DocumentStore ) : return self [ field ] . valida... | Validatie a field |
20,627 | def validate ( self ) : if not self . mustValidate : return True res = { } for field in self . validators . keys ( ) : try : if isinstance ( self . validators [ field ] , dict ) and field not in self . store : self . store [ field ] = DocumentStore ( self . collection , validators = self . validators [ field ] , initDc... | Validate the whole document |
20,628 | def set ( self , dct ) : for field , value in dct . items ( ) : if field not in self . collection . arangoPrivates : if isinstance ( value , dict ) : if field in self . validators and isinstance ( self . validators [ field ] , dict ) : vals = self . validators [ field ] else : vals = { } self [ field ] = DocumentStore ... | Set the store using a dictionary |
20,629 | def reset ( self , collection , jsonFieldInit = None ) : if not jsonFieldInit : jsonFieldInit = { } self . collection = collection self . connection = self . collection . connection self . documentsURL = self . collection . documentsURL self . URL = None self . setPrivates ( jsonFieldInit ) self . _store = DocumentStor... | replaces the current values in the document by those in jsonFieldInit |
20,630 | def validate ( self ) : self . _store . validate ( ) for pField in self . collection . arangoPrivates : self . collection . validatePrivate ( pField , getattr ( self , pField ) ) | validate the document |
20,631 | def setPrivates ( self , fieldDict ) : for priv in self . privates : if priv in fieldDict : setattr ( self , priv , fieldDict [ priv ] ) else : setattr ( self , priv , None ) if self . _id is not None : self . URL = "%s/%s" % ( self . documentsURL , self . _id ) | will set self . _id self . _rev and self . _key field . |
20,632 | def patch ( self , keepNull = True , ** docArgs ) : if self . URL is None : raise ValueError ( "Cannot patch a document that was not previously saved" ) payload = self . _store . getPatches ( ) if self . collection . _validation [ 'on_save' ] : self . validate ( ) if len ( payload ) > 0 : params = dict ( docArgs ) para... | Saves the document by only updating the modified fields . The default behaviour concening the keepNull parameter is the opposite of ArangoDB s default Null values won t be ignored Use docArgs for things such as waitForSync = True |
20,633 | def delete ( self ) : "deletes the document from the database" if self . URL is None : raise DeletionError ( "Can't delete a document that was not saved" ) r = self . connection . session . delete ( self . URL ) data = r . json ( ) if ( r . status_code != 200 and r . status_code != 202 ) or 'error' in data : raise Dele... | deletes the document from the database |
20,634 | def getEdges ( self , edges , inEdges = True , outEdges = True , rawResults = False ) : try : return edges . getEdges ( self , inEdges , outEdges , rawResults ) except AttributeError : raise AttributeError ( "%s does not seem to be a valid Edges object" % edges ) | returns in out or both edges linked to self belonging the collection edges . If rawResults a arango results will be return as fetched if false will return a liste of Edge objects |
20,635 | def getStore ( self ) : store = self . _store . getStore ( ) for priv in self . privates : v = getattr ( self , priv ) if v : store [ priv ] = v return store | return the store in a dict format |
20,636 | def links ( self , fromVertice , toVertice , ** edgeArgs ) : if isinstance ( fromVertice , Document ) or isinstance ( getattr ( fromVertice , 'document' , None ) , Document ) : if not fromVertice . _id : fromVertice . save ( ) self . _from = fromVertice . _id elif ( type ( fromVertice ) is bytes ) or ( type ( fromVerti... | An alias to save that updates the _from and _to attributes . fromVertice and toVertice can be either strings or documents . It they are unsaved documents they will be automatically saved . |
20,637 | def _set ( self , jsonData ) : self [ "username" ] = jsonData [ "user" ] self [ "active" ] = jsonData [ "active" ] self [ "extra" ] = jsonData [ "extra" ] try : self [ "changePassword" ] = jsonData [ "changePassword" ] except Exception as e : pass try : self [ "password" ] = jsonData [ "passwd" ] except KeyError : self... | Initialize all fields at once . If no password is specified it will be set as an empty string |
20,638 | def delete ( self ) : if not self . URL : raise CreationError ( "Please save user first" , None , None ) r = self . connection . session . delete ( self . URL ) if r . status_code < 200 or r . status_code > 202 : raise DeletionError ( "Unable to delete user, url: %s, status: %s" % ( r . url , r . status_code ) , r . co... | Permanently remove the user |
20,639 | def fetchAllUsers ( self , rawResults = False ) : r = self . connection . session . get ( self . URL ) if r . status_code == 200 : data = r . json ( ) if rawResults : return data [ "result" ] else : res = [ ] for resu in data [ "result" ] : u = User ( self , resu ) res . append ( u ) return res else : raise ConnectionE... | Returns all available users . if rawResults the result will be a list of python dicts instead of User objects |
20,640 | def fetchUser ( self , username , rawResults = False ) : url = "%s/%s" % ( self . URL , username ) r = self . connection . session . get ( url ) if r . status_code == 200 : data = r . json ( ) if rawResults : return data [ "result" ] else : u = User ( self , data ) return u else : raise KeyError ( "Unable to get user: ... | Returns a single user . if rawResults the result will be a list of python dicts instead of User objects |
20,641 | def resetSession ( self , username = None , password = None , verify = True ) : self . disconnectSession ( ) self . session = AikidoSession ( username , password , verify ) | resets the session |
20,642 | def reload ( self ) : r = self . session . get ( self . databasesURL ) data = r . json ( ) if r . status_code == 200 and not data [ "error" ] : self . databases = { } for dbName in data [ "result" ] : if dbName not in self . databases : self . databases [ dbName ] = DBHandle ( self , dbName ) else : raise ConnectionErr... | Reloads the database list . Because loading a database triggers the loading of all collections and graphs within only handles are loaded when this function is called . The full databases are loaded on demand when accessed |
20,643 | def createDatabase ( self , name , ** dbArgs ) : "use dbArgs for arguments other than name. for a full list of arguments please have a look at arangoDB's doc" dbArgs [ 'name' ] = name payload = json . dumps ( dbArgs , default = str ) url = self . URL + "/database" r = self . session . post ( url , data = payload ) data... | use dbArgs for arguments other than name . for a full list of arguments please have a look at arangoDB s doc |
20,644 | def output ( self , args ) : print ( "SensuPlugin: {}" . format ( ' ' . join ( str ( a ) for a in args ) ) ) | Print the output message . |
20,645 | def __make_dynamic ( self , method ) : def dynamic ( * args ) : self . plugin_info [ 'status' ] = method if not args : args = None self . output ( args ) sys . exit ( getattr ( self . exit_code , method ) ) method_lc = method . lower ( ) dynamic . __doc__ = "%s method" % method_lc dynamic . __name__ = method_lc setattr... | Create a method for each of the exit codes . |
20,646 | def __exitfunction ( self ) : if self . _hook . exit_code is None and self . _hook . exception is None : print ( "Check did not exit! You should call an exit code method." ) sys . stdout . flush ( ) os . _exit ( 1 ) elif self . _hook . exception : print ( "Check failed to run: %s, %s" % ( sys . last_type , traceback . ... | Method called by exit hook ensures that both an exit code and output is supplied also catches errors . |
20,647 | def run ( self ) : stdin = self . read_stdin ( ) self . event = self . read_event ( stdin ) self . settings = get_settings ( ) self . api_settings = self . get_api_settings ( ) self . parser = argparse . ArgumentParser ( ) self . parser . add_argument ( "--map-v2-event-into-v1" , action = "store_true" , default = False... | Set up the event object global settings and command line arguments . |
20,648 | def filter ( self ) : if self . deprecated_filtering_enabled ( ) : print ( 'warning: event filtering in sensu-plugin is deprecated,' + 'see http://bit.ly/sensu-plugin' ) self . filter_disabled ( ) self . filter_silenced ( ) self . filter_dependencies ( ) if self . deprecated_occurrence_filtering ( ) : print ( 'warning:... | Filters exit the proccess if the event should not be handled . Filtering events is deprecated and will be removed in a future release . |
20,649 | def bail ( self , msg ) : client_name = self . event [ 'client' ] . get ( 'name' , 'error:no-client-name' ) check_name = self . event [ 'check' ] . get ( 'name' , 'error:no-check-name' ) print ( '{}: {}/{}' . format ( msg , client_name , check_name ) ) sys . exit ( 0 ) | Gracefully terminate with message |
20,650 | def api_request ( self , method , path ) : if not hasattr ( self , 'api_settings' ) : ValueError ( 'api.json settings not found' ) if method . lower ( ) == 'get' : _request = requests . get elif method . lower ( ) == 'post' : _request = requests . post domain = self . api_settings [ 'host' ] uri = '{}:{}/{}' . format (... | Query Sensu api for information . |
20,651 | def event_exists ( self , client , check ) : return self . api_request ( 'get' , 'events/{}/{}' . format ( client , check ) ) . status_code == 200 | Query Sensu API for event . |
20,652 | def filter_silenced ( self ) : stashes = [ ( 'client' , '/silence/{}' . format ( self . event [ 'client' ] [ 'name' ] ) ) , ( 'check' , '/silence/{}/{}' . format ( self . event [ 'client' ] [ 'name' ] , self . event [ 'check' ] [ 'name' ] ) ) , ( 'check' , '/silence/all/{}' . format ( self . event [ 'check' ] [ 'name' ... | Determine whether a check is silenced and shouldn t handle . |
20,653 | def filter_dependencies ( self ) : dependencies = self . event [ 'check' ] . get ( 'dependencies' , None ) if dependencies is None or not isinstance ( dependencies , list ) : return for dependency in self . event [ 'check' ] [ 'dependencies' ] : if not str ( dependency ) : continue dependency_split = tuple ( dependency... | Determine whether a check has dependencies . |
20,654 | def filter_repeated ( self ) : defaults = { 'occurrences' : 1 , 'interval' : 30 , 'refresh' : 1800 } if isinstance ( self . settings [ 'sensu_plugin' ] , dict ) : defaults . update ( self . settings [ 'sensu_plugin' ] ) occurrences = int ( self . event [ 'check' ] . get ( 'occurrences' , defaults [ 'occurrences' ] ) ) ... | Determine whether a check is repeating . |
20,655 | def config_files ( ) : sensu_loaded_tempfile = os . environ . get ( 'SENSU_LOADED_TEMPFILE' ) sensu_config_files = os . environ . get ( 'SENSU_CONFIG_FILES' ) sensu_v1_config = '/etc/sensu/config.json' sensu_v1_confd = '/etc/sensu/conf.d' if sensu_loaded_tempfile and os . path . isfile ( sensu_loaded_tempfile ) : with ... | Get list of currently used config files . |
20,656 | def get_settings ( ) : settings = { } for config_file in config_files ( ) : config_contents = load_config ( config_file ) if config_contents is not None : settings = deep_merge ( settings , config_contents ) return settings | Get all currently loaded settings . |
20,657 | def load_config ( filename ) : try : with open ( filename , 'r' ) as config_file : return json . loads ( config_file . read ( ) ) except IOError : pass | Read contents of config file . |
20,658 | def deep_merge ( dict_one , dict_two ) : merged = dict_one . copy ( ) for key , value in dict_two . items ( ) : if ( key in dict_one and isinstance ( dict_one [ key ] , dict ) and isinstance ( value , dict ) ) : merged [ key ] = deep_merge ( dict_one [ key ] , value ) elif ( key in dict_one and isinstance ( dict_one [ ... | Deep merge two dicts . |
20,659 | def map_v2_event_into_v1 ( event ) : if "v2_event_mapped_into_v1" in event : return event if not bool ( event . get ( 'client' ) ) and "entity" in event : event [ 'client' ] = event [ 'entity' ] if "name" not in event [ 'client' ] : event [ 'client' ] [ 'name' ] = event [ 'entity' ] [ 'id' ] if "subscribers" not in eve... | Helper method to convert Sensu 2 . x event into Sensu 1 . x event . |
20,660 | def check_name ( self , name = None ) : if name : self . plugin_info [ 'check_name' ] = name if self . plugin_info [ 'check_name' ] is not None : return self . plugin_info [ 'check_name' ] return self . __class__ . __name__ | Checks the plugin name and sets it accordingly . Uses name if specified class name if not set . |
20,661 | def sampled_logs ( self , logs_limit = - 1 ) : logs_count = len ( self . logs ) if logs_limit == - 1 or logs_count <= logs_limit : return self . logs elif logs_limit == 0 : return [ ] elif logs_limit == 1 : return [ self . logs [ - 1 ] ] else : def get_sampled_log ( idx ) : return self . logs [ idx * ( logs_count - 1 )... | Return up to logs_limit logs . |
20,662 | def serialize_with_sampled_logs ( self , logs_limit = - 1 ) : return { 'id' : self . id , 'pathName' : self . path_name , 'name' : self . name , 'isUnregistered' : self . is_unregistered , 'logs' : [ log . serialize for log in self . sampled_logs ( logs_limit ) ] , 'args' : self . args . serialize if self . args is not... | serialize a result with up to logs_limit logs . |
20,663 | def reporter ( prefix = None , out = None , subdir = '' , timeout = 5 , ** kwargs ) : report = _Reporter ( prefix , out , subdir , ** kwargs ) yield report report . save ( timeout ) | Summary media assets to visualize . |
20,664 | def audio ( audio , sample_rate , name = None , out = None , subdir = '' , timeout = 5 , ** kwargs ) : from chainerui . report . audio_report import check_available if not check_available ( ) : return from chainerui . report . audio_report import report as _audio out_root = _chainerui_asset_observer . get_outpath ( out... | summary audio files to listen on a browser . |
20,665 | def audio ( self , audio , sample_rate , name = None , subdir = '' ) : from chainerui . report . audio_report import check_available if not check_available ( ) : return from chainerui . report . audio_report import report as _audio col_name = self . get_col_name ( name , 'audio' ) out_dir , rel_out_dir = self . get_sub... | Summary audio to listen on web browser . |
20,666 | def create ( cls , path_name = None , name = None , crawlable = True ) : project = cls ( path_name , name , crawlable ) db . session . add ( project ) db . session . commit ( ) return collect_results ( project , force = True ) | initialize an instance and save it to db . |
20,667 | def collect_assets ( result , force = False ) : path_name = result . path_name info_path = os . path . join ( path_name , summary . CHAINERUI_ASSETS_METAFILE_NAME ) if not os . path . isfile ( info_path ) : return start_idx = len ( result . assets ) file_modified_at = datetime . datetime . fromtimestamp ( os . path . g... | collect assets from meta file |
20,668 | def save_args ( conditions , out_path ) : if isinstance ( conditions , argparse . Namespace ) : args = vars ( conditions ) else : args = conditions try : os . makedirs ( out_path ) except OSError : pass with tempdir ( prefix = 'args' , dir = out_path ) as tempd : path = os . path . join ( tempd , 'args.json' ) with ope... | A util function to save experiment condition for job table . |
20,669 | def _path_insensitive ( path ) : path = str ( path ) if path == '' or os . path . exists ( path ) : return path base = os . path . basename ( path ) dirname = os . path . dirname ( path ) suffix = '' if not base : if len ( dirname ) < len ( path ) : suffix = path [ : len ( path ) - len ( dirname ) ] base = os . path . ... | Recursive part of path_insensitive to do the work . |
20,670 | def form_option ( str_opt ) : str_base = '#cmdoption-arg-' str_opt_x = str_base + str_opt . lower ( ) . replace ( '_' , '-' ) . replace ( '(' , '-' ) . replace ( ')' , '' ) return str_opt_x | generate option name based suffix for URL |
20,671 | def gen_url_option ( str_opt , set_site = set_site , set_runcontrol = set_runcontrol , set_initcond = set_initcond , source = 'docs' ) : dict_base = { 'docs' : URL ( 'https://suews-docs.readthedocs.io/en/latest/input_files/' ) , 'github' : URL ( 'https://github.com/Urban-Meteorology-Reading/SUEWS-Docs/raw/master/docs/s... | construct a URL for option based on source |
20,672 | def gen_df_forcing ( path_csv_in = 'SSss_YYYY_data_tt.csv' , url_base = url_repo_input , ) -> pd . DataFrame : try : urlpath_table = url_base / path_csv_in df_var_info = pd . read_csv ( urlpath_table ) except : print ( f'{urlpath_table} not existing!' ) else : df_var_forcing = df_var_info . drop ( [ 'No.' , 'Use' ] , a... | Generate description info of supy forcing data into a dataframe |
20,673 | def gen_df_output ( list_csv_in = [ 'SSss_YYYY_SUEWS_TT.csv' , 'SSss_DailyState.csv' , 'SSss_YYYY_snow_TT.csv' , ] , url_base = url_repo_output ) -> Path : list_url_table = [ url_base / table for table in list_csv_in ] try : df_var_info = pd . concat ( [ pd . read_csv ( f ) for f in list_url_table ] , sort = False ) ex... | Generate description info of supy output results into dataframe |
20,674 | def gen_opt_str ( ser_rec : pd . Series ) -> str : name = ser_rec . name indent = r' ' str_opt = f'.. option:: {name}' + '\n\n' for spec in ser_rec . sort_index ( ) . index : str_opt += indent + f':{spec}:' + '\n' spec_content = ser_rec [ spec ] str_opt += indent + indent + f'{spec_content}' + '\n' return str_opt | generate rst option string |
20,675 | def init_supy ( path_init : str ) -> pd . DataFrame : try : path_init_x = Path ( path_init ) . expanduser ( ) . resolve ( ) except FileNotFoundError : print ( '{path} does not exists!' . format ( path = path_init_x ) ) else : if path_init_x . suffix == '.nml' : df_state_init = load_InitialCond_grid_df ( path_init_x ) e... | Initialise supy by loading initial model states . |
20,676 | def load_SampleData ( ) -> Tuple [ pandas . DataFrame , pandas . DataFrame ] : path_SampleData = Path ( path_supy_module ) / 'sample_run' path_runcontrol = path_SampleData / 'RunControl.nml' df_state_init = init_supy ( path_runcontrol ) df_forcing = load_forcing_grid ( path_runcontrol , df_state_init . index [ 0 ] ) re... | Load sample data for quickly starting a demo run . |
20,677 | def save_supy ( df_output : pandas . DataFrame , df_state_final : pandas . DataFrame , freq_s : int = 3600 , site : str = '' , path_dir_save : str = Path ( '.' ) , path_runcontrol : str = None , ) -> list : if path_runcontrol is not None : freq_s , path_dir_save , site = get_save_info ( path_runcontrol ) list_path_save... | Save SuPy run results to files |
20,678 | def load_df_state ( path_csv : Path ) -> pd . DataFrame : df_state = pd . read_csv ( path_csv , header = [ 0 , 1 ] , index_col = [ 0 , 1 ] , parse_dates = True , infer_datetime_format = True , ) return df_state | load df_state from path_csv |
20,679 | def extract_var_suews ( dict_var_full : dict , var_supy : str ) -> list : x = sp . supy_load . flatten_list ( dict_var_full [ var_supy ] ) x = np . unique ( x ) x = [ xx for xx in x if xx not in [ 'base' , 'const' , '0.0' ] + [ str ( x ) for x in range ( 24 ) ] ] x = [ xx for xx in x if 'Code' not in xx ] return x | extract related SUEWS variables for a supy variable var_supy |
20,680 | def gen_df_site ( list_csv_in = list_table , url_base = url_repo_input_site ) -> pd . DataFrame : list_url_table = [ url_base / table for table in list_csv_in ] try : df_var_info = pd . concat ( [ pd . read_csv ( f ) for f in list_url_table ] ) except : for url in list_url_table : if not url . get ( ) . ok : print ( f'... | Generate description info of supy output results as a dataframe |
20,681 | def gen_rst_url_split_opts ( opts_str ) : if opts_str is not 'None' : list_opts = opts_str . split ( ',' ) list_rst = [ opt . strip ( ) for opt in list_opts ] list_rst = [ f':option:`{opt} <suews:{opt}>`' for opt in list_rst ] list_url_rst = ', ' . join ( list_rst ) else : list_url_rst = 'None' return list_url_rst | generate option list for RST docs |
20,682 | def gen_df_state ( list_table : list , set_initcond : set , set_runcontrol : set , set_input_runcontrol : set ) -> pd . DataFrame : df_var_site = gen_df_site ( list_table ) df_var_runcontrol = gen_df_runcontrol ( set_initcond , set_runcontrol , set_input_runcontrol ) df_var_initcond = gen_df_initcond ( set_initcond , s... | generate dataframe of all state variables used by supy |
20,683 | def gen_df_save ( df_grid_group : pd . DataFrame ) -> pd . DataFrame : idx_dt = df_grid_group . index ser_year = pd . Series ( idx_dt . year , index = idx_dt , name = 'Year' ) ser_DOY = pd . Series ( idx_dt . dayofyear , index = idx_dt , name = 'DOY' ) ser_hour = pd . Series ( idx_dt . hour , index = idx_dt , name = 'H... | generate a dataframe for saving |
20,684 | def save_df_output ( df_output : pd . DataFrame , freq_s : int = 3600 , site : str = '' , path_dir_save : Path = Path ( '.' ) , ) -> list : list_path_save = [ ] list_group = df_output . columns . get_level_values ( 'group' ) . unique ( ) list_grid = df_output . index . get_level_values ( 'grid' ) . unique ( ) for grid ... | save supy output dataframe to txt files |
20,685 | def save_df_state ( df_state : pd . DataFrame , site : str = '' , path_dir_save : Path = Path ( '.' ) , ) -> Path : file_state_save = 'df_state_{site}.csv' . format ( site = site ) file_state_save = file_state_save . replace ( '_.csv' , '.csv' ) path_state_save = path_dir_save / file_state_save print ( 'writing out: {p... | save df_state to a csv file |
20,686 | def gen_FS_DF ( df_output ) : df_day = pd . pivot_table ( df_output , values = [ 'T2' , 'U10' , 'Kdown' , 'RH2' ] , index = [ 'Year' , 'Month' , 'Day' ] , aggfunc = [ min , max , np . mean , ] ) df_day_all_year = pd . pivot_table ( df_output , values = [ 'T2' , 'U10' , 'Kdown' , 'RH2' ] , index = [ 'Month' , 'Day' ] , ... | generate DataFrame of scores . |
20,687 | def gen_WS_DF ( df_WS_data ) : df_fs = gen_FS_DF ( df_WS_data ) list_index = [ ( 'mean' , 'T2' ) , ( 'max' , 'T2' ) , ( 'min' , 'T2' ) , ( 'mean' , 'U10' ) , ( 'max' , 'U10' ) , ( 'min' , 'U10' ) , ( 'mean' , 'RH2' ) , ( 'max' , 'RH2' ) , ( 'min' , 'RH2' ) , ( 'mean' , 'Kdown' ) ] list_const = [ getattr ( const , attr ... | generate DataFrame of weighted sums . |
20,688 | def _geoid_radius ( latitude : float ) -> float : lat = deg2rad ( latitude ) return sqrt ( 1 / ( cos ( lat ) ** 2 / Rmax_WGS84 ** 2 + sin ( lat ) ** 2 / Rmin_WGS84 ** 2 ) ) | Calculates the GEOID radius at a given latitude |
20,689 | def geometric2geopotential ( z : float , latitude : float ) -> float : twolat = deg2rad ( 2 * latitude ) g = 9.80616 * ( 1 - 0.002637 * cos ( twolat ) + 0.0000059 * cos ( twolat ) ** 2 ) re = _geoid_radius ( latitude ) return z * g * re / ( re + z ) | Converts geometric height to geopoential height |
20,690 | def geopotential2geometric ( h : float , latitude : float ) -> float : twolat = deg2rad ( 2 * latitude ) g = 9.80616 * ( 1 - 0.002637 * cos ( twolat ) + 0.0000059 * cos ( twolat ) ** 2 ) re = _geoid_radius ( latitude ) return h * re / ( g * re - h ) | Converts geopoential height to geometric height |
20,691 | def get_ser_val_alt ( lat : float , lon : float , da_alt_x : xr . DataArray , da_alt : xr . DataArray , da_val : xr . DataArray ) -> pd . Series : alt_t_1d = da_alt . sel ( latitude = lat , longitude = lon , method = 'nearest' ) val_t_1d = da_val . sel ( latitude = lat , longitude = lon , method = 'nearest' ) alt_x = d... | interpolate atmospheric variable to a specified altitude |
20,692 | def get_df_val_alt ( lat : float , lon : float , da_alt_meas : xr . DataArray , ds_val : xr . Dataset ) : da_alt = geopotential2geometric ( ds_val . z , ds_val . latitude ) da_alt_x = da_alt . sel ( latitude = lat , longitude = lon , method = 'nearest' ) alt_meas_x = da_alt_meas . sel ( latitude = lat , longitude = lon... | interpolate atmospheric variables to a specified altitude |
20,693 | def sel_list_pres ( ds_sfc_x ) : p_min , p_max = ds_sfc_x . sp . min ( ) . values , ds_sfc_x . sp . max ( ) . values list_pres_level = [ '1' , '2' , '3' , '5' , '7' , '10' , '20' , '30' , '50' , '70' , '100' , '125' , '150' , '175' , '200' , '225' , '250' , '300' , '350' , '400' , '450' , '500' , '550' , '600' , '650' ... | select proper levels for model level data download |
20,694 | def load_world ( filename ) : import ecell4_base vinfo = ecell4_base . core . load_version_information ( filename ) if vinfo . startswith ( "ecell4-bd" ) : return ecell4_base . bd . World ( filename ) elif vinfo . startswith ( "ecell4-egfrd" ) : return ecell4_base . egfrd . World ( filename ) elif vinfo . startswith ( ... | Load a world from the given HDF5 filename . The return type is determined by ecell4_base . core . load_version_information . |
20,695 | def show ( target , * args , ** kwargs ) : if isinstance ( target , ( ecell4_base . core . FixedIntervalNumberObserver , ecell4_base . core . NumberObserver , ecell4_base . core . TimingNumberObserver , ) ) : plot_number_observer ( target , * args , ** kwargs ) elif isinstance ( target , ( ecell4_base . core . FixedInt... | An utility function to display the given target object in the proper way . |
20,696 | def print_batch_exception ( batch_exception ) : _log . error ( '-------------------------------------------' ) _log . error ( 'Exception encountered:' ) if batch_exception . error and batch_exception . error . message and batch_exception . error . message . value : _log . error ( batch_exception . error . message . val... | Prints the contents of the specified Batch exception . |
20,697 | def upload_file_to_container ( block_blob_client , container_name , file_path ) : blob_name = os . path . basename ( file_path ) _log . info ( 'Uploading file {} to container [{}]...' . format ( file_path , container_name ) ) block_blob_client . create_blob_from_path ( container_name , blob_name , file_path ) sas_token... | Uploads a local file to an Azure Blob storage container . |
20,698 | def get_container_sas_token ( block_blob_client , container_name , blob_permissions ) : container_sas_token = block_blob_client . generate_container_shared_access_signature ( container_name , permission = blob_permissions , expiry = datetime . datetime . utcnow ( ) + datetime . timedelta ( hours = 2 ) ) return containe... | Obtains a shared access signature granting the specified permissions to the container . |
20,699 | def create_pool ( batch_service_client , pool_id , resource_files , publisher , offer , sku , task_file , vm_size , node_count ) : _log . info ( 'Creating pool [{}]...' . format ( pool_id ) ) task_commands = [ 'cp -p {} $AZ_BATCH_NODE_SHARED_DIR' . format ( os . path . basename ( task_file ) ) , 'curl -fSsL https://boo... | Creates a pool of compute nodes with the specified OS settings . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.