text
stringlengths
81
112k
updatereplication <identifier> [identifier ...] Update the Replication Policy on one or more existing Science Data Objects. def do_updatereplication(self, line): """updatereplication <identifier> [identifier ...] Update the Replication Policy on one or more existing Science Data Objects.""" ...
search [query] Comprehensive search for Science Data Objects across all available MNs. See https://releases.dataone.org/online/api- documentation-v2.0.1/design/SearchMetadata.html for the available search terms. def do_search(self, line): """search [query] Comprehensive search for Scie...
ping [base-url ...] Check if a server responds to the DataONE ping() API method ping (no arguments): Ping the CN and MN that is specified in the session ping <base-url> [base-url ...]: Ping each CN or MN. If an incomplete base-url is provided, default CN and MN base URLs at the given ur...
queue Print the queue of write operations. def do_queue(self, line): """queue Print the queue of write operations.""" self._split_args(line, 0, 0) self._command_processor.get_operation_queue().display()
run Perform each operation in the queue of write operations. def do_run(self, line): """run Perform each operation in the queue of write operations.""" self._split_args(line, 0, 0) self._command_processor.get_operation_queue().execute() self._print_info_if_verbose( "All oper...
edit Edit the queue of write operations. def do_edit(self, line): """edit Edit the queue of write operations.""" self._split_args(line, 0, 0) self._command_processor.get_operation_queue().edit() self._print_info_if_verbose("The write operation queue was successfully edited")
clearqueue Remove the operations in the queue of write operations without performing them. def do_clearqueue(self, line): """clearqueue Remove the operations in the queue of write operations without performing them.""" self._split_args(line, 0, 0) self._command_processor.get_ope...
Custom help message to group commands by functionality. def _print_help(self): """Custom help message to group commands by functionality.""" msg = """Commands (type help <command> for details) CLI: help history exit quit Session, General: set load save reset Session, Access ...
Return queryset of all ``Group`` objects with *any* object permissions for the given ``obj``. def get_groups_with_perms(obj, attach_perms=False): """Return queryset of all ``Group`` objects with *any* object permissions for the given ``obj``.""" ctype = get_content_type(obj) group_model = get_group_obj_per...
Group permissions by group. Input is list of tuples of length 3, where each tuple is in following format:: (<group_id>, <group_name>, <single_permission>) Permissions are regrouped and returned in such way that there is only one tuple for each group:: (<group_id>, <group_name>, [<fir...
Get permissins for user groups. Based on guardian.core.ObjectPermissionChecker. def get_user_group_perms(user_or_group, obj): """Get permissins for user groups. Based on guardian.core.ObjectPermissionChecker. """ user, group = get_identity(user_or_group) if user and not user.is_active: ...
Return permissions for given object in Resolwe specific format. Function returns permissions for given object ``obj`` in following format:: { "type": "group"/"user"/"public", "id": <group_or_user_id>, "name": <group_or_user_name>, "permissions": [<first_permi...
Return queryset with required permissions. def get_objects_for_user(user, perms, klass=None, use_groups=True, any_perm=False, with_superuser=True, accept_global_perms=True, perms_filter='pk__in'): """Return queryset with required permissions.""" if isinstance(perms, str): perms...
Return users with specific permission on object. :param obj: Object to return users for :param permission: Permission codename def get_users_with_permission(obj, permission): """Return users with specific permission on object. :param obj: Object to return users for :param permission: Permission c...
Run purge for the object with ``location_id`` specified in ``event`` argument. def purge_run(self, event): """Run purge for the object with ``location_id`` specified in ``event`` argument.""" location_id = event['location_id'] verbosity = event['verbosity'] try: logger.info...
Get the core count and memory usage limits for this process. :return: A dictionary with the resource limits, containing the following keys: - ``memory``: Memory usage limit, in MB. Defaults to 4096 if not otherwise specified in the resource requirements. - ``c...
Ensure no unsupported query params were used. def validate_query_params(self): """Ensure no unsupported query params were used.""" allowed_params = set(self.get_filters().keys()) allowed_params.update(self.get_always_allowed_arguments()) unallowed = set(self.request.query_params.keys()...
Class method. Set the default value of the option `key` (string) to `value` for all future instances of the class. Note that this does not affect existing instances or the instance called from. def set_default_option(cls, key, value): """Class method. Set the default value of the optio...
Set the option `key` (string) to `value`. Instance method, affects only current instance. This will clear the cache. def set_option(self, key, value): """Set the option `key` (string) to `value`. Instance method, affects only current instance. This will clear the cache.""" ...
Return the current value of the option `key` (string). Instance method, only refers to current instance. def get_option(self, key): """Return the current value of the option `key` (string). Instance method, only refers to current instance.""" return self._options.get(key, self._defaul...
Return a `Wilson` instance initialized by a `wcxf.WC` instance def from_wc(cls, wc): """Return a `Wilson` instance initialized by a `wcxf.WC` instance""" return cls(wcdict=wc.dict, scale=wc.scale, eft=wc.eft, basis=wc.basis)
Return a `Wilson` instance initialized by a WCxf file-like object def load_wc(cls, stream): """Return a `Wilson` instance initialized by a WCxf file-like object""" wc = wcxf.WC.load(stream) return cls.from_wc(wc)
Run the Wilson coefficients to a different scale (and possibly different EFT) and return them as `wcxf.WC` instance. Parameters: - `scale`: output scale in GeV - `eft`: output EFT - `basis`: output basis - `sectors`: in the case of WET (or WET-4 or WET-3), a tup...
Try to load a set of Wilson coefficients from the cache, else return None. def _get_from_cache(self, sector, scale, eft, basis): """Try to load a set of Wilson coefficients from the cache, else return None.""" try: return self._cache[eft][scale][basis][sector] except...
Return a tuple of arrays x, y that can be fed to plt.plot, where x is the scale in GeV and y is the parameter of interest. Parameters: - key: dicionary key of the parameter to be plotted (e.g. a WCxf coefficient name or a SM parameter like 'g') - part: plot the real part 're'...
Plot the RG evolution of parameter `key`. Parameters: - part, scale, steps: see `plotdata` - legend: boolean, show the legend (default: True) - plotargs: dictionary of arguments to be passed to plt.plot def plot(self, key, part='re', scale='log', steps=50, legend=True, plotargs={}): ...
Run the consumer until it finishes processing. :param timeout: Set maximum execution time before cancellation, or ``None`` (default) for unlimited. :param dry_run: If ``True``, don't actually dispatch messages, just dequeue them. Defaults to ``False``. async def run_consumer(timeout=None, dry_...
Discover available extensions. def discover_extensions(self): """Discover available extensions.""" if self._discovery_done: return try: previous_state = self._extensions.copy() for app_config in apps.get_app_configs(): indexes_path = '{}.ext...
Return class path for a given class. :param klass_or_instance: Class or instance of given class :return: String containing the class path def _get_class_path(self, klass_or_instance): """Return class path for a given class. :param klass_or_instance: Class or instance of given class ...
Register an extension for a class. :param klass: Class to register an extension for :param extension: Extension (arbitrary type) def add_extension(self, klass, extension): """Register an extension for a class. :param klass: Class to register an extension for :param extension: ...
Return all registered extensions of a class. :param klass: Class to get registered extensions for :return: All registered extensions for given class def get_extensions(self, klass): """Return all registered extensions of a class. :param klass: Class to get registered extensions for ...
Get the running parameters (e.g. quark masses and the strong coupling at a given scale. def _get_running_parameters(self, scale, f, loop=3): """Get the running parameters (e.g. quark masses and the strong coupling at a given scale.""" p = {} p['alpha_s'] = qcd.alpha_s(scale, sel...
Evolve the Wilson coefficients to the scale `scale_out`. Parameters: - scale_out: output scale - sectors: optional. If provided, must be a tuple of strings corresponding to WCxf sector names. Only Wilson coefficients belonging to these sectors will be present in the output....
Returns: int : The total number of bytes that will be returned by the iterator. def size(self): """Returns: int : The total number of bytes that will be returned by the iterator. """ if hasattr(self._stream, 'len'): return len(self._stream) elif hasattr(self....
Get the public TLS/SSL X.509 certificate from the root CN of the DataONE environment. The certificate is used for validating the signature of the JWTs. If certificate retrieval fails, a new attempt to retrieve the certificate is performed after the cache expires (settings.CACHES.default.TIMEOUT). If s...
Takes a user's API key string which applies content settings. API keys can be found at <https://derpibooru.org/users/edit>. def key(self, key=""): """ Takes a user's API key string which applies content settings. API keys can be found at <https://derpibooru.org/users/edit>. """ params = join_pa...
Takes one or more strings for searching by tag and/or metadata. def query(self, *q): """ Takes one or more strings for searching by tag and/or metadata. """ params = join_params(self.parameters, {"q": q}) return self.__class__(**params)
Determines how to sort search results. Available sorting methods are sort.SCORE, sort.COMMENTS, sort.HEIGHT, sort.RELEVANCE, sort.CREATED_AT, and sort.RANDOM; default is sort.CREATED_AT. def sort_by(self, sf): """ Determines how to sort search results. Available sorting methods are sort.SCORE, sort...
Set absolute limit on number of images to return, or set to None to return as many results as needed; default 50 posts. def limit(self, limit): """ Set absolute limit on number of images to return, or set to None to return as many results as needed; default 50 posts. """ params = join_params(se...
Takes a filter's ID to be used in the current search context. Filter IDs can be found at <https://derpibooru.org/filters/> by inspecting the URL parameters. If no filter is provided, the user's current filter will be used. def filter(self, filter_id=""): """ Takes a filter's ID to be used in the c...
Set whether to filter by a user's faves list. Options available are user.ONLY, user.NOT, and None; default is None. def faves(self, option): """ Set whether to filter by a user's faves list. Options available are user.ONLY, user.NOT, and None; default is None. """ params = join_params(self.para...
Set whether to filter by a user's upvoted list. Options available are user.ONLY, user.NOT, and None; default is None. def upvotes(self, option): """ Set whether to filter by a user's upvoted list. Options available are user.ONLY, user.NOT, and None; default is None. """ params = join_params(sel...
Set whether to filter by a user's uploads list. Options available are user.ONLY, user.NOT, and None; default is None. def uploads(self, option): """ Set whether to filter by a user's uploads list. Options available are user.ONLY, user.NOT, and None; default is None. """ params = join_params(sel...
Set whether to filter by a user's watchlist. Options available are user.ONLY, user.NOT, and None; default is None. def watched(self, option): """ Set whether to filter by a user's watchlist. Options available are user.ONLY, user.NOT, and None; default is None. """ params = join_params(self.para...
Define contributor by adding it to request.data. def define_contributor(self, request): """Define contributor by adding it to request.data.""" request.data['contributor'] = self.resolve_user(request.user).pk
Create a resource. def create(self, request, *args, **kwargs): """Create a resource.""" self.define_contributor(request) try: return super().create(request, *args, **kwargs) except IntegrityError as ex: return Response({'error': str(ex)}, status=status.HTTP_409...
Create a resource. def perform_create(self, serializer): """Create a resource.""" with transaction.atomic(): instance = serializer.save() # Assign all permissions to the object contributor. assign_contributor_permissions(instance)
Update a resource. def update(self, request, *args, **kwargs): """Update a resource.""" # NOTE: Use the original method instead when support for locking is added: # https://github.com/encode/django-rest-framework/issues/4675 # return super().update(request, *args, **kwargs) ...
Update a resource. def _update(self, request, *args, **kwargs): """Update a resource.""" partial = kwargs.pop('partial', False) # NOTE: The line below was changed. instance = self.get_object_with_lock() serializer = self.get_serializer(instance, data=request.data, partial=partia...
Check if given url slug exists. Check if slug given in query parameter ``name`` exists. Return ``True`` if slug already exists and ``False`` otherwise. def slug_exists(self, request): """Check if given url slug exists. Check if slug given in query parameter ``name`` exists. Return ...
Extract a list of integers from request data. def get_ids(self, request_data, parameter_name='ids'): """Extract a list of integers from request data.""" if parameter_name not in request_data: raise ParseError("`{}` parameter is required".format(parameter_name)) ids = request_data.g...
Extract an integer from request data. def get_id(self, request_data, parameter_name='id'): """Extract an integer from request data.""" if parameter_name not in request_data: raise ParseError("`{}` parameter is required".format(parameter_name)) id_parameter = request_data.get(parame...
Deserialize a DataONE Exception XML doc. def deserialize(dataone_exception_xml): """Deserialize a DataONE Exception XML doc.""" # logging.debug('dataone_exception_xml="{}"' # .format(d1_common.xml.pretty_xml(dataone_exception_xml))) try: dataone_exception_pyxb = d1_common.xml.deserialize_d1_exc...
Deserialize a DataONE Exception that is stored in a map of HTTP headers (used in responses to HTTP HEAD requests). def deserialize_from_headers(headers): """Deserialize a DataONE Exception that is stored in a map of HTTP headers (used in responses to HTTP HEAD requests).""" return create_exception_by_n...
Create a DataONEException based object by name. Args: name: str The type name of a DataONE Exception. E.g. NotFound. If an unknown type name is used, it is automatically set to ServiceFailure. As the XML Schema for DataONE Exceptions does not restrict the type names, this may...
Create a DataONE Exception object by errorCode. See Also: For args, see: ``DataONEException()`` def create_exception_by_error_code( errorCode, detailCode='0', description='', traceInformation=None, identifier=None, nodeId=None, ): """Create a DataONE Exception object by errorCode. ...
Format a string for inclusion in the exception's string representation. If msg is None, format to empty string. If msg has a single line, format to: tag: msg If msg has multiple lines, format to: tag: line 1 line 2 Msg is truncated to 1024 chars. def _fmt(self, tag, msg): """Format...
Serialize to a format more suitable for displaying to end users. def friendly_format(self): """Serialize to a format more suitable for displaying to end users.""" if self.description is not None: msg = self.description else: msg = 'errorCode: {} / detailCode: {}'.format(...
Serialize to XML ``bytes`` with prolog. Args: encoding: str Encoding to use for XML doc bytes xslt_url: str If specified, add a processing instruction to the XML doc that specifies the download location for an XSLT stylesheet. Returns: ...
Serialize to a pretty printed Unicode str, suitable for display. Args: xslt_url: url Optional link to an XSLT stylesheet. If provided, a processing instruction for the stylesheet is included in the XML prolog. def serialize_to_display(self, xslt_url=None): """Serialize to a pretty pr...
Serialize to a dict of HTTP headers. Used in responses to HTTP HEAD requests. As with regular HTTP GET requests, HEAD requests may return DataONE Exceptions. Since a response to a HEAD request cannot include a body, the error is returned as a set of HTTP headers instead of an XML docume...
Generate a DataONE Exception PyXB object. The PyXB object supports directly reading and writing the individual values that may be included in a DataONE Exception. def get_pyxb(self): """Generate a DataONE Exception PyXB object. The PyXB object supports directly reading and writing the...
Create empty dependency relation if parent has been deleted. def recreate_parent_dependencies(apps, schema_editor): """Create empty dependency relation if parent has been deleted.""" Data = apps.get_model('flow', 'Data') DataDependency = apps.get_model('flow', 'DataDependency') def process_dependency(...
Filter records that do not have ``read`` or better access for one or more of the active subjects. Since ``read`` is the lowest access level that a subject can have, this method only has to filter on the presence of the subject. def add_access_policy_filter(request, query, column_name): """Filter recor...
Flag LogEntry records that require ``ipAddress`` and ``subject`` fields to be redacted before being returned to the client. Only trusted subjects and subjects with ``write`` or ``changePermission`` on a SciObj receive unredacted ``ipAddress`` and ``subject`` in LogEntry records for the associated SciOb...
Add ``total_size`` field to all file/dir-type outputs. def calculate_total_size(apps, schema_editor): """Add ``total_size`` field to all file/dir-type outputs.""" Data = apps.get_model('flow', 'Data') for data in Data.objects.all(): hydrate_size(data, force=True) data.save()
Remove ``total_size`` field from all file/dir-type outputs. def remove_total_size(apps, schema_editor): """Remove ``total_size`` field from all file/dir-type outputs.""" Data = apps.get_model('flow', 'Data') for data in Data.objects.all(): for field_schema, fields in iterate_fields(data.output, dat...
Assert that ``did`` can be used as a PID for creating a new object with MNStorage.create() or MNStorage.update(). def is_valid_pid_for_create(did): """Assert that ``did`` can be used as a PID for creating a new object with MNStorage.create() or MNStorage.update().""" if not d1_gmn.app.did.is_valid_pid_...
Assert that ``did`` is the PID of an object that can be updated (obsoleted) with MNStorage.update() def is_valid_pid_to_be_updated(did): """Assert that ``did`` is the PID of an object that can be updated (obsoleted) with MNStorage.update()""" if not d1_gmn.app.did.is_valid_pid_to_be_updated(did): ...
Validate that a MMP POST contains all required sections. :param request: Django Request :param parts: [(part_type, part_name), ...] :return: None or raises exception. Where information is stored in the request: part_type header: request.META['HTTP_<UPPER CASE NAME>'] part_type file: request.FI...
Return a list of decades which is covered by date range. def _decade_ranges_in_date_range(self, begin_date, end_date): """Return a list of decades which is covered by date range.""" begin_dated = begin_date.year / 10 end_dated = end_date.year / 10 decades = [] for d in range(beg...
Return a list of years in one decade which is covered by date range. def _years_in_date_range_within_decade(self, decade, begin_date, end_date): """Return a list of years in one decade which is covered by date range.""" begin_year = begin_date.year end_year = end_date.year if begin_year...
Solve the SMEFT RGEs in the leading log approximation. Input C_in and output C_out are dictionaries of arrays. def smeft_evolve_leadinglog(C_in, scale_in, scale_out, newphys=True): """Solve the SMEFT RGEs in the leading log approximation. Input C_in and output C_out are dictionaries of arrays.""" C_o...
Axuliary function used in `smeft_evolve` and `smeft_evolve_continuous` def _smeft_evolve(C_in, scale_in, scale_out, newphys=True, **kwargs): """Axuliary function used in `smeft_evolve` and `smeft_evolve_continuous`""" def fun(t0, y): return beta.beta_array(C=C_array2dict(y.view(complex)), ...
Solve the SMEFT RGEs by numeric integration. Input C_in and output C_out are dictionaries of arrays. def smeft_evolve(C_in, scale_in, scale_out, newphys=True, **kwargs): """Solve the SMEFT RGEs by numeric integration. Input C_in and output C_out are dictionaries of arrays.""" sol = _smeft_evolve(C_in...
Solve the SMEFT RGEs by numeric integration, returning a function that allows to compute an interpolated solution at arbitrary intermediate scales. def smeft_evolve_continuous(C_in, scale_in, scale_out, newphys=True, **kwargs): """Solve the SMEFT RGEs by numeric integration, returning a function that a...
Show an invalid index error message. def invalid_index(self, name): """Show an invalid index error message.""" self.stderr.write("Unknown index: {}".format(name)) self.stderr.write("Supported indices are:") for index in index_builder.indexes: self.stderr.write(" * {}".forma...
Filter indices and execute an action for each index. def filter_indices(self, options, verbosity, *args, **kwargs): """Filter indices and execute an action for each index.""" index_name_map = { index.__class__.__name__: index for index in index_builder.indexes } ...
Generate display name for contributor. def get_contributor_sort_value(self, obj): """Generate display name for contributor.""" user = obj.contributor if user.first_name or user.last_name: contributor = user.get_full_name() else: contributor = user.username ...
Generate user filtering tokens. def _get_user(self, user): """Generate user filtering tokens.""" return ' '.join([user.username, user.first_name, user.last_name])
Extract owners' ids. def get_owner_ids_value(self, obj): """Extract owners' ids.""" return [ user.pk for user in get_users_with_permission(obj, get_full_perm('owner', obj)) ]
Extract owners' names. def get_owner_names_value(self, obj): """Extract owners' names.""" return [ self._get_user(user) for user in get_users_with_permission(obj, get_full_perm('owner', obj)) ]
Return ``param_str`` converted to an int. If str cannot be converted to int or int is not zero or positive, raise InvalidRequest. def _get_and_assert_slice_param(url_dict, param_name, default_int): """Return ``param_str`` converted to an int. If str cannot be converted to int or int is not zero or po...
Assert that the number of objects visible to the active subject is higher than the requested start position for the slice. This ensures that it's possible to create a valid slice. def _assert_valid_start(start_int, count_int, total_int): """Assert that the number of objects visible to the active subject i...
Adjust requested object count down if there are not enough objects visible to the active subjects to cover the requested slice start and count. Preconditions: start is verified to be lower than the number of visible objects, making it possible to create a valid slice by adjusting count. def _adjust_count_...
Create a slice of a query based on request start and count parameters. This adds `OFFSET <start> LIMIT <count>` to the SQL query, which causes slicing to run very slowly on large result sets. def _add_fallback_slice_filter(query, start_int, count_int, total_int): """Create a slice of a query based on requ...
Return None if cache entry does not exist. def _cache_get_last_in_slice(url_dict, start_int, total_int, authn_subj_list): """Return None if cache entry does not exist.""" key_str = _gen_cache_key_for_slice(url_dict, start_int, total_int, authn_subj_list) # TODO: Django docs state that cache.get() should re...
Generate cache key for the REST URL the client is currently accessing or is expected to access in order to get the slice starting at the given ``start_int`` of a multi-slice result set. When used for finding the key to check in the current call, ``start_int`` is 0, or the start that was passed in the c...
Construct a numpy array with Wilson coefficient values from a dictionary of label-value pairs corresponding to the non-redundant elements. def smeft_toarray(wc_name, wc_dict): """Construct a numpy array with Wilson coefficient values from a dictionary of label-value pairs corresponding to the non-redun...
Translate from the Warsaw basis to the 'Warsaw mass' basis. Parameters used: - `Vus`, `Vub`, `Vcb`, `gamma`: elements of the unitary CKM matrix (defined as the mismatch between left-handed quark mass matrix diagonalization matrices). def warsaw_to_warsawmass(C, parameters=None, sectors=None): ...
Translate from the 'Warsaw up' basis to the Warsaw basis. Parameters used: - `Vus`, `Vub`, `Vcb`, `gamma`: elements of the unitary CKM matrix (defined as the mismatch between left-handed quark mass matrix diagonalization matrices). def warsaw_up_to_warsaw(C, parameters=None, sectors=None): """...
Add a remote Member Node to the list of preferred replication targets to this System Metadata object. Also remove the target MN from the list of blocked Member Nodes if present. If the target MN is already in the preferred list and not in the blocked list, this function is a no-op. Args: sy...
Normalize a ReplicationPolicy PyXB type in place. The preferred and blocked lists are sorted alphabetically. As blocked nodes override preferred nodes, and any node present in both lists is removed from the preferred list. Args: rp_pyxb : ReplicationPolicy PyXB object The object will be ...
Check if two ReplicationPolicy XML docs are semantically equivalent. The ReplicationPolicy XML docs are normalized before comparison. Args: a_xml, b_xml: ReplicationPolicy XML docs to compare Returns: bool: ``True`` if the resulting policies for the two objects are semantically equivale...
Convert ReplicationPolicy PyXB object to a normalized dict. Args: rp_pyxb: ReplicationPolicy to convert. Returns: dict : Replication Policy as normalized dict. Example:: { 'allowed': True, 'num': 3, 'blockedMemberNode': {'urn:node:NODE1', 'urn:node:NODE2', 'ur...
Convert dict to ReplicationPolicy PyXB object. Args: rp_dict: Native Python structure representing a Replication Policy. Example:: { 'allowed': True, 'num': 3, 'blockedMemberNode': {'urn:node:NODE1', 'urn:node:NODE2', 'urn:node:NODE3'}, 'preferredMemberNode': {'urn...
Ensure that RP allows replication. def _ensure_allow_rp(rp_pyxb): """Ensure that RP allows replication.""" if not rp_pyxb.replicationAllowed: rp_pyxb.replicationAllowed = True if not rp_pyxb.numberReplicas: rp_pyxb.numberReplicas = 3
Convert a time interval into a human-readable string. :param i: The interval to convert, in seconds. def _display_interval(i): """Convert a time interval into a human-readable string. :param i: The interval to convert, in seconds. """ sigils = ["d", "h", "m", "s"] factors = [24 * 60 * 60, 60 ...
Update metrics with the new number. def update(self, num): """Update metrics with the new number.""" num = float(num) self.count += 1 self.low = min(self.low, num) self.high = max(self.high, num) # Welford's online mean and variance algorithm. delta = num - self...
Pack the stats computed into a dictionary. def to_dict(self): """Pack the stats computed into a dictionary.""" return { 'high': self.high, 'low': self.low, 'mean': self.mean, 'count': self.count, 'deviation': self.deviation, }