code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
command, = self._split_args(line, 0, 1) if command is None: return self._print_help() cmd.Cmd.do_help(self, line)
def do_help(self, line)
Get help on commands "help" or "?" with no arguments displays a list_objects of commands for which help is available "help <command>" or "? <command>" gives help on <command>
4.582483
5.96117
0.768722
self._split_args(line, 0, 0) for idx, item in enumerate(self._history): d1_cli.impl.util.print_info("{0: 3d} {1}".format(idx, item))
def do_history(self, line)
history Display a list of commands that have been entered.
7.327442
6.573704
1.11466
n_remaining_operations = len(self._command_processor.get_operation_queue()) if n_remaining_operations: d1_cli.impl.util.print_warn( .format( n_remaining_operations ) ) if not d1_cli.impl.util.confirm("Exit?"...
def do_exit(self, line)
exit Exit from the CLI.
5.680375
5.316449
1.068453
d1_cli.impl.util.print_info("") self.do_exit(line)
def do_eof(self, line)
Exit on system EOF character.
20.450752
12.725614
1.607054
session_parameter, value = self._split_args(line, 0, 2) if value is None: self._command_processor.get_session().print_variable(session_parameter) else: self._command_processor.get_session().set_with_conversion( session_parameter, value ...
def do_set(self, line)
set [parameter [value]] set (without parameters): Display the value of all session variables. set <session variable>: Display the value of a single session variable. set <session variable> <value>: Set the value of a session variable.
4.487434
4.169893
1.076151
config_file = self._split_args(line, 0, 1)[0] self._command_processor.get_session().load(config_file) if config_file is None: config_file = ( self._command_processor.get_session().get_default_pickle_file_path() ) self._print_info_if_verbos...
def do_load(self, line)
load [file] Load session variables from file load (without parameters): Load session from default file ~/.dataone_cli.conf load. <file>: Load session from specified file.
4.538645
4.454736
1.018836
config_file = self._split_args(line, 0, 1)[0] self._command_processor.get_session().save(config_file) if config_file is None: config_file = ( self._command_processor.get_session().get_default_pickle_file_path() ) self._print_info_if_verbos...
def do_save(self, line)
save [config_file] Save session variables to file save (without parameters): Save session to default file ~/.dataone_cli.conf save. <file>: Save session to specified file.
4.564795
4.128079
1.105792
self._split_args(line, 0, 0) self._command_processor.get_session().reset() self._print_info_if_verbose("Successfully reset session variables")
def do_reset(self, line)
reset Set all session variables to their default values.
10.288648
7.074898
1.454247
subject, permission = self._split_args(line, 1, 1) self._command_processor.get_session().get_access_control().add_allowed_subject( subject, permission ) self._print_info_if_verbose( 'Set {} access for subject "{}"'.format(permission, subject) )
def do_allowaccess(self, line)
allowaccess <subject> [access-level] Set the access level for subject Access level is "read", "write" or "changePermission". Access level defaults to "read" if not specified. Special subjects: public: Any subject, authenticated and not authenticated authenticatedUser: Any subject th...
5.915517
7.141212
0.828363
subject, = self._split_args(line, 1, 0) self._command_processor.get_session().get_access_control().remove_allowed_subject( subject ) self._print_info_if_verbose( 'Removed subject "{}" from access policy'.format(subject) )
def do_denyaccess(self, line)
denyaccess <subject> Remove subject from access policy.
6.353676
4.756065
1.33591
self._split_args(line, 0, 0) self._command_processor.get_session().get_access_control().clear() self._print_info_if_verbose("Removed all subjects from access policy")
def do_clearaccess(self, line)
clearaccess Remove all subjects from access policy Only the submitter will have access to the object.
9.395386
6.36738
1.47555
self._split_args(line, 0, 0) self._command_processor.get_session().get_replication_policy().set_replication_allowed( True ) self._print_info_if_verbose("Set replication policy to allow replication")
def do_allowrep(self, line)
allowrep Allow new objects to be replicated.
7.725974
6.64952
1.161884
self._split_args(line, 0, 0) self._command_processor.get_session().get_replication_policy().set_replication_allowed( False ) self._print_info_if_verbose("Set replication policy to deny replication")
def do_denyrep(self, line)
denyrep Prevent new objects from being replicated.
8.225805
6.701137
1.227524
mns = self._split_args(line, 1, -1) self._command_processor.get_session().get_replication_policy().add_preferred( mns ) self._print_info_if_verbose( "Set {} as preferred replication target(s)".format(", ".join(mns)) )
def do_preferrep(self, line)
preferrep <member node> [member node ...] Add one or more preferred Member Nodes to replication policy.
7.851447
5.861604
1.339471
mns = self._split_args(line, 1, -1) self._command_processor.get_session().get_replication_policy().add_blocked(mns) self._print_info_if_verbose( "Set {} as blocked replication target(s)".format(", ".join(mns)) )
def do_blockrep(self, line)
blockrep <member node> [member node ...] Add one or more blocked Member Node to replication policy.
8.834518
6.057619
1.458414
mns = self._split_args(line, 1, -1) self._command_processor.get_session().get_replication_policy().repremove(mns) self._print_info_if_verbose( "Removed {} from replication policy".format(", ".join(mns)) )
def do_removerep(self, line)
removerep <member node> [member node ...] Remove one or more Member Nodes from replication policy.
9.002724
6.873678
1.309739
n_replicas = self._split_args(line, 1, 0)[0] self._command_processor.get_session().get_replication_policy().set_number_of_replicas( n_replicas ) self._print_info_if_verbose("Set number of replicas to {}".format(n_replicas))
def do_numberrep(self, line)
numberrep <number of replicas> Set preferred number of replicas for new objects If the preferred number of replicas is set to zero, replication is also disallowed.
5.389613
4.739638
1.137136
self._split_args(line, 0, 0) self._command_processor.get_session().get_replication_policy().clear() self._print_info_if_verbose("Cleared the replication policy")
def do_clearrep(self, line)
clearrep Set the replication policy to default. The default replication policy has no preferred or blocked member nodes, allows replication and sets the preferred number of replicas to 3.
8.256083
7.741608
1.066456
pid, output_file = self._split_args(line, 2, 0) self._command_processor.science_object_get(pid, output_file) self._print_info_if_verbose( 'Downloaded "{}" to file: {}'.format(pid, output_file) )
def do_get(self, line)
get <identifier> <file> Get an object from a Member Node. The object is saved to <file>.
7.449368
7.022881
1.060728
pid, output_file = self._split_args(line, 1, 1) self._command_processor.system_metadata_get(pid, output_file) if output_file is not None: self._print_info_if_verbose( 'Downloaded system metadata for "{}" to file: {}'.format( pid, output_fi...
def do_meta(self, line)
meta <identifier> [file] Get the System Metadata that is associated with a Science Object. If the metadata is not on the Coordinating Node, the Member Node is checked. Provide ``file`` to save the System Metada to disk instead of displaying it.
5.994728
5.401838
1.109757
path = self._split_args(line, 0, 1, pad=False) if len(path): path = path[0] self._command_processor.list_objects(path)
def do_list(self, line)
list [path] Retrieve a list of available Science Data Objects from Member Node The response is filtered by the from-date, to-date, search, start and count session variables. See also: search
6.625425
7.512974
0.881865
path = self._split_args(line, 0, 1, pad=False) if len(path): path = path[0] self._command_processor.log(path)
def do_log(self, line)
log [path] Retrieve event log from Member Node The response is filtered by the from-date, to-date, start and count session parameters.
6.467855
6.178467
1.046838
pid, = self._split_args(line, 1, 0) self._command_processor.resolve(pid)
def do_resolve(self, line)
resolve <identifier> Find all locations from which the given Science Object can be downloaded.
8.33589
8.481483
0.982834
pid, sciobj_path = self._split_args(line, 2, 0) self._command_processor.science_object_create(pid, sciobj_path) self._print_info_if_verbose( 'Added create operation for identifier "{}" to write queue'.format(pid) )
def do_create(self, line)
create <identifier> <file> Create a new Science Object on a Member Node. The System Metadata that becomes associated with the new Science Object is generated from the session variables.
8.764614
8.684167
1.009264
curr_pid, pid_new, input_file = self._split_args(line, 3, 0) self._command_processor.science_object_update(curr_pid, input_file, pid_new) self._print_info_if_verbose( 'Added update operation for identifier "{}" to write queue'.format(curr_pid) )
def do_update(self, line)
update <old-pid> <new-pid> <file> Replace an existing Science Object in a. :term:`MN` with another.
9.269197
7.556708
1.226618
pids = self._split_args(line, 3, -1, pad=False) self._command_processor.create_package(pids) self._print_info_if_verbose( 'Added package create operation for identifier "{}" to write queue'.format( pids[0] ) )
def do_package(self, line)
package <package-pid> <science-metadata-pid> <science-pid> [science- pid. ...] Create a simple OAI-ORE Resource Map on a Member Node.
10.333218
8.745137
1.181596
pids = self._split_args(line, 1, -1) self._command_processor.science_object_archive(pids) self._print_info_if_verbose( "Added archive operation for identifier(s) {} to write queue".format( ", ".join(pids) ) )
def do_archive(self, line)
archive <identifier> [identifier ...] Mark one or more existing Science Objects as archived.
9.020128
7.429288
1.214131
pids = self._split_args(line, 1, -1) self._command_processor.update_access_policy(pids) self._print_info_if_verbose( "Added access policy update operation for identifiers {} to write queue".format( ", ".join(pids) ) )
def do_updateaccess(self, line)
updateaccess <identifier> [identifier ...] Update the Access Policy on one or more existing Science Data Objects.
8.678158
7.192906
1.206488
pids = self._split_args(line, 1, -1) self._command_processor.update_replication_policy(pids) self._print_info_if_verbose( "Added replication policy update operation for identifiers {} to write queue".format( ", ".join(pids) ) )
def do_updatereplication(self, line)
updatereplication <identifier> [identifier ...] Update the Replication Policy on one or more existing Science Data Objects.
8.7812
6.853902
1.281197
args = self._split_args(line, 0, -1) query = " ".join([_f for _f in args if _f]) self._command_processor.search(query)
def do_search(self, line)
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.
5.28894
5.483319
0.964551
hosts = self._split_args(line, 0, 99, pad=False) self._command_processor.ping(hosts)
def do_ping(self, line)
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...
12.500116
15.128727
0.82625
self._split_args(line, 0, 0) self._command_processor.get_operation_queue().display()
def do_queue(self, line)
queue Print the queue of write operations.
13.734498
9.897062
1.387735
self._split_args(line, 0, 0) self._command_processor.get_operation_queue().execute() self._print_info_if_verbose( "All operations in the write queue were successfully executed" )
def do_run(self, line)
run Perform each operation in the queue of write operations.
11.480684
7.589628
1.512681
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")
def do_edit(self, line)
edit Edit the queue of write operations.
13.506626
8.458892
1.596737
self._split_args(line, 0, 0) self._command_processor.get_operation_queue().clear() self._print_info_if_verbose("All operations in the write queue were cleared")
def do_clearqueue(self, line)
clearqueue Remove the operations in the queue of write operations without performing them.
10.006097
7.025872
1.424179
msg = if platform.system() != "Windows": msg += d1_cli.impl.util.print_info(msg)
def _print_help(self)
Custom help message to group commands by functionality.
15.734468
13.817713
1.138717
ctype = get_content_type(obj) group_model = get_group_obj_perms_model(obj) if not attach_perms: # It's much easier without attached perms so we do it first if that is the case group_rel_name = group_model.group.field.related_query_name() if group_model.objects.is_generic(): ...
def get_groups_with_perms(obj, attach_perms=False)
Return queryset of all ``Group`` objects with *any* object permissions for the given ``obj``.
2.648315
2.612822
1.013584
perm_list = sorted(perm_list, key=lambda tup: tup[0]) grouped_perms = [] for key, group in groupby(perm_list, lambda tup: (tup[0], tup[1])): grouped_perms.append((key[0], key[1], [g[2] for g in group])) return grouped_perms
def _group_groups(perm_list)
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...
2.208413
2.738611
0.806399
user, group = get_identity(user_or_group) if user and not user.is_active: return [], [] user_model = get_user_model() ctype = ContentType.objects.get_for_model(obj) group_model = get_group_obj_perms_model(obj) group_rel_name = group_model.permission.field.related_query_name() ...
def get_user_group_perms(user_or_group, obj)
Get permissins for user groups. Based on guardian.core.ObjectPermissionChecker.
2.014643
2.006576
1.00402
def format_permissions(perms): ctype = ContentType.objects.get_for_model(obj) return [perm.replace('_{}'.format(ctype.name), '') for perm in perms] perms_list = [] if user: if user.is_authenticated: user_perms, group_perms = get_user_group_perms(user, obj)...
def get_object_perms(obj, user=None)
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...
1.911657
1.954258
0.978201
user_model = get_user_model() return user_model.objects.filter( userobjectpermission__object_pk=obj.pk, userobjectpermission__permission__codename=permission, ).distinct()
def get_users_with_permission(obj, permission)
Return users with specific permission on object. :param obj: Object to return users for :param permission: Permission codename
2.700976
3.240162
0.833593
location_id = event['location_id'] verbosity = event['verbosity'] try: logger.info(__("Running purge for location id {}.", location_id)) location_purge(location_id=location_id, delete=True, verbosity=verbosity) except Exception: # pylint: disable=broad-...
def purge_run(self, event)
Run purge for the object with ``location_id`` specified in ``event`` argument.
4.160688
3.526212
1.179931
# Get limit defaults and overrides. limit_defaults = getattr(settings, 'FLOW_PROCESS_RESOURCE_DEFAULTS', {}) limit_overrides = getattr(settings, 'FLOW_PROCESS_RESOURCE_OVERRIDES', {}) limits = {} resources = self.requirements.get('resources', {}) # pylint: disable=no-...
def get_resource_limits(self)
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...
3.005713
2.9106
1.032678
allowed_params = set(self.get_filters().keys()) allowed_params.update(self.get_always_allowed_arguments()) unallowed = set(self.request.query_params.keys()) - allowed_params if unallowed: msg = 'Unsupported parameter(s): {}. Please use a combination of: {}.'.format...
def validate_query_params(self)
Ensure no unsupported query params were used.
3.604321
3.271725
1.101658
cls._default_options.update(cls._option_schema({key: value}))
def set_default_option(cls, key, value)
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.
9.6762
12.488166
0.77483
self._options.update(self._option_schema({key: value})) self.clear_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.
8.587335
7.623981
1.126358
return self._options.get(key, self._default_options[key])
def get_option(self, key)
Return the current value of the option `key` (string). Instance method, only refers to current instance.
4.487881
4.769652
0.940924
return cls(wcdict=wc.dict, scale=wc.scale, eft=wc.eft, basis=wc.basis)
def from_wc(cls, wc)
Return a `Wilson` instance initialized by a `wcxf.WC` instance
9.20366
7.404847
1.242924
wc = wcxf.WC.load(stream) return cls.from_wc(wc)
def load_wc(cls, stream)
Return a `Wilson` instance initialized by a WCxf file-like object
6.891339
3.836094
1.796447
try: return self._cache[eft][scale][basis][sector] except KeyError: 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.
3.357689
2.820816
1.190326
if scale == 'log': x = np.logspace(log(self.scale_min), log(self.scale_max), steps, base=e) elif scale == 'linear': x = np.linspace(self.scale_min, self.scale_...
def plotdata(self, key, part='re', scale='log', steps=50)
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'...
2.269473
2.198977
1.032058
try: import matplotlib.pyplot as plt except ImportError: raise ImportError("Please install matplotlib if you want to use the plot method") pdat = self.plotdata(key, part=part, scale=scale, steps=steps) plt.plot(*pdat, label=key, **plotargs) if sca...
def plot(self, key, part='re', scale='log', steps=50, legend=True, plotargs={})
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
2.465178
2.4037
1.025577
channel = state.MANAGER_CONTROL_CHANNEL scope = { 'type': 'control_event', 'channel': channel, } app = ApplicationCommunicator(ManagerConsumer, scope) channel_layer = get_channel_layer() async def _consume_loop(): while True: message = await c...
async def run_consumer(timeout=None, dry_run=False)
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``.
6.317431
6.908347
0.914464
if self._discovery_done: return try: previous_state = self._extensions.copy() for app_config in apps.get_app_configs(): indexes_path = '{}.extensions'.format(app_config.name) try: import_module(indexes_pat...
def discover_extensions(self)
Discover available extensions.
5.049134
4.886038
1.03338
if inspect.isclass(klass_or_instance): klass = '{}.{}'.format(klass_or_instance.__module__, klass_or_instance.__name__) elif not isinstance(klass_or_instance, str): klass = klass_or_instance.__class__ klass = '{}.{}'.format(klass.__module__, klass.__name__) ...
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 :return: String containing the class path
1.895103
2.106364
0.899703
klass = self._get_class_path(klass) # TODO: Take order into account. self._extensions.setdefault(klass, []).append(extension)
def add_extension(self, klass, extension)
Register an extension for a class. :param klass: Class to register an extension for :param extension: Extension (arbitrary type)
7.207879
8.842971
0.815097
self.discover_extensions() return self._extensions.get(self._get_class_path(klass), [])
def get_extensions(self, klass)
Return all registered extensions of a class. :param klass: Class to get registered extensions for :return: All registered extensions for given class
8.57122
10.72767
0.798983
p = {} p['alpha_s'] = qcd.alpha_s(scale, self.f, self.parameters['alpha_s'], loop=loop) p['m_b'] = qcd.m_b(self.parameters['m_b'], scale, self.f, self.parameters['alpha_s'], loop=loop) p['m_c'] = qcd.m_c(self.parameters['m_c'], scale, self.f, self.parameters['alpha_s'], loop=loo...
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.
1.803355
1.729928
1.042445
C_out = self._run_dict(scale_out, sectors=sectors) all_wcs = set(wcxf.Basis[self.eft, 'JMS'].all_wcs) # to speed up lookup C_out = {k: v for k, v in C_out.items() if v != 0 and k in all_wcs} return wcxf.WC(eft=self.eft, basis='JMS', scale...
def run(self, scale_out, sectors='all')
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....
7.59957
6.261335
1.21373
if hasattr(self._stream, 'len'): return len(self._stream) elif hasattr(self._stream, 'fileno'): return os.fstat(self._stream.fileno()).st_size else: cur_pos = self._stream.tell() size = self._stream.seek(0, os.SEEK_END) self._s...
def size(self)
Returns: int : The total number of bytes that will be returned by the iterator.
2.199413
2.089597
1.052553
try: cert_obj = django.core.cache.cache.cn_cert_obj d1_common.cert.x509.log_cert_info( logging.debug, 'Using cached CN cert for JWT validation', cert_obj ) return cert_obj except AttributeError: cn_cert_obj = _download_and_decode_cn_cert() django....
def _get_cn_cert()
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...
3.851855
3.691576
1.043418
params = join_params(self.parameters, {"key": key}) return self.__class__(**params)
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>.
10.635845
12.333061
0.862385
params = join_params(self.parameters, {"q": q}) return self.__class__(**params)
def query(self, *q)
Takes one or more strings for searching by tag and/or metadata.
14.798429
12.158503
1.217126
params = join_params(self.parameters, {"sf": sf}) return self.__class__(**params)
def sort_by(self, sf)
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.
12.549415
17.681835
0.709735
params = join_params(self.parameters, {"limit": limit}) return self.__class__(**params)
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.
12.331335
15.504842
0.795322
params = join_params(self.parameters, {"filter_id": filter_id}) return self.__class__(**params)
def filter(self, filter_id="")
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.
8.547225
11.446122
0.746735
params = join_params(self.parameters, {"faves": option}) return self.__class__(**params)
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.
13.524693
15.047078
0.898825
params = join_params(self.parameters, {"upvotes": option}) return self.__class__(**params)
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.
14.320098
15.411241
0.929198
params = join_params(self.parameters, {"uploads": option}) return self.__class__(**params)
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.
16.06628
18.947063
0.847956
params = join_params(self.parameters, {"watched": option}) return self.__class__(**params)
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.
13.86263
17.671434
0.784465
request.data['contributor'] = self.resolve_user(request.user).pk
def define_contributor(self, request)
Define contributor by adding it to request.data.
11.369807
6.510033
1.746505
self.define_contributor(request) try: return super().create(request, *args, **kwargs) except IntegrityError as ex: return Response({'error': str(ex)}, status=status.HTTP_409_CONFLICT)
def create(self, request, *args, **kwargs)
Create a resource.
3.537228
3.07386
1.150745
with transaction.atomic(): instance = serializer.save() # Assign all permissions to the object contributor. assign_contributor_permissions(instance)
def perform_create(self, serializer)
Create a resource.
9.283212
9.111975
1.018793
# 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) with transaction.atomic(): return self._update(request, *args, **kwargs)
def update(self, request, *args, **kwargs)
Update a resource.
4.668556
4.243028
1.100289
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=partial) serializer.is_valid(raise_exception=True) self.perform_update(serializ...
def _update(self, request, *args, **kwargs)
Update a resource.
1.853346
1.761031
1.052421
if not request.user.is_authenticated: return Response(status=status.HTTP_401_UNAUTHORIZED) if 'name' not in request.query_params: return Response({'error': 'Query parameter `name` must be given.'}, status=status.HTTP_400_BAD_REQUEST) ...
def slug_exists(self, request)
Check if given url slug exists. Check if slug given in query parameter ``name`` exists. Return ``True`` if slug already exists and ``False`` otherwise.
2.127787
1.945079
1.093934
if parameter_name not in request_data: raise ParseError("`{}` parameter is required".format(parameter_name)) ids = request_data.get(parameter_name) if not isinstance(ids, list): raise ParseError("`{}` parameter not a list".format(parameter_name)) if not...
def get_ids(self, request_data, parameter_name='ids')
Extract a list of integers from request data.
1.846006
1.790745
1.030859
if parameter_name not in request_data: raise ParseError("`{}` parameter is required".format(parameter_name)) id_parameter = request_data.get(parameter_name, None) if not isinstance(id_parameter, int): raise ParseError("`{}` parameter not an integer".format(param...
def get_id(self, request_data, parameter_name='id')
Extract an integer from request data.
2.321525
2.1751
1.067319
# logging.debug('dataone_exception_xml="{}"' # .format(d1_common.xml.pretty_xml(dataone_exception_xml))) try: dataone_exception_pyxb = d1_common.xml.deserialize_d1_exception( dataone_exception_xml ) except ValueError as e: raise ServiceFailure( detail...
def deserialize(dataone_exception_xml)
Deserialize a DataONE Exception XML doc.
3.372465
3.346561
1.00774
return create_exception_by_name( _get_header(headers, 'DataONE-Exception-Name'), _get_header(headers, 'DataONE-Exception-DetailCode'), _get_header(headers, 'DataONE-Exception-Description'), _get_header(headers, 'DataONE-Exception-TraceInformation'), _get_header(headers, ...
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).
3.142755
2.661966
1.180614
try: dataone_exception = globals()[name] except LookupError: dataone_exception = ServiceFailure return dataone_exception( detailCode, description, traceInformation, identifier, nodeId )
def create_exception_by_name( name, detailCode='0', description='', traceInformation=None, identifier=None, nodeId=None, )
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...
5.45157
3.843396
1.418425
try: dataone_exception = ERROR_CODE_TO_EXCEPTION_DICT[errorCode] except LookupError: dataone_exception = ServiceFailure return dataone_exception( detailCode, description, traceInformation, identifier, nodeId )
def create_exception_by_error_code( errorCode, detailCode='0', description='', traceInformation=None, identifier=None, nodeId=None, )
Create a DataONE Exception object by errorCode. See Also: For args, see: ``DataONEException()``
4.6812
3.908353
1.197742
msg = msg or '<unset>' msg = str(msg) msg = msg.strip() if not msg: return if len(msg) > 2048: msg = msg[:1024] + '...' if msg.count('\n') <= 1: return '{}: {}\n'.format(tag, msg.strip()) else: return '{}:\n...
def _fmt(self, tag, msg)
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.
2.777048
2.60333
1.066729
if self.description is not None: msg = self.description else: msg = 'errorCode: {} / detailCode: {}'.format( self.errorCode, self.detailCode ) return self._fmt(self.name, msg)
def friendly_format(self)
Serialize to a format more suitable for displaying to end users.
5.900342
5.620033
1.049877
assert encoding in ('utf-8', 'UTF-8') dataone_exception_pyxb = self.get_pyxb() return d1_common.xml.serialize_for_transport( dataone_exception_pyxb, xslt_url=xslt_url )
def serialize_to_transport(self, encoding='utf-8', xslt_url=None)
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: ...
5.181796
4.819587
1.075153
return d1_common.xml.serialize_to_xml_str( self.get_pyxb(), pretty=True, xslt_url=xslt_url )
def serialize_to_display(self, xslt_url=None)
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.
4.00721
4.802711
0.834364
return { 'DataONE-Exception-Name': self.__class__.__name__, 'DataONE-Exception-ErrorCode': self._format_header(self.errorCode), 'DataONE-Exception-DetailCode': self._format_header(self.detailCode), 'DataONE-Exception-Description': self._format_header(self...
def serialize_to_headers(self)
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...
2.818712
2.516445
1.120116
dataone_exception_pyxb = dataoneErrors.error() dataone_exception_pyxb.name = self.__class__.__name__ dataone_exception_pyxb.errorCode = self.errorCode dataone_exception_pyxb.detailCode = self.detailCode if self.description is not None: dataone_exception_pyxb....
def get_pyxb(self)
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.
2.405183
2.153312
1.116969
Data = apps.get_model('flow', 'Data') DataDependency = apps.get_model('flow', 'DataDependency') def process_dependency(data, parent): if not Data.objects.filter(pk=parent).exists(): DataDependency.objects.create( child=data, parent=None, kind='io' ) ...
def recreate_parent_dependencies(apps, schema_editor)
Create empty dependency relation if parent has been deleted.
3.180815
3.10853
1.023254
q = d1_gmn.app.models.Subject.objects.filter( subject__in=request.all_subjects_set ).values('permission__sciobj') filter_arg = '{}__in'.format(column_name) return query.filter(**{filter_arg: q})
def add_access_policy_filter(request, query, column_name)
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.
6.288295
6.664642
0.943531
return query.annotate( redact=django.db.models.Exists( d1_gmn.app.models.Permission.objects.filter( sciobj=django.db.models.OuterRef('sciobj'), subject__subject__in=request.all_subjects_set, level__gte=d1_gmn.app.auth.WRITE_LEVEL, ...
def add_redact_annotation(request, query)
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...
5.039076
5.072757
0.99336
Data = apps.get_model('flow', 'Data') for data in Data.objects.all(): hydrate_size(data, force=True) data.save()
def calculate_total_size(apps, schema_editor)
Add ``total_size`` field to all file/dir-type outputs.
4.779155
5.083721
0.94009
Data = apps.get_model('flow', 'Data') for data in Data.objects.all(): for field_schema, fields in iterate_fields(data.output, data.process.output_schema): name = field_schema['name'] value = fields[name] if 'type' in field_schema: if field_schema[...
def remove_total_size(apps, schema_editor)
Remove ``total_size`` field from all file/dir-type outputs.
2.572248
2.434985
1.056371
if not d1_gmn.app.did.is_valid_pid_for_create(did): raise d1_common.types.exceptions.IdentifierNotUnique( 0, 'Identifier is already in use as {}. did="{}"'.format( d1_gmn.app.did.classify_identifier(did), did ), identifier=did, )
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().
4.139365
4.19523
0.986684
if not d1_gmn.app.did.is_valid_pid_to_be_updated(did): raise d1_common.types.exceptions.InvalidRequest( 0, 'Object cannot be updated because the identifier for the object to be ' 'updated is {}. did="{}"'.format( d1_gmn.app.did.classify_identifier(did...
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()
4.20544
4.004405
1.050203
missing = [] for part_type, part_name in parts: if part_type == 'header': if 'HTTP_' + part_name.upper() not in request.META: missing.append('{}: {}'.format(part_type, part_name)) elif part_type == 'file': if part_name not in list(request.FILES.keys(...
def post_has_mime_parts(request, parts)
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...
2.130347
1.93925
1.098542
begin_dated = begin_date.year / 10 end_dated = end_date.year / 10 decades = [] for d in range(begin_dated, end_dated + 1): decades.append('{}-{}'.format(d * 10, d * 10 + 9)) return decades
def _decade_ranges_in_date_range(self, begin_date, end_date)
Return a list of decades which is covered by date range.
2.245197
1.926841
1.165221
begin_year = begin_date.year end_year = end_date.year if begin_year < decade: begin_year = decade if end_year > decade + 9: end_year = decade + 9 return list(range(begin_year, end_year + 1))
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.
1.742709
1.524789
1.142918
C_out = deepcopy(C_in) b = beta.beta(C_out, newphys=newphys) for k, C in C_out.items(): C_out[k] = C + b[k] / (16 * pi**2) * log(scale_out / scale_in) return C_out
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.
4.057024
4.15997
0.975253
def fun(t0, y): return beta.beta_array(C=C_array2dict(y.view(complex)), newphys=newphys).view(float) / (16 * pi**2) y0 = C_dict2array(C_in).view(float) sol = solve_ivp(fun=fun, t_span=(log(scale_in), log(scale_out)), y0=y0, ...
def _smeft_evolve(C_in, scale_in, scale_out, newphys=True, **kwargs)
Axuliary function used in `smeft_evolve` and `smeft_evolve_continuous`
6.098536
5.991401
1.017881