code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
cert_subj = _get_client_side_certificate_subject()
return (
d1_gmn.app.node_registry.get_cn_subjects()
| django.conf.settings.DATAONE_TRUSTED_SUBJECTS
| {cert_subj}
if cert_subj is not None
else set()
) | def get_trusted_subjects() | Get set of subjects that have unlimited access to all SciObj and APIs on this
node. | 6.349353 | 6.39545 | 0.992792 |
logging.debug('Active subjects: {}'.format(', '.join(request.all_subjects_set)))
logging.debug('Trusted subjects: {}'.format(', '.join(get_trusted_subjects())))
return not request.all_subjects_set.isdisjoint(get_trusted_subjects()) | def is_trusted_subject(request) | Determine if calling subject is fully trusted. | 3.922978 | 3.810788 | 1.02944 |
subject = django.core.cache.cache.get('client_side_certificate_subject')
if subject is not None:
return subject
cert_pem = _get_client_side_certificate_pem()
if cert_pem is None:
return None
subject = _extract_subject_from_pem(cert_pem)
django.core.cache.cache.set('client_si... | def _get_client_side_certificate_subject() | Return the DN from the client side certificate as a D1 subject if a client side
cert has been configured.
Else return None. | 2.162924 | 2.202963 | 0.981825 |
if is_trusted_subject(request):
return True
return d1_gmn.app.models.Permission.objects.filter(
sciobj__pid__did=pid,
subject__subject__in=request.all_subjects_set,
level__gte=level,
).exists() | def is_allowed(request, level, pid) | Check if one or more subjects are allowed to perform action level on object.
If a subject holds permissions for one action level on object, all lower action
levels are also allowed. Any included subject that is unknown to this MN is treated
as a subject without permissions.
Returns:
bool
... | 6.45294 | 6.480024 | 0.99582 |
if not has_create_update_delete_permission(request):
raise d1_common.types.exceptions.NotAuthorized(
0,
'Access allowed only for subjects with Create/Update/Delete '
'permission. active_subjects="{}"'.format(format_active_subjects(request)),
) | def assert_create_update_delete_permission(request) | Access only by subjects with Create/Update/Delete permission and by trusted
infrastructure (CNs). | 6.36582 | 5.113018 | 1.245022 |
if not d1_gmn.app.models.ScienceObject.objects.filter(pid__did=pid).exists():
raise d1_common.types.exceptions.NotFound(
0,
'Attempted to perform operation on non-existing object. pid="{}"'.format(
pid
),
)
if not is_allowed(request, level... | def assert_allowed(request, level, pid) | Assert that one or more subjects are allowed to perform action on object.
Raise NotAuthorized if object exists and subject is not allowed. Raise NotFound if
object does not exist. | 3.736481 | 3.710702 | 1.006947 |
decorated_subject_list = [request.primary_subject_str + ' (primary)']
for subject in request.all_subjects_set:
if subject != request.primary_subject_str:
decorated_subject_list.append(subject)
return ', '.join(decorated_subject_list) | def format_active_subjects(request) | Create a string listing active subjects for this connection, suitable for
appending to authentication error messages. | 3.931822 | 3.695643 | 1.063907 |
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument("path", nargs="+", help="File or directory path")
parser.add_argument("--exclude", nargs="+", help="Exclude glob patterns")
parser.add_argument(
"--n... | def main() | Remove unused imports Unsafe!
Only tested on our codebase, which uses simple absolute imports on the form, "import
a.b.c". | 2.512754 | 2.480551 | 1.012982 |
unused_dot_str = ".".join(unused_dot_list)
for n in r("ImportNode"):
if n.names()[0] == unused_dot_str:
# The "!" is inserted so that this line doesn't show up when searching for
# the comment pattern in code.
n.replace("#{}# {}".format("!", str(n)))
... | def comment_import(r, unused_dot_list) | Comment out import for {dot_str}. | 10.465019 | 10.106341 | 1.03549 |
dot_set = set()
for n in r.find_all(("atomtrailers",)):
name_list = []
for x in n.value:
if x.type != "name":
break
name_list.append(x.value)
if name_list:
dot_set.add(tuple(name_list))
return sorted(dot_set) | def get_atomtrailer_list(r) | Capture only the leading dotted name list.
A full sequence typically includes function calls and parameters.
pkga.pkgb.pkgc.one_call(arg1, arg2, arg3=4) | 3.412488 | 3.487983 | 0.978356 |
if not isinstance(value, list):
value = value.split(',')
filters = [Q('match', **{'tags': item}) for item in value]
search = search.query('bool', must=filters)
return search | def custom_filter_tags(self, value, search) | Support tags query. | 3.509229 | 3.218582 | 1.090303 |
if isinstance(value, list):
value = ' '.join(value)
should = [
Q('match', slug={'query': value, 'operator': 'and', 'boost': 10.0}),
Q('match', **{'slug.ngrams': {'query': value, 'operator': 'and', 'boost': 5.0}}),
Q('match', name={'query': value,... | def custom_filter_text(self, value, search) | Support general query using the 'text' attribute. | 2.037932 | 2.010724 | 1.013532 |
for entity in obj.entity_set.all():
if user.has_perm('share_entity', entity):
update_permission(entity, payload)
# Data doesn't have "ADD" permission, so it has to be removed
payload = remove_permission(payload, 'add')
for data in obj.data.all():
... | def set_content_permissions(self, user, obj, payload) | Apply permissions to data objects and entities in ``Collection``. | 4.444592 | 4.257882 | 1.04385 |
if not request.user.is_authenticated:
raise exceptions.NotFound
return super().create(request, *args, **kwargs) | def create(self, request, *args, **kwargs) | Only authenticated usesr can create new collections. | 3.558648 | 2.827733 | 1.258481 |
obj = self.get_object()
user = request.user
if strtobool(request.query_params.get('delete_content', 'false')):
for entity in obj.entity_set.all():
if user.has_perm('edit_entity', entity):
entity.delete()
for data in obj.data.... | def destroy(self, request, *args, **kwargs) | Destroy a model instance.
If ``delete_content`` flag is set in query parameters, also all
Data objects and Entities, on which user has ``EDIT``
permission, contained in collection will be deleted. | 2.620016 | 2.014024 | 1.300886 |
collection = self.get_object()
if 'ids' not in request.data:
return Response({"error": "`ids`parameter is required"}, status=status.HTTP_400_BAD_REQUEST)
missing = []
for data_id in request.data['ids']:
if not Data.objects.filter(pk=data_id).exists():
... | def add_data(self, request, pk=None) | Add data to collection. | 2.260897 | 2.128967 | 1.061969 |
collection = self.get_object()
if 'ids' not in request.data:
return Response({"error": "`ids`parameter is required"}, status=status.HTTP_400_BAD_REQUEST)
for data_id in request.data['ids']:
collection.data.remove(data_id)
return Response() | def remove_data(self, request, pk=None) | Remove data from collection. | 3.153689 | 2.79094 | 1.129974 |
if not request.user.is_authenticated:
raise exceptions.NotFound
ids = self.get_ids(request.data)
queryset = get_objects_for_user(request.user, 'view_collection', Collection.objects.filter(id__in=ids))
actual_ids = queryset.values_list('id', flat=True)
missin... | def duplicate(self, request, *args, **kwargs) | Duplicate (make copy of) ``Collection`` models. | 2.492492 | 2.392826 | 1.041652 |
try:
await client.describe(pid)
except d1_common.types.exceptions.DataONEException:
return False
return True | async def is_object_synced_to_cn(self, client, pid) | Check if object with {pid} has successfully synced to the CN.
CNRead.describe() is used as it's a light-weight HTTP HEAD request.
This assumes that the call is being made over a connection that has been
authenticated and has read or better access on the given object if it exists. | 5.205881 | 3.640563 | 1.429966 |
return search.query(
self.query_type( # pylint: disable=not-callable
**{
field: {
self.operator: self.get_value_query(value)
}
}
)
) | def apply(self, search, field, value) | Apply lookup expression to search query. | 4.113175 | 4.120446 | 0.998235 |
if not isinstance(value, list):
value = [x for x in value.strip().split(',') if x]
filters = [Q('match', **{field: item}) for item in value]
return search.query('bool', should=filters) | def apply(self, search, field, value) | Apply lookup expression to search query. | 3.710245 | 3.704639 | 1.001513 |
# We assume that the field in question has a "raw" counterpart.
return search.query('match', **{'{}.raw'.format(field): value}) | def apply(self, search, field, value) | Apply lookup expression to search query. | 9.393517 | 9.462405 | 0.99272 |
if lookup.operator in self._lookups:
raise KeyError("Lookup for operator '{}' is already registered".format(lookup.operator))
self._lookups[lookup.operator] = lookup() | def register_lookup(self, lookup) | Register lookup. | 4.191556 | 4.021192 | 1.042367 |
try:
return self._lookups[operator]
except KeyError:
raise NotImplementedError("Lookup operator '{}' is not supported".format(operator)) | def get_lookup(self, operator) | Look up a lookup.
:param operator: Name of the lookup operator | 4.215361 | 4.960888 | 0.849719 |
unmatched_items = {}
for expression, value in raw_query.items():
# Parse query expression into tokens.
tokens = expression.split(TOKEN_SEPARATOR)
field = tokens[0]
tail = tokens[1:]
if field not in self.fields:
unmatc... | def build(self, search, raw_query) | Build query.
:param search: Search query instance
:param raw_query: Raw query arguments dictionary | 3.744771 | 3.81289 | 0.982135 |
@functools.wraps(f)
def wrapper(request, did, *args, **kwargs):
pid = resolve_sid_func(request, did)
return f(request, pid, *args, **kwargs)
return wrapper | def resolve_sid(f) | View handler decorator that adds SID resolve and PID validation.
- For v1 calls, assume that ``did`` is a pid and raise NotFound exception if it's
not valid.
- For v2 calls, if DID is a valid PID, return it. If not, try to resolve it as a
SID and, if successful, return the new PID. Else, raise NotF... | 3.262856 | 2.777274 | 1.174841 |
@functools.wraps(f)
def wrapper(request, did, *args, **kwargs):
return f(request, decode_path_segment(did), *args, **kwargs)
return wrapper | def decode_did(f) | View handler decorator that decodes "%2f" ("/") in SID or PID extracted from URL
path segment by Django. | 3.319419 | 2.374571 | 1.397903 |
@functools.wraps(f)
def wrapper(request, *args, **kwargs):
trusted(request)
return f(request, *args, **kwargs)
return wrapper | def trusted_permission(f) | Access only by D1 infrastructure. | 2.702096 | 2.709724 | 0.997185 |
@functools.wraps(f)
def wrapper(request, *args, **kwargs):
if not django.conf.settings.PUBLIC_OBJECT_LIST:
trusted(request)
return f(request, *args, **kwargs)
return wrapper | def list_objects_access(f) | Access to listObjects() controlled by settings.PUBLIC_OBJECT_LIST. | 3.885901 | 2.780038 | 1.397787 |
@functools.wraps(f)
def wrapper(request, *args, **kwargs):
if not django.conf.settings.PUBLIC_LOG_RECORDS:
trusted(request)
return f(request, *args, **kwargs)
return wrapper | def get_log_records_access(f) | Access to getLogRecords() controlled by settings.PUBLIC_LOG_RECORDS. | 3.852186 | 2.720819 | 1.415819 |
@functools.wraps(f)
def wrapper(request, *args, **kwargs):
d1_gmn.app.auth.assert_create_update_delete_permission(request)
return f(request, *args, **kwargs)
return wrapper | def assert_create_update_delete_permission(f) | Access only by subjects with Create/Update/Delete permission and by trusted
infrastructure (CNs). | 2.469867 | 2.369723 | 1.042259 |
@functools.wraps(f)
def wrapper(request, *args, **kwargs):
if d1_common.const.SUBJECT_AUTHENTICATED not in request.all_subjects_set:
raise d1_common.types.exceptions.NotAuthorized(
0,
'Access allowed only for authenticated subjects. Please reconnect with... | def authenticated(f) | Access only with a valid session. | 4.664964 | 4.478862 | 1.041551 |
@functools.wraps(f)
def wrapper(request, pid, *args, **kwargs):
d1_gmn.app.auth.assert_allowed(request, level, pid)
return f(request, pid, *args, **kwargs)
return wrapper | def required_permission(f, level) | Assert that subject has access at given level or higher for object. | 3.244426 | 3.009045 | 1.078224 |
try:
return d1_common.xml.deserialize(response.content)
except ValueError as e:
self._raise_service_failure_invalid_dataone_type(response, e) | def _read_and_deserialize_dataone_type(self, response) | Given a response body, try to create an instance of a DataONE type.
The return value will be either an instance of a type or a DataONE exception. | 5.392446 | 5.425293 | 0.993946 |
response = self.getResponse(pid, stream, vendorSpecific)
return self._read_stream_response(response) | def get(self, pid, stream=False, vendorSpecific=None) | Initiate a MNRead.get(). Return a Requests Response object from which the
object bytes can be retrieved.
When ``stream`` is False, Requests buffers the entire object in memory before
returning the Response. This can exhaust available memory on the local machine
when retrieving large sci... | 6.623801 | 11.028853 | 0.600588 |
response = self.get(pid, stream=True, vendorSpecific=vendorSpecific)
try:
if create_missing_dirs:
d1_common.utils.filesystem.create_missing_directories_for_file(
sciobj_stream
)
for chunk_str in response.iter_content(
... | def get_and_save(
self, pid, sciobj_stream, create_missing_dirs=False, vendorSpecific=None
) | Like MNRead.get(), but also retrieve the object bytes and store them in a
stream. This method does not have the potential issue with excessive memory
usage that get() with ``stream``=False has.
Also see MNRead.get(). | 2.705968 | 2.644615 | 1.023199 |
response = self.describeResponse(pid, vendorSpecific=vendorSpecific)
return self._read_header_response(response) | def describe(self, pid, vendorSpecific=None) | Note: If the server returns a status code other than 200 OK, a ServiceFailure
will be raised, as this method is based on a HEAD request, which cannot carry
exception information. | 6.930964 | 5.83022 | 1.1888 |
response = self.isAuthorizedResponse(pid, action, vendorSpecific)
return self._read_boolean_401_response(response) | def isAuthorized(self, pid, action, vendorSpecific=None) | Return True if user is allowed to perform ``action`` on ``pid``, else
False. | 7.555653 | 7.990892 | 0.945533 |
fields = super().fields
return apply_subfield_projection(self, copy.copy(fields)) | def fields(self) | Filter fields based on request query parameters. | 28.127182 | 24.358261 | 1.154729 |
if path_prefix is not None and path_prefix != '' and path_prefix[-1] != '.':
path_prefix += '.'
schema_dict = {val['name']: val for val in schema}
for field_id, properties in fields.items():
path = '{}{}'.format(path_prefix, field_id) if path_prefix is not None else None
if fie... | def iterate_fields(fields, schema, path_prefix=None) | Iterate over all field values sub-fields.
This will iterate over all field values. Some fields defined in the schema
might not be visited.
:param fields: field values to iterate over
:type fields: dict
:param schema: schema to iterate over
:type schema: dict
:return: (field schema, field v... | 2.773557 | 2.853089 | 0.972124 |
if path_prefix and path_prefix[-1] != '.':
path_prefix += '.'
for field_schema in schema:
name = field_schema['name']
if 'group' in field_schema:
for rvals in iterate_schema(fields[name] if name in fields else {},
field_schema['gr... | def iterate_schema(fields, schema, path_prefix='') | Iterate over all schema sub-fields.
This will iterate over all field definitions in the schema. Some field v
alues might be None.
:param fields: field values to iterate over
:type fields: dict
:param schema: schema to iterate over
:type schema: dict
:param path_prefix: dot separated path p... | 2.97341 | 2.859076 | 1.03999 |
if path is None:
path = []
for key, value in container.items():
if callable(exclude) and exclude(key, value):
continue
if isinstance(value, collections.Mapping):
for inner_path, inner_key, inner_value in iterate_dict(value, exclude=exclude, path=path + [key... | def iterate_dict(container, exclude=None, path=None) | Iterate over a nested dictionary.
The dictionary is iterated over in a depth first manner.
:param container: Dictionary to iterate over
:param exclude: Optional callable, which is given key and value as
arguments and may return True to stop iteration of that branch
:return: (path, key, value) ... | 1.897175 | 1.945099 | 0.975362 |
if _is_certificate_provided(request):
try:
return get_authenticated_subjects(request.META['SSL_CLIENT_CERT'])
except Exception as e:
raise d1_common.types.exceptions.InvalidToken(
0,
'Error extracting session from certificate. error="{}"'.... | def get_subjects(request) | Get all subjects in the certificate.
- Returns: primary_str (primary subject), equivalent_set (equivalent identities,
groups and group memberships)
- The primary subject is the certificate subject DN, serialized to a DataONE
compliant subject string. | 5.761584 | 5.922589 | 0.972815 |
if isinstance(cert_pem, str):
cert_pem = cert_pem.encode('utf-8')
return d1_common.cert.subjects.extract_subjects(cert_pem) | def get_authenticated_subjects(cert_pem) | Return primary subject and set of equivalents authenticated by certificate.
- ``cert_pem`` can be str or bytes | 3.86592 | 4.201357 | 0.92016 |
base_class = super().get_serializer_class()
class SerializerWithPermissions(base_class):
def get_fields(serializer_self): # pylint: disable=no-self-argument
fields = super().get_fields()
fields['current_user_permission... | def get_serializer_class(self) | Augment base serializer class.
Include permissions information with objects. | 2.618522 | 2.539295 | 1.0312 |
obj = self.get_object()
if request.method == 'POST':
content_type = ContentType.objects.get_for_model(obj)
payload = request.data
share_content = strtobool(payload.pop('share_content', 'false'))
user = request.user
is_owner = user.has... | def detail_permissions(self, request, pk=None) | Get or set permissions API endpoint. | 3.366864 | 3.325176 | 1.012537 |
if self.descriptor_schema:
try:
validate_schema(self.descriptor, self.descriptor_schema.schema) # pylint: disable=no-member
self.descriptor_dirty = False
except DirtyError:
self.descriptor_dirty = True
elif self.descriptor... | def save(self, *args, **kwargs) | Perform descriptor validation and save object. | 4.725152 | 3.973845 | 1.189063 |
duplicate = Collection.objects.get(id=self.id)
duplicate.pk = None
duplicate.slug = None
duplicate.name = 'Copy of {}'.format(self.name)
duplicate.duplicated = now()
if contributor:
duplicate.contributor = contributor
duplicate.save(force_ins... | def duplicate(self, contributor=None) | Duplicate (make a copy). | 3.601382 | 3.564433 | 1.010366 |
da = {}
for k, v in d.items():
if '_' not in k:
da[k] = v
else:
name = ''.join(k.split('_')[:-1])
ind = k.split('_')[-1]
dim = len(ind)
if name not in da:
shape = tuple(3 for i in range(dim))
da[name... | def _scalar2array(d) | Convert a dictionary with scalar elements and string indices '_1234'
to a dictionary of arrays. Unspecified entries are np.nan. | 2.536249 | 2.334028 | 1.086641 |
nans = np.isnan(C)
C[nans] = np.einsum('jilk', C)[nans].conj()
return C | def _symm_herm(C) | To get rid of NaNs produced by _scalar2array, symmetrize operators
where C_ijkl = C_jilk* | 6.871948 | 5.483549 | 1.253193 |
nans = np.isnan(C)
C[nans] = np.einsum('klij', C)[nans]
return C | def _symm_current(C) | To get rid of NaNs produced by _scalar2array, symmetrize operators
where C_ijkl = C_klij | 6.216282 | 4.4155 | 1.407832 |
nans = np.isnan(C)
C[nans] = -np.einsum('jikl', C)[nans]
return C | def _antisymm_12(C) | To get rid of NaNs produced by _scalar2array, antisymmetrize the first
two indices of operators where C_ijkl = -C_jikl | 5.520339 | 4.051075 | 1.362685 |
if sectors is None:
wc_keys = wcxf.Basis['WET', 'JMS'].all_wcs
else:
try:
wc_keys = [k for s in sectors for k in wcxf.Basis['WET', 'JMS'].sectors[s]]
except KeyError:
print(sectors)
# fill in zeros for missing coefficients
C_complete = {k: C.get(k, 0)... | def JMS_to_array(C, sectors=None) | For a dictionary with JMS Wilson coefficients, return a dictionary
of arrays. | 3.900213 | 3.72266 | 1.047695 |
wc_keys = set(wcxf.Basis['WET', 'JMS'].all_wcs)
Cs = {}
for op, v in C.items():
if '_' not in op or op in wc_keys:
Cs[op] = v
continue
name, ind = op.split('_')
if name in C_symm_keys[5]:
i, j, k, l = ind
indnew = ''.join([j, i, l,... | def symmetrize_JMS_dict(C) | For a dictionary with JMS Wilson coefficients but keys that might not be
in the non-redundant basis, return a dictionary with keys from the basis
and values conjugated if necessary. | 2.292632 | 2.224596 | 1.030584 |
C = C_in.copy()
V = ckmutil.ckm.ckm_tree(p["Vus"], p["Vub"], p["Vcb"], p["delta"])
UdL = V
## B conserving operators
# type dL dL dL dL
for k in ['VddLL']:
C[k] = np.einsum('ia,jb,kc,ld,ijkl->abcd',
UdL.conj(), UdL, UdL.conj(), UdL,
... | def rotate_down(C_in, p) | Redefinition of all Wilson coefficients in the JMS basis when rotating
down-type quark fields from the flavour to the mass basis.
C_in is expected to be an array-valued dictionary containg a key
for all Wilson coefficient matrices. | 3.118397 | 3.079087 | 1.012767 |
return {k: v / _scale_dict[k] for k, v in C.items()} | def scale_dict_wet(C) | To account for the fact that arXiv:Jenkins:2017jig uses a flavour
non-redundant basis in contrast to WCxf, symmetry factors of two have to
be introduced in several places for operators that are symmetric
under the interchange of two currents. | 4.536269 | 5.613071 | 0.808162 |
return {k: _scale_dict[k] * v for k, v in C.items()} | def unscale_dict_wet(C) | Undo the scaling applied in `scale_dict_wet`. | 5.314789 | 4.668366 | 1.138469 |
with open(req_path, 'w') as f:
f.write('\n'.join(req_list) + "\n") | def write_reqs(req_path, req_list) | Args:
req_path:
req_list: | 2.341674 | 2.521663 | 0.928623 |
logger.debug(__(
"Connector '{}' running for Data with id {} ({}).",
self.__class__.__module__,
data.id,
repr(argv)
))
subprocess.Popen(
argv,
cwd=runtime_dir,
stdin=subprocess.DEVNULL
).wait() | def submit(self, data, runtime_dir, argv) | Run process locally.
For details, see
:meth:`~resolwe.flow.managers.workload_connectors.base.BaseConnector.submit`. | 7.145819 | 6.534896 | 1.093486 |
checksum_str = calculate_checksum_on_stream(f, algorithm)
checksum_pyxb = d1_common.types.dataoneTypes.checksum(checksum_str)
checksum_pyxb.algorithm = algorithm
return checksum_pyxb | def create_checksum_object_from_stream(
f, algorithm=d1_common.const.DEFAULT_CHECKSUM_ALGORITHM
) | Calculate the checksum of a stream.
Args:
f: file-like object
Only requirement is a ``read()`` method that returns ``bytes``.
algorithm: str
Checksum algorithm, ``MD5`` or ``SHA1`` / ``SHA-1``.
Returns:
Populated Checksum PyXB object. | 3.411351 | 3.671692 | 0.929095 |
checksum_str = calculate_checksum_on_iterator(itr, algorithm)
checksum_pyxb = d1_common.types.dataoneTypes.checksum(checksum_str)
checksum_pyxb.algorithm = algorithm
return checksum_pyxb | def create_checksum_object_from_iterator(
itr, algorithm=d1_common.const.DEFAULT_CHECKSUM_ALGORITHM
) | Calculate the checksum of an iterator.
Args:
itr: iterable
Object which supports the iterator protocol.
algorithm: str
Checksum algorithm, ``MD5`` or ``SHA1`` / ``SHA-1``.
Returns:
Populated Checksum PyXB object. | 3.500827 | 3.550782 | 0.985931 |
checksum_str = calculate_checksum_on_bytes(b, algorithm)
checksum_pyxb = d1_common.types.dataoneTypes.checksum(checksum_str)
checksum_pyxb.algorithm = algorithm
return checksum_pyxb | def create_checksum_object_from_bytes(
b, algorithm=d1_common.const.DEFAULT_CHECKSUM_ALGORITHM
) | Calculate the checksum of ``bytes``.
Warning:
This method requires the entire object to be buffered in (virtual) memory, which
should normally be avoided in production code.
Args:
b: bytes
Raw bytes
algorithm: str
Checksum algorithm, ``MD5`` or ``SHA1`` / ``SHA-1``.
... | 3.384428 | 3.794514 | 0.891927 |
checksum_calc = get_checksum_calculator_by_dataone_designator(algorithm)
while True:
chunk = f.read(chunk_size)
if not chunk:
break
checksum_calc.update(chunk)
return checksum_calc.hexdigest() | def calculate_checksum_on_stream(
f,
algorithm=d1_common.const.DEFAULT_CHECKSUM_ALGORITHM,
chunk_size=DEFAULT_CHUNK_SIZE,
) | Calculate the checksum of a stream.
Args:
f: file-like object
Only requirement is a ``read()`` method that returns ``bytes``.
algorithm: str
Checksum algorithm, ``MD5`` or ``SHA1`` / ``SHA-1``.
chunk_size : int
Number of bytes to read from the file and add to the checksu... | 3.455128 | 4.514942 | 0.765265 |
checksum_calc = get_checksum_calculator_by_dataone_designator(algorithm)
for chunk in itr:
checksum_calc.update(chunk)
return checksum_calc.hexdigest() | def calculate_checksum_on_iterator(
itr, algorithm=d1_common.const.DEFAULT_CHECKSUM_ALGORITHM
) | Calculate the checksum of an iterator.
Args:
itr: iterable
Object which supports the iterator protocol.
algorithm: str
Checksum algorithm, ``MD5`` or ``SHA1`` / ``SHA-1``.
Returns:
str : Checksum as a hexadecimal string, with length decided by the algorithm. | 5.494124 | 7.361951 | 0.746286 |
checksum_calc = get_checksum_calculator_by_dataone_designator(algorithm)
checksum_calc.update(b)
return checksum_calc.hexdigest() | def calculate_checksum_on_bytes(
b, algorithm=d1_common.const.DEFAULT_CHECKSUM_ALGORITHM
) | Calculate the checksum of ``bytes``.
Warning: This method requires the entire object to be buffered in (virtual) memory,
which should normally be avoided in production code.
Args:
b: bytes
Raw bytes
algorithm: str
Checksum algorithm, ``MD5`` or ``SHA1`` / ``SHA-1``.
Retur... | 6.984938 | 9.473236 | 0.737334 |
if checksum_a_pyxb.algorithm != checksum_b_pyxb.algorithm:
raise ValueError(
'Cannot compare checksums calculated with different algorithms. '
'a="{}" b="{}"'.format(checksum_a_pyxb.algorithm, checksum_b_pyxb.algorithm)
)
return checksum_a_pyxb.value().lower() == che... | def are_checksums_equal(checksum_a_pyxb, checksum_b_pyxb) | Determine if checksums are equal.
Args:
checksum_a_pyxb, checksum_b_pyxb: PyXB Checksum objects to compare.
Returns:
bool
- **True**: The checksums contain the same hexadecimal values calculated with
the same algorithm. Identical checksums guarantee (for all practical
... | 2.298912 | 2.265085 | 1.014934 |
return '{}/{}'.format(
checksum_pyxb.algorithm.upper().replace('-', ''), checksum_pyxb.value().lower()
) | def format_checksum(checksum_pyxb) | Create string representation of a PyXB Checksum object.
Args:
PyXB Checksum object
Returns:
str : Combined hexadecimal value and algorithm name. | 5.668745 | 8.851898 | 0.640399 |
listener = ExecutorListener(redis_params=getattr(settings, 'FLOW_MANAGER', {}).get('REDIS_CONNECTION', {}))
def _killer(signum, frame):
listener.terminate()
signal(SIGINT, _killer)
signal(SIGTERM, _killer)
async def _runner():
... | def handle(self, *args, **kwargs) | Run the executor listener. This method never returns. | 5.272584 | 4.716894 | 1.117809 |
# Discover the root manually. We cannot use either `self.root` or `self.context`
# due to a bug with incorrect caching (see DRF issue #5087).
prefix = []
root = field
while root.parent is not None:
# Skip anonymous serializers (e.g., intermediate ListSerializers).
if root.field_... | def apply_subfield_projection(field, value, deep=False) | Apply projection from request context.
The passed dictionary may be mutated.
:param field: An instance of `Field` or `Serializer`
:type field: `Field` or `Serializer`
:param value: Dictionary to apply the projection to
:type value: dict
:param deep: Also process all deep projections
:type ... | 4.357554 | 4.370985 | 0.996927 |
if isinstance(value, Sequence):
# Apply projection to each item in the list.
return [
apply_projection(projection, item)
for item in value
]
elif not isinstance(value, Mapping):
# Non-dictionary values are simply ignored.
return value
# E... | def apply_projection(projection, value) | Apply projection. | 2.601029 | 2.5517 | 1.019332 |
for partition in partitions:
RelationPartition.objects.create(
relation=instance,
entity=partition['entity'],
label=partition.get('label', None),
position=partition.get('position', None),
) | def _create_partitions(self, instance, partitions) | Create partitions. | 3.703739 | 3.468946 | 1.067684 |
# `partitions` field is renamed to `relationpartition_set` based on source of nested serializer
partitions = validated_data.pop('relationpartition_set')
with transaction.atomic():
instance = Relation.objects.create(**validated_data)
self._create_partitions(insta... | def create(self, validated_data) | Create ``Relation`` object and add partitions of ``Entities``. | 7.562912 | 5.536359 | 1.366044 |
# `partitions` field is renamed to `relationpartition_set` based on source of nested serializer
partitions = validated_data.pop('relationpartition_set', None)
with transaction.atomic():
instance = super().update(instance, validated_data)
if partitions is not No... | def update(self, instance, validated_data) | Update ``Relation``. | 5.710092 | 5.170169 | 1.10443 |
if not path:
for line in file_like_object:
if verbose:
print_info(line.rstrip())
else:
print(line.rstrip())
else:
try:
object_file = open(os.path.expanduser(path), "w", encoding="utf-8")
shutil.copyfileobj(file_... | def output(file_like_object, path, verbose=False) | Display or save file like object. | 2.470753 | 2.453867 | 1.006881 |
for l in str(msg.rstrip()).split("\n"):
print("{0:<9s}{1}".format(level, str(l))) | def _print_level(level, msg) | Print the information in Unicode safe manner. | 6.345493 | 5.869359 | 1.081122 |
with open(fname) as file_:
for i, line in enumerate(file_):
if re.search(r'slug:\s*{}'.format(slug), line):
return i + 1
# In case starting line is not found just return first line
return 1 | def get_process_definition_start(fname, slug) | Find the first line of process definition.
The first line of process definition is the line with a slug.
:param str fname: Path to filename with processes
:param string slug: process slug
:return: line where the process definiton starts
:rtype: int | 4.437324 | 4.301649 | 1.03154 |
global PROCESS_CACHE # pylint: disable=global-statement
if PROCESS_CACHE is not None:
return PROCESS_CACHE
all_process_files = []
process_file_extensions = ['*.yaml', '*.yml']
for root, _, filenames in os.walk(process_dir):
for extension in process_file_extensions:
... | def get_processes(process_dir, base_source_uri) | Find processes in path.
:param str process_dir: Path to the directory where to search for processes
:param str base_source_uri: Base URL of the source code repository with process definitions
:return: Dictionary of processes where keys are URLs pointing to processes'
source code and values are processe... | 2.846003 | 2.859166 | 0.995396 |
app.add_config_value('autoprocess_process_dir', '', 'env')
app.add_config_value('autoprocess_source_base_url', '', 'env')
app.add_config_value('autoprocess_definitions_uri', '', 'env')
app.add_directive('autoprocess', AutoProcessDirective)
app.add_directive('autoprocesscategory', AutoProcessCa... | def setup(app) | Register directives.
When sphinx loads the extension (= imports the extension module) it
also executes the setup() function. Setup is the way extension
informs Sphinx about everything that the extension enables: which
config_values are introduced, which custom nodes/directives/roles
and which event... | 3.686946 | 3.80635 | 0.96863 |
name = nodes.field_name()
name += nodes.Text(field_name)
paragraph = nodes.paragraph()
if isinstance(field_body, str):
# This is the case when field_body is just a string:
paragraph += nodes.Text(field_body)
else:
# This is the case w... | def make_field(self, field_name, field_body) | Fill content into nodes.
:param string field_name: Field name of the field
:param field_name: Field body if the field
:type field_name: str or instance of docutils.nodes
:return: field instance filled with given name and body
:rtype: nodes.field | 3.40396 | 3.389545 | 1.004253 |
properties_list = nodes.field_list()
# changing the order of elements in this list affects
# the order in which they are displayed
property_names = ['label', 'type', 'description', 'required',
'disabled', 'hidden', 'default', 'placeholder',
... | def make_properties_list(self, field) | Fill the ``field`` into a properties list and return it.
:param dict field: the content of the property list to make
:return: field_list instance filled with given field
:rtype: nodes.field_list | 3.387043 | 3.397887 | 0.996809 |
node = addnodes.desc()
signode = addnodes.desc_signature(slug, '')
node.append(signode)
node['objtype'] = node['desctype'] = typ
signode += addnodes.desc_annotation(typ, typ, classes=['process-type'])
signode += addnodes.desc_addname('', '')
signode += ... | def make_process_header(self, slug, typ, version, source_uri, description, inputs) | Generate a process definition header.
:param str slug: process' slug
:param str typ: process' type
:param str version: process' version
:param str source_uri: url to the process definition
:param str description: process' description
:param dict inputs: process' inputs | 3.459987 | 3.551146 | 0.97433 |
name = process['name']
slug = process['slug']
typ = process['type']
version = process['version']
description = process.get('description', '')
source_uri = process['source_uri']
inputs = process.get('input', [])
outputs = process.get('output', [])
... | def make_process_node(self, process) | Fill the content of process definiton node.
:param dict process: process data as given from yaml.load function
:return: process node | 2.38602 | 2.400148 | 0.994114 |
config = self.state.document.settings.env.config
# Get all processes:
processes = get_processes(config.autoprocess_process_dir, config.autoprocess_source_base_url)
process_nodes = []
for process in sorted(processes, key=itemgetter('name')):
process_nodes.ex... | def run(self) | Create a list of process definitions. | 4.938145 | 4.111576 | 1.201035 |
config = self.state.document.settings.env.config
# Group processes by category
processes = get_processes(config.autoprocess_process_dir, config.autoprocess_source_base_url)
processes.sort(key=itemgetter('category'))
categorized_processes = {k: list(g) for k, g in groupb... | def run(self) | Create a category tree. | 3.091185 | 3.022324 | 1.022784 |
config = self.state.document.settings.env.config
# Group processes by category
processes = get_processes(config.autoprocess_process_dir, config.autoprocess_source_base_url)
processes.sort(key=itemgetter('type'))
processes_by_types = {k: list(g) for k, g in groupby(proce... | def run(self) | Create a type list. | 2.959692 | 2.866688 | 1.032443 |
async with await self._retry_request(
"get", ["object", pid], vendor_specific=vendor_specific
) as response:
self._assert_valid_response(response)
async for chunk_str, _ in response.content.iter_chunks():
file_stream.write(chunk_str) | async def get(self, file_stream, pid, vendor_specific=None) | MNRead.get()
Retrieve the SciObj bytes and write them to a file or other stream.
Args:
file_stream: Open file-like object
Stream to which the SciObj bytes will be written.
pid: str
vendor_specific: dict
Custom HTTP headers to includ... | 4.756042 | 4.983677 | 0.954324 |
return await self._request_pyxb(
"post",
["synchronize", pid],
{},
mmp_dict={"pid": pid},
vendor_specific=vendor_specific,
) | async def synchronize(self, pid, vendor_specific=None) | Send an object synchronization request to the CN. | 9.181214 | 8.220653 | 1.116847 |
return {
k: v if not isinstance(v, datetime.datetime) else v.isoformat()
for k, v in list(query_dict.items())
} | def _datetime_to_iso8601(self, query_dict) | Encode any datetime query parameters to ISO8601. | 2.659698 | 2.384038 | 1.115627 |
value = apply_subfield_projection(self, value, deep=True)
return super().to_representation(value) | def to_representation(self, value) | Project outgoing native value. | 10.768673 | 9.158067 | 1.175867 |
mmp_dict = {'pid': pid}
return self.POST(['synchronize'], fields=mmp_dict, headers=vendorSpecific) | def synchronizeResponse(self, pid, vendorSpecific=None) | CNRead.synchronize(session, pid) → boolean POST /synchronize.
Args: pid: vendorSpecific: | 12.872377 | 15.346013 | 0.838809 |
response = self.synchronizeResponse(pid, vendorSpecific)
return self._read_boolean_response(response) | def synchronize(self, pid, vendorSpecific=None) | See Also: synchronizeResponse() Args: pid: vendorSpecific:
Returns: | 8.235517 | 7.931737 | 1.038299 |
verbosity = int(options['verbosity'])
if self.has_filter(options):
self.filter_indices(options, verbosity)
else:
# Process all indices.
index_builder.build() | def handle(self, *args, **options) | Command handle. | 8.759573 | 8.785183 | 0.997085 |
_assert_zip_file(bagit_path)
bagit_zip = zipfile.ZipFile(bagit_path)
manifest_info_list = _get_manifest_info_list(bagit_zip)
_validate_checksums(bagit_zip, manifest_info_list)
return True | def validate_bagit_file(bagit_path) | Check if a BagIt file is valid.
Raises:
ServiceFailure
If the BagIt zip archive file fails any of the following checks:
- Is a valid zip file.
- The tag and manifest files are correctly formatted.
- Contains all the files listed in the manifests.
... | 3.00646 | 3.286987 | 0.914655 |
zip_file = zipstream.ZipFile(mode='w', compression=zipstream.ZIP_DEFLATED)
_add_path(dir_name, payload_info_list)
payload_byte_count, payload_file_count = _add_payload_files(
zip_file, payload_info_list
)
tag_info_list = _add_tag_files(
zip_file, dir_name, payload_info_list, pay... | def create_bagit_stream(dir_name, payload_info_list) | Create a stream containing a BagIt zip archive.
Args:
dir_name : str
The name of the root directory in the zip file, under which all the files
are placed (avoids "zip bombs").
payload_info_list: list
List of payload_info_dict, each dict describing a file.
... | 2.240453 | 2.533166 | 0.884448 |
for payload_info_dict in payload_info_list:
file_name = payload_info_dict['filename'] or payload_info_dict['pid']
payload_info_dict['path'] = d1_common.utils.filesystem.gen_safe_path(
dir_name, 'data', file_name
) | def _add_path(dir_name, payload_info_list) | Add a key with the path to each payload_info_dict. | 3.60696 | 3.223022 | 1.119124 |
payload_byte_count = 0
payload_file_count = 0
for payload_info_dict in payload_info_list:
zip_file.write_iter(payload_info_dict['path'], payload_info_dict['iter'])
payload_byte_count += payload_info_dict['iter'].size
payload_file_count += 1
return payload_byte_count, payload... | def _add_payload_files(zip_file, payload_info_list) | Add the payload files to the zip. | 2.313012 | 2.213958 | 1.044741 |
tag_info_list = []
_add_tag_file(zip_file, dir_name, tag_info_list, _gen_bagit_text_file_tup())
_add_tag_file(
zip_file,
dir_name,
tag_info_list,
_gen_bag_info_file_tup(payload_byte_count, payload_file_count),
)
_add_tag_file(
zip_file, dir_name, tag_info... | def _add_tag_files(
zip_file, dir_name, payload_info_list, payload_byte_count, payload_file_count
) | Generate the tag files and add them to the zip. | 2.468373 | 2.346389 | 1.051988 |
for checksum_algorithm in _get_checksum_algorithm_set(payload_info_list):
_add_tag_file(
zip_file,
dir_name,
tag_info_list,
_gen_manifest_file_tup(payload_info_list, checksum_algorithm),
) | def _add_manifest_files(zip_file, dir_name, payload_info_list, tag_info_list) | Generate the manifest files and add them to the zip. | 3.994476 | 3.767309 | 1.0603 |
_add_tag_file(
zip_file, dir_name, tag_info_list, _gen_tag_manifest_file_tup(tag_info_list)
) | def _add_tag_manifest_file(zip_file, dir_name, tag_info_list) | Generate the tag manifest file and add it to the zip. | 4.320941 | 3.759238 | 1.149419 |
tag_name, tag_str = tag_tup
tag_path = d1_common.utils.filesystem.gen_safe_path(dir_name, tag_name)
tag_iter = _create_and_add_tag_iter(zip_file, tag_path, tag_str)
tag_info_list.append(
{
'path': tag_path,
'checksum': d1_common.checksum.calculate_checksum_on_iterato... | def _add_tag_file(zip_file, dir_name, tag_info_list, tag_tup) | Add a tag file to zip_file and record info for the tag manifest file. | 3.264736 | 3.17243 | 1.029096 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.