Search is not available for this dataset
text
stringlengths
75
104k
def write_ioc(root, output_dir=None, force=False): """ Serialize an IOC, as defined by a set of etree Elements, to a .IOC file. :param root: etree Element to write out. Should have the tag 'OpenIOC' :param output_dir: Directory to write the ioc out to. default is current working directory. :param...
def write_ioc_string(root, force=False): """ Serialize an IOC, as defined by a set of etree Elements, to a String. :param root: etree Element to serialize. Should have the tag 'OpenIOC' :param force: Skip the root node tag check. :return: """ root_tag = 'OpenIOC' if not force and root.t...
def open_ioc(fn): """ Opens an IOC file, or XML string. Returns the root element, top level indicator element, and parameters element. If the IOC or string fails to parse, an IOCParseError is raised. This is a helper function used by __init__. :param fn: This is a pat...
def make_ioc(name=None, description='Automatically generated IOC', author='IOC_api', links=None, keywords=None, iocid=None): """ This generates all parts of an IOC, but without any definition. This is a helper ...
def set_lastmodified_date(self, date=None): """ Set the last modified date of a IOC to the current date. User may specify the date they want to set as well. :param date: Date value to set the last modified date to. This should be in the xsdDate form. This defaults to the curre...
def set_published_date(self, date=None): """ Set the published date of a IOC to the current date. User may specify the date they want to set as well. :param date: Date value to set the published date to. This should be in the xsdDate form. This defaults to the current date if ...
def set_created_date(self, date=None): """ Set the created date of a IOC to the current date. User may specify the date they want to set as well. :param date: Date value to set the created date to. This should be in the xsdDate form. This defaults to the current date if it is ...
def add_parameter(self, indicator_id, content, name='comment', ptype='string'): """ Add a a parameter to the IOC. :param indicator_id: The unique Indicator/IndicatorItem id the parameter is associated with. :param content: The value of the parameter. :param name: The name of the...
def add_link(self, rel, value, href=None): """ Add a Link metadata element to the IOC. :param rel: Type of the link. :param value: Value of the link text. :param href: A href value assigned to the link. :return: True """ links_node = self.metadata.find('l...
def update_name(self, name): """ Update the name (short description) of an IOC This creates the short description node if it is not present. :param name: Value to set the short description too :return: """ short_desc_node = self.metadata.find('short_description'...
def update_description(self, description): """ Update the description) of an IOC This creates the description node if it is not present. :param description: Value to set the description too :return: True """ desc_node = self.metadata.find('description') i...
def update_link_rel_based(self, old_rel, new_rel=None, new_text=None, single_link=False): """ Update link nodes, based on the existing link/@rel values. This requires specifying a link/@rel value to update, and either a new link/@rel value, or a new link/text() value for all links which...
def update_link_rewrite(self, old_rel, old_text, new_text, single_link=False): """ Rewrite the text() value of a link based on the link/@rel and link/text() value. This is similar to update_link_rel_based but users link/@rel AND link/text() values to determine which links have their lin...
def update_parameter(self, parameter_id, content=None, name=None, param_type=None): """ Updates the parameter attached to an Indicator or IndicatorItem node. All inputs must be strings or unicode objects. :param parameter_id: The unique id of the parameter to modify :param cont...
def remove_link(self, rel, value=None, href=None): """ Removes link nodes based on the function arguments. This can remove link nodes based on the following combinations of arguments: link/@rel link/@rel & link/text() link/@rel & link/@href link/@...
def remove_indicator(self, nid, prune=False): """ Removes a Indicator or IndicatorItem node from the IOC. By default, if nodes are removed, any children nodes are inherited by the removed node. It has the ability to delete all children Indicator and IndicatorItem nodes undernea...
def remove_parameter(self, param_id=None, name=None, ref_id=None, ): """ Removes parameters based on function arguments. This can remove parameters based on the following param values: param/@id param/@name param/@ref_id Each input is mutually exclus...
def remove_name(self): """ Removes the name (short_description node) from the metadata node, if present. :return: True if the node is removed. False is the node is node is not present. """ short_description_node = self.metadata.find('short_description') if short_descrip...
def remove_description(self): """ Removes the description node from the metadata node, if present. :return: Returns True if the description node is removed. Returns False if the node is not present. """ description_node = self.metadata.find('description') if description_...
def write_ioc_to_file(self, output_dir=None, force=False): """ Serialize the IOC to a .ioc file. :param output_dir: Directory to write the ioc out to. default is the current working directory. :param force: If specified, will not validate the root node of the IOC is 'OpenIOC'. ...
def display_ioc(self, width=120, sep=' ', params=False): """ Get a string representation of an IOC. :param width: Width to print the description too. :param sep: Separator used for displaying the contents of the criteria nodes. :param params: Boolean, set to True in order to di...
def link_text(self): """ Get a text represention of the links node. :return: """ s = '' links_node = self.metadata.find('links') if links_node is None: return s links = links_node.getchildren() if links is None: return s ...
def criteria_text(self, sep=' ', params=False): """ 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: """ s = '' ...
def get_node_text(self, node, depth, sep, params=False,): """ 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...
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: {}'.format(node.tag)) s = node.get('operator').upper() return s
def get_ii_text(node): """ Get the text for IndicatorItem node. :param node: IndicatorItem node. :return: """ if node.tag != 'IndicatorItem': raise IOCParseError('Invalid tag: {}'.format(node.tag)) condition = node.attrib.get('condition') pres...
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 = [] params = self.parameters.xpath('.//param[@ref-id="{}"]'.format(nid)) if not params: return r ...
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 object or None """ parser = et.XMLParser(remove_blank_text=True) isfile=False try: isfile = os.path.exists(filename) except ...
def remove_namespace(doc, namespace): """ 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 t...
def delete_namespace(parsed_xml): """ 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. """ if parsed_xml.getroot().tag.st...
def insert(self, filename): """ 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. """ errors = [] if os.path.isfile(filename): ...
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 to parse. :return: """ ioc_xml = xmlutils.read_xml_no_ns(fn) if not ioc_xml: return False root = ioc_x...
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.iocs_11 """ if len(self) < 1: log.error('No iocs available to modify.') return False log.info('...
def convert_branch(self, old_node, new_node, comment_dict=None): """ 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 ...
def insert(self, filename): """ 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. """ errors = [] if os.path.isfile(filename): ...
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_obj.iocid try: sd = ioc_obj.metadata.xpath('.//short_description/text()')[0] ...
def register_parser_callback(self, func): """ 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 singl...
def create(self, permission): """ Create single permission for the given object. :param Permission permission: A single Permission object to be set. """ parent_url = self.client.get_url(self.parent_object._manager._URL_KEY, 'GET', 'single', {'id': self.parent_object.id}) ...
def set(self, permissions): """ 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. """ parent_url = self.client.get_url(self.parent_object._manager._URL_KEY, 'GET', '...
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._URL_KEY, 'GET', 'multi') return b...
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. """ parent_url = self.client.get_url(self.parent_object._manager._URL_KEY, 'GET', 'single', {'id': self.parent_object.id...
def get_config(): """Read the configfile and return config dict. Returns ------- dict Dictionary with the content of the configpath file. """ configpath = get_configpath() if not configpath.exists(): raise IOError("Config file {} not found.".format(str(configpath))) else...
def set_database_path(dbfolder): """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. """ configpath = get_configpath() try: d = get_config() exce...
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
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.glob("[N,W]*"))) print("Number of WACs and NACs in database: {}".format(n_ids)) print("These kind of data ...
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
def download_and_calibrate_parallel(list_of_ids, n=None): """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 """ setup_clu...
def download_and_calibrate(img_id=None, overwrite=False, recalibrate=False, **kwargs): """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: bo...
def spiceinit(self): """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. """ shape = "ringplane" ...
def check_label(self): """ 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 -------- ...
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 'READTIME_CONTENT_SUPPORT' must be" "a li...
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_int and not is_dict: raise TypeError(("Settings 'READTIME...
def initialize_settings(self, sender): """ Initializes ReadTimeParser with configuration values set by the site author. """ try: self.initialized = True settings_content_types = sender.settings.get( 'READTIME_CONTENT_SUPPORT', self.content_type_su...
def read_time(self, content): """ Core function used to generate the read_time for content. Parameters: :param content: Instance of pelican.content.Content Returns: None """ if get_class_name(content) in self.content_type_supported: # Exit if...
def pluralize(self, measure, singular, plural): """ 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 ...
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), target_url)
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}) return self.client.get_manager(Datasource)._ge...
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', 'multi', {'source_id': source_id}) else: target_url = self.client...
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(target_url)
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)
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={}) return self.client.get_manager(Scan).crea...
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)
def delete(self): """ Delete this source """ r = self._client.request('DELETE', self.url) logger.info("delete(): %s", r.status_code)
def add_file(self, fp, upload_path=None, content_type=None): """ 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 mus...
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, 'scan_id': scan_id}) r = self.client.request('GET', target_url, headers...
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)
def get_creative_commons(self, slug, jurisdiction=None): """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)...
def mad(arr, relative=True): """ Median Absolute Deviation: a "Robust" version of standard deviation. Indices variabililty of the sample. https://en.wikipedia.org/wiki/Median_absolute_deviation """ with warnings.catch_warnings(): warnings.simplefilter("ignore") med = np.nanme...
def calc_offset(cube): """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 """ i = 0 while pd.Series(cube.img[:, i]).count() < 200: ...
def imshow( self, data=None, save=False, ax=None, interpolation="none", extra_title=None, show_resonances="some", set_extent=True, equalized=False, rmin=None, rmax=None, savepath=".", **kwargs, ): """Powe...
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_value) if m: self._count = int(m.group(1)) else: ...
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: params['sort'] = self._order_by for k, vl in self....
def extra(self, **params): """ Set extra query parameters (eg. filter expressions/attributes that don't validate). Appends to any previous extras set. :rtype: Query """ q = self._clone() for key, value in params.items(): q._extra[key].append(value) ...
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(): filter_key = re.split('__', key) filter_attr = filter_key[0] ...
def order_by(self, sort_key=None): """ 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 """ if s...
def _deserialize(self, data): """ 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 _serialize(self, skip_empty=True): """ 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/di...
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] elif isinstance(value, dict): return dict([(k, self._se...
def refresh(self): """ 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 o...
def get_feature(self, croplayer_id, cropfeature_id): """ Gets a crop feature :param int croplayer_id: ID of a cropping layer :param int cropfeature_id: ID of a cropping feature :rtype: CropFeature """ target_url = self.client.get_url('CROPFEATURE', 'GET', 'single...
def create(self, export): """ Create and start processing a new Export. :param Export export: The Export to create. :rtype: Export """ target_url = self.client.get_url(self._URL_KEY, 'POST', 'create') r = self.client.request('POST', target_url, json=export._seria...
def validate(self, export): """ Validates an Export. :param Export export: :rtype: ExportValidationResponse """ target_url = self.client.get_url(self._URL_KEY, 'POST', 'validate') response_object = ExportValidationResponse() r = self.client.request('POST...
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('OPTIONS', target_url) self._options_cache = r....
def get_formats(self): """ Returns a dictionary of format options keyed by data kind. .. code-block:: python { "vector": { "application/x-ogc-gpkg": "GeoPackage", "application/x-zipped-shp": "Shapefile", #....
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 """ export_item = { "item": item.url, } export_item.update(options) self.items.append(exp...
def download(self, path, progress_callback=None, chunk_size=1024**2): """ 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`` parame...
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_code return HTTP_ERRORS.get(status_code, cls)(error=err, ...
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 from koordinates.client import Client parser = argparse.ArgumentParser(...
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()
def create(self, token, email, password): """ 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. """ target_url = self.client.ge...
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 = indexdir / "cumindex.hdf" df = pd.read_hdf(path,...
def read_ring_images_index(): """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 """ meta = read_cumulative_iss_index() ri...
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
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())
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)
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 '/layers/' in url: r = self._client.request('GET...
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)
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)
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(newticks) ax.set_xticks(ticks) names = list(ax.get_xticklabels()) names.extend(newnames) ax...
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)