text
stringlengths
81
112k
Get a text representation of the criteria node. :param sep: Separator used to indent the contents of the node. :param params: Boolean, set to True in order to display node parameters. :return: def criteria_text(self, sep=' ', params=False): """ Get a text representation of the...
Get the text for a given Indicator or IndicatorItem node. This does walk an IndicatorItem node to get its children text as well. :param node: Node to get the text for. :param depth: Track the number of recursions that have occured, modifies the indentation. :param sep: Seperator used fo...
Get the text for an Indicator node. :param node: Indicator node. :return: def get_i_text(node): """ Get the text for an Indicator node. :param node: Indicator node. :return: """ if node.tag != 'Indicator': raise IOCParseError('Invalid tag: {...
Get the text for IndicatorItem node. :param node: IndicatorItem node. :return: def get_ii_text(node): """ Get the text for IndicatorItem node. :param node: IndicatorItem node. :return: """ if node.tag != 'IndicatorItem': raise IOCParseError(...
Get a list of parameters as text values for a given node id. :param nid: id to look for. :return: def get_param_text(self, nid): """ Get a list of parameters as text values for a given node id. :param nid: id to look for. :return: """ r = [] par...
Use et to read in a xml file, or string, into a Element object. :param filename: File to parse. :return: lxml._elementTree object or None def read_xml(filename): """ Use et to read in a xml file, or string, into a Element object. :param filename: File to parse. :return: lxml._elementTree obje...
Takes in a ElementTree object and namespace value. The length of that namespace value is removed from all Element nodes within the document. This effectively removes the namespace from that document. :param doc: lxml.etree :param namespace: Namespace that needs to be removed. :return: Returns the ...
Identifies the namespace associated with the root node of a XML document and removes that names from the document. :param parsed_xml: lxml.Etree object. :return: Returns the sources document with the namespace removed. def delete_namespace(parsed_xml): """ Identifies the namespace associated with ...
Parses files to load them into memory and insert them into the class. :param filename: File or directory pointing to .ioc files. :return: A list of .ioc files which could not be parsed. def insert(self, filename): """ Parses files to load them into memory and insert them into the class...
Parses a file into a lxml.etree structure with namespaces remove. This tree is added to self.iocs. :param fn: File to parse. :return: def parse(self, fn): """ Parses a file into a lxml.etree structure with namespaces remove. This tree is added to self.iocs. :param fn: File t...
converts the iocs in self.iocs from openioc 1.0 to openioc 1.1 format. the converted iocs are stored in the dictionary self.iocs_11 def convert_to_11(self): """ converts the iocs in self.iocs from openioc 1.0 to openioc 1.1 format. the converted iocs are stored in the dictionary self.io...
recursively walk a indicator logic tree, starting from a Indicator node. converts OpenIOC 1.0 Indicator/IndicatorItems to Openioc 1.1 and preserves order. :param old_node: Indicator node, which we walk down to convert :param new_node: Indicator node, which we add new IndicatorItem and Indicator...
Parses files to load them into memory and insert them into the class. :param filename: File or directory pointing to .ioc files. :return: A list of .ioc files which could not be parsed. def insert(self, filename): """ Parses files to load them into memory and insert them into the class...
parses an ioc to populate self.iocs and self.ioc_name :param ioc_obj: :return: def parse(self, ioc_obj): """ parses an ioc to populate self.iocs and self.ioc_name :param ioc_obj: :return: """ if ioc_obj is None: return iocid = ioc_ob...
Register a callback function that is called after self.iocs and self.ioc_name is populated. This is intended for use by subclasses that may have additional parsing requirements. :param func: A callable function. This should accept a single input, which will be an IOC class. :return: def reg...
Create single permission for the given object. :param Permission permission: A single Permission object to be set. def create(self, permission): """ Create single permission for the given object. :param Permission permission: A single Permission object to be set. """ p...
Set the object permissions. If the parent object already has permissions, they will be overwritten. :param [] permissions: A group of Permission objects to be set. def set(self, permissions): """ Set the object permissions. If the parent object already has permissions, they will be overwritten...
List permissions for the given object. def list(self): """ List permissions for the given object. """ parent_url = self.client.get_url(self.parent_object._manager._URL_KEY, 'GET', 'single', {'id': self.parent_object.id}) target_url = parent_url + self.client.get_url_path(self._U...
List a specific permisison for the given object. :param str permission_id: the id of the Permission to be listed. def get(self, permission_id, expand=[]): """ List a specific permisison for the given object. :param str permission_id: the id of the Permission to be listed. """ ...
Read the configfile and return config dict. Returns ------- dict Dictionary with the content of the configpath file. def get_config(): """Read the configfile and return config dict. Returns ------- dict Dictionary with the content of the configpath file. """ config...
Use to write the database path into the config. Parameters ---------- dbfolder : str or pathlib.Path Path to where pyciss will store the ISS images it downloads and receives. def set_database_path(dbfolder): """Use to write the database path into the config. Parameters ---------- ...
Read dbroot folder from config and mkdir if required. def get_db_root(): "Read dbroot folder from config and mkdir if required." d = get_config() dbroot = Path(d['pyciss_db']['path']) dbroot.mkdir(exist_ok=True) return dbroot
Print database stats. Returns ------- pd.DataFrame Table with the found data items per type. def print_db_stats(): """Print database stats. Returns ------- pd.DataFrame Table with the found data items per type. """ dbroot = get_db_root() n_ids = len(list(dbroot...
Check Label file for the compression type. def is_lossy(label): """Check Label file for the compression type. """ val = getkey(from_=label, keyword='INST_CMPRS_TYPE').decode().strip() if val == 'LOSSY': return True else: return False
Download and calibrate in parallel. Parameters ---------- list_of_ids : list, optional container with img_ids to process n : int Number of cores for the parallel processing. Default: n_cores_system//2 def download_and_calibrate_parallel(list_of_ids, n=None): """Download and calibra...
Download and calibrate one or more image ids, in parallel. Parameters ---------- img_id : str or io.PathManager, optional If more than one item is in img_id, a parallel process is started overwrite: bool, optional If the pm.cubepath exists, this switch controls if it is being overwritte...
Perform either normal spiceinit or one for ringdata. Note how Python name-spacing can distinguish between the method and the function with the same name. `spiceinit` from the outer namespace is the one imported from pysis. def spiceinit(self): """Perform either normal spiceinit or one ...
Check label for target and fix if necessary. Forcing the target name to Saturn here, because some observations of the rings have moons as a target, but then the standard map projection onto the Saturn ring plane fails. See also -------- https://isis.astrogeology.usgs.go...
Checks and sets the supported content types configuration value. def _set_supported_content_type(self, content_types_supported): """ Checks and sets the supported content types configuration value. """ if not isinstance(content_types_supported, list): raise TypeError(("Settings 'REA...
Checks and sets the per language WPM, singular and plural values. def _set_lang_settings(self, lang_settings): """ Checks and sets the per language WPM, singular and plural values. """ is_int = isinstance(lang_settings, int) is_dict = isinstance(lang_settings, dict) if not is_in...
Initializes ReadTimeParser with configuration values set by the site author. def initialize_settings(self, sender): """ Initializes ReadTimeParser with configuration values set by the site author. """ try: self.initialized = True settings_content_types =...
Core function used to generate the read_time for content. Parameters: :param content: Instance of pelican.content.Content Returns: None def read_time(self, content): """ Core function used to generate the read_time for content. Parameters: :param c...
Returns a string that contains the measure (amount) and its plural or singular form depending on the amount. Parameters: :param measure: Amount, value, always a numerical value :param singular: The singular form of the chosen word :param plural: The plural form of th...
Filterable list of Datasources for a Source. def list_datasources(self, source_id): """ Filterable list of Datasources for a Source. """ target_url = self.client.get_url('DATASOURCE', 'GET', 'multi', {'source_id': source_id}) return base.Query(self.client.get_manager(Datasource)...
Get a Datasource object :rtype: Datasource def get_datasource(self, source_id, datasource_id): """ Get a Datasource object :rtype: Datasource """ target_url = self.client.get_url('DATASOURCE', 'GET', 'single', {'source_id': source_id, 'datasource_id': datasource_id}) ...
Filterable list of Scans for a Source. Ordered newest to oldest by default def list_scans(self, source_id=None): """ Filterable list of Scans for a Source. Ordered newest to oldest by default """ if source_id: target_url = self.client.get_url('SCAN', 'GET', '...
Get a Scan object :rtype: Scan def get_scan(self, source_id, scan_id): """ Get a Scan object :rtype: Scan """ target_url = self.client.get_url('SCAN', 'GET', 'single', {'source_id': source_id, 'scan_id': scan_id}) return self.client.get_manager(Scan)._get(targe...
Get the log text for a Scan :rtype: Iterator over log lines. def get_scan_log_lines(self, source_id, scan_id): """ Get the log text for a Scan :rtype: Iterator over log lines. """ return self.client.get_manager(Scan).get_log_lines(source_id=source_id, scan_id=scan_id)
Start a new scan of a Source. :rtype: Scan def start_scan(self, source_id): """ Start a new scan of a Source. :rtype: Scan """ target_url = self.client.get_url('SCAN', 'POST', 'create', {'source_id': source_id}) r = self.client.request('POST', target_url, json=...
Edits this Source def save(self, with_data=False): """ Edits this Source """ r = self._client.request('PUT', self.url, json=self._serialize(with_data=with_data)) return self._deserialize(r.json(), self._manager)
Delete this source def delete(self): """ Delete this source """ r = self._client.request('DELETE', self.url) logger.info("delete(): %s", r.status_code)
Add a single file or archive to upload. To add metadata records with a file, add a .xml file with the same upload path basename eg. ``points-with-metadata.geojson`` & ``points-with-metadata.xml`` Datasource XML must be in one of these three formats: - ISO 19115/19139 - FGDC...
Get the log text for a scan object :rtype: Iterator over log lines. def get_log_lines(self, source_id, scan_id): """ Get the log text for a scan object :rtype: Iterator over log lines. """ target_url = self.client.get_url('SCAN', 'GET', 'log', {'source_id': source_id, 's...
Get the log text for a scan object :rtype: Iterator over log lines. def get_log_lines(self): """ Get the log text for a scan object :rtype: Iterator over log lines. """ rel = self._client.reverse_url('SCAN', self.url) return self._manager.get_log_lines(**rel)
Returns the Creative Commons license for the given attributes. :param str slug: the type of Creative Commons license. It must start with ``cc-by`` and can optionally contain ``nc`` (non-commercial), ``sa`` (share-alike), ``nd`` (no derivatives) terms, seperated by hyphens. N...
Median Absolute Deviation: a "Robust" version of standard deviation. Indices variabililty of the sample. https://en.wikipedia.org/wiki/Median_absolute_deviation def mad(arr, relative=True): """ Median Absolute Deviation: a "Robust" version of standard deviation. Indices variabililty of the ...
Calculate an offset. Calculate offset from the side of data so that at least 200 image pixels are in the MAD stats. Parameters ========== cube : pyciss.ringcube.RingCube Cubefile with ring image def calc_offset(cube): """Calculate an offset. Calculate offset from the side of data so ...
Powerful default display. show_resonances can be True, a list, 'all', or 'some' def imshow( self, data=None, save=False, ax=None, interpolation="none", extra_title=None, show_resonances="some", set_extent=True, equalized=False, rm...
Update the query count property from the `X-Resource-Range` response header def _update_range(self, response): """ Update the query count property from the `X-Resource-Range` response header """ header_value = response.headers.get('x-resource-range', '') m = re.match(r'\d+-\d+/(\d+)$', header_v...
Serialises this query into a request-able URL including parameters def _to_url(self): """ Serialises this query into a request-able URL including parameters """ url = self._target_url params = collections.defaultdict(list, copy.deepcopy(self._filters)) if self._order_by is not None: ...
Set extra query parameters (eg. filter expressions/attributes that don't validate). Appends to any previous extras set. :rtype: Query def extra(self, **params): """ Set extra query parameters (eg. filter expressions/attributes that don't validate). Appends to any previous extra...
Add a filter to this query. Appends to any previous filters set. :rtype: Query def filter(self, **filters): """ Add a filter to this query. Appends to any previous filters set. :rtype: Query """ q = self._clone() for key, value in filters.items...
Set the sort for this query. Not all attributes are sorting candidates. To sort in descending order, call ``Query.order_by('-attribute')``. Calling ``Query.order_by()`` replaces any previous ordering. :rtype: Query def order_by(self, sort_key=None): """ Set the sort for this q...
Deserialise from JSON response data. String items named ``*_at`` are turned into dates. Filters out: * attribute names in ``Meta.deserialize_skip`` :param data dict: JSON-style object with instance data. :return: this instance def _deserialize(self, data): """ ...
Serialise this instance into JSON-style request data. Filters out: * attribute names starting with ``_`` * attribute values that are ``None`` (unless ``skip_empty`` is ``False``) * attribute values that are empty lists/tuples/dicts (unless ``skip_empty`` is ``False``) * attribut...
Called by :py:meth:`._serialize` to serialise an individual value. def _serialize_value(self, value): """ Called by :py:meth:`._serialize` to serialise an individual value. """ if isinstance(value, (list, tuple, set)): return [self._serialize_value(v) for v in value] ...
Refresh this model from the server. Updates attributes with the server-defined values. This is useful where the Model instance came from a partial response (eg. a list query) and additional details are required. Existing attribute values will be overwritten. def refresh(self): ...
Gets a crop feature :param int croplayer_id: ID of a cropping layer :param int cropfeature_id: ID of a cropping feature :rtype: CropFeature def get_feature(self, croplayer_id, cropfeature_id): """ Gets a crop feature :param int croplayer_id: ID of a cropping layer ...
Create and start processing a new Export. :param Export export: The Export to create. :rtype: Export def create(self, export): """ Create and start processing a new Export. :param Export export: The Export to create. :rtype: Export """ target_url = self...
Validates an Export. :param Export export: :rtype: ExportValidationResponse def validate(self, export): """ Validates an Export. :param Export export: :rtype: ExportValidationResponse """ target_url = self.client.get_url(self._URL_KEY, 'POST', 'valida...
Returns a raw options object :rtype: dict def _options(self): """ Returns a raw options object :rtype: dict """ if self._options_cache is None: target_url = self.client.get_url(self._URL_KEY, 'OPTIONS', 'options') r = self.client.request('OPTION...
Returns a dictionary of format options keyed by data kind. .. code-block:: python { "vector": { "application/x-ogc-gpkg": "GeoPackage", "application/x-zipped-shp": "Shapefile", #... }, "tabl...
Add a layer or table item to the export. :param Layer|Table item: The Layer or Table to add :rtype: self def add_item(self, item, **options): """ Add a layer or table item to the export. :param Layer|Table item: The Layer or Table to add :rtype: self """ ...
Download the export archive. .. warning:: If you pass this function an open file-like object as the ``path`` parameter, the function will not close that file for you. If a ``path`` parameter is a directory, this function will use the Export name to determine the name o...
Raises a subclass of ServerError based on the HTTP response code. def from_requests_error(cls, err): """ Raises a subclass of ServerError based on the HTTP response code. """ import requests if isinstance(err, requests.HTTPError): status_code = err.response.status_co...
Command line tool (``koordinates-create-token``) used to create an API token. def console_create(): """ Command line tool (``koordinates-create-token``) used to create an API token. """ import argparse import getpass import re import sys import requests from six.moves import input ...
Delete a token def delete(self, id ): """ Delete a token """ target_url = self.client.get_url('TOKEN', 'DELETE', 'single', {'id':id}) r = self.client.request('DELETE', target_url, headers={'Content-type': 'application/json'}) r.raise_for_status()
Create a new token :param Token token: Token instance to create. :param str email: Email address of the Koordinates user account. :param str password: Koordinates user account password. def create(self, token, email, password): """ Create a new token :param Token token...
Read in the whole cumulative index and return dataframe. def read_cumulative_iss_index(): "Read in the whole cumulative index and return dataframe." indexdir = get_index_dir() path = indexdir / "COISS_2999_index.hdf" try: df = pd.read_hdf(path, "df") except FileNotFoundError: path ...
Filter cumulative index for ring images. This is done by matching the column TARGET_DESC to contain the string 'ring' Returns ------- pandas.DataFrame data table containing only meta-data for ring images def read_ring_images_index(): """Filter cumulative index for ring images. This i...
filter for covered ringspan, giver in km. def filter_for_ringspan(clearnacs, spanlimit): "filter for covered ringspan, giver in km." delta = clearnacs.MAXIMUM_RING_RADIUS - clearnacs.MINIMUM_RING_RADIUS f = delta < spanlimit ringspan = clearnacs[f].copy() return ringspan
Creates a new publish group. def create(self, publish): """ Creates a new publish group. """ target_url = self.client.get_url('PUBLISH', 'POST', 'create') r = self.client.request('POST', target_url, json=publish._serialize()) return self.create_from_result(r.json())
Cancel a pending publish task def cancel(self): """ Cancel a pending publish task """ target_url = self._client.get_url('PUBLISH', 'DELETE', 'single', {'id': self.id}) r = self._client.request('DELETE', target_url) logger.info("cancel(): %s", r.status_code)
Return the item models associated with this Publish group. def get_items(self): """ Return the item models associated with this Publish group. """ from .layers import Layer # no expansion support, just URLs results = [] for url in self.items: if '/la...
Adds a Layer to the publish group. def add_layer_item(self, layer): """ Adds a Layer to the publish group. """ if not layer.is_draft_version: raise ValueError("Layer isn't a draft version") self.items.append(layer.latest_version)
Adds a Table to the publish group. def add_table_item(self, table): """ Adds a Table to the publish group. """ if not table.is_draft_version: raise ValueError("Table isn't a draft version") self.items.append(table.latest_version)
Add new ticks to an axis. I use this for the right-hand plotting of resonance names in my plots. def add_ticks_to_x(ax, newticks, newnames): """Add new ticks to an axis. I use this for the right-hand plotting of resonance names in my plots. """ ticks = list(ax.get_xticks()) ticks.extend(newti...
Creates a new Set. def create(self, set): """ Creates a new Set. """ target_url = self.client.get_url('SET', 'POST', 'create') r = self.client.request('POST', target_url, json=set._serialize()) return set._deserialize(r.json(), self)
Set the XML metadata on a set. :param file fp: file-like object to read the XML metadata from. def set_metadata(self, set_id, fp): """ Set the XML metadata on a set. :param file fp: file-like object to read the XML metadata from. """ base_url = self.client.get_url('SET...
Set the XML metadata on a set. :param file fp: file-like object to read the XML metadata from. def set_metadata(self, fp): """ Set the XML metadata on a set. :param file fp: file-like object to read the XML metadata from. """ base_url = self._client.get_url('SET', 'GET...
If the parent object already has XML metadata, it will be overwritten. Accepts XML metadata in any of the three supported formats. The format will be detected from the XML content. The Metadata object becomes invalid after setting :param file fp: A reference to an open file-like objec...
Returns the XML metadata for this source, converted to the requested format. Converted metadata may not contain all the same information as the native format. :param file fp: A path, or an open file-like object which the content should be written to. :param str format: desired format for the ou...
Return the available format names for this metadata def get_formats(self): """ Return the available format names for this metadata """ formats = [] for key in (self.FORMAT_DC, self.FORMAT_FGDC, self.FORMAT_ISO): if hasattr(self, key): formats.append(key) retu...
Decorator that asserts the model instance is bound. Requires: 1. an ``id`` attribute 2. a ``url`` attribute 2. a manager set def is_bound(method): """ Decorator that asserts the model instance is bound. Requires: 1. an ``id`` attribute 2. a ``url`` attribute 2. a manager set ...
Query OPUS via the image_id. This is a query using the 'primaryfilespec' field of the OPUS database. It returns a list of URLS into the `obsids` attribute. This example queries for an image of Titan: >>> opus = opusapi.OPUS() >>> opus.query_image_id('N1695760475_1') A...
api/data.[fmt], api/images/[size].[fmt] api/files.[fmt] kind = ['data', 'images', 'files'] def create_request_with_query(self, kind, query, size="thumb", fmt="json"): """api/data.[fmt], api/images/[size].[fmt] api/files.[fmt] kind = ['data', 'images', 'files'] """ if kind ==...
Query for OPUS data between times t1 and t2. Parameters ---------- t1, t2 : datetime.datetime, strings Start and end time for the query. If type is datetime, will be converted to isoformat string. If type is string already, it needs to be in an accepted inter...
Shows preview images using the Jupyter notebook HTML display. Parameters ========== size : {'small', 'med', 'thumb', 'full'} Determines the size of the preview image to be shown. def show_images(self, size="small"): """Shows preview images using the Jupyter notebook HTML di...
Download the previously found and stored Opus obsids. Parameters ========== savedir: str or pathlib.Path, optional If the database root folder as defined by the config.ini should not be used, provide a different savedir here. It will be handed to PathManager. def downlo...
Download preview files for the previously found and stored Opus obsids. Parameters ========== savedir: str or pathlib.Path, optional If the database root folder as defined by the config.ini should not be used, provide a different savedir here. It will be handed to PathMa...
Find which swap situtation we are in by time. Starting from 2006-01-21 where a Janus-Epimetheus swap occured, and defining the next 4 years until the next swap as `scenario1, and the 4 years after that `scenario2`. Calculate in units of 4 years, in which scenario the given time falls. Parameters ...
A filterable list views of layers, returning the draft version of each layer. If the most recent version of a layer or table has been published already, it won’t be returned here. def list_drafts(self): """ A filterable list views of layers, returning the draft version of each layer. ...
Filterable list of versions of a layer, always ordered newest to oldest. If the version’s source supports revisions, you can get a specific revision using ``.filter(data__source__revision=value)``. Specific values depend on the source type. Use ``data__source_revision__lt`` or ``data__source_re...
Get a specific version of a layer. def get_version(self, layer_id, version_id, expand=[]): """ Get a specific version of a layer. """ target_url = self.client.get_url('VERSION', 'GET', 'single', {'layer_id': layer_id, 'version_id': version_id}) return self._get(target_url, expan...
Get the current draft version of a layer. :raises NotFound: if there is no draft version. def get_draft(self, layer_id, expand=[]): """ Get the current draft version of a layer. :raises NotFound: if there is no draft version. """ target_url = self.client.get_url('VERSION...
Get the latest published version of this layer. :raises NotFound: if there is no published version. def get_published(self, layer_id, expand=[]): """ Get the latest published version of this layer. :raises NotFound: if there is no published version. """ target_url = self...
Creates a new draft version. If anything in the data object has changed then an import will begin immediately. Otherwise to force a re-import from the previous sources call :py:meth:`koordinates.layers.LayerManager.start_import`. :rtype: Layer :return: the new version :raises C...
Starts importing the specified draft version (cancelling any running import), even if the data object hasn’t changed from the previous version. def start_import(self, layer_id, version_id): """ Starts importing the specified draft version (cancelling any running import), even if the dat...
A shortcut to create a new version and start importing it. Effectively the same as :py:meth:`koordinates.layers.LayerManager.create_draft` followed by :py:meth:`koordinates.layers.LayerManager.start_import`. def start_update(self, layer_id): """ A shortcut to create a new version and start impo...
Set the XML metadata on a layer draft version. :param file fp: file-like object to read the XML metadata from. :raises NotAllowed: if the version is already published. def set_metadata(self, layer_id, version_id, fp): """ Set the XML metadata on a layer draft version. :param f...