text
stringlengths
81
112k
Equivalent to inserting a new item followed by removing the top priority item, but faster. Raises ``KeyError`` if the new key is already in the pqdict. def pushpopitem(self, key, value, node_factory=_Node): """ Equivalent to inserting a new item followed by removing the top prio...
Update the priority value of an existing item. Raises ``KeyError`` if key is not in the pqdict. def updateitem(self, key, new_val): """ Update the priority value of an existing item. Raises ``KeyError`` if key is not in the pqdict. """ if key not in self._position: ...
Replace the key of an existing heap node in place. Raises ``KeyError`` if the key to replace does not exist or if the new key is already in the pqdict. def replace_key(self, key, new_key): """ Replace the key of an existing heap node in place. Raises ``KeyError`` if the key to r...
Fast way to swap the priority level of two items in the pqdict. Raises ``KeyError`` if either key does not exist. def swap_priority(self, key1, key2): """ Fast way to swap the priority level of two items in the pqdict. Raises ``KeyError`` if either key does not exist. """ ...
Repair a broken heap. If the state of an item's priority value changes you can re-sort the relevant item only by providing ``key``. def heapify(self, key=__marker): """ Repair a broken heap. If the state of an item's priority value changes you can re-sort the relevant item only by provi...
Check to make sure _version.py is contained in the package def package_has_version_file(package_name): """ Check to make sure _version.py is contained in the package """ version_file_path = helpers.package_file_path('_version.py', package_name) return os.path.isfile(version_file_path)
Grab the project name out of setup.py def get_project_name(): """ Grab the project name out of setup.py """ setup_py_content = helpers.get_file_content('setup.py') ret = helpers.value_of_named_argument_in_function( 'name', 'setup', setup_py_content, resolve_varname=True ) if ret and ret[0] ...
Get the version which is currently configured by the package def get_version(package_name, ignore_cache=False): """ Get the version which is currently configured by the package """ if ignore_cache: with microcache.temporarily_disabled(): found = helpers.regex_in_package_file( ...
Set the version in _version.py to version_str def set_version(package_name, version_str): """ Set the version in _version.py to version_str """ current_version = get_version(package_name) version_file_path = helpers.package_file_path('_version.py', package_name) version_file_content = helpers.get_file_...
Check to see if the version specified is a valid as far as pkg_resources is concerned >>> version_is_valid('blah') False >>> version_is_valid('1.2.3') True def version_is_valid(version_str): """ Check to see if the version specified is a valid as far as pkg_resources is concerned >>> version_...
Query the pypi index at index_url using warehouse api to find all of the "releases" def _get_uploaded_versions_warehouse(project_name, index_url, requests_verify=True): """ Query the pypi index at index_url using warehouse api to find all of the "releases" """ url = '/'.join((index_url, project_name, 'json')) ...
Query the pypi index at index_url using pypicloud api to find all versions def _get_uploaded_versions_pypicloud(project_name, index_url, requests_verify=True): """ Query the pypi index at index_url using pypicloud api to find all versions """ api_url = index_url for suffix in ('/pypi', '/pypi/', '/simple',...
Check to see if the version specified has already been uploaded to the configured index def version_already_uploaded(project_name, version_str, index_url, requests_verify=True): """ Check to see if the version specified has already been uploaded to the configured index """ all_versions = _get_uploaded_vers...
Attempt to convert a README.md file into README.rst def convert_readme_to_rst(): """ Attempt to convert a README.md file into README.rst """ project_files = os.listdir('.') for filename in project_files: if filename.lower() == 'readme': raise ProjectError( 'found {} in p...
Collect relative paths to all files which have already been packaged def get_packaged_files(package_name): """ Collect relative paths to all files which have already been packaged """ if not os.path.isdir('dist'): return [] return [os.path.join('dist', filename) for filename in os.listdir('dist')]
Look through built package directory and see if there are multiple versions there def multiple_packaged_versions(package_name): """ Look through built package directory and see if there are multiple versions there """ dist_files = os.listdir('dist') versions = set() for filename in dist_files: ...
Calculate the neighborhood probability over the full period of the forecast Args: radius: circular radius from each point in km smoothing: width of Gaussian smoother in km threshold: intensity of exceedance stride: number of grid points to skip for reduced neighb...
Constrói uma :class:`RespostaSAT` ou especialização dependendo da função SAT encontrada na sessão consultada. :param unicode retorno: Retorno da função ``ConsultarNumeroSessao``. def analisar(retorno): """Constrói uma :class:`RespostaSAT` ou especialização dependendo da função SAT enco...
Analisa o retorno (supostamente um retorno de uma função do SAT) conforme o padrão e campos esperados. O retorno deverá possuir dados separados entre si através de pipes e o número de campos deverá coincidir com os campos especificados. O campos devem ser especificados como uma tupla onde cada elemento...
Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.comunicar_certificado_icpbrasil`. def comunicar_certificado_icpbrasil(retorno): """Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.comunicar_ce...
Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.consultar_sat`. def consultar_sat(retorno): """Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.consultar_sat`. """ resposta = a...
Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.configurar_interface_de_rede`. def configurar_interface_de_rede(retorno): """Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.configurar_interfa...
Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.associar_assinatura`. def associar_assinatura(retorno): """Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.associar_assinatura`. """ ...
Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.atualizar_software_sat`. def atualizar_software_sat(retorno): """Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.atualizar_software_sat`. ...
Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.bloquear_sat`. def bloquear_sat(retorno): """Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.bloquear_sat`. """ resposta = anal...
Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.desbloquear_sat`. def desbloquear_sat(retorno): """Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.desbloquear_sat`. """ respos...
Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.trocar_codigo_de_ativacao`. def trocar_codigo_de_ativacao(retorno): """Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.trocar_codigo_de_ativaca...
Load the specified variable from the ensemble files, then close the files. def load_data(self): """ Load the specified variable from the ensemble files, then close the files. """ if self.ensemble_name.upper() == "SSEF": if self.variable[0:2] == "rh": pressure...
Load map projection information and create latitude, longitude, x, y, i, and j grids for the projection. Args: map_file: File specifying the projection information. def load_map_info(self, map_file): """ Load map projection information and create latitude, longitude, x, y, i, and j...
Reads a geojson file containing an STObject and initializes a new STObject from the information in the file. Args: filename: Name of the geojson file Returns: an STObject def read_geojson(filename): """ Reads a geojson file containing an STObject and initializes a new STObject from th...
Calculate the center of mass at a given timestep. Args: time: Time at which the center of mass calculation is performed Returns: The x- and y-coordinates of the center of mass. def center_of_mass(self, time): """ Calculate the center of mass at a given timestep...
Calculates the center of mass for each time step and outputs an array Returns: def trajectory(self): """ Calculates the center of mass for each time step and outputs an array Returns: """ traj = np.zeros((2, self.times.size)) for t, time in enumerate(self.time...
Gets the corner array indices of the STObject at a given time that corresponds to the upper left corner of the bounding box for the STObject. Args: time: time at which the corner is being extracted. Returns: corner index. def get_corner(self, time): """ ...
Gets the size of the object at a given time. Args: time: Time value being queried. Returns: size of the object in pixels def size(self, time): """ Gets the size of the object at a given time. Args: time: Time value being queried. R...
Gets the largest size of the object over all timesteps. Returns: Maximum size of the object in pixels def max_size(self): """ Gets the largest size of the object over all timesteps. Returns: Maximum size of the object in pixels """ ...
Calculate the maximum intensity found at a timestep. def max_intensity(self, time): """ Calculate the maximum intensity found at a timestep. """ ti = np.where(time == self.times)[0][0] return self.timesteps[ti].max()
Adds the data from another STObject to this object. Args: step: another STObject being added after the current one in time. def extend(self, step): """ Adds the data from another STObject to this object. Args: step: another STObject being added ...
Get coordinates of object boundary in counter-clockwise order def boundary_polygon(self, time): """ Get coordinates of object boundary in counter-clockwise order """ ti = np.where(time == self.times)[0][0] com_x, com_y = self.center_of_mass(time) # If at least one point ...
Estimate the motion of the object with cross-correlation on the intensity values from the previous time step. Args: time: time being evaluated. intensity_grid: 2D array of intensities used in cross correlation. max_u: Maximum x-component of motion. Used to limit search area....
Counts the number of points that overlap between this STObject and another STObject. Used for tracking. def count_overlap(self, time, other_object, other_time): """ Counts the number of points that overlap between this STObject and another STObject. Used for tracking. """ ti = np.where(...
Extracts the data from a ModelOutput or ModelGrid object within the bounding box region of the STObject. Args: model_grid: A ModelGrid or ModelOutput Object potential: Extracts from the time before instead of the same time as the object def extract_attribute_grid(self, model_gr...
Extracts data from a 2D array that has the same dimensions as the grid used to identify the object. Args: data_array: 2D numpy array def extract_attribute_array(self, data_array, var_name): """ Extracts data from a 2D array that has the same dimensions as the grid used to identify ...
Extracts the difference in model outputs Args: model_grid: ModelOutput or ModelGrid object. def extract_tendency_grid(self, model_grid): """ Extracts the difference in model outputs Args: model_grid: ModelOutput or ModelGrid object. """ var_nam...
Calculates summary statistics over the domains of each attribute. Args: statistic_name (string): numpy statistic, such as mean, std, max, min Returns: dict of statistics from each attribute grid. def calc_attribute_statistics(self, statistic_name): """ ...
Calculate statistics based on the values of an attribute. The following statistics are supported: mean, max, min, std, ptp (range), median, skew (mean - median), and percentile_(percentile value). Args: attribute: Attribute extracted from model grid statistic: Name of statistic ...
Calculate statistics from the primary attribute of the StObject. Args: statistic: statistic being calculated time: Timestep being investigated Returns: Value of the statistic def calc_timestep_statistic(self, statistic, time): """ Calculate statisti...
Calculate shape statistics using regionprops applied to the object mask. Args: stat_names: List of statistics to be extracted from those calculated by regionprops. Returns: Dictionary of shape statistics def calc_shape_statistics(self, stat_names): """ ...
Calculate shape statistics for a single time step Args: stat_names: List of shape statistics calculated from region props time: Time being investigated Returns: List of shape statistics def calc_shape_step(self, stat_names, time): """ Calculate shap...
Output the data in the STObject to a geoJSON file. Args: filename: Name of the file proj: PyProj object for converting the x and y coordinates back to latitude and longitue values. metadata: Metadata describing the object to be included in the top-level properties. def to_g...
Set the properties and write to disk. def rewrite_properties(self, properties): """Set the properties and write to disk.""" with self.__library_storage_lock: self.__library_storage = properties self.__write_properties(None)
Returns the model of node v def model(self, v=None): "Returns the model of node v" if v is None: v = self.estopping hist = self.hist trace = self.trace(v) ins = None if self._base._probability_calibration is not None: node = hist[-1] n...
Restore the position in the history of individual v's nodes def trace(self, n): "Restore the position in the history of individual v's nodes" trace_map = {} self._trace(n, trace_map) s = list(trace_map.keys()) s.sort() return s
Tournament selection and when negative is True it performs negative tournament selection def tournament(self, negative=False): """Tournament selection and when negative is True it performs negative tournament selection""" if self.generation <= self._random_generations and not negative: ...
Create the initial population def create_population(self): "Create the initial population" base = self._base if base._share_inputs: used_inputs_var = SelectNumbers([x for x in range(base.nvar)]) used_inputs_naive = used_inputs_var if base._pr_variable == 0: ...
Add an individual to the population def add(self, v): "Add an individual to the population" self.population.append(v) self._current_popsize += 1 v.position = len(self._hist) self._hist.append(v) self.bsf = v self.estopping = v self._density += self.get_de...
Replace an individual selected by negative tournament selection with individual v def replace(self, v): """Replace an individual selected by negative tournament selection with individual v""" if self.popsize < self._popsize: return self.add(v) k = self.tournament(neg...
Make the directory path, if needed. def make_directory_if_needed(directory_path): """ Make the directory path, if needed. """ if os.path.exists(directory_path): if not os.path.isdir(directory_path): raise OSError("Path is not a directory:", directory_path) else: os.m...
Main entry point for the hatchery program def hatchery(): """ Main entry point for the hatchery program """ args = docopt.docopt(__doc__) task_list = args['<task>'] if not task_list or 'help' in task_list or args['--help']: print(__doc__.format(version=_version.__version__, config_files=config...
Call an arbitary command and return the exit value, stdout, and stderr as a tuple Command can be passed in as either a string or iterable >>> result = call('hatchery', suppress_output=True) >>> result.exitval 0 >>> result = call(['hatchery', 'notreal']) >>> result.exitval 1 def call(cmd_a...
Call a setup.py command or list of commands >>> result = setup('--name', suppress_output=True) >>> result.exitval 0 >>> result = setup('notreal') >>> result.exitval 1 def setup(cmd_args, suppress_output=False): """ Call a setup.py command or list of commands >>> result = setup('--name...
Loads data files and stores the output in the data attribute. def load_data(self): """ Loads data files and stores the output in the data attribute. """ data = [] valid_dates = [] mrms_files = np.array(sorted(os.listdir(self.path + self.variable + "/"))) mrms_fil...
Rescale your input data so that is ranges over integer values, which will perform better in the watershed. Args: data: 2D or 3D ndarray being rescaled data_min: minimum value of input data for scaling purposes data_max: maximum value of input data for scaling purposes out_min: minim...
Labels input grid using enhanced watershed algorithm. Args: input_grid (numpy.ndarray): Grid to be labeled. Returns: Array of labeled pixels def label(self, input_grid): """ Labels input grid using enhanced watershed algorithm. Args: input_...
Finds the local maxima in the inputGrid and perform region growing to identify objects. Args: input_grid: Raw input data. Returns: array with labeled objects. def find_local_maxima(self, input_grid): """ Finds the local maxima in the inputGrid and perform regio...
Grow a region at a certain bin level and check if the region has reached the maximum size. Args: q_data: Quantized data array marked: Array marking points that are objects center: Coordinates of the center pixel of the region being grown bin_lower: Intensity leve...
Mark points determined to be foothills as globbed, so that they are not included in future searches. Also searches neighboring points to foothill points to determine if they should also be considered foothills. Args: q_data: Quantized data marked: Marked bin_...
Quantize a grid into discrete steps based on input parameters. Args: input_grid: 2-d array of values Returns: Dictionary of value pointing to pixel locations, and quantized 2-d array of data def quantize(self, input_grid): """ Quantize a grid into discrete step...
will display all the filenames. Result can be stored in an array for easy fetching of gistNames for future purposes. eg. a = Gist().mygists().listall() print a[0] #to fetch first gistName def listall(self): ''' will display all the filenames. Result can be stored in an array for easy fetching of gist...
Doesn't require manual fetching of gistID of a gist passing gistName will return the content of gist. In case, names are ambigious, provide GistID or it will return the contents of recent ambigious gistname def content(self, **args): ''' Doesn't require manual fetching of gistID of a gist passing gistName ...
Doesn't require manual fetching of gistID of a gist passing gistName will return edit the gist def edit(self, **args): ''' Doesn't require manual fetching of gistID of a gist passing gistName will return edit the gist ''' self.gist_name = '' if 'description' in args: self.description = args['descripti...
Delete a gist by gistname/gistID def delete(self, **args): ''' Delete a gist by gistname/gistID ''' if 'name' in args: self.gist_name = args['name'] self.gist_id = self.getMyID(self.gist_name) elif 'id' in args: self.gist_id = args['id'] else: raise Exception('Provide GistName to delete') u...
List the authenticated user's starred gists def starred(self, **args): ''' List the authenticated user's starred gists ''' ids =[] r = requests.get( '%s/gists/starred'%BASE_URL, headers=self.gist.header ) if 'limit' in args: limit = args['limit'] else: limit = len(r.json()) if (r.statu...
Return Gist URL-Link, Clone-Link and Script-Link to embed def links(self,**args): ''' Return Gist URL-Link, Clone-Link and Script-Link to embed ''' if 'name' in args: self.gist_name = args['name'] self.gist_id = self.getMyID(self.gist_name) elif 'id' in args: self.gist_id = args['id'] else: rai...
Load neighborhood probability forecasts. def load_forecasts(self): """ Load neighborhood probability forecasts. """ run_date_str = self.run_date.strftime("%Y%m%d") forecast_file = self.forecast_path + "{0}/{1}_{2}_{3}_consensus_{0}.nc".format(run_date_str, ...
Loads observations and masking grid (if needed). Args: mask_threshold: Values greater than the threshold are kept, others are masked. def load_obs(self, mask_threshold=0.5): """ Loads observations and masking grid (if needed). Args: mask_threshold: Values grea...
Loads lat-lon coordinates from a netCDF file. def load_coordinates(self): """ Loads lat-lon coordinates from a netCDF file. """ coord_file = Dataset(self.coordinate_file) if "lon" in coord_file.variables.keys(): self.coordinates["lon"] = coord_file.variables["lon"][:...
Calculates ROC curves and Reliability scores for each forecast hour. Returns: A pandas DataFrame containing forecast metadata as well as DistributedROC and Reliability objects. def evaluate_hourly_forecasts(self): """ Calculates ROC curves and Reliability scores for each forecast h...
Evaluates ROC and Reliability scores for forecasts over the full period from start hour to end hour Returns: A pandas DataFrame with full-period metadata and verification statistics def evaluate_period_forecasts(self): """ Evaluates ROC and Reliability scores for forecasts over the...
Main function explicitly called from the C++ code. Return the main application object. def bootstrap_main(args): """ Main function explicitly called from the C++ code. Return the main application object. """ version_info = sys.version_info if version_info.major != 3 or version_info.minor < ...
Migrate library to latest version. def _migrate_library(workspace_dir: pathlib.Path, do_logging: bool=True) -> pathlib.Path: """ Migrate library to latest version. """ library_path_11 = workspace_dir / "Nion Swift Workspace.nslib" library_path_12 = workspace_dir / "Nion Swift Library 12.nslib" library...
Nome amigável do campo ``ESTADO_OPERACAO``, conforme a "Tabela de Informações do Status do SAT". def status(self): """Nome amigável do campo ``ESTADO_OPERACAO``, conforme a "Tabela de Informações do Status do SAT". """ for valor, rotulo in ESTADOS_OPERACAO: if self.E...
Constrói uma :class:`RespostaConsultarStatusOperacional` a partir do retorno informado. :param unicode retorno: Retorno da função ``ConsultarStatusOperacional``. def analisar(retorno): """Constrói uma :class:`RespostaConsultarStatusOperacional` a partir do retorno informado. :...
Reads forecasts from json files and merges them with the input data from the step csv files. Args: input_csv_file: Name of the input data csv file being processed forecast_json_path: Path to the forecast json files toplevel directory condition_models: List of models used to forecast hail or...
Called from item to indicate its data or metadata has changed. def mark_data_dirty(self): """ Called from item to indicate its data or metadata has changed.""" self.__cache.set_cached_value_dirty(self.__display_item, self.__cache_property_name) self.__initialize_cache() self.__cached_va...
Initialize the cache values (cache values are used for optimization). def __initialize_cache(self): """Initialize the cache values (cache values are used for optimization).""" if self.__cached_value_dirty is None: self.__cached_value_dirty = self.__cache.is_cached_value_dirty(self.__display...
Recompute the data on a thread, if necessary. If the data has recently been computed, this call will be rescheduled for the future. If the data is currently being computed, it do nothing. def recompute_if_necessary(self, ui): """Recompute the data on a thread, if necessary. If the da...
Compute the data associated with this processor. This method is thread safe and may take a long time to return. It should not be called from the UI thread. Upon return, the results will be calculated with the latest data available and the cache will not be marked dirty. def recompute_data(se...
Returned ThumbnailSource must be closed. def thumbnail_source_for_display_item(self, ui, display_item: DisplayItem.DisplayItem) -> ThumbnailSource: """Returned ThumbnailSource must be closed.""" with self.__lock: thumbnail_source = self.__thumbnail_sources.get(display_item) if n...
Load plug-ins. def load_plug_ins(app, root_dir): """Load plug-ins.""" global extensions ui = app.ui # a list of directories in which sub-directories PlugIns will be searched. subdirectories = [] # the default location is where the directory main packages are located. if root_dir: ...
Getting gistID of a gist in order to make the workflow easy and uninterrupted. def getMyID(self,gist_name): ''' Getting gistID of a gist in order to make the workflow easy and uninterrupted. ''' r = requests.get( '%s'%BASE_URL+'/users/%s/gists' % self.user, headers=self.gist.header ) if (r.statu...
Close the document controller. This method must be called to shut down the document controller. There are several paths by which it can be called, though. * User quits application via menu item. The menu item will call back to Application.exit which will close each document con...
Add a listener function and return listener token. Token can be closed or deleted to unlisten. def add_periodic(self, interval: float, listener_fn): """Add a listener function and return listener token. Token can be closed or deleted to unlisten.""" class PeriodicListener: def __init__(self...
Update the data item model with a new container, filter, and sorting. This is called when the data item model is created or when the user changes the data group or sorting settings. def __update_display_items_model(self, display_items_model: ListModel.FilteredListModel, data_group: typing.Optional[Dat...
Return the data item with keyboard focus. def focused_data_item(self) -> typing.Optional[DataItem.DataItem]: """Return the data item with keyboard focus.""" return self.__focused_display_item.data_item if self.__focused_display_item else None
Return the selected display item. The selected display is the display ite that has keyboard focus in the data panel or a display panel. def selected_display_item(self) -> typing.Optional[DisplayItem.DisplayItem]: """Return the selected display item. The selected display is the display ite tha...
Get two sensible data sources, which may be the same. def _get_two_data_sources(self): """Get two sensible data sources, which may be the same.""" selected_display_items = self.selected_display_items if len(selected_display_items) < 2: selected_display_items = list() dis...
Calculate origin and size for canvas size, data shape, and image display parameters. def calculate_origin_and_size(canvas_size, data_shape, image_canvas_mode, image_zoom, image_position) -> typing.Tuple[typing.Any, typing.Any]: """Calculate origin and size for canvas size, data shape, and image display parameters....
Read data items from the data reference handler and return as a list. Data items will have persistent_object_context set upon return, but caller will need to call finish_reading on each of the data items. def read_library(persistent_storage_system, ignore_older_files) -> typing.Dict: """Read data items fr...
Migrate items from the storage system to the object context. Files in data_item_uuids have already been loaded and are ignored (not migrated). Files in deletes have been deleted in object context and are ignored (not migrated) and then added to the utilized deletions list. Data items will have persis...
Set the properties and write to disk. def rewrite_properties(self, properties): """Set the properties and write to disk.""" with self.__properties_lock: self.__properties = properties self.__write_properties(None)