text
stringlengths
18
773k
def post_object_list(request): """MNStorage.create(session, did, object, sysmeta) → Identifier.""" d1_gmn.app.views.assert_db.post_has_mime_parts( request, (('field', 'pid'), ('file', 'object'), ('file', 'sysmeta')) ) url_pid = request.POST['pid'] sysmeta_pyxb = d1_gmn.app.sysmeta.deserializ...
def put_object(request, old_pid): """MNStorage.update(session, pid, object, newPid, sysmeta) → Identifier.""" if django.conf.settings.REQUIRE_WHITELIST_FOR_UPDATE: d1_gmn.app.auth.assert_create_update_delete_permission(request) d1_gmn.app.util.coerce_put_post(request) d1_gmn.app.views.assert_db....
def post_generate_identifier(request): """MNStorage.generateIdentifier(session, scheme[, fragment]) → Identifier.""" d1_gmn.app.views.assert_db.post_has_mime_parts(request, (('field', 'scheme'),)) if request.POST['scheme'] != 'UUID': raise d1_common.types.exceptions.InvalidRequest( 0, 'O...
def put_archive(request, pid): """MNStorage.archive(session, did) → Identifier.""" d1_gmn.app.views.assert_db.is_not_replica(pid) d1_gmn.app.views.assert_db.is_not_archived(pid) d1_gmn.app.sysmeta.archive_sciobj(pid) return pid
def post_replicate(request): """MNReplication.replicate(session, sysmeta, sourceNode) → boolean.""" d1_gmn.app.views.assert_db.post_has_mime_parts( request, (('field', 'sourceNode'), ('file', 'sysmeta')) ) sysmeta_pyxb = d1_gmn.app.sysmeta.deserialize(request.FILES['sysmeta']) d1_gmn.app.loc...
def contribute_to_class(self, process, fields, name): """Register this field with a specific process. :param process: Process descriptor instance :param fields: Fields registry to use :param name: Field name """ self.name = name self.process = process fie...
def to_schema(self): """Return field schema for this field.""" if not self.name or not self.process: raise ValueError("field is not registered with process") schema = { 'name': self.name, 'type': self.get_field_type(), } if self.required is no...
def validate(self, value): """Validate field value.""" if self.required and value is None: raise ValidationError("field is required") if value is not None and self.choices is not None: choices = [choice for choice, _ in self.choices] if value not in choices: ...
def clean(self, value): """Run validators and return the clean value.""" if value is None: value = self.default try: value = self.to_python(value) self.validate(value) except ValidationError as error: raise ValidationError("invalid value f...
def validate(self, value): """Validate field value.""" if value is not None and not isinstance(value, str): raise ValidationError("field must be a string") super().validate(value)
def validate(self, value): """Validate field value.""" if value is not None and not isinstance(value, bool): raise ValidationError("field must be a boolean") super().validate(value)
def to_output(self, value): """Convert value to process output format.""" return json.loads(resolwe_runtime_utils.save(self.name, str(value)))
def to_python(self, value): """Convert value if needed.""" if isinstance(value, str): return value elif isinstance(value, dict): try: value = value['url'] except KeyError: raise ValidationError("dictionary must contain an 'url' ...
def import_file(self, imported_format=None, progress_from=0.0, progress_to=None): """Import field source file to working directory. :param imported_format: Import file format (extracted, compressed or both) :param progress_from: Initial progress value :param progress_to: Final progress ...
def to_python(self, value): """Convert value if needed.""" if isinstance(value, FileDescriptor): return value elif isinstance(value, str): return FileDescriptor(value) elif isinstance(value, dict): try: path = value['file'] ...
def to_output(self, value): """Convert value to process output format.""" return json.loads(resolwe_runtime_utils.save_file(self.name, value.path, *value.refs))
def to_python(self, value): """Convert value if needed.""" if isinstance(value, DirDescriptor): return value elif isinstance(value, str): return DirDescriptor(value) elif isinstance(value, dict): try: path = value['dir'] exc...
def contribute_to_class(self, process, fields, name): """Register this field with a specific process. :param process: Process descriptor instance :param fields: Fields registry to use :param name: Field name """ super().contribute_to_class(process, fields, name) ...
def to_output(self, value): """Convert value to process output format.""" return {self.name: [self.inner.to_output(v)[self.name] for v in value]}
def validate(self, value): """Validate field value.""" if value is not None: if not isinstance(value, list): raise ValidationError("field must be a list") for index, element in enumerate(value): try: self.inner.validate(element...
def _get(self, key): """Return given key from cache.""" self._populate_cache() if key not in self._cache: raise AttributeError("DataField has no member {}".format(key)) return self._cache[key]
def to_python(self, value): """Convert value if needed.""" cache = None if value is None: return None if isinstance(value, DataDescriptor): return value elif isinstance(value, dict): # Allow pre-hydrated data objects. cache = value...
def contribute_to_class(self, process, fields, name): """Register this field with a specific process. :param process: Process descriptor instance :param fields: Fields registry to use :param name: Field name """ # Use order-preserving definition namespace (__dict__) to r...
def to_python(self, value): """Convert value if needed.""" if isinstance(value, GroupDescriptor): value = value._value # pylint: disable=protected-access result = {} for name, field in self.fields.items(): result[name] = field.to_python(value.get(name, None)) ...
def to_schema(self): """Return field schema for this field.""" schema = super().to_schema() if self.disabled is not None: schema['disabled'] = self.disabled if self.collapsed is not None: schema['collapsed'] = self.collapsed group = [] for field i...
def update_constants(): """Recreate channel name constants with changed settings. This kludge is mostly needed due to the way Django settings are patched for testing and how modules need to be imported throughout the project. On import time, settings are not patched yet, but some of the code needs ...
def destroy_channels(self): """Destroy Redis channels managed by this state instance.""" for item_name in dir(self): item = getattr(self, item_name) if isinstance(item, self.RedisAtomicBase): self.redis.delete(item.item_name)
def render_to_image_file( self, image_out_path, width_pixels=None, height_pixels=None, dpi=90 ): """Render the SubjectInfo to an image file. Args: image_out_path : str Path to where image image will be written. Valid extensions are ``.svg,`` ``.pd...
def browse_in_qt5_ui(self): """Browse and edit the SubjectInfo in a simple Qt5 based UI.""" self._render_type = "browse" self._tree.show(tree_style=self._get_tree_style())
def _gen_etetoolkit_tree(self, node, subject_info_tree): """Copy SubjectInfoTree to a ETE Tree.""" for si_node in subject_info_tree.child_list: if si_node.type_str == TYPE_NODE_TAG: child = self._add_type_node(node, si_node.label_str) elif si_node.type_str == SUBJ...
def _add_type_node(self, node, label): """Add a node representing a SubjectInfo type.""" child = node.add_child(name=label) child.add_feature(TYPE_NODE_TAG, True) return child
def _add_subject_node(self, node, subj_str): """Add a node containing a subject string.""" child = node.add_child(name=subj_str) child.add_feature(SUBJECT_NODE_TAG, True) return child
def _get_node_path(self, node): """Return the path from the root to ``node`` as a list of node names.""" path = [] while node.up: path.append(node.name) node = node.up return list(reversed(path))
def _layout(self, node): """ETE calls this function to style each node before rendering. - ETE terms: - A Style is a specification for how to render the node itself - A Face defines extra information that is rendered outside of the node - Face objects are used here to provide mo...
def extend_settings(self, data_id, files, secrets): """Prevent processes requiring access to secrets from being run.""" process = Data.objects.get(pk=data_id).process if process.requirements.get('resources', {}).get('secrets', False): raise PermissionDenied( "Process ...
def get_finder(import_path): """Get a process finder.""" finder_class = import_string(import_path) if not issubclass(finder_class, BaseProcessesFinder): raise ImproperlyConfigured( 'Finder "{}" is not a subclass of "{}"'.format(finder_class, BaseProcessesFinder)) return finder_class(...
def _find_folders(self, folder_name): """Return a list of sub-directories.""" found_folders = [] for app_config in apps.get_app_configs(): folder_path = os.path.join(app_config.path, folder_name) if os.path.isdir(folder_path): found_folders.append(folder_p...
def sanity(request, sysmeta_pyxb): """Check that sysmeta_pyxb is suitable for creating a new object and matches the uploaded sciobj bytes.""" _does_not_contain_replica_sections(sysmeta_pyxb) _is_not_archived(sysmeta_pyxb) _obsoleted_by_not_specified(sysmeta_pyxb) if 'HTTP_VENDOR_GMN_REMOTE_URL' ...
def is_valid_sid_for_new_standalone(sysmeta_pyxb): """Assert that any SID in ``sysmeta_pyxb`` can be assigned to a new standalone object.""" sid = d1_common.xml.get_opt_val(sysmeta_pyxb, 'seriesId') if not d1_gmn.app.did.is_valid_sid_for_new_standalone(sid): raise d1_common.types.exceptions.Iden...
def is_valid_sid_for_chain(pid, sid): """Assert that ``sid`` can be assigned to the single object ``pid`` or to the chain to which ``pid`` belongs. - If the chain does not have a SID, the new SID must be previously unused. - If the chain already has a SID, the new SID must match the existing SID. ...
def _does_not_contain_replica_sections(sysmeta_pyxb): """Assert that ``sysmeta_pyxb`` does not contain any replica information.""" if len(getattr(sysmeta_pyxb, 'replica', [])): raise d1_common.types.exceptions.InvalidSystemMetadata( 0, 'A replica section was included. A new objec...
def _is_not_archived(sysmeta_pyxb): """Assert that ``sysmeta_pyxb`` does not have have the archived flag set.""" if _is_archived(sysmeta_pyxb): raise d1_common.types.exceptions.InvalidSystemMetadata( 0, 'Archived flag was set. A new object created via create() or update() ' ...
def get_d1_env_by_base_url(cn_base_url): """Given the BaseURL for a CN, return the DataONE environment dict for the CN's environemnt.""" for k, v in D1_ENV_DICT: if v['base_url'].startswith(cn_base_url): return D1_ENV_DICT[k]
def match_all(d_SMEFT, parameters=None): """Match the SMEFT Warsaw basis onto the WET JMS basis.""" p = default_parameters.copy() if parameters is not None: # if parameters are passed in, overwrite the default values p.update(parameters) C = wilson.util.smeftutil.wcxf2arrays_symmetrized(...
def _debug_mode_responses(self, request, response): """Extra functionality available in debug mode. - If pretty printed output was requested, force the content type to text. This causes the browser to not try to format the output in any way. - If SQL profiling is turned on, return a p...
def queryResponse( self, queryEngine, query_str, vendorSpecific=None, do_post=False, **kwargs ): """CNRead.query(session, queryEngine, query) → OctetStream https://releases.dataone.org/online/api- documentation-v2.0.1/apis/CN_APIs.html#CNRead.query MNQuery.query(session, quer...
def query( self, queryEngine, query_str, vendorSpecific=None, do_post=False, **kwargs ): """See Also: queryResponse() Args: queryEngine: query_str: vendorSpecific: do_post: **kwargs: Returns: """ response = self.que...
def getQueryEngineDescriptionResponse(self, queryEngine, vendorSpecific=None, **kwargs): """CNRead.getQueryEngineDescription(session, queryEngine) → QueryEngineDescription https://releases.dataone.org/online/api- documentation-v2.0.1/apis/CN_APIs.html#CNRead.getQueryEngineDescription MNQ...
def getQueryEngineDescription(self, queryEngine, **kwargs): """See Also: getQueryEngineDescriptionResponse() Args: queryEngine: **kwargs: Returns: """ response = self.getQueryEngineDescriptionResponse(queryEngine, **kwargs) return self._read_dataone...
def _get_cache_key(self, obj): """Derive cache key for given object.""" if obj is not None: # Make sure that key is REALLY unique. return '{}-{}'.format(id(self), obj.pk) return "{}-None".format(id(self))
def set(self, obj, build_kwargs): """Set cached value.""" if build_kwargs is None: build_kwargs = {} cached = {} if 'queryset' in build_kwargs: cached = { 'model': build_kwargs['queryset'].model, 'pks': list(build_kwargs['queryset'...
def take(self, obj): """Get cached value and clean cache.""" cached = self._thread_local.cache[self._get_cache_key(obj)] build_kwargs = {} if 'model' in cached and 'pks' in cached: build_kwargs['queryset'] = cached['model'].objects.filter(pk__in=cached['pks']) elif ...
def connect(self, signal, **kwargs): """Connect a specific signal type to this receiver.""" signal.connect(self, **kwargs) self.connections.append((signal, kwargs))
def disconnect(self): """Disconnect all connected signal types from this receiver.""" for signal, kwargs in self.connections: signal.disconnect(self, **kwargs)
def connect(self, index): """Connect signals needed for dependency updates. Pre- and post-delete signals have to be handled separately, as: * in the pre-delete signal we have the information which objects to rebuild, but affected relations are still presented, so rebu...
def connect(self, index): """Connect signals needed for dependency updates.""" # Determine which model is the target model as either side of the relation # may be passed as `field`. if index.object_type == self.field.rel.model: self.model = self.field.rel.related_model ...
def _filter(self, objects, **kwargs): """Determine if dependent object should be processed.""" for obj in objects: if self.filter(obj, **kwargs) is False: return False return True
def _get_build_kwargs(self, obj, pk_set=None, action=None, update_fields=None, reverse=None, **kwargs): """Prepare arguments for rebuilding indices.""" if action is None: # Check filter before rebuilding index. if not self._filter([obj], update_fields=update_fields): ...
def process_predelete(self, obj, pk_set=None, action=None, update_fields=None, **kwargs): """Render the queryset of influenced objects and cache it.""" build_kwargs = self._get_build_kwargs(obj, pk_set, action, update_fields, **kwargs) self.delete_cache.set(obj, build_kwargs)
def process_delete(self, obj, pk_set=None, action=None, update_fields=None, **kwargs): """Recreate queryset from the index and rebuild the index.""" build_kwargs = self.delete_cache.take(obj) if build_kwargs: self.index.build(**build_kwargs)
def process_m2m(self, obj, pk_set=None, action=None, update_fields=None, cache_key=None, **kwargs): """Process signals from dependencies. Remove signal is processed in two parts. For details see: :func:`~Dependency.connect` """ if action not in (None, 'post_add', 'pre_remove', '...
def _process_m2m_through(self, obj, action): """Process custom M2M through model actions.""" source = getattr(obj, self.field.rel.field.m2m_field_name()) target = getattr(obj, self.field.rel.field.m2m_reverse_field_name()) pk_set = set() if target: pk_set.add(target....
def process_m2m_through_save(self, obj, created=False, **kwargs): """Process M2M post save for custom through model.""" # We are only interested in signals that establish relations. if not created: return self._process_m2m_through(obj, 'post_add')
def process(self, obj, pk_set=None, action=None, update_fields=None, **kwargs): """Process signals from dependencies.""" build_kwargs = self._get_build_kwargs(obj, pk_set, action, update_fields, **kwargs) if build_kwargs: self.index.build(**build_kwargs)
def _connect_signal(self, index): """Create signals for building indexes.""" post_save_signal = ElasticSignal(index, 'build') post_save_signal.connect(post_save, sender=index.object_type) self.signals.append(post_save_signal) post_delete_signal = ElasticSignal(index, 'remove_obj...
def register_signals(self): """Register signals for all indexes.""" for index in self.indexes: if index.object_type: self._connect_signal(index)
def discover_indexes(self): """Save list of index builders into ``_index_builders``.""" self.indexes = [] for app_config in apps.get_app_configs(): indexes_path = '{}.elastic_indexes'.format(app_config.name) try: indexes_module = import_module(indexes_pat...
def build(self, obj=None, queryset=None, push=True): """Trigger building of the indexes. Support passing ``obj`` parameter to the indexes, so we can trigger build only for one object. """ for index in self.indexes: index.build(obj, queryset, push)
def push(self, index=None): """Push built documents to ElasticSearch. If ``index`` is specified, only that index will be pushed. """ for ind in self.indexes: if index and not isinstance(ind, index): continue ind.push()
def delete(self, skip_mapping=False): """Delete all entries from ElasticSearch.""" for index in self.indexes: index.destroy() if not skip_mapping: index.create_mapping()
def destroy(self): """Delete all indexes from Elasticsearch and index builder.""" self.unregister_signals() for index in self.indexes: index.destroy() self.indexes = []
def _set_initial(self, C_in, scale_in): r"""Set the initial values for parameters and Wilson coefficients at the scale `scale_in`.""" self.C_in = C_in self.scale_in = scale_in
def _set_initial_wcxf(self, wc, get_smpar=True): """Load the initial values for Wilson coefficients from a wcxf.WC instance. Parameters: - `get_smpar`: boolean, optional, defaults to True. If True, an attempt is made to determine the SM parameters from the requirement of ...
def _to_wcxf(self, C_out, scale_out): """Return the Wilson coefficients `C_out` as a wcxf.WC instance. Note that the Wilson coefficients are rotated into the Warsaw basis as defined in WCxf, i.e. to the basis where the down-type and charged lepton mass matrices are diagonal.""" ...
def _rgevolve(self, scale_out, **kwargs): """Solve the SMEFT RGEs from the initial scale to `scale_out`. Returns a dictionary with parameters and Wilson coefficients at `scale_out`. Additional keyword arguments will be passed to the ODE solver `scipy.integrate.odeint`.""" self._c...
def _rgevolve_leadinglog(self, scale_out): """Compute the leading logarithmic approximation to the solution of the SMEFT RGEs from the initial scale to `scale_out`. Returns a dictionary with parameters and Wilson coefficients. Much faster but less precise that `rgevolve`. """ ...
def _run_sm_scale_in(self, C_out, scale_sm=91.1876): """Get the SM parameters at the EW scale, using an estimate `C_out` of the Wilson coefficients at that scale, and run them to the input scale.""" # initialize an empty SMEFT instance smeft_sm = SMEFT(wc=None) C_in_sm = ...
def get_smpar(self, accuracy='integrate', scale_sm=91.1876): """Compute the SM MS-bar parameters at the electroweak scale. This method can be used to validate the accuracy of the iterative extraction of SM parameters. If successful, the values returned by this method should agree with t...
def _get_sm_scale_in(self, scale_sm=91.1876): """Get an estimate of the SM parameters at the input scale by running them from the EW scale using constant values for the Wilson coefficients (corresponding to their leading log approximated values at the EW scale). Note that this i...
def run(self, scale, accuracy='integrate', **kwargs): """Return the Wilson coefficients (as wcxf.WC instance) evolved to the scale `scale`. Parameters: - `scale`: scale in GeV - accuracy: whether to use the numerical solution to the RGE ('integrate', the default, slow ...
def run_continuous(self, scale): """Return a continuous solution to the RGE as `RGsolution` instance.""" if scale == self.scale_in: raise ValueError("The scale must be different from the input scale") elif scale < self.scale_in: scale_min = scale scale_max = s...
def deconstruct(self): """Deconstruct method.""" name, path, args, kwargs = super().deconstruct() if self.populate_from is not None: kwargs['populate_from'] = self.populate_from if self.unique_with != (): kwargs['unique_with'] = self.unique_with kwar...
def _get_unique_constraints(self, instance): """Return SQL filter for filtering by fields in ``unique_with`` attribute. Filter is returned as tuple of two elements where first one is placeholder which is safe to insert into SQL query and second one may include potentially dangerous valu...
def _get_populate_from_value(self, instance): """Get the value from ``populate_from`` attribute.""" if hasattr(self.populate_from, '__call__'): # ResolweSlugField(populate_from=lambda instance: ...) return self.populate_from(instance) else: # ResolweSlugField(...
def pre_save(self, instance, add): """Ensure slug uniqunes before save.""" slug = self.value_from_object(instance) # We don't want to change slug defined by user. predefined_slug = bool(slug) if not slug and self.populate_from: slug = self._get_populate_from_value(i...
def discover_process(self, path): """Perform process discovery in given path. This method will be called during process registration and should return a list of dictionaries with discovered process schemas. """ if not path.lower().endswith(('.yml', '.yaml')): ...
def _evaluate_expressions(self, expression_engine, step_id, values, context): """Recursively evaluate expressions in a dictionary of values.""" if expression_engine is None: return values processed = {} for name, value in values.items(): if isinstance(value, str)...
def evaluate(self, data): """Evaluate the code needed to compute a given Data object.""" expression_engine = data.process.requirements.get('expression-engine', None) if expression_engine is not None: expression_engine = self.get_expression_engine(expression_engine) # Parse s...
async def init(): """Create a connection to the Redis server.""" global redis_conn # pylint: disable=global-statement,invalid-name conn = await aioredis.create_connection( 'redis://{}:{}'.format( SETTINGS.get('FLOW_EXECUTOR', {}).get('REDIS_CONNECTION', {}).get('host', 'localhost'), ...
async def send_manager_command(cmd, expect_reply=True, extra_fields={}): """Send a properly formatted command to the manager. :param cmd: The command to send (:class:`str`). :param expect_reply: If ``True``, wait for the manager to reply with an acknowledgement packet. :param extra_fields: A di...
def extract_values_query(query, field_list, out_stream=None): """Get list of dicts where each dict holds values from one SciObj. Args: field_list: list of str List of field names for which to return values. Must be strings from FIELD_NAME_TO_generate_dict.keys(). If...
def extract_values(field_list=None, filter_arg_dict=None, out_stream=None): """Get list of dicts where each dict holds values from one SciObj. Args: field_list: list of str List of field names for which to return values. Must be strings from FIELD_NAME_TO_generate_dict.keys(). ...
def assert_invalid_field_list(field_list): """raise d1_common.types.exceptions.InvalidRequest() if ``field_list`` contains any invalid field names. A list of the invalid fields is included in the exception. - Implicitly called by ``extract_values()``. """ if field_list is not None: invalid...
def _annotate_query(query, generate_dict): """Add annotations to the query to retrieve values required by field value generate functions.""" annotate_key_list = [] for field_name, annotate_dict in generate_dict.items(): for annotate_name, annotate_func in annotate_dict["annotate_dict"].items(): ...
def _value_list_to_sciobj_dict( sciobj_value_list, lookup_list, lookup_dict, generate_dict ): """Create a dict where the keys are the requested field names, from the values returned by Django.""" sciobj_dict = {} # for sciobj_value, lookup_str in zip(sciobj_value_list, lookup_list): lookup_to_...
def _split_field_list(field_list): """Split the list of fields for which to extract values into lists by extraction methods. - Remove any duplicated field names. - Raises ValueError with list of any invalid field names in ``field_list``. """ lookup_dict = {} generate_dict = {} for fie...
def dataoneTypes(request): """Return the PyXB binding to use when handling a request.""" if is_v1_api(request): return d1_common.types.dataoneTypes_v1_1 elif is_v2_api(request) or is_diag_api(request): return d1_common.types.dataoneTypes_v2_0 else: raise d1_common.types.exception...
def parse_and_normalize_url_date(date_str): """Parse a ISO 8601 date-time with optional timezone. - Return as datetime with timezone adjusted to UTC. - Return naive date-time set to UTC. """ if date_str is None: return None try: return d1_common.date_time.dt_from_iso8601_str(da...
def get(self, doc_id): """Retrieve the specified document.""" resp_dict = self._get_query(q='id:{}'.format(doc_id)) if resp_dict['response']['numFound'] > 0: return resp_dict['response']['docs'][0]
def get_ids(self, start=0, rows=1000, **query_dict): """Retrieve a list of identifiers for documents matching the query.""" resp_dict = self._get_query(start=start, rows=rows, **query_dict) return { 'matches': resp_dict['response']['numFound'], 'start': start, ...