text
stringlengths
18
773k
def count(self, **query_dict): """Return the number of entries that match query.""" param_dict = query_dict.copy() param_dict['count'] = 0 resp_dict = self._get_query(**param_dict) return resp_dict['response']['numFound']
def get_field_values(self, name, maxvalues=-1, sort=True, **query_dict): """Retrieve the unique values for a field, along with their usage counts. :param name: Name of field for which to retrieve values :type name: string :param sort: Sort the result :param maxvalues: Maximum ...
def get_field_min_max(self, name, **query_dict): """Returns the minimum and maximum values of the specified field. This requires two search calls to the service, each requesting a single value of a single field. @param name(string) Name of the field @param q(string) Query identi...
def field_alpha_histogram( self, name, n_bins=10, include_queries=True, **query_dict ): """Generates a histogram of values from a string field. Output is: [[low, high, count, query], ... ]. Bin edges is determined by equal division of the fields. """ bin_list = [] ...
def add_docs(self, docs): """docs is a list of fields that are a dictionary of name:value for a record.""" return self.query( 'solr', '<add>{}</add>'.format( ''.join([self._format_add(fields) for fields in docs]) ), do_post=True, )
def _coerce_type(self, field_type, value): """Returns unicode(value) after trying to coerce it into the Solr field type. @param field_type(string) The Solr field type for the value @param value(any) The value that is to be represented as Unicode text. """ if value is None: ...
def _get_solr_type(self, field): """Returns the Solr type of the specified field name. Assumes the convention of dynamic fields using an underscore + type character code for the field name. """ field_type = 'string' try: field_type = FIELD_TYPE_CONVERSION_MA...
def _get_query(self, **query_dict): """Perform a GET query against Solr and return the response as a Python dict.""" param_dict = query_dict.copy() return self._send_query(do_post=False, **param_dict)
def _post_query(self, **query_dict): """Perform a POST query against Solr and return the response as a Python dict.""" param_dict = query_dict.copy() return self._send_query(do_post=True, **param_dict)
def _send_query(self, do_post=False, **query_dict): """Perform a query against Solr and return the response as a Python dict.""" # self._prepare_query_term() param_dict = query_dict.copy() param_dict.setdefault('wt', 'json') param_dict.setdefault('q', '*.*') param_dict.se...
def _prepare_query_term(self, field, term): """Prepare a query term for inclusion in a query. This escapes the term and if necessary, wraps the term in quotes. """ if term == "*": return term add_star = False if term[len(term) - 1] == '*': add_st...
def _escape_query_term(self, term): """Escape a query term for inclusion in a query. - Also see: prepare_query_term(). """ term = term.replace('\\', '\\\\') for c in RESERVED_CHAR_LIST: term = term.replace(c, r'\{}'.format(c)) return term
def _next_page(self, offset): """Retrieves the next set of results from the service.""" self._log.debug("Iterator c_record={}".format(self.c_record)) page_size = self.page_size if (offset + page_size) > self.max_records: page_size = self.max_records - offset param_dic...
def _next_page(self, offset): """Retrieves the next set of results from the service.""" self._log.debug("Iterator c_record={}".format(self.c_record)) param_dict = self.query_dict.copy() param_dict.update( { 'rows': '0', 'facet': 'true', ...
def migrate_flow_collection(apps, schema_editor): """Migrate 'flow_collection' field to 'entity_type'.""" Process = apps.get_model('flow', 'Process') DescriptorSchema = apps.get_model('flow', 'DescriptorSchema') for process in Process.objects.all(): process.entity_type = process.flow_collection...
def get_pyxb_binding_by_api_version(api_major, api_minor=0): """Map DataONE API version tag to PyXB binding. Given a DataONE API major version number, return PyXB binding that can serialize and deserialize DataONE XML docs of that version. Args: api_major, api_minor: str or int DataONE A...
def extract_version_tag_from_url(url): """Extract a DataONE API version tag from a MN or CN service endpoint URL. Args: url : str Service endpoint URL. E.g.: ``https://mn.example.org/path/v2/object/pid``. Returns: str : Valid version tags are currently ``v1`` or ``v2``. """ m ...
def str_to_v1_str(xml_str): """Convert a API v2 XML doc to v1 XML doc. Removes elements that are only valid for v2 and changes namespace to v1. If doc is already v1, it is returned unchanged. Args: xml_str : str API v2 XML doc. E.g.: ``SystemMetadata v2``. Returns: str : API ...
def str_to_v2_str(xml_str): """Convert a API v1 XML doc to v2 XML doc. All v1 elements are valid for v2, so only changes namespace. Args: xml_str : str API v1 XML doc. E.g.: ``SystemMetadata v1``. Returns: str : API v2 XML doc. E.g.: ``SystemMetadata v2``. """ if str_is_v...
def str_is_well_formed(xml_str): """ Args: xml_str : str DataONE API XML doc. Returns: bool: **True** if XML doc is well formed. """ try: str_to_etree(xml_str) except xml.etree.ElementTree.ParseError: return False else: return True
def pyxb_is_v1(pyxb_obj): """ Args: pyxb_obj : PyXB object PyXB object holding an unknown type. Returns: bool: **True** if ``pyxb_obj`` holds an API v1 type. """ # TODO: Will not detect v1.2 as v1. return ( pyxb_obj._element().name().namespace() == d1_common.types.dataon...
def pyxb_is_v2(pyxb_obj): """ Args: pyxb_obj : PyXB object PyXB object holding an unknown type. Returns: bool: **True** if ``pyxb_obj`` holds an API v2 type. """ return ( pyxb_obj._element().name().namespace() == d1_common.types.dataoneTypes_v2_0.Namespace )
def str_to_etree(xml_str, encoding='utf-8'): """Deserialize API XML doc to an ElementTree. Args: xml_str: bytes DataONE API XML doc encoding: str Decoder to use when converting the XML doc ``bytes`` to a Unicode str. Returns: ElementTree: Matching the API version of the ...
def replace_namespace_with_prefix(tag_str, ns_reverse_dict=None): """Convert XML tag names with namespace on the form ``{namespace}tag`` to form ``prefix:tag``. Args: tag_str: str Tag name with namespace. E.g.: ``{http://www.openarchives.org/ore/terms/}ResourceMap``. ns_reverse...
def etree_replace_namespace(etree_obj, ns_str): """In-place change the namespace of elements in an ElementTree. Args: etree_obj: ElementTree ns_str : str The namespace to set. E.g.: ``http://ns.dataone.org/service/types/v1``. """ def _replace_recursive(el, n): el.tag = re...
def strip_v2_elements(etree_obj): """In-place remove elements and attributes that are only valid in v2 types. Args: etree_obj: ElementTree ElementTree holding one of the DataONE API types that changed between v1 and v2. """ if etree_obj.tag == v2_0_tag('logEntry'): strip_logEntry(etr...
def strip_system_metadata(etree_obj): """In-place remove elements and attributes that are only valid in v2 types from v1 System Metadata. Args: etree_obj: ElementTree ElementTree holding a v1 SystemMetadata. """ for series_id_el in etree_obj.findall('seriesId'): etree_obj.remove(seri...
def _create_replica(self, sysmeta_pyxb, sciobj_bytestream): """GMN handles replicas differently from native objects, with the main differences being related to handling of restrictions related to revision chains and SIDs. So this create sequence differs significantly from the regular on...
async def restricted_import(self, async_client, node_type): """Import only the Science Objects specified by a text file. The file must be UTF-8 encoded and contain one PIDs or SIDs per line. """ item_task_name = "Importing objects" pid_path = self.options['pid_path'] i...
async def import_aggregated(self, async_client, pid): """Import the SciObj at {pid}. If the SciObj is a Resource Map, also recursively import the aggregated objects. """ self._logger.info('Importing: {}'.format(pid)) task_set = set() object_info_pyxb = d1_common.types...
async def get_object_proxy_location(self, client, pid): """If object is proxied, return the proxy location URL. If object is local, return None. """ try: return (await client.describe(pid)).get("DataONE-Proxy") except d1_common.types.exceptions.DataONEException: ...
def get_list_objects_arg_dict(self, node_type): """Create a dict of arguments that will be passed to listObjects(). If {node_type} is a CN, add filtering to include only objects from this GMN instance in the ObjectList returned by CNCore.listObjects(). """ arg_dict = { ...
def get_log_records_arg_dict(self, node_type): """Create a dict of arguments that will be passed to getLogRecords(). If {node_type} is a CN, add filtering to include only objects from this GMN instance in the ObjectList returned by CNCore.listObjects(). """ arg_dict = { ...
async def is_cn(self, client): """Return True if node at {base_url} is a CN, False if it is an MN. Raise a DataONEException if it's not a functional CN or MN. """ node_pyxb = await client.get_capabilities() return d1_common.type_conversions.pyxb_get_type_name(node_pyxb) == "Nod...
async def probe_node_type_major(self, client): """Determine if import source node is a CN or MN and which major version API to use.""" try: node_pyxb = await self.get_node_doc(client) except d1_common.types.exceptions.DataONEException as e: raise django.core.manag...
def find_node(self, node_list_pyxb, base_url): """Search NodeList for Node that has {base_url}. Return matching Node or None """ for node_pyxb in node_list_pyxb.node: if node_pyxb.baseURL == base_url: return node_pyxb
def assert_is_known_node_id(self, node_list_pyxb, node_id): """When importing from a CN, ensure that the NodeID which the ObjectList will be filtered by is known to the CN.""" node_pyxb = self.find_node_by_id(node_list_pyxb, node_id) assert node_pyxb is not None, ( "The NodeI...
def find_node_api_version(self, node_pyxb): """Find the highest API major version supported by node.""" max_major = 0 for s in node_pyxb.services.service: max_major = max(max_major, int(s.version[1:])) return max_major
def find_node_by_id(self, node_list_pyxb, node_id): """Search NodeList for Node with {node_id}. Return matching Node or None """ for node_pyxb in node_list_pyxb.node: # if node_pyxb.baseURL == base_url: if d1_common.xml.get_req_val(node_pyxb.identifier) == node_...
def celery_run(data_id, runtime_dir, argv): """Run process executor. :param data_id: The id of the :class:`~resolwe.flow.models.Data` object to be processed. :param runtime_dir: The directory from which to run the executor. :param argv: The argument vector used to run the executor. :param v...
def archive_sciobj(pid): """Set the status of an object to archived. Preconditions: - The object with the pid is verified to exist. - The object is not a replica. - The object is not archived. """ sciobj_model = d1_gmn.app.model_util.get_sci_model(pid) sciobj_model.is_archived = True ...
def create_or_update(sysmeta_pyxb, sciobj_url=None): """Create or update database representation of a System Metadata object and closely related internal state. - If ``sciobj_url`` is not passed on create, storage in the internal sciobj store is assumed - If ``sciobj_url`` is passed on create, it...
def _access_policy_pyxb_to_model(sci_model, sysmeta_pyxb): """Create or update the database representation of the sysmeta_pyxb access policy. If called without an access policy, any existing permissions on the object are removed and the access policy for the rights holder is recreated. Preconditions: ...
def add_arguments(self, parser): """Args: parser: """ parser.description = __doc__ parser.formatter_class = argparse.RawDescriptionHelpFormatter parser.add_argument("--debug", action="store_true", help="Debug level logging") parser.add_argument( "--f...
def handle(self, *args, **opt): """Args: *args: **opt: """ d1_gmn.app.management.commands.util.util.log_setup(opt["debug"]) logging.info( "Running management command: {}".format( __name__ ) # util.get_command_name()) ) ...
def _create_log_entry(self, log_record_pyxb): """Args: log_record_pyxb: """ event_log_model = d1_gmn.app.event_log.create_log_entry( d1_gmn.app.model_util.get_sci_model( d1_common.xml.get_req_val(log_record_pyxb.identifier) ), log_rec...
def _download_source_sciobj_bytes_to_store(self, client, pid): """Args: client: pid: """ if d1_gmn.app.sciobj_store.is_existing_sciobj_file(pid): self._events.log_and_count( "Skipped download of existing sciobj bytes", 'pid="{}"'.format(pid) ) ...
def _assert_path_is_dir(self, dir_path): """Args: dir_path: """ if not os.path.isdir(dir_path): raise django.core.management.base.CommandError( 'Invalid dir path. path="{}"'.format(dir_path) )
def deserialize_subject_info(subject_info_xml_path): """Deserialize a SubjectInfo XML file to a PyXB object.""" try: with open(subject_info_xml_path) as f: return d1_common.xml.deserialize(f.read()) except ValueError as e: raise d1_common.types.exceptions.InvalidToken( ...
def HEAD(self, rest_path_list, **kwargs): """Send a HEAD request. See requests.sessions.request for optional parameters. :returns: Response object """ kwargs.setdefault("allow_redirects", False) return self._request("HEAD", rest_path_list, **kwargs)
def POST(self, rest_path_list, **kwargs): """Send a POST request with optional streaming multipart encoding. See requests.sessions.request for optional parameters. To post regular data, pass a string, iterator or generator as the ``data`` argument. To post a multipart stream, pass a dict...
def PUT(self, rest_path_list, **kwargs): """Send a PUT request with optional streaming multipart encoding. See requests.sessions.request for optional parameters. See post() for parameters. :returns: Response object """ fields = kwargs.pop("fields", None) if fields is no...
def get_curl_command_line(self, method, url, **kwargs): """Get request as cURL command line for debugging.""" if kwargs.get("query"): url = "{}?{}".format(url, d1_common.url.urlencode(kwargs["query"])) curl_list = ["curl"] if method.lower() == "head": curl_list.ap...
def dump_request_and_response(self, response): """Return a string containing a nicely formatted representation of the request and response objects for logging and debugging. - Note: Does not work if the request or response body is a MultipartEncoder object. """ if res...
def _timeout_to_float(self, timeout): """Convert timeout to float. Return None if timeout is None, 0 or 0.0. timeout=None disables timeouts in Requests. """ if timeout is not None: try: timeout_float = float(timeout) except ValueError: ...
def main(): """Print the RedBaron syntax tree for a Python module.""" parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter ) parser.add_argument("path", help="Python module path") args = parser.parse_args() r = d1_dev.util.redbaron_...
def abs_path_from_base(base_path, rel_path): """Join a base and a relative path and return an absolute path to the resulting location. Args: base_path: str Relative or absolute path to prepend to ``rel_path``. rel_path: str Path relative to the location of the module file from ...
def abs_path(rel_path): """Convert a path that is relative to the module from which this function is called, to an absolute path. Args: rel_path: str Path relative to the location of the module file from which this function is called. Returns: str : Absolute path to the location ...
def get_xml(self, encoding='unicode'): """Returns: str : Current state of the wrapper as XML """ return xml.etree.ElementTree.tostring(self._root_el, encoding)
def get_pretty_xml(self, encoding='unicode'): """Returns: str : Current state of the wrapper as a pretty printed XML string. """ return d1_common.xml.reformat_to_pretty_xml( xml.etree.ElementTree.tostring(self._root_el, encoding) )
def get_xml_below_element(self, el_name, el_idx=0, encoding='unicode'): """ Args: el_name : str Name of element that is the base of the branch to retrieve. el_idx : int Index of element to use as base in the event that there are multiple sibling elements with the same na...
def get_element_by_xpath(self, xpath_str, namespaces=None): """ Args: xpath_str : str XPath matching the elements for which to search. Returns: list : List of elements matching ``xpath_str``. If there are no matching elements, an empty list is returned. """ try: ...
def get_element_by_name(self, el_name, el_idx=0): """ Args: el_name : str Name of element to get. el_idx : int Index of element to use as base in the event that there are multiple sibling elements with the same name. Returns: element : The selected element. ...
def get_element_by_attr_key(self, attr_key, el_idx=0): """ Args: attr_key : str Name of attribute for which to search el_idx : int Index of element to use as base in the event that there are multiple sibling elements with the same name. Returns: Element contai...
def set_element_text(self, el_name, el_text, el_idx=0): """ Args: el_name : str Name of element to update. el_text : str Text to set for element. el_idx : int Index of element to use in the event that there are multiple sibling elements with the same name....
def set_element_text_by_attr_key(self, attr_key, el_text, el_idx=0): """ Args: attr_key : str Name of attribute for which to search el_text : str Text to set for element. el_idx : int Index of element to use in the event that there are multiple sibling ele...
def get_attr_value(self, attr_key, el_idx=0): """Return the value of the selected attribute in the selected element. Args: attr_key : str Name of attribute for which to search el_idx : int Index of element to use in the event that there are multiple sibling ...
def set_attr_text(self, attr_key, attr_val, el_idx=0): """Set the value of the selected attribute of the selected element. Args: attr_key : str Name of attribute for which to search attr_val : str Text to set for the attribute. el_idx : int ...
def get_element_dt(self, el_name, tz=None, el_idx=0): """Return the text of the selected element as a ``datetime.datetime`` object. The element text must be a ISO8601 formatted datetime Args: el_name : str Name of element to use. tz : datetime.tzinfo ...
def set_element_dt(self, el_name, dt, tz=None, el_idx=0): """Set the text of the selected element to an ISO8601 formatted datetime. Args: el_name : str Name of element to update. dt : datetime.datetime Date and time to set tz : datetime.tzinfo ...
def replace_by_etree(self, root_el, el_idx=0): """Replace element. Select element that has the same name as ``root_el``, then replace the selected element with ``root_el`` ``root_el`` can be a single element or the root of an element tree. Args: root_el : element ...
def replace_by_xml(self, xml_str, el_idx=0): """Replace element. Select element that has the same name as ``xml_str``, then replace the selected element with ``xml_str`` - ``xml_str`` must have a single element in the root. - The root element in ``xml_str`` can have an arbitrar...
def as_sql(self, compiler, connection): # pylint: disable=arguments-differ """Compile SQL for this function.""" sql, params = super().as_sql(compiler, connection) params.append(self.path) return sql, params
def with_json_path(self, path, field=None): """Annotate Storage objects with a specific JSON path. :param path: Path to get inside the stored object, which can be either a list of path components or a comma-separated string :param field: Optional output field name ...
def get_json_path(self, path): """Return only a specific JSON path of Storage objects. :param path: Path to get inside the stored object, which can be either a list of path components or a comma-separated string """ return self.with_json_path(path, field='result'...
def _get_storage(self): """Load `json` field from `Storage` object.""" if self._json is None: self._json = Storage.objects.get(**self._kwargs).json
def database_forwards(self, app_label, schema_editor, from_state, to_state): """Perform forward migration.""" Process = from_state.apps.get_model('flow', 'Process') # pylint: disable=invalid-name Data = from_state.apps.get_model('flow', 'Data') # pylint: disable=invalid-name try: ...
def deconstruct(self): """Deconstruct operation.""" return ( self.__class__.__name__, [], { 'process': self.process, 'field': self._raw_field, 'schema': self.schema, 'default': self.default, }...
def migrate_process_schema(self, process, schema, from_state): """Migrate process schema. :param process: Process instance :param schema: Process schema to migrate :param from_state: Database model state :return: True if the process was migrated, False otherwise """ ...
def migrate_data(self, data, from_state): """Migrate data objects. :param data: Queryset containing all data objects that need to be migrated :param from_state: Database model state """ if not self.default: return self.default.prepare(data, from_...
def deconstruct(self): """Deconstruct operation.""" return ( self.__class__.__name__, [], { 'process': self.process, 'field': self._raw_field, 'new_field': self.new_field, } )
def migrate_process_schema(self, process, schema, from_state): """Migrate process schema. :param process: Process instance :param schema: Process schema to migrate :param from_state: Database model state :return: True if the process was migrated, False otherwise """ ...
def migrate_data(self, data, from_state): """Migrate data objects. :param data: Queryset containing all data objects that need to be migrated :param from_state: Database model state """ for instance in data: if instance.status == 'ER': con...
def database_forwards(self, app_label, schema_editor, from_state, to_state): """Perform forward migration.""" from resolwe.flow.models.data import DataQuerySet # pylint: disable=protected-access Data = from_state.apps.get_model('flow', 'Data') # pylint: disable=invalid-name Dat...
def database_forwards(self, app_label, schema_editor, from_state, to_state): """Perform forward migration.""" from resolwe.flow.models.data import DataQuerySet # pylint: disable=protected-access Data = from_state.apps.get_model('flow', 'Data') # pylint: disable=invalid-name Dat...
def migrate_process_schema(self, process, schema, from_state): """Migrate process schema. :param process: Process instance :param schema: Process schema to migrate :param from_state: Database model state :return: True if the process was migrated, False otherwise """ ...
def database_forwards(self, app_label, schema_editor, from_state, to_state): """Perform forward migration.""" Process = from_state.apps.get_model('flow', 'Process') # pylint: disable=invalid-name # Validate process types to ensure consistency. errors = validate_process_types(Process.ob...
def home(request): """Home page. Root of web server should redirect to here. """ if request.path.endswith('/'): return django.http.HttpResponseRedirect(request.path[:-1]) return django.http.HttpResponse( generate_status_xml(), d1_common.const.CONTENT_TYPE_XML )
def error_404(request, exception): """Handle 404s outside of the valid API URL endpoints Note: Cannot raise NotFound() here, as this method is not covered by the GMN middleware handler that catches DataONE exceptions raised by normal views.""" return django.http.HttpResponseNotFound( d1_common.t...
def get_obj_store_free_space_bytes(): """Return total free space available on the disk on which the object storage resides (in bytes)""" obj_store_path = django.conf.settings.OBJECT_STORE_PATH if platform.system() == 'Windows': free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.Ge...
def m2Lambda_to_vMh2(m2, Lambda, C): """Function to numerically determine the physical Higgs VEV and mass given the parameters of the Higgs potential.""" try: v = (sqrt(2 * m2 / Lambda) + 3 * m2**(3 / 2) / (sqrt(2) * Lambda**(5 / 2)) * C['phi']) except ValueError: v = 0 ...
def vMh2_to_m2Lambda(v, Mh2, C): """Function to numerically determine the parameters of the Higgs potential given the physical Higgs VEV and mass.""" if C['phi'] == 0 and C['phiBox'] == 0 and C['phiD'] == 0: return _vMh2_to_m2Lambda_SM(v, Mh2) else: def f0(x): # we want the root of this...
def get_gpbar(ebar, gbar, v, C): r"""Function to numerically determine the hypercharge gauge coupling in terms of $\bar e$, $\bar g$, v, and the Wilson coefficients.""" if C['phiWB'] == 0: # this is the trivial case gpbar = ebar * gbar / sqrt(gbar**2 - ebar**2) else: # if epsilon != 0, need to...
def smeftpar(scale, C, basis): """Get the running parameters in SMEFT.""" # start with a zero dict and update it with the input values MW = p['m_W'] # MZ = p['m_Z'] GF = p['GF'] Mh = p['m_h'] vb = sqrt(1 / sqrt(2) / GF) v = vb # TODO _d = vMh2_to_m2Lambda(v=v, Mh2=Mh**2, C=C) m2...
def smpar(C): """Get the running effective SM parameters.""" m2 = C['m2'].real Lambda = C['Lambda'].real v = (sqrt(2 * m2 / Lambda) + 3 * m2**(3 / 2) / (sqrt(2) * Lambda**(5 / 2)) * C['phi']) GF = 1 / (sqrt(2) * v**2) # TODO Mh2 = 2 * m2 * (1 - m2 / Lambda * (3 * C['phi'] - 4 * Lambda ...
def scale_8(b): """Translations necessary for class-8 coefficients to go from a basis with only non-redundant WCxf operators to a basis where the Wilson coefficients are symmetrized like the operators.""" a = np.array(b, copy=True, dtype=complex) for i in range(3): a[0, 0, 1, i] = 1/2 * ...
def symmetrize(C): """Symmetrize the Wilson coefficient arrays. Note that this function does not take into account the symmetry factors that occur when transitioning from a basis with only non-redundant operators (like in WCxf) to a basis where the Wilson coefficients are symmetrized like the opera...
def arrays2wcxf(C): """Convert a dictionary with Wilson coefficient names as keys and numbers or numpy arrays as values to a dictionary with a Wilson coefficient name followed by underscore and numeric indices as keys and numbers as values. This is needed for the output in WCxf format.""" d = {} ...
def wcxf2arrays(d): """Convert a dictionary with a Wilson coefficient name followed by underscore and numeric indices as keys and numbers as values to a dictionary with Wilson coefficient names as keys and numbers or numpy arrays as values. This is needed for the parsing of input in WCxf format.""" ...
def add_missing(C): """Add arrays with zeros for missing Wilson coefficient keys""" C_out = C.copy() for k in (set(WC_keys) - set(C.keys())): C_out[k] = np.zeros(C_keys_shape[k]) return C_out