repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
genialis/resolwe | resolwe/flow/views/collection.py | CollectionViewSet.remove_data | def remove_data(self, request, pk=None):
"""Remove data from collection."""
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() | python | def remove_data(self, request, pk=None):
"""Remove data from collection."""
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",
")",
":",
"collection",
"=",
"self",
".",
"get_object",
"(",
")",
"if",
"'ids'",
"not",
"in",
"request",
".",
"data",
":",
"return",
"Response",
"(",
"{",
"\"error\"",
":",
"\... | Remove data from collection. | [
"Remove",
"data",
"from",
"collection",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/views/collection.py#L176-L186 | train | 45,100 |
genialis/resolwe | resolwe/elastic/lookup.py | QueryBuilder.register_lookup | def register_lookup(self, lookup):
"""Register lookup."""
if lookup.operator in self._lookups:
raise KeyError("Lookup for operator '{}' is already registered".format(lookup.operator))
self._lookups[lookup.operator] = lookup() | python | def register_lookup(self, lookup):
"""Register lookup."""
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",
")",
":",
"if",
"lookup",
".",
"operator",
"in",
"self",
".",
"_lookups",
":",
"raise",
"KeyError",
"(",
"\"Lookup for operator '{}' is already registered\"",
".",
"format",
"(",
"lookup",
".",
"operator",
")... | Register lookup. | [
"Register",
"lookup",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/lookup.py#L127-L132 | train | 45,101 |
genialis/resolwe | resolwe/elastic/lookup.py | QueryBuilder.get_lookup | def get_lookup(self, operator):
"""Look up a lookup.
:param operator: Name of the lookup operator
"""
try:
return self._lookups[operator]
except KeyError:
raise NotImplementedError("Lookup operator '{}' is not supported".format(operator)) | python | def get_lookup(self, operator):
"""Look up a lookup.
:param operator: Name of the lookup operator
"""
try:
return self._lookups[operator]
except KeyError:
raise NotImplementedError("Lookup operator '{}' is not supported".format(operator)) | [
"def",
"get_lookup",
"(",
"self",
",",
"operator",
")",
":",
"try",
":",
"return",
"self",
".",
"_lookups",
"[",
"operator",
"]",
"except",
"KeyError",
":",
"raise",
"NotImplementedError",
"(",
"\"Lookup operator '{}' is not supported\"",
".",
"format",
"(",
"op... | Look up a lookup.
:param operator: Name of the lookup operator | [
"Look",
"up",
"a",
"lookup",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/lookup.py#L134-L142 | train | 45,102 |
genialis/resolwe | resolwe/elastic/lookup.py | QueryBuilder.build | def build(self, search, raw_query):
"""Build query.
:param search: Search query instance
:param raw_query: Raw query arguments dictionary
"""
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:
unmatched_items[expression] = value
continue
# Map field alias to final field.
field = self.fields_map.get(field, field)
# Parse lookup expression. Currently only no token or a single token is allowed.
if tail:
if len(tail) > 1:
raise NotImplementedError("Nested lookup expressions are not supported")
lookup = self.get_lookup(tail[0])
search = lookup.apply(search, field, value)
else:
# Default lookup.
custom_filter = getattr(self.custom_filter_object, 'custom_filter_{}'.format(field), None)
if custom_filter is not None:
search = custom_filter(value, search)
elif isinstance(value, list):
# Default is 'should' between matches. If you need anything else,
# a custom filter for this field should be implemented.
filters = [Q('match', **{field: item}) for item in value]
search = search.query('bool', should=filters)
else:
search = search.query('match', **{field: {'query': value, 'operator': 'and'}})
return (search, unmatched_items) | python | def build(self, search, raw_query):
"""Build query.
:param search: Search query instance
:param raw_query: Raw query arguments dictionary
"""
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:
unmatched_items[expression] = value
continue
# Map field alias to final field.
field = self.fields_map.get(field, field)
# Parse lookup expression. Currently only no token or a single token is allowed.
if tail:
if len(tail) > 1:
raise NotImplementedError("Nested lookup expressions are not supported")
lookup = self.get_lookup(tail[0])
search = lookup.apply(search, field, value)
else:
# Default lookup.
custom_filter = getattr(self.custom_filter_object, 'custom_filter_{}'.format(field), None)
if custom_filter is not None:
search = custom_filter(value, search)
elif isinstance(value, list):
# Default is 'should' between matches. If you need anything else,
# a custom filter for this field should be implemented.
filters = [Q('match', **{field: item}) for item in value]
search = search.query('bool', should=filters)
else:
search = search.query('match', **{field: {'query': value, 'operator': 'and'}})
return (search, unmatched_items) | [
"def",
"build",
"(",
"self",
",",
"search",
",",
"raw_query",
")",
":",
"unmatched_items",
"=",
"{",
"}",
"for",
"expression",
",",
"value",
"in",
"raw_query",
".",
"items",
"(",
")",
":",
"# Parse query expression into tokens.",
"tokens",
"=",
"expression",
... | Build query.
:param search: Search query instance
:param raw_query: Raw query arguments dictionary | [
"Build",
"query",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/lookup.py#L144-L185 | train | 45,103 |
DataONEorg/d1_python | gmn/src/d1_gmn/app/views/decorators.py | resolve_sid | 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 NotFound exception.
"""
@functools.wraps(f)
def wrapper(request, did, *args, **kwargs):
pid = resolve_sid_func(request, did)
return f(request, pid, *args, **kwargs)
return wrapper | python | 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 NotFound exception.
"""
@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",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"request",
",",
"did",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"pid",
"=",
"resolve_sid_func",
"(",
"request",
",",
"did",
... | 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 NotFound exception. | [
"View",
"handler",
"decorator",
"that",
"adds",
"SID",
"resolve",
"and",
"PID",
"validation",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/views/decorators.py#L39-L54 | train | 45,104 |
DataONEorg/d1_python | gmn/src/d1_gmn/app/views/decorators.py | trusted_permission | def trusted_permission(f):
"""Access only by D1 infrastructure."""
@functools.wraps(f)
def wrapper(request, *args, **kwargs):
trusted(request)
return f(request, *args, **kwargs)
return wrapper | python | def trusted_permission(f):
"""Access only by D1 infrastructure."""
@functools.wraps(f)
def wrapper(request, *args, **kwargs):
trusted(request)
return f(request, *args, **kwargs)
return wrapper | [
"def",
"trusted_permission",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"trusted",
"(",
"request",
")",
"return",
"f",
"(",
"request",
",... | Access only by D1 infrastructure. | [
"Access",
"only",
"by",
"D1",
"infrastructure",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/views/decorators.py#L108-L116 | train | 45,105 |
DataONEorg/d1_python | gmn/src/d1_gmn/app/views/decorators.py | authenticated | def authenticated(f):
"""Access only with a valid session."""
@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 '
'a valid DataONE session certificate. active_subjects="{}"'.format(
d1_gmn.app.auth.format_active_subjects(request)
),
)
return f(request, *args, **kwargs)
return wrapper | python | def authenticated(f):
"""Access only with a valid session."""
@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 '
'a valid DataONE session certificate. active_subjects="{}"'.format(
d1_gmn.app.auth.format_active_subjects(request)
),
)
return f(request, *args, **kwargs)
return wrapper | [
"def",
"authenticated",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"d1_common",
".",
"const",
".",
"SUBJECT_AUTHENTICATED",
"not",
"i... | Access only with a valid session. | [
"Access",
"only",
"with",
"a",
"valid",
"session",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/views/decorators.py#L167-L182 | train | 45,106 |
DataONEorg/d1_python | gmn/src/d1_gmn/app/views/decorators.py | required_permission | def required_permission(f, level):
"""Assert that subject has access at given level or higher for object."""
@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 | python | def required_permission(f, level):
"""Assert that subject has access at given level or higher for object."""
@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",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"request",
",",
"pid",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"d1_gmn",
".",
"app",
".",
"auth",
"... | Assert that subject has access at given level or higher for object. | [
"Assert",
"that",
"subject",
"has",
"access",
"at",
"given",
"level",
"or",
"higher",
"for",
"object",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/views/decorators.py#L204-L212 | train | 45,107 |
DataONEorg/d1_python | lib_client/src/d1_client/baseclient.py | DataONEBaseClient._read_and_deserialize_dataone_type | 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.
"""
try:
return d1_common.xml.deserialize(response.content)
except ValueError as e:
self._raise_service_failure_invalid_dataone_type(response, e) | python | 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.
"""
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",
")",
":",
"try",
":",
"return",
"d1_common",
".",
"xml",
".",
"deserialize",
"(",
"response",
".",
"content",
")",
"except",
"ValueError",
"as",
"e",
":",
"self",
".",
"_raise_service_f... | 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. | [
"Given",
"a",
"response",
"body",
"try",
"to",
"create",
"an",
"instance",
"of",
"a",
"DataONE",
"type",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_client/src/d1_client/baseclient.py#L319-L328 | train | 45,108 |
DataONEorg/d1_python | lib_client/src/d1_client/baseclient.py | DataONEBaseClient.isAuthorized | def isAuthorized(self, pid, action, vendorSpecific=None):
"""Return True if user is allowed to perform ``action`` on ``pid``, else
False."""
response = self.isAuthorizedResponse(pid, action, vendorSpecific)
return self._read_boolean_401_response(response) | python | def isAuthorized(self, pid, action, vendorSpecific=None):
"""Return True if user is allowed to perform ``action`` on ``pid``, else
False."""
response = self.isAuthorizedResponse(pid, action, vendorSpecific)
return self._read_boolean_401_response(response) | [
"def",
"isAuthorized",
"(",
"self",
",",
"pid",
",",
"action",
",",
"vendorSpecific",
"=",
"None",
")",
":",
"response",
"=",
"self",
".",
"isAuthorizedResponse",
"(",
"pid",
",",
"action",
",",
"vendorSpecific",
")",
"return",
"self",
".",
"_read_boolean_40... | Return True if user is allowed to perform ``action`` on ``pid``, else
False. | [
"Return",
"True",
"if",
"user",
"is",
"allowed",
"to",
"perform",
"action",
"on",
"pid",
"else",
"False",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_client/src/d1_client/baseclient.py#L675-L679 | train | 45,109 |
genialis/resolwe | resolwe/rest/serializers.py | SelectiveFieldMixin.fields | def fields(self):
"""Filter fields based on request query parameters."""
fields = super().fields
return apply_subfield_projection(self, copy.copy(fields)) | python | def fields(self):
"""Filter fields based on request query parameters."""
fields = super().fields
return apply_subfield_projection(self, copy.copy(fields)) | [
"def",
"fields",
"(",
"self",
")",
":",
"fields",
"=",
"super",
"(",
")",
".",
"fields",
"return",
"apply_subfield_projection",
"(",
"self",
",",
"copy",
".",
"copy",
"(",
"fields",
")",
")"
] | Filter fields based on request query parameters. | [
"Filter",
"fields",
"based",
"on",
"request",
"query",
"parameters",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/rest/serializers.py#L11-L14 | train | 45,110 |
genialis/resolwe | resolwe/flow/utils/iterators.py | iterate_fields | 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 value)
:rtype: tuple
"""
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 field_id not in schema_dict:
raise KeyError("Field definition ({}) missing in schema".format(field_id))
if 'group' in schema_dict[field_id]:
for rvals in iterate_fields(properties, schema_dict[field_id]['group'], path):
yield rvals if path_prefix is not None else rvals[:2]
else:
rvals = (schema_dict[field_id], fields, path)
yield rvals if path_prefix is not None else rvals[:2] | python | 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 value)
:rtype: tuple
"""
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 field_id not in schema_dict:
raise KeyError("Field definition ({}) missing in schema".format(field_id))
if 'group' in schema_dict[field_id]:
for rvals in iterate_fields(properties, schema_dict[field_id]['group'], path):
yield rvals if path_prefix is not None else rvals[:2]
else:
rvals = (schema_dict[field_id], fields, path)
yield rvals if path_prefix is not None else rvals[:2] | [
"def",
"iterate_fields",
"(",
"fields",
",",
"schema",
",",
"path_prefix",
"=",
"None",
")",
":",
"if",
"path_prefix",
"is",
"not",
"None",
"and",
"path_prefix",
"!=",
"''",
"and",
"path_prefix",
"[",
"-",
"1",
"]",
"!=",
"'.'",
":",
"path_prefix",
"+=",... | 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 value)
:rtype: tuple | [
"Iterate",
"over",
"all",
"field",
"values",
"sub",
"-",
"fields",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/utils/iterators.py#L5-L32 | train | 45,111 |
genialis/resolwe | resolwe/flow/utils/iterators.py | iterate_schema | 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 prefix
:type path_prefix: str
:return: (field schema, field value, field path)
:rtype: tuple
"""
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['group'], '{}{}'.format(path_prefix, name)):
yield rvals
else:
yield (field_schema, fields, '{}{}'.format(path_prefix, name)) | python | 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 prefix
:type path_prefix: str
:return: (field schema, field value, field path)
:rtype: tuple
"""
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['group'], '{}{}'.format(path_prefix, name)):
yield rvals
else:
yield (field_schema, fields, '{}{}'.format(path_prefix, name)) | [
"def",
"iterate_schema",
"(",
"fields",
",",
"schema",
",",
"path_prefix",
"=",
"''",
")",
":",
"if",
"path_prefix",
"and",
"path_prefix",
"[",
"-",
"1",
"]",
"!=",
"'.'",
":",
"path_prefix",
"+=",
"'.'",
"for",
"field_schema",
"in",
"schema",
":",
"name... | 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 prefix
:type path_prefix: str
:return: (field schema, field value, field path)
:rtype: tuple | [
"Iterate",
"over",
"all",
"schema",
"sub",
"-",
"fields",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/utils/iterators.py#L35-L61 | train | 45,112 |
genialis/resolwe | resolwe/flow/utils/iterators.py | iterate_dict | 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) tuple
"""
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]):
yield inner_path, inner_key, inner_value
yield path, key, value | python | 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) tuple
"""
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]):
yield inner_path, inner_key, inner_value
yield path, key, value | [
"def",
"iterate_dict",
"(",
"container",
",",
"exclude",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"container",
".",
"items",
"(",
")",
":",
"if",
"c... | 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) tuple | [
"Iterate",
"over",
"a",
"nested",
"dictionary",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/utils/iterators.py#L64-L85 | train | 45,113 |
DataONEorg/d1_python | gmn/src/d1_gmn/app/middleware/session_cert.py | get_subjects | 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.
"""
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="{}"'.format(str(e)),
)
else:
return d1_common.const.SUBJECT_PUBLIC, set() | python | 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.
"""
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="{}"'.format(str(e)),
)
else:
return d1_common.const.SUBJECT_PUBLIC, set() | [
"def",
"get_subjects",
"(",
"request",
")",
":",
"if",
"_is_certificate_provided",
"(",
"request",
")",
":",
"try",
":",
"return",
"get_authenticated_subjects",
"(",
"request",
".",
"META",
"[",
"'SSL_CLIENT_CERT'",
"]",
")",
"except",
"Exception",
"as",
"e",
... | 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. | [
"Get",
"all",
"subjects",
"in",
"the",
"certificate",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/middleware/session_cert.py#L38-L56 | train | 45,114 |
DataONEorg/d1_python | gmn/src/d1_gmn/app/middleware/session_cert.py | get_authenticated_subjects | def get_authenticated_subjects(cert_pem):
"""Return primary subject and set of equivalents authenticated by certificate.
- ``cert_pem`` can be str or bytes
"""
if isinstance(cert_pem, str):
cert_pem = cert_pem.encode('utf-8')
return d1_common.cert.subjects.extract_subjects(cert_pem) | python | def get_authenticated_subjects(cert_pem):
"""Return primary subject and set of equivalents authenticated by certificate.
- ``cert_pem`` can be str or bytes
"""
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",
")",
":",
"if",
"isinstance",
"(",
"cert_pem",
",",
"str",
")",
":",
"cert_pem",
"=",
"cert_pem",
".",
"encode",
"(",
"'utf-8'",
")",
"return",
"d1_common",
".",
"cert",
".",
"subjects",
".",
"extract_sub... | Return primary subject and set of equivalents authenticated by certificate.
- ``cert_pem`` can be str or bytes | [
"Return",
"primary",
"subject",
"and",
"set",
"of",
"equivalents",
"authenticated",
"by",
"certificate",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/middleware/session_cert.py#L59-L67 | train | 45,115 |
genialis/resolwe | resolwe/permissions/mixins.py | ResolwePermissionsMixin.get_serializer_class | def get_serializer_class(self):
"""Augment base serializer class.
Include permissions information with objects.
"""
base_class = super().get_serializer_class()
class SerializerWithPermissions(base_class):
"""Augment serializer class."""
def get_fields(serializer_self): # pylint: disable=no-self-argument
"""Return serializer's fields."""
fields = super().get_fields()
fields['current_user_permissions'] = CurrentUserPermissionsSerializer(read_only=True)
return fields
def to_representation(serializer_self, instance): # pylint: disable=no-self-argument
"""Object serializer."""
data = super().to_representation(instance)
if ('fields' not in self.request.query_params
or 'current_user_permissions' in self.request.query_params['fields']):
data['current_user_permissions'] = get_object_perms(instance, self.request.user)
return data
return SerializerWithPermissions | python | def get_serializer_class(self):
"""Augment base serializer class.
Include permissions information with objects.
"""
base_class = super().get_serializer_class()
class SerializerWithPermissions(base_class):
"""Augment serializer class."""
def get_fields(serializer_self): # pylint: disable=no-self-argument
"""Return serializer's fields."""
fields = super().get_fields()
fields['current_user_permissions'] = CurrentUserPermissionsSerializer(read_only=True)
return fields
def to_representation(serializer_self, instance): # pylint: disable=no-self-argument
"""Object serializer."""
data = super().to_representation(instance)
if ('fields' not in self.request.query_params
or 'current_user_permissions' in self.request.query_params['fields']):
data['current_user_permissions'] = get_object_perms(instance, self.request.user)
return data
return SerializerWithPermissions | [
"def",
"get_serializer_class",
"(",
"self",
")",
":",
"base_class",
"=",
"super",
"(",
")",
".",
"get_serializer_class",
"(",
")",
"class",
"SerializerWithPermissions",
"(",
"base_class",
")",
":",
"\"\"\"Augment serializer class.\"\"\"",
"def",
"get_fields",
"(",
"... | Augment base serializer class.
Include permissions information with objects. | [
"Augment",
"base",
"serializer",
"class",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/permissions/mixins.py#L31-L58 | train | 45,116 |
genialis/resolwe | resolwe/permissions/mixins.py | ResolwePermissionsMixin.detail_permissions | def detail_permissions(self, request, pk=None):
"""Get or set permissions API endpoint."""
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_perm('owner_{}'.format(content_type), obj=obj)
allow_owner = is_owner or user.is_superuser
check_owner_permission(payload, allow_owner)
check_public_permissions(payload)
check_user_permissions(payload, request.user.pk)
with transaction.atomic():
update_permission(obj, payload)
owner_count = UserObjectPermission.objects.filter(
object_pk=obj.id,
content_type=content_type,
permission__codename__startswith='owner_'
).count()
if not owner_count:
raise exceptions.ParseError('Object must have at least one owner.')
if share_content:
self.set_content_permissions(user, obj, payload)
return Response(get_object_perms(obj)) | python | def detail_permissions(self, request, pk=None):
"""Get or set permissions API endpoint."""
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_perm('owner_{}'.format(content_type), obj=obj)
allow_owner = is_owner or user.is_superuser
check_owner_permission(payload, allow_owner)
check_public_permissions(payload)
check_user_permissions(payload, request.user.pk)
with transaction.atomic():
update_permission(obj, payload)
owner_count = UserObjectPermission.objects.filter(
object_pk=obj.id,
content_type=content_type,
permission__codename__startswith='owner_'
).count()
if not owner_count:
raise exceptions.ParseError('Object must have at least one owner.')
if share_content:
self.set_content_permissions(user, obj, payload)
return Response(get_object_perms(obj)) | [
"def",
"detail_permissions",
"(",
"self",
",",
"request",
",",
"pk",
"=",
"None",
")",
":",
"obj",
"=",
"self",
".",
"get_object",
"(",
")",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"... | Get or set permissions API endpoint. | [
"Get",
"or",
"set",
"permissions",
"API",
"endpoint",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/permissions/mixins.py#L70-L101 | train | 45,117 |
genialis/resolwe | resolwe/flow/models/collection.py | BaseCollection.save | def save(self, *args, **kwargs):
"""Perform descriptor validation and save object."""
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 and self.descriptor != {}:
raise ValueError("`descriptor_schema` must be defined if `descriptor` is given")
super().save() | python | def save(self, *args, **kwargs):
"""Perform descriptor validation and save object."""
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 and self.descriptor != {}:
raise ValueError("`descriptor_schema` must be defined if `descriptor` is given")
super().save() | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"descriptor_schema",
":",
"try",
":",
"validate_schema",
"(",
"self",
".",
"descriptor",
",",
"self",
".",
"descriptor_schema",
".",
"schema",
")",
"# p... | Perform descriptor validation and save object. | [
"Perform",
"descriptor",
"validation",
"and",
"save",
"object",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/collection.py#L40-L51 | train | 45,118 |
wilson-eft/wilson | wilson/util/wetutil.py | _scalar2array | def _scalar2array(d):
"""Convert a dictionary with scalar elements and string indices '_1234'
to a dictionary of arrays. Unspecified entries are np.nan."""
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] = np.empty(shape, dtype=complex)
da[name][:] = np.nan
da[name][tuple(int(i) - 1 for i in ind)] = v
return da | python | def _scalar2array(d):
"""Convert a dictionary with scalar elements and string indices '_1234'
to a dictionary of arrays. Unspecified entries are np.nan."""
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] = np.empty(shape, dtype=complex)
da[name][:] = np.nan
da[name][tuple(int(i) - 1 for i in ind)] = v
return da | [
"def",
"_scalar2array",
"(",
"d",
")",
":",
"da",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"d",
".",
"items",
"(",
")",
":",
"if",
"'_'",
"not",
"in",
"k",
":",
"da",
"[",
"k",
"]",
"=",
"v",
"else",
":",
"name",
"=",
"''",
".",
"join",... | Convert a dictionary with scalar elements and string indices '_1234'
to a dictionary of arrays. Unspecified entries are np.nan. | [
"Convert",
"a",
"dictionary",
"with",
"scalar",
"elements",
"and",
"string",
"indices",
"_1234",
"to",
"a",
"dictionary",
"of",
"arrays",
".",
"Unspecified",
"entries",
"are",
"np",
".",
"nan",
"."
] | 4164f55ff663d4f668c6e2b4575fd41562662cc9 | https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/util/wetutil.py#L41-L57 | train | 45,119 |
wilson-eft/wilson | wilson/util/wetutil.py | _symm_current | def _symm_current(C):
"""To get rid of NaNs produced by _scalar2array, symmetrize operators
where C_ijkl = C_klij"""
nans = np.isnan(C)
C[nans] = np.einsum('klij', C)[nans]
return C | python | def _symm_current(C):
"""To get rid of NaNs produced by _scalar2array, symmetrize operators
where C_ijkl = C_klij"""
nans = np.isnan(C)
C[nans] = np.einsum('klij', C)[nans]
return C | [
"def",
"_symm_current",
"(",
"C",
")",
":",
"nans",
"=",
"np",
".",
"isnan",
"(",
"C",
")",
"C",
"[",
"nans",
"]",
"=",
"np",
".",
"einsum",
"(",
"'klij'",
",",
"C",
")",
"[",
"nans",
"]",
"return",
"C"
] | To get rid of NaNs produced by _scalar2array, symmetrize operators
where C_ijkl = C_klij | [
"To",
"get",
"rid",
"of",
"NaNs",
"produced",
"by",
"_scalar2array",
"symmetrize",
"operators",
"where",
"C_ijkl",
"=",
"C_klij"
] | 4164f55ff663d4f668c6e2b4575fd41562662cc9 | https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/util/wetutil.py#L68-L73 | train | 45,120 |
wilson-eft/wilson | wilson/util/wetutil.py | _antisymm_12 | def _antisymm_12(C):
"""To get rid of NaNs produced by _scalar2array, antisymmetrize the first
two indices of operators where C_ijkl = -C_jikl"""
nans = np.isnan(C)
C[nans] = -np.einsum('jikl', C)[nans]
return C | python | def _antisymm_12(C):
"""To get rid of NaNs produced by _scalar2array, antisymmetrize the first
two indices of operators where C_ijkl = -C_jikl"""
nans = np.isnan(C)
C[nans] = -np.einsum('jikl', C)[nans]
return C | [
"def",
"_antisymm_12",
"(",
"C",
")",
":",
"nans",
"=",
"np",
".",
"isnan",
"(",
"C",
")",
"C",
"[",
"nans",
"]",
"=",
"-",
"np",
".",
"einsum",
"(",
"'jikl'",
",",
"C",
")",
"[",
"nans",
"]",
"return",
"C"
] | To get rid of NaNs produced by _scalar2array, antisymmetrize the first
two indices of operators where C_ijkl = -C_jikl | [
"To",
"get",
"rid",
"of",
"NaNs",
"produced",
"by",
"_scalar2array",
"antisymmetrize",
"the",
"first",
"two",
"indices",
"of",
"operators",
"where",
"C_ijkl",
"=",
"-",
"C_jikl"
] | 4164f55ff663d4f668c6e2b4575fd41562662cc9 | https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/util/wetutil.py#L75-L80 | train | 45,121 |
wilson-eft/wilson | wilson/util/wetutil.py | JMS_to_array | def JMS_to_array(C, sectors=None):
"""For a dictionary with JMS Wilson coefficients, return a dictionary
of arrays."""
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) for k in wc_keys}
Ca = _scalar2array(C_complete)
for k in Ca:
if k in C_symm_keys[5]:
Ca[k] = _symm_herm(Ca[k])
if k in C_symm_keys[41]:
Ca[k] = _symm_current(Ca[k])
if k in C_symm_keys[4]:
Ca[k] = _symm_herm(_symm_current(Ca[k]))
if k in C_symm_keys[9]:
Ca[k] = _antisymm_12(Ca[k])
return Ca | python | def JMS_to_array(C, sectors=None):
"""For a dictionary with JMS Wilson coefficients, return a dictionary
of arrays."""
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) for k in wc_keys}
Ca = _scalar2array(C_complete)
for k in Ca:
if k in C_symm_keys[5]:
Ca[k] = _symm_herm(Ca[k])
if k in C_symm_keys[41]:
Ca[k] = _symm_current(Ca[k])
if k in C_symm_keys[4]:
Ca[k] = _symm_herm(_symm_current(Ca[k]))
if k in C_symm_keys[9]:
Ca[k] = _antisymm_12(Ca[k])
return Ca | [
"def",
"JMS_to_array",
"(",
"C",
",",
"sectors",
"=",
"None",
")",
":",
"if",
"sectors",
"is",
"None",
":",
"wc_keys",
"=",
"wcxf",
".",
"Basis",
"[",
"'WET'",
",",
"'JMS'",
"]",
".",
"all_wcs",
"else",
":",
"try",
":",
"wc_keys",
"=",
"[",
"k",
... | For a dictionary with JMS Wilson coefficients, return a dictionary
of arrays. | [
"For",
"a",
"dictionary",
"with",
"JMS",
"Wilson",
"coefficients",
"return",
"a",
"dictionary",
"of",
"arrays",
"."
] | 4164f55ff663d4f668c6e2b4575fd41562662cc9 | https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/util/wetutil.py#L83-L105 | train | 45,122 |
wilson-eft/wilson | wilson/util/wetutil.py | symmetrize_JMS_dict | 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."""
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, k])
Cs['_'.join([name, indnew])] = v.conjugate()
elif name in C_symm_keys[41]:
i, j, k, l = ind
indnew = ''.join([k, l, i, j])
Cs['_'.join([name, indnew])] = v
elif name in C_symm_keys[4]:
i, j, k, l = ind
indnew = ''.join([l, k, j, i])
newname = '_'.join([name, indnew])
if newname in wc_keys:
Cs[newname] = v.conjugate()
else:
indnew = ''.join([j, i, l, k])
newname = '_'.join([name, indnew])
if newname in wc_keys:
Cs[newname] = v.conjugate()
else:
indnew = ''.join([k, l, i, j])
newname = '_'.join([name, indnew])
Cs[newname] = v
elif name in C_symm_keys[9]:
i, j, k, l = ind
indnew = ''.join([j, i, k, l])
Cs['_'.join([name, indnew])] = -v
return Cs | python | 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."""
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, k])
Cs['_'.join([name, indnew])] = v.conjugate()
elif name in C_symm_keys[41]:
i, j, k, l = ind
indnew = ''.join([k, l, i, j])
Cs['_'.join([name, indnew])] = v
elif name in C_symm_keys[4]:
i, j, k, l = ind
indnew = ''.join([l, k, j, i])
newname = '_'.join([name, indnew])
if newname in wc_keys:
Cs[newname] = v.conjugate()
else:
indnew = ''.join([j, i, l, k])
newname = '_'.join([name, indnew])
if newname in wc_keys:
Cs[newname] = v.conjugate()
else:
indnew = ''.join([k, l, i, j])
newname = '_'.join([name, indnew])
Cs[newname] = v
elif name in C_symm_keys[9]:
i, j, k, l = ind
indnew = ''.join([j, i, k, l])
Cs['_'.join([name, indnew])] = -v
return Cs | [
"def",
"symmetrize_JMS_dict",
"(",
"C",
")",
":",
"wc_keys",
"=",
"set",
"(",
"wcxf",
".",
"Basis",
"[",
"'WET'",
",",
"'JMS'",
"]",
".",
"all_wcs",
")",
"Cs",
"=",
"{",
"}",
"for",
"op",
",",
"v",
"in",
"C",
".",
"items",
"(",
")",
":",
"if",
... | 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. | [
"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",... | 4164f55ff663d4f668c6e2b4575fd41562662cc9 | https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/util/wetutil.py#L108-L146 | train | 45,123 |
wilson-eft/wilson | wilson/util/wetutil.py | rotate_down | 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."""
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,
C_in[k])
# type X X dL dL
for k in ['V1udLL', 'V8udLL', 'VedLL', 'VnudLL']:
C[k] = np.einsum('kc,ld,ijkl->ijcd',
UdL.conj(), UdL,
C_in[k])
# type dL dL X X
for k in ['V1ddLR', 'V1duLR', 'V8ddLR', 'V8duLR', 'VdeLR']:
C[k] = np.einsum('ia,jb,ijkl->abkl',
UdL.conj(), UdL,
C_in[k])
# type dL X dL X
for k in ['S1ddRR', 'S8ddRR']:
C[k] = np.einsum('ia,kc,ijkl->ajcl',
UdL.conj(), UdL.conj(),
C_in[k])
# type X dL X X
for k in ['V1udduLR', 'V8udduLR']:
C[k] = np.einsum('jb,ijkl->ibkl',
UdL,
C_in[k])
# type X X dL X
for k in ['VnueduLL', 'SedRR', 'TedRR', 'SnueduRR', 'TnueduRR',
'S1udRR', 'S8udRR', 'S1udduRR', 'S8udduRR', ]:
C[k] = np.einsum('kc,ijkl->ijcl',
UdL.conj(),
C_in[k])
# type X X X dL
for k in ['SedRL', ]:
C[k] = np.einsum('ld,ijkl->ijkd',
UdL,
C_in[k])
## DeltaB=DeltaL=1 operators
# type dL X X X
for k in ['SduuLL', 'SduuLR']:
C[k] = np.einsum('ia,ijkl->ajkl',
UdL,
C_in[k])
# type X X dL X
for k in ['SuudRL', 'SdudRL']:
C[k] = np.einsum('kc,ijkl->ijcl',
UdL,
C_in[k])
# type X dL dL X
for k in ['SuddLL']:
C[k] = np.einsum('jb,kc,ijkl->ibcl',
UdL, UdL,
C_in[k])
return C | python | 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."""
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,
C_in[k])
# type X X dL dL
for k in ['V1udLL', 'V8udLL', 'VedLL', 'VnudLL']:
C[k] = np.einsum('kc,ld,ijkl->ijcd',
UdL.conj(), UdL,
C_in[k])
# type dL dL X X
for k in ['V1ddLR', 'V1duLR', 'V8ddLR', 'V8duLR', 'VdeLR']:
C[k] = np.einsum('ia,jb,ijkl->abkl',
UdL.conj(), UdL,
C_in[k])
# type dL X dL X
for k in ['S1ddRR', 'S8ddRR']:
C[k] = np.einsum('ia,kc,ijkl->ajcl',
UdL.conj(), UdL.conj(),
C_in[k])
# type X dL X X
for k in ['V1udduLR', 'V8udduLR']:
C[k] = np.einsum('jb,ijkl->ibkl',
UdL,
C_in[k])
# type X X dL X
for k in ['VnueduLL', 'SedRR', 'TedRR', 'SnueduRR', 'TnueduRR',
'S1udRR', 'S8udRR', 'S1udduRR', 'S8udduRR', ]:
C[k] = np.einsum('kc,ijkl->ijcl',
UdL.conj(),
C_in[k])
# type X X X dL
for k in ['SedRL', ]:
C[k] = np.einsum('ld,ijkl->ijkd',
UdL,
C_in[k])
## DeltaB=DeltaL=1 operators
# type dL X X X
for k in ['SduuLL', 'SduuLR']:
C[k] = np.einsum('ia,ijkl->ajkl',
UdL,
C_in[k])
# type X X dL X
for k in ['SuudRL', 'SdudRL']:
C[k] = np.einsum('kc,ijkl->ijcl',
UdL,
C_in[k])
# type X dL dL X
for k in ['SuddLL']:
C[k] = np.einsum('jb,kc,ijkl->ibcl',
UdL, UdL,
C_in[k])
return C | [
"def",
"rotate_down",
"(",
"C_in",
",",
"p",
")",
":",
"C",
"=",
"C_in",
".",
"copy",
"(",
")",
"V",
"=",
"ckmutil",
".",
"ckm",
".",
"ckm_tree",
"(",
"p",
"[",
"\"Vus\"",
"]",
",",
"p",
"[",
"\"Vub\"",
"]",
",",
"p",
"[",
"\"Vcb\"",
"]",
","... | 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. | [
"Redefinition",
"of",
"all",
"Wilson",
"coefficients",
"in",
"the",
"JMS",
"basis",
"when",
"rotating",
"down",
"-",
"type",
"quark",
"fields",
"from",
"the",
"flavour",
"to",
"the",
"mass",
"basis",
"."
] | 4164f55ff663d4f668c6e2b4575fd41562662cc9 | https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/util/wetutil.py#L149-L211 | train | 45,124 |
wilson-eft/wilson | wilson/util/wetutil.py | unscale_dict_wet | def unscale_dict_wet(C):
"""Undo the scaling applied in `scale_dict_wet`."""
return {k: _scale_dict[k] * v for k, v in C.items()} | python | def unscale_dict_wet(C):
"""Undo the scaling applied in `scale_dict_wet`."""
return {k: _scale_dict[k] * v for k, v in C.items()} | [
"def",
"unscale_dict_wet",
"(",
"C",
")",
":",
"return",
"{",
"k",
":",
"_scale_dict",
"[",
"k",
"]",
"*",
"v",
"for",
"k",
",",
"v",
"in",
"C",
".",
"items",
"(",
")",
"}"
] | Undo the scaling applied in `scale_dict_wet`. | [
"Undo",
"the",
"scaling",
"applied",
"in",
"scale_dict_wet",
"."
] | 4164f55ff663d4f668c6e2b4575fd41562662cc9 | https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/util/wetutil.py#L240-L242 | train | 45,125 |
genialis/resolwe | resolwe/flow/managers/workload_connectors/local.py | Connector.submit | def submit(self, data, runtime_dir, argv):
"""Run process locally.
For details, see
:meth:`~resolwe.flow.managers.workload_connectors.base.BaseConnector.submit`.
"""
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() | python | def submit(self, data, runtime_dir, argv):
"""Run process locally.
For details, see
:meth:`~resolwe.flow.managers.workload_connectors.base.BaseConnector.submit`.
"""
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",
")",
":",
"logger",
".",
"debug",
"(",
"__",
"(",
"\"Connector '{}' running for Data with id {} ({}).\"",
",",
"self",
".",
"__class__",
".",
"__module__",
",",
"data",
".",
"id",
",... | Run process locally.
For details, see
:meth:`~resolwe.flow.managers.workload_connectors.base.BaseConnector.submit`. | [
"Run",
"process",
"locally",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/managers/workload_connectors/local.py#L21-L37 | train | 45,126 |
DataONEorg/d1_python | lib_common/src/d1_common/checksum.py | are_checksums_equal | 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
purposes) that the checksums were calculated from the same sequence of bytes.
- **False**: The checksums were calculated with the same algorithm but the
hexadecimal values are different.
Raises:
ValueError
The checksums were calculated with different algorithms, hence cannot be
compared.
"""
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() == checksum_b_pyxb.value().lower() | python | 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
purposes) that the checksums were calculated from the same sequence of bytes.
- **False**: The checksums were calculated with the same algorithm but the
hexadecimal values are different.
Raises:
ValueError
The checksums were calculated with different algorithms, hence cannot be
compared.
"""
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() == checksum_b_pyxb.value().lower() | [
"def",
"are_checksums_equal",
"(",
"checksum_a_pyxb",
",",
"checksum_b_pyxb",
")",
":",
"if",
"checksum_a_pyxb",
".",
"algorithm",
"!=",
"checksum_b_pyxb",
".",
"algorithm",
":",
"raise",
"ValueError",
"(",
"'Cannot compare checksums calculated with different algorithms. '",
... | 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
purposes) that the checksums were calculated from the same sequence of bytes.
- **False**: The checksums were calculated with the same algorithm but the
hexadecimal values are different.
Raises:
ValueError
The checksums were calculated with different algorithms, hence cannot be
compared. | [
"Determine",
"if",
"checksums",
"are",
"equal",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/checksum.py#L195-L220 | train | 45,127 |
DataONEorg/d1_python | lib_common/src/d1_common/checksum.py | format_checksum | 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.
"""
return '{}/{}'.format(
checksum_pyxb.algorithm.upper().replace('-', ''), checksum_pyxb.value().lower()
) | python | 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.
"""
return '{}/{}'.format(
checksum_pyxb.algorithm.upper().replace('-', ''), checksum_pyxb.value().lower()
) | [
"def",
"format_checksum",
"(",
"checksum_pyxb",
")",
":",
"return",
"'{}/{}'",
".",
"format",
"(",
"checksum_pyxb",
".",
"algorithm",
".",
"upper",
"(",
")",
".",
"replace",
"(",
"'-'",
",",
"''",
")",
",",
"checksum_pyxb",
".",
"value",
"(",
")",
".",
... | Create string representation of a PyXB Checksum object.
Args:
PyXB Checksum object
Returns:
str : Combined hexadecimal value and algorithm name. | [
"Create",
"string",
"representation",
"of",
"a",
"PyXB",
"Checksum",
"object",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/checksum.py#L289-L301 | train | 45,128 |
genialis/resolwe | resolwe/flow/management/commands/runlistener.py | Command.handle | def handle(self, *args, **kwargs):
"""Run the executor listener. This method never returns."""
listener = ExecutorListener(redis_params=getattr(settings, 'FLOW_MANAGER', {}).get('REDIS_CONNECTION', {}))
def _killer(signum, frame):
"""Kill the listener on receipt of a signal."""
listener.terminate()
signal(SIGINT, _killer)
signal(SIGTERM, _killer)
async def _runner():
"""Run the listener instance."""
if kwargs['clear_queue']:
await listener.clear_queue()
async with listener:
pass
loop = asyncio.new_event_loop()
loop.run_until_complete(_runner())
loop.close() | python | def handle(self, *args, **kwargs):
"""Run the executor listener. This method never returns."""
listener = ExecutorListener(redis_params=getattr(settings, 'FLOW_MANAGER', {}).get('REDIS_CONNECTION', {}))
def _killer(signum, frame):
"""Kill the listener on receipt of a signal."""
listener.terminate()
signal(SIGINT, _killer)
signal(SIGTERM, _killer)
async def _runner():
"""Run the listener instance."""
if kwargs['clear_queue']:
await listener.clear_queue()
async with listener:
pass
loop = asyncio.new_event_loop()
loop.run_until_complete(_runner())
loop.close() | [
"def",
"handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"listener",
"=",
"ExecutorListener",
"(",
"redis_params",
"=",
"getattr",
"(",
"settings",
",",
"'FLOW_MANAGER'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'REDIS_CONNECTION'"... | Run the executor listener. This method never returns. | [
"Run",
"the",
"executor",
"listener",
".",
"This",
"method",
"never",
"returns",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/management/commands/runlistener.py#L33-L52 | train | 45,129 |
genialis/resolwe | resolwe/rest/projection.py | apply_subfield_projection | 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 deep: bool
"""
# 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_name:
prefix.append(root.field_name)
root = root.parent
prefix = prefix[::-1]
context = getattr(root, '_context', {})
# If there is no request, we cannot perform filtering.
request = context.get('request')
if request is None:
return value
filtered = set(request.query_params.get('fields', '').split(FIELD_SEPARATOR))
filtered.discard('')
if not filtered:
# If there are no fields specified in the filter, return all fields.
return value
# Extract projection for current and deeper levels.
current_level = len(prefix)
current_projection = []
for item in filtered:
item = item.split(FIELD_DEREFERENCE)
if len(item) <= current_level:
continue
if item[:current_level] == prefix:
if deep:
current_projection.append(item[current_level:])
else:
current_projection.append([item[current_level]])
if deep and not current_projection:
# For deep projections, an empty projection means that all fields should
# be returned without any projection.
return value
# Apply projection.
return apply_projection(current_projection, value) | python | 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 deep: bool
"""
# 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_name:
prefix.append(root.field_name)
root = root.parent
prefix = prefix[::-1]
context = getattr(root, '_context', {})
# If there is no request, we cannot perform filtering.
request = context.get('request')
if request is None:
return value
filtered = set(request.query_params.get('fields', '').split(FIELD_SEPARATOR))
filtered.discard('')
if not filtered:
# If there are no fields specified in the filter, return all fields.
return value
# Extract projection for current and deeper levels.
current_level = len(prefix)
current_projection = []
for item in filtered:
item = item.split(FIELD_DEREFERENCE)
if len(item) <= current_level:
continue
if item[:current_level] == prefix:
if deep:
current_projection.append(item[current_level:])
else:
current_projection.append([item[current_level]])
if deep and not current_projection:
# For deep projections, an empty projection means that all fields should
# be returned without any projection.
return value
# Apply projection.
return apply_projection(current_projection, value) | [
"def",
"apply_subfield_projection",
"(",
"field",
",",
"value",
",",
"deep",
"=",
"False",
")",
":",
"# 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"... | 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 deep: bool | [
"Apply",
"projection",
"from",
"request",
"context",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/rest/projection.py#L8-L64 | train | 45,130 |
genialis/resolwe | resolwe/rest/projection.py | apply_projection | def apply_projection(projection, value):
"""Apply projection."""
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
# Extract projection for current level.
try:
current_projection = [p[0] for p in projection]
except IndexError:
return value
# Apply projection.
for name in list(value.keys()):
if name not in current_projection:
value.pop(name)
elif isinstance(value[name], dict):
# Apply projection recursively.
value[name] = apply_projection(
[p[1:] for p in projection if p[0] == name],
value[name]
)
return value | python | def apply_projection(projection, value):
"""Apply projection."""
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
# Extract projection for current level.
try:
current_projection = [p[0] for p in projection]
except IndexError:
return value
# Apply projection.
for name in list(value.keys()):
if name not in current_projection:
value.pop(name)
elif isinstance(value[name], dict):
# Apply projection recursively.
value[name] = apply_projection(
[p[1:] for p in projection if p[0] == name],
value[name]
)
return value | [
"def",
"apply_projection",
"(",
"projection",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"Sequence",
")",
":",
"# Apply projection to each item in the list.",
"return",
"[",
"apply_projection",
"(",
"projection",
",",
"item",
")",
"for",
"item"... | Apply projection. | [
"Apply",
"projection",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/rest/projection.py#L67-L96 | train | 45,131 |
genialis/resolwe | resolwe/flow/serializers/relation.py | RelationSerializer._create_partitions | def _create_partitions(self, instance, partitions):
"""Create partitions."""
for partition in partitions:
RelationPartition.objects.create(
relation=instance,
entity=partition['entity'],
label=partition.get('label', None),
position=partition.get('position', None),
) | python | def _create_partitions(self, instance, partitions):
"""Create partitions."""
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",
")",
":",
"for",
"partition",
"in",
"partitions",
":",
"RelationPartition",
".",
"objects",
".",
"create",
"(",
"relation",
"=",
"instance",
",",
"entity",
"=",
"partition",
"[",
"... | Create partitions. | [
"Create",
"partitions",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/serializers/relation.py#L57-L65 | train | 45,132 |
genialis/resolwe | resolwe/flow/serializers/relation.py | RelationSerializer.create | def create(self, validated_data):
"""Create ``Relation`` object and add partitions of ``Entities``."""
# `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(instance, partitions)
return instance | python | def create(self, validated_data):
"""Create ``Relation`` object and add partitions of ``Entities``."""
# `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(instance, partitions)
return instance | [
"def",
"create",
"(",
"self",
",",
"validated_data",
")",
":",
"# `partitions` field is renamed to `relationpartition_set` based on source of nested serializer",
"partitions",
"=",
"validated_data",
".",
"pop",
"(",
"'relationpartition_set'",
")",
"with",
"transaction",
".",
... | Create ``Relation`` object and add partitions of ``Entities``. | [
"Create",
"Relation",
"object",
"and",
"add",
"partitions",
"of",
"Entities",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/serializers/relation.py#L67-L76 | train | 45,133 |
genialis/resolwe | resolwe/flow/serializers/relation.py | RelationSerializer.update | def update(self, instance, validated_data):
"""Update ``Relation``."""
# `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 None:
# TODO: Apply the diff instead of recreating all objects.
instance.relationpartition_set.all().delete()
self._create_partitions(instance, partitions)
return instance | python | def update(self, instance, validated_data):
"""Update ``Relation``."""
# `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 None:
# TODO: Apply the diff instead of recreating all objects.
instance.relationpartition_set.all().delete()
self._create_partitions(instance, partitions)
return instance | [
"def",
"update",
"(",
"self",
",",
"instance",
",",
"validated_data",
")",
":",
"# `partitions` field is renamed to `relationpartition_set` based on source of nested serializer",
"partitions",
"=",
"validated_data",
".",
"pop",
"(",
"'relationpartition_set'",
",",
"None",
")"... | Update ``Relation``. | [
"Update",
"Relation",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/serializers/relation.py#L78-L91 | train | 45,134 |
DataONEorg/d1_python | client_cli/src/d1_cli/impl/util.py | _print_level | def _print_level(level, msg):
"""Print the information in Unicode safe manner."""
for l in str(msg.rstrip()).split("\n"):
print("{0:<9s}{1}".format(level, str(l))) | python | def _print_level(level, msg):
"""Print the information in Unicode safe manner."""
for l in str(msg.rstrip()).split("\n"):
print("{0:<9s}{1}".format(level, str(l))) | [
"def",
"_print_level",
"(",
"level",
",",
"msg",
")",
":",
"for",
"l",
"in",
"str",
"(",
"msg",
".",
"rstrip",
"(",
")",
")",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"print",
"(",
"\"{0:<9s}{1}\"",
".",
"format",
"(",
"level",
",",
"str",
"(",
"l... | Print the information in Unicode safe manner. | [
"Print",
"the",
"information",
"in",
"Unicode",
"safe",
"manner",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/client_cli/src/d1_cli/impl/util.py#L147-L150 | train | 45,135 |
genialis/resolwe | resolwe/flow/utils/docs/autoprocess.py | get_process_definition_start | 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
"""
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 | python | 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
"""
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",
")",
":",
"with",
"open",
"(",
"fname",
")",
"as",
"file_",
":",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"file_",
")",
":",
"if",
"re",
".",
"search",
"(",
"r'slug:\\s*{}'",
"."... | 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 | [
"Find",
"the",
"first",
"line",
"of",
"process",
"definition",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/utils/docs/autoprocess.py#L45-L61 | train | 45,136 |
genialis/resolwe | resolwe/flow/utils/docs/autoprocess.py | get_processes | 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 processes' definitions parsed from YAML files
:rtype: dict
:raises: ValueError: if multiple processes with the same slug are found
"""
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:
for filename in fnmatch.filter(filenames, extension):
all_process_files.append(os.path.join(root, filename))
def read_yaml_file(fname):
"""Read the yaml file."""
with open(fname) as f:
return yaml.load(f, Loader=yaml.FullLoader)
processes = []
for process_file in all_process_files:
processes_in_file = read_yaml_file(process_file)
for process in processes_in_file:
# This section finds the line in file where the
# defintion of the process starts. (there are
# multiple process definition in some files).
startline = get_process_definition_start(process_file, process['slug'])
# Put together URL to starting line of process definition.
process['source_uri'] = base_source_uri + process_file[len(process_dir) + 1:] + '#L' + str(startline)
if 'category' not in process:
process['category'] = 'uncategorized'
processes.append(process)
PROCESS_CACHE = processes
return processes | python | 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 processes' definitions parsed from YAML files
:rtype: dict
:raises: ValueError: if multiple processes with the same slug are found
"""
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:
for filename in fnmatch.filter(filenames, extension):
all_process_files.append(os.path.join(root, filename))
def read_yaml_file(fname):
"""Read the yaml file."""
with open(fname) as f:
return yaml.load(f, Loader=yaml.FullLoader)
processes = []
for process_file in all_process_files:
processes_in_file = read_yaml_file(process_file)
for process in processes_in_file:
# This section finds the line in file where the
# defintion of the process starts. (there are
# multiple process definition in some files).
startline = get_process_definition_start(process_file, process['slug'])
# Put together URL to starting line of process definition.
process['source_uri'] = base_source_uri + process_file[len(process_dir) + 1:] + '#L' + str(startline)
if 'category' not in process:
process['category'] = 'uncategorized'
processes.append(process)
PROCESS_CACHE = processes
return processes | [
"def",
"get_processes",
"(",
"process_dir",
",",
"base_source_uri",
")",
":",
"global",
"PROCESS_CACHE",
"# pylint: disable=global-statement",
"if",
"PROCESS_CACHE",
"is",
"not",
"None",
":",
"return",
"PROCESS_CACHE",
"all_process_files",
"=",
"[",
"]",
"process_file_e... | 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 processes' definitions parsed from YAML files
:rtype: dict
:raises: ValueError: if multiple processes with the same slug are found | [
"Find",
"processes",
"in",
"path",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/utils/docs/autoprocess.py#L64-L109 | train | 45,137 |
genialis/resolwe | resolwe/flow/utils/docs/autoprocess.py | setup | 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 events are defined in extension.
In this case, only one new directive is created. All used nodes are
constructed from already existing nodes in docutils.nodes package.
"""
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', AutoProcessCategoryDirective)
app.add_directive('autoprocesstype', AutoProcessTypesDirective)
# The setup() function can return a dictionary. This is treated by
# Sphinx as metadata of the extension:
return {'version': '0.2'} | python | 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 events are defined in extension.
In this case, only one new directive is created. All used nodes are
constructed from already existing nodes in docutils.nodes package.
"""
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', AutoProcessCategoryDirective)
app.add_directive('autoprocesstype', AutoProcessTypesDirective)
# The setup() function can return a dictionary. This is treated by
# Sphinx as metadata of the extension:
return {'version': '0.2'} | [
"def",
"setup",
"(",
"app",
")",
":",
"app",
".",
"add_config_value",
"(",
"'autoprocess_process_dir'",
",",
"''",
",",
"'env'",
")",
"app",
".",
"add_config_value",
"(",
"'autoprocess_source_base_url'",
",",
"''",
",",
"'env'",
")",
"app",
".",
"add_config_va... | 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 events are defined in extension.
In this case, only one new directive is created. All used nodes are
constructed from already existing nodes in docutils.nodes package. | [
"Register",
"directives",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/utils/docs/autoprocess.py#L414-L437 | train | 45,138 |
genialis/resolwe | resolwe/flow/utils/docs/autoprocess.py | AutoProcessDirective.make_field | 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
"""
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 when field_body is a complex node:
# useful when constructing nested field lists
paragraph += field_body
body = nodes.field_body()
body += paragraph
field = nodes.field()
field.extend([name, body])
return field | python | 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
"""
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 when field_body is a complex node:
# useful when constructing nested field lists
paragraph += field_body
body = nodes.field_body()
body += paragraph
field = nodes.field()
field.extend([name, body])
return field | [
"def",
"make_field",
"(",
"self",
",",
"field_name",
",",
"field_body",
")",
":",
"name",
"=",
"nodes",
".",
"field_name",
"(",
")",
"name",
"+=",
"nodes",
".",
"Text",
"(",
"field_name",
")",
"paragraph",
"=",
"nodes",
".",
"paragraph",
"(",
")",
"if"... | 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 | [
"Fill",
"content",
"into",
"nodes",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/utils/docs/autoprocess.py#L121-L148 | train | 45,139 |
genialis/resolwe | resolwe/flow/utils/docs/autoprocess.py | AutoProcessDirective.make_properties_list | 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
"""
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',
'validate_regex', 'choices', 'collapse', 'group']
for name in property_names:
if name not in field:
continue
value = field[name]
# Value should be formatted in code-style (=literal) mode
if name in ['type', 'default', 'placeholder', 'validate_regex']:
literal_node = nodes.literal(str(value), str(value))
properties_list += self.make_field(name, literal_node)
# Special formating of ``value`` is needed if name == 'choices'
elif name == 'choices':
bullet_list = nodes.bullet_list()
for choice in value:
label = nodes.Text(choice['label'] + ': ')
val = nodes.literal(choice['value'], choice['value'])
paragraph = nodes.paragraph()
paragraph += label
paragraph += val
list_item = nodes.list_item()
list_item += paragraph
bullet_list += list_item
properties_list += self.make_field(name, bullet_list)
else:
properties_list += self.make_field(name, str(value))
return properties_list | python | 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
"""
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',
'validate_regex', 'choices', 'collapse', 'group']
for name in property_names:
if name not in field:
continue
value = field[name]
# Value should be formatted in code-style (=literal) mode
if name in ['type', 'default', 'placeholder', 'validate_regex']:
literal_node = nodes.literal(str(value), str(value))
properties_list += self.make_field(name, literal_node)
# Special formating of ``value`` is needed if name == 'choices'
elif name == 'choices':
bullet_list = nodes.bullet_list()
for choice in value:
label = nodes.Text(choice['label'] + ': ')
val = nodes.literal(choice['value'], choice['value'])
paragraph = nodes.paragraph()
paragraph += label
paragraph += val
list_item = nodes.list_item()
list_item += paragraph
bullet_list += list_item
properties_list += self.make_field(name, bullet_list)
else:
properties_list += self.make_field(name, str(value))
return properties_list | [
"def",
"make_properties_list",
"(",
"self",
",",
"field",
")",
":",
"properties_list",
"=",
"nodes",
".",
"field_list",
"(",
")",
"# changing the order of elements in this list affects",
"# the order in which they are displayed",
"property_names",
"=",
"[",
"'label'",
",",
... | 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 | [
"Fill",
"the",
"field",
"into",
"a",
"properties",
"list",
"and",
"return",
"it",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/utils/docs/autoprocess.py#L150-L196 | train | 45,140 |
genialis/resolwe | resolwe/flow/utils/docs/autoprocess.py | AutoProcessDirective.make_process_header | 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
"""
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 += addnodes.desc_name(slug + ' ', slug + ' ')
paramlist = addnodes.desc_parameterlist()
for field_schema, _, _ in iterate_schema({}, inputs, ''):
field_type = field_schema['type']
field_name = field_schema['name']
field_default = field_schema.get('default', None)
field_default = '' if field_default is None else '={}'.format(field_default)
param = addnodes.desc_parameter('', '', noemph=True)
param += nodes.emphasis(field_type, field_type, classes=['process-type'])
# separate by non-breaking space in the output
param += nodes.strong(text='\xa0\xa0' + field_name)
paramlist += param
signode += paramlist
signode += nodes.reference('', nodes.Text('[Source: v{}]'.format(version)),
refuri=source_uri, classes=['viewcode-link'])
desc = nodes.paragraph()
desc += nodes.Text(description, description)
return [node, desc] | python | 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
"""
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 += addnodes.desc_name(slug + ' ', slug + ' ')
paramlist = addnodes.desc_parameterlist()
for field_schema, _, _ in iterate_schema({}, inputs, ''):
field_type = field_schema['type']
field_name = field_schema['name']
field_default = field_schema.get('default', None)
field_default = '' if field_default is None else '={}'.format(field_default)
param = addnodes.desc_parameter('', '', noemph=True)
param += nodes.emphasis(field_type, field_type, classes=['process-type'])
# separate by non-breaking space in the output
param += nodes.strong(text='\xa0\xa0' + field_name)
paramlist += param
signode += paramlist
signode += nodes.reference('', nodes.Text('[Source: v{}]'.format(version)),
refuri=source_uri, classes=['viewcode-link'])
desc = nodes.paragraph()
desc += nodes.Text(description, description)
return [node, desc] | [
"def",
"make_process_header",
"(",
"self",
",",
"slug",
",",
"typ",
",",
"version",
",",
"source_uri",
",",
"description",
",",
"inputs",
")",
":",
"node",
"=",
"addnodes",
".",
"desc",
"(",
")",
"signode",
"=",
"addnodes",
".",
"desc_signature",
"(",
"s... | 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 | [
"Generate",
"a",
"process",
"definition",
"header",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/utils/docs/autoprocess.py#L198-L242 | train | 45,141 |
genialis/resolwe | resolwe/flow/utils/docs/autoprocess.py | AutoProcessDirective.make_process_node | 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
"""
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', [])
# Make process name a section title:
section = nodes.section(ids=['process-' + slug])
section += nodes.title(name, name)
# Make process header:
section += self.make_process_header(slug, typ, version, source_uri, description, inputs)
# Make inputs section:
container_node = nodes.container(classes=['toggle'])
container_header = nodes.paragraph(classes=['header'])
container_header += nodes.strong(text='Input arguments')
container_node += container_header
container_body = nodes.container()
for field_schema, _, path in iterate_schema({}, inputs, ''):
container_body += nodes.strong(text=path)
container_body += self.make_properties_list(field_schema)
container_node += container_body
section += container_node
# Make outputs section:
container_node = nodes.container(classes=['toggle'])
container_header = nodes.paragraph(classes=['header'])
container_header += nodes.strong(text='Output results')
container_node += container_header
container_body = nodes.container()
for field_schema, _, path in iterate_schema({}, outputs, ''):
container_body += nodes.strong(text=path)
container_body += self.make_properties_list(field_schema)
container_node += container_body
section += container_node
return [section, addnodes.index(entries=[('single', name, 'process-' + slug, '', None)])] | python | 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
"""
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', [])
# Make process name a section title:
section = nodes.section(ids=['process-' + slug])
section += nodes.title(name, name)
# Make process header:
section += self.make_process_header(slug, typ, version, source_uri, description, inputs)
# Make inputs section:
container_node = nodes.container(classes=['toggle'])
container_header = nodes.paragraph(classes=['header'])
container_header += nodes.strong(text='Input arguments')
container_node += container_header
container_body = nodes.container()
for field_schema, _, path in iterate_schema({}, inputs, ''):
container_body += nodes.strong(text=path)
container_body += self.make_properties_list(field_schema)
container_node += container_body
section += container_node
# Make outputs section:
container_node = nodes.container(classes=['toggle'])
container_header = nodes.paragraph(classes=['header'])
container_header += nodes.strong(text='Output results')
container_node += container_header
container_body = nodes.container()
for field_schema, _, path in iterate_schema({}, outputs, ''):
container_body += nodes.strong(text=path)
container_body += self.make_properties_list(field_schema)
container_node += container_body
section += container_node
return [section, addnodes.index(entries=[('single', name, 'process-' + slug, '', None)])] | [
"def",
"make_process_node",
"(",
"self",
",",
"process",
")",
":",
"name",
"=",
"process",
"[",
"'name'",
"]",
"slug",
"=",
"process",
"[",
"'slug'",
"]",
"typ",
"=",
"process",
"[",
"'type'",
"]",
"version",
"=",
"process",
"[",
"'version'",
"]",
"des... | Fill the content of process definiton node.
:param dict process: process data as given from yaml.load function
:return: process node | [
"Fill",
"the",
"content",
"of",
"process",
"definiton",
"node",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/utils/docs/autoprocess.py#L244-L295 | train | 45,142 |
genialis/resolwe | resolwe/flow/utils/docs/autoprocess.py | AutoProcessDirective.run | def run(self):
"""Create a list of process definitions."""
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.extend(self.make_process_node(process))
return process_nodes | python | def run(self):
"""Create a list of process definitions."""
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.extend(self.make_process_node(process))
return process_nodes | [
"def",
"run",
"(",
"self",
")",
":",
"config",
"=",
"self",
".",
"state",
".",
"document",
".",
"settings",
".",
"env",
".",
"config",
"# Get all processes:",
"processes",
"=",
"get_processes",
"(",
"config",
".",
"autoprocess_process_dir",
",",
"config",
".... | Create a list of process definitions. | [
"Create",
"a",
"list",
"of",
"process",
"definitions",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/utils/docs/autoprocess.py#L297-L308 | train | 45,143 |
genialis/resolwe | resolwe/flow/utils/docs/autoprocess.py | AutoProcessCategoryDirective.run | def run(self):
"""Create a category tree."""
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 groupby(processes, itemgetter('category'))}
# Build category tree
category_sections = {'': nodes.container(ids=['categories'])}
top_categories = []
for category in sorted(categorized_processes.keys()):
category_path = ''
for category_node in category.split(':'):
parent_category_path = category_path
category_path += '{}:'.format(category_node)
if category_path in category_sections:
continue
category_name = category_node.capitalize()
section = nodes.section(ids=['category-' + category_node])
section += nodes.title(category_name, category_name)
# Add process list
category_key = category_path[:-1]
if category_key in categorized_processes:
listnode = nodes.bullet_list()
section += listnode
for process in categorized_processes[category_key]:
par = nodes.paragraph()
node = nodes.reference('', process['name'], internal=True)
node['refuri'] = config.autoprocess_definitions_uri + '#process-' + process['slug']
node['reftitle'] = process['name']
par += node
listnode += nodes.list_item('', par)
category_sections[parent_category_path] += section
category_sections[category_path] = section
if parent_category_path == '':
top_categories.append(section)
# Return top sections only
return top_categories | python | def run(self):
"""Create a category tree."""
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 groupby(processes, itemgetter('category'))}
# Build category tree
category_sections = {'': nodes.container(ids=['categories'])}
top_categories = []
for category in sorted(categorized_processes.keys()):
category_path = ''
for category_node in category.split(':'):
parent_category_path = category_path
category_path += '{}:'.format(category_node)
if category_path in category_sections:
continue
category_name = category_node.capitalize()
section = nodes.section(ids=['category-' + category_node])
section += nodes.title(category_name, category_name)
# Add process list
category_key = category_path[:-1]
if category_key in categorized_processes:
listnode = nodes.bullet_list()
section += listnode
for process in categorized_processes[category_key]:
par = nodes.paragraph()
node = nodes.reference('', process['name'], internal=True)
node['refuri'] = config.autoprocess_definitions_uri + '#process-' + process['slug']
node['reftitle'] = process['name']
par += node
listnode += nodes.list_item('', par)
category_sections[parent_category_path] += section
category_sections[category_path] = section
if parent_category_path == '':
top_categories.append(section)
# Return top sections only
return top_categories | [
"def",
"run",
"(",
"self",
")",
":",
"config",
"=",
"self",
".",
"state",
".",
"document",
".",
"settings",
".",
"env",
".",
"config",
"# Group processes by category",
"processes",
"=",
"get_processes",
"(",
"config",
".",
"autoprocess_process_dir",
",",
"conf... | Create a category tree. | [
"Create",
"a",
"category",
"tree",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/utils/docs/autoprocess.py#L320-L371 | train | 45,144 |
genialis/resolwe | resolwe/flow/utils/docs/autoprocess.py | AutoProcessTypesDirective.run | def run(self):
"""Create a type list."""
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(processes, itemgetter('type'))}
listnode = nodes.bullet_list()
for typ in sorted(processes_by_types.keys()):
par = nodes.paragraph()
par += nodes.literal(typ, typ)
par += nodes.Text(' - ')
processes = sorted(processes_by_types[typ], key=itemgetter('name'))
last_process = processes[-1]
for process in processes:
node = nodes.reference('', process['name'], internal=True)
node['refuri'] = config.autoprocess_definitions_uri + '#process-' + process['slug']
node['reftitle'] = process['name']
par += node
if process != last_process:
par += nodes.Text(', ')
listnode += nodes.list_item('', par)
return [listnode] | python | def run(self):
"""Create a type list."""
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(processes, itemgetter('type'))}
listnode = nodes.bullet_list()
for typ in sorted(processes_by_types.keys()):
par = nodes.paragraph()
par += nodes.literal(typ, typ)
par += nodes.Text(' - ')
processes = sorted(processes_by_types[typ], key=itemgetter('name'))
last_process = processes[-1]
for process in processes:
node = nodes.reference('', process['name'], internal=True)
node['refuri'] = config.autoprocess_definitions_uri + '#process-' + process['slug']
node['reftitle'] = process['name']
par += node
if process != last_process:
par += nodes.Text(', ')
listnode += nodes.list_item('', par)
return [listnode] | [
"def",
"run",
"(",
"self",
")",
":",
"config",
"=",
"self",
".",
"state",
".",
"document",
".",
"settings",
".",
"env",
".",
"config",
"# Group processes by category",
"processes",
"=",
"get_processes",
"(",
"config",
".",
"autoprocess_process_dir",
",",
"conf... | Create a type list. | [
"Create",
"a",
"type",
"list",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/utils/docs/autoprocess.py#L383-L411 | train | 45,145 |
DataONEorg/d1_python | gmn/src/d1_gmn/app/management/commands/async_client.py | AsyncDataONEClient.synchronize | async def synchronize(self, pid, vendor_specific=None):
"""Send an object synchronization request to the CN."""
return await self._request_pyxb(
"post",
["synchronize", pid],
{},
mmp_dict={"pid": pid},
vendor_specific=vendor_specific,
) | python | async def synchronize(self, pid, vendor_specific=None):
"""Send an object synchronization request to the CN."""
return await self._request_pyxb(
"post",
["synchronize", pid],
{},
mmp_dict={"pid": pid},
vendor_specific=vendor_specific,
) | [
"async",
"def",
"synchronize",
"(",
"self",
",",
"pid",
",",
"vendor_specific",
"=",
"None",
")",
":",
"return",
"await",
"self",
".",
"_request_pyxb",
"(",
"\"post\"",
",",
"[",
"\"synchronize\"",
",",
"pid",
"]",
",",
"{",
"}",
",",
"mmp_dict",
"=",
... | Send an object synchronization request to the CN. | [
"Send",
"an",
"object",
"synchronization",
"request",
"to",
"the",
"CN",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/management/commands/async_client.py#L182-L190 | train | 45,146 |
DataONEorg/d1_python | gmn/src/d1_gmn/app/management/commands/async_client.py | AsyncDataONEClient._datetime_to_iso8601 | def _datetime_to_iso8601(self, query_dict):
"""Encode any datetime query parameters to ISO8601."""
return {
k: v if not isinstance(v, datetime.datetime) else v.isoformat()
for k, v in list(query_dict.items())
} | python | def _datetime_to_iso8601(self, query_dict):
"""Encode any datetime query parameters to ISO8601."""
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",
")",
":",
"return",
"{",
"k",
":",
"v",
"if",
"not",
"isinstance",
"(",
"v",
",",
"datetime",
".",
"datetime",
")",
"else",
"v",
".",
"isoformat",
"(",
")",
"for",
"k",
",",
"v",
"in",
... | Encode any datetime query parameters to ISO8601. | [
"Encode",
"any",
"datetime",
"query",
"parameters",
"to",
"ISO8601",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/management/commands/async_client.py#L285-L290 | train | 45,147 |
genialis/resolwe | resolwe/rest/fields.py | ProjectableJSONField.to_representation | def to_representation(self, value):
"""Project outgoing native value."""
value = apply_subfield_projection(self, value, deep=True)
return super().to_representation(value) | python | def to_representation(self, value):
"""Project outgoing native value."""
value = apply_subfield_projection(self, value, deep=True)
return super().to_representation(value) | [
"def",
"to_representation",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"apply_subfield_projection",
"(",
"self",
",",
"value",
",",
"deep",
"=",
"True",
")",
"return",
"super",
"(",
")",
".",
"to_representation",
"(",
"value",
")"
] | Project outgoing native value. | [
"Project",
"outgoing",
"native",
"value",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/rest/fields.py#L10-L13 | train | 45,148 |
DataONEorg/d1_python | lib_common/src/d1_common/bagit.py | validate_bagit_file | 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.
- The file checksums match the manifests.
"""
_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 | python | 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.
- The file checksums match the manifests.
"""
_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",
")",
":",
"_assert_zip_file",
"(",
"bagit_path",
")",
"bagit_zip",
"=",
"zipfile",
".",
"ZipFile",
"(",
"bagit_path",
")",
"manifest_info_list",
"=",
"_get_manifest_info_list",
"(",
"bagit_zip",
")",
"_validate_checksum... | 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.
- The file checksums match the manifests. | [
"Check",
"if",
"a",
"BagIt",
"file",
"is",
"valid",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/bagit.py#L58-L75 | train | 45,149 |
DataONEorg/d1_python | lib_common/src/d1_common/bagit.py | create_bagit_stream | 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.
- keys: pid, filename, iter, checksum, checksum_algorithm
- If the filename is None, the pid is used for the filename.
"""
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, payload_byte_count, payload_file_count
)
_add_manifest_files(zip_file, dir_name, payload_info_list, tag_info_list)
_add_tag_manifest_file(zip_file, dir_name, tag_info_list)
return zip_file | python | 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.
- keys: pid, filename, iter, checksum, checksum_algorithm
- If the filename is None, the pid is used for the filename.
"""
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, payload_byte_count, payload_file_count
)
_add_manifest_files(zip_file, dir_name, payload_info_list, tag_info_list)
_add_tag_manifest_file(zip_file, dir_name, tag_info_list)
return zip_file | [
"def",
"create_bagit_stream",
"(",
"dir_name",
",",
"payload_info_list",
")",
":",
"zip_file",
"=",
"zipstream",
".",
"ZipFile",
"(",
"mode",
"=",
"'w'",
",",
"compression",
"=",
"zipstream",
".",
"ZIP_DEFLATED",
")",
"_add_path",
"(",
"dir_name",
",",
"payloa... | 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.
- keys: pid, filename, iter, checksum, checksum_algorithm
- If the filename is None, the pid is used for the filename. | [
"Create",
"a",
"stream",
"containing",
"a",
"BagIt",
"zip",
"archive",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/bagit.py#L78-L103 | train | 45,150 |
DataONEorg/d1_python | lib_common/src/d1_common/bagit.py | _add_path | def _add_path(dir_name, payload_info_list):
"""Add a key with the path to each payload_info_dict."""
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
) | python | def _add_path(dir_name, payload_info_list):
"""Add a key with the path to each payload_info_dict."""
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",
")",
":",
"for",
"payload_info_dict",
"in",
"payload_info_list",
":",
"file_name",
"=",
"payload_info_dict",
"[",
"'filename'",
"]",
"or",
"payload_info_dict",
"[",
"'pid'",
"]",
"payload_info_dict",
"["... | Add a key with the path to each payload_info_dict. | [
"Add",
"a",
"key",
"with",
"the",
"path",
"to",
"each",
"payload_info_dict",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/bagit.py#L183-L189 | train | 45,151 |
DataONEorg/d1_python | lib_common/src/d1_common/bagit.py | _add_payload_files | def _add_payload_files(zip_file, payload_info_list):
"""Add the payload files to the zip."""
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_file_count | python | def _add_payload_files(zip_file, payload_info_list):
"""Add the payload files to the zip."""
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_file_count | [
"def",
"_add_payload_files",
"(",
"zip_file",
",",
"payload_info_list",
")",
":",
"payload_byte_count",
"=",
"0",
"payload_file_count",
"=",
"0",
"for",
"payload_info_dict",
"in",
"payload_info_list",
":",
"zip_file",
".",
"write_iter",
"(",
"payload_info_dict",
"[",
... | Add the payload files to the zip. | [
"Add",
"the",
"payload",
"files",
"to",
"the",
"zip",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/bagit.py#L192-L200 | train | 45,152 |
DataONEorg/d1_python | lib_common/src/d1_common/bagit.py | _add_tag_files | 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."""
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_list, _gen_pid_mapping_file_tup(payload_info_list)
)
return tag_info_list | python | 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."""
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_list, _gen_pid_mapping_file_tup(payload_info_list)
)
return tag_info_list | [
"def",
"_add_tag_files",
"(",
"zip_file",
",",
"dir_name",
",",
"payload_info_list",
",",
"payload_byte_count",
",",
"payload_file_count",
")",
":",
"tag_info_list",
"=",
"[",
"]",
"_add_tag_file",
"(",
"zip_file",
",",
"dir_name",
",",
"tag_info_list",
",",
"_gen... | Generate the tag files and add them to the zip. | [
"Generate",
"the",
"tag",
"files",
"and",
"add",
"them",
"to",
"the",
"zip",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/bagit.py#L203-L218 | train | 45,153 |
DataONEorg/d1_python | lib_common/src/d1_common/bagit.py | _add_manifest_files | def _add_manifest_files(zip_file, dir_name, payload_info_list, tag_info_list):
"""Generate the manifest files and add them to the zip."""
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),
) | python | def _add_manifest_files(zip_file, dir_name, payload_info_list, tag_info_list):
"""Generate the manifest files and add them to the zip."""
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",
")",
":",
"for",
"checksum_algorithm",
"in",
"_get_checksum_algorithm_set",
"(",
"payload_info_list",
")",
":",
"_add_tag_file",
"(",
"zip_file",
",",
"dir_... | Generate the manifest files and add them to the zip. | [
"Generate",
"the",
"manifest",
"files",
"and",
"add",
"them",
"to",
"the",
"zip",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/bagit.py#L221-L229 | train | 45,154 |
DataONEorg/d1_python | lib_common/src/d1_common/bagit.py | _add_tag_manifest_file | def _add_tag_manifest_file(zip_file, dir_name, tag_info_list):
"""Generate the tag manifest file and add it to the zip."""
_add_tag_file(
zip_file, dir_name, tag_info_list, _gen_tag_manifest_file_tup(tag_info_list)
) | python | def _add_tag_manifest_file(zip_file, dir_name, tag_info_list):
"""Generate the tag manifest file and add it to the zip."""
_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",
")",
":",
"_add_tag_file",
"(",
"zip_file",
",",
"dir_name",
",",
"tag_info_list",
",",
"_gen_tag_manifest_file_tup",
"(",
"tag_info_list",
")",
")"
] | Generate the tag manifest file and add it to the zip. | [
"Generate",
"the",
"tag",
"manifest",
"file",
"and",
"add",
"it",
"to",
"the",
"zip",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/bagit.py#L232-L236 | train | 45,155 |
DataONEorg/d1_python | lib_common/src/d1_common/bagit.py | _add_tag_file | 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."""
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_iterator(
tag_iter, TAG_CHECKSUM_ALGO
),
}
) | python | 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."""
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_iterator(
tag_iter, TAG_CHECKSUM_ALGO
),
}
) | [
"def",
"_add_tag_file",
"(",
"zip_file",
",",
"dir_name",
",",
"tag_info_list",
",",
"tag_tup",
")",
":",
"tag_name",
",",
"tag_str",
"=",
"tag_tup",
"tag_path",
"=",
"d1_common",
".",
"utils",
".",
"filesystem",
".",
"gen_safe_path",
"(",
"dir_name",
",",
"... | Add a tag file to zip_file and record info for the tag manifest file. | [
"Add",
"a",
"tag",
"file",
"to",
"zip_file",
"and",
"record",
"info",
"for",
"the",
"tag",
"manifest",
"file",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/bagit.py#L239-L251 | train | 45,156 |
genialis/resolwe | resolwe/permissions/filters.py | ResolwePermissionsFilter.filter_queryset | def filter_queryset(self, request, queryset, view):
"""Filter permissions queryset."""
user = request.user
app_label = queryset.model._meta.app_label # pylint: disable=protected-access
model_name = queryset.model._meta.model_name # pylint: disable=protected-access
kwargs = {}
if model_name == 'storage':
model_name = 'data'
kwargs['perms_filter'] = 'data__pk__in'
if model_name == 'relation':
model_name = 'collection'
kwargs['perms_filter'] = 'collection__pk__in'
permission = '{}.view_{}'.format(app_label, model_name)
return get_objects_for_user(user, permission, queryset, **kwargs) | python | def filter_queryset(self, request, queryset, view):
"""Filter permissions queryset."""
user = request.user
app_label = queryset.model._meta.app_label # pylint: disable=protected-access
model_name = queryset.model._meta.model_name # pylint: disable=protected-access
kwargs = {}
if model_name == 'storage':
model_name = 'data'
kwargs['perms_filter'] = 'data__pk__in'
if model_name == 'relation':
model_name = 'collection'
kwargs['perms_filter'] = 'collection__pk__in'
permission = '{}.view_{}'.format(app_label, model_name)
return get_objects_for_user(user, permission, queryset, **kwargs) | [
"def",
"filter_queryset",
"(",
"self",
",",
"request",
",",
"queryset",
",",
"view",
")",
":",
"user",
"=",
"request",
".",
"user",
"app_label",
"=",
"queryset",
".",
"model",
".",
"_meta",
".",
"app_label",
"# pylint: disable=protected-access",
"model_name",
... | Filter permissions queryset. | [
"Filter",
"permissions",
"queryset",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/permissions/filters.py#L16-L34 | train | 45,157 |
genialis/resolwe | resolwe/permissions/permissions.py | ResolwePermissions.has_object_permission | def has_object_permission(self, request, view, obj):
"""Check object permissions."""
# admins can do anything
if request.user.is_superuser:
return True
# `share` permission is required for editing permissions
if 'permissions' in view.action:
self.perms_map['POST'] = ['%(app_label)s.share_%(model_name)s']
if view.action in ['add_data', 'remove_data']:
self.perms_map['POST'] = ['%(app_label)s.add_%(model_name)s']
if hasattr(view, 'get_queryset'):
queryset = view.get_queryset()
else:
queryset = getattr(view, 'queryset', None)
assert queryset is not None, (
'Cannot apply DjangoObjectPermissions on a view that '
'does not set `.queryset` or have a `.get_queryset()` method.'
)
model_cls = queryset.model
user = request.user
perms = self.get_required_object_permissions(request.method, model_cls)
if not user.has_perms(perms, obj) and not AnonymousUser().has_perms(perms, obj):
# If the user does not have permissions we need to determine if
# they have read permissions to see 403, or not, and simply see
# a 404 response.
if request.method in permissions.SAFE_METHODS:
# Read permissions already checked and failed, no need
# to make another lookup.
raise Http404
read_perms = self.get_required_object_permissions('GET', model_cls)
if not user.has_perms(read_perms, obj):
raise Http404
# Has read permissions.
return False
return True | python | def has_object_permission(self, request, view, obj):
"""Check object permissions."""
# admins can do anything
if request.user.is_superuser:
return True
# `share` permission is required for editing permissions
if 'permissions' in view.action:
self.perms_map['POST'] = ['%(app_label)s.share_%(model_name)s']
if view.action in ['add_data', 'remove_data']:
self.perms_map['POST'] = ['%(app_label)s.add_%(model_name)s']
if hasattr(view, 'get_queryset'):
queryset = view.get_queryset()
else:
queryset = getattr(view, 'queryset', None)
assert queryset is not None, (
'Cannot apply DjangoObjectPermissions on a view that '
'does not set `.queryset` or have a `.get_queryset()` method.'
)
model_cls = queryset.model
user = request.user
perms = self.get_required_object_permissions(request.method, model_cls)
if not user.has_perms(perms, obj) and not AnonymousUser().has_perms(perms, obj):
# If the user does not have permissions we need to determine if
# they have read permissions to see 403, or not, and simply see
# a 404 response.
if request.method in permissions.SAFE_METHODS:
# Read permissions already checked and failed, no need
# to make another lookup.
raise Http404
read_perms = self.get_required_object_permissions('GET', model_cls)
if not user.has_perms(read_perms, obj):
raise Http404
# Has read permissions.
return False
return True | [
"def",
"has_object_permission",
"(",
"self",
",",
"request",
",",
"view",
",",
"obj",
")",
":",
"# admins can do anything",
"if",
"request",
".",
"user",
".",
"is_superuser",
":",
"return",
"True",
"# `share` permission is required for editing permissions",
"if",
"'pe... | Check object permissions. | [
"Check",
"object",
"permissions",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/permissions/permissions.py#L25-L70 | train | 45,158 |
DataONEorg/d1_python | gmn/src/d1_gmn/app/middleware/view_handler.py | ViewHandler.get_active_subject_set | def get_active_subject_set(self, request):
"""Get a set containing all subjects for which the current connection has been
successfully authenticated."""
# Handle complete certificate in vendor specific extension.
if django.conf.settings.DEBUG_GMN:
if 'HTTP_VENDOR_INCLUDE_CERTIFICATE' in request.META:
request.META[
'SSL_CLIENT_CERT'
] = self.pem_in_http_header_to_pem_in_string(
request.META['HTTP_VENDOR_INCLUDE_CERTIFICATE']
)
# Add subjects from any provided certificate and JWT and store them in
# the Django request obj.
cert_primary_str, cert_equivalent_set = d1_gmn.app.middleware.session_cert.get_subjects(
request
)
jwt_subject_list = d1_gmn.app.middleware.session_jwt.validate_jwt_and_get_subject_list(
request
)
primary_subject_str = cert_primary_str
all_subjects_set = (
cert_equivalent_set | {cert_primary_str} | set(jwt_subject_list)
)
if len(jwt_subject_list) == 1:
jwt_primary_str = jwt_subject_list[0]
if jwt_primary_str != cert_primary_str:
if cert_primary_str == d1_common.const.SUBJECT_PUBLIC:
primary_subject_str = jwt_primary_str
else:
logging.warning(
'Both a certificate and a JWT were provided and the primary '
'subjects differ. Using the certificate for primary subject and'
'the JWT as equivalent.'
)
logging.info('Primary active subject: {}'.format(primary_subject_str))
logging.info(
'All active subjects: {}'.format(', '.join(sorted(all_subjects_set)))
)
# Handle list of subjects in vendor specific extension:
if django.conf.settings.DEBUG_GMN:
# This is added to any subjects obtained from cert and/or JWT.
if 'HTTP_VENDOR_INCLUDE_SUBJECTS' in request.META:
request.all_subjects_set.update(
request.META['HTTP_VENDOR_INCLUDE_SUBJECTS'].split('\t')
)
return primary_subject_str, all_subjects_set | python | def get_active_subject_set(self, request):
"""Get a set containing all subjects for which the current connection has been
successfully authenticated."""
# Handle complete certificate in vendor specific extension.
if django.conf.settings.DEBUG_GMN:
if 'HTTP_VENDOR_INCLUDE_CERTIFICATE' in request.META:
request.META[
'SSL_CLIENT_CERT'
] = self.pem_in_http_header_to_pem_in_string(
request.META['HTTP_VENDOR_INCLUDE_CERTIFICATE']
)
# Add subjects from any provided certificate and JWT and store them in
# the Django request obj.
cert_primary_str, cert_equivalent_set = d1_gmn.app.middleware.session_cert.get_subjects(
request
)
jwt_subject_list = d1_gmn.app.middleware.session_jwt.validate_jwt_and_get_subject_list(
request
)
primary_subject_str = cert_primary_str
all_subjects_set = (
cert_equivalent_set | {cert_primary_str} | set(jwt_subject_list)
)
if len(jwt_subject_list) == 1:
jwt_primary_str = jwt_subject_list[0]
if jwt_primary_str != cert_primary_str:
if cert_primary_str == d1_common.const.SUBJECT_PUBLIC:
primary_subject_str = jwt_primary_str
else:
logging.warning(
'Both a certificate and a JWT were provided and the primary '
'subjects differ. Using the certificate for primary subject and'
'the JWT as equivalent.'
)
logging.info('Primary active subject: {}'.format(primary_subject_str))
logging.info(
'All active subjects: {}'.format(', '.join(sorted(all_subjects_set)))
)
# Handle list of subjects in vendor specific extension:
if django.conf.settings.DEBUG_GMN:
# This is added to any subjects obtained from cert and/or JWT.
if 'HTTP_VENDOR_INCLUDE_SUBJECTS' in request.META:
request.all_subjects_set.update(
request.META['HTTP_VENDOR_INCLUDE_SUBJECTS'].split('\t')
)
return primary_subject_str, all_subjects_set | [
"def",
"get_active_subject_set",
"(",
"self",
",",
"request",
")",
":",
"# Handle complete certificate in vendor specific extension.",
"if",
"django",
".",
"conf",
".",
"settings",
".",
"DEBUG_GMN",
":",
"if",
"'HTTP_VENDOR_INCLUDE_CERTIFICATE'",
"in",
"request",
".",
"... | Get a set containing all subjects for which the current connection has been
successfully authenticated. | [
"Get",
"a",
"set",
"containing",
"all",
"subjects",
"for",
"which",
"the",
"current",
"connection",
"has",
"been",
"successfully",
"authenticated",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/middleware/view_handler.py#L80-L129 | train | 45,159 |
DataONEorg/d1_python | gmn/src/d1_gmn/app/management/commands/util/util.py | log_setup | def log_setup(debug_bool):
"""Set up logging.
We output only to stdout. Instead of also writing to a log file, redirect stdout to
a log file when the script is executed from cron.
"""
level = logging.DEBUG if debug_bool else logging.INFO
logging.config.dictConfig(
{
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"verbose": {
"format": "%(asctime)s %(levelname)-8s %(name)s %(module)s "
"%(process)d %(thread)d %(message)s",
"datefmt": "%Y-%m-%d %H:%M:%S",
}
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"formatter": "verbose",
"level": level,
"stream": "ext://sys.stdout",
}
},
"loggers": {
"": {
"handlers": ["console"],
"level": level,
"class": "logging.StreamHandler",
}
},
}
) | python | def log_setup(debug_bool):
"""Set up logging.
We output only to stdout. Instead of also writing to a log file, redirect stdout to
a log file when the script is executed from cron.
"""
level = logging.DEBUG if debug_bool else logging.INFO
logging.config.dictConfig(
{
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"verbose": {
"format": "%(asctime)s %(levelname)-8s %(name)s %(module)s "
"%(process)d %(thread)d %(message)s",
"datefmt": "%Y-%m-%d %H:%M:%S",
}
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"formatter": "verbose",
"level": level,
"stream": "ext://sys.stdout",
}
},
"loggers": {
"": {
"handlers": ["console"],
"level": level,
"class": "logging.StreamHandler",
}
},
}
) | [
"def",
"log_setup",
"(",
"debug_bool",
")",
":",
"level",
"=",
"logging",
".",
"DEBUG",
"if",
"debug_bool",
"else",
"logging",
".",
"INFO",
"logging",
".",
"config",
".",
"dictConfig",
"(",
"{",
"\"version\"",
":",
"1",
",",
"\"disable_existing_loggers\"",
"... | Set up logging.
We output only to stdout. Instead of also writing to a log file, redirect stdout to
a log file when the script is executed from cron. | [
"Set",
"up",
"logging",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/management/commands/util/util.py#L42-L79 | train | 45,160 |
DataONEorg/d1_python | gmn/src/d1_gmn/app/management/commands/util/util.py | Db.connect | def connect(self, dsn):
"""Connect to DB.
dbname: the database name user: user name used to authenticate password:
password used to authenticate host: database host address (defaults to UNIX
socket if not provided) port: connection port number (defaults to 5432 if not
provided)
"""
self.con = psycopg2.connect(dsn)
self.cur = self.con.cursor(cursor_factory=psycopg2.extras.DictCursor)
# autocommit: Disable automatic transactions
self.con.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) | python | def connect(self, dsn):
"""Connect to DB.
dbname: the database name user: user name used to authenticate password:
password used to authenticate host: database host address (defaults to UNIX
socket if not provided) port: connection port number (defaults to 5432 if not
provided)
"""
self.con = psycopg2.connect(dsn)
self.cur = self.con.cursor(cursor_factory=psycopg2.extras.DictCursor)
# autocommit: Disable automatic transactions
self.con.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) | [
"def",
"connect",
"(",
"self",
",",
"dsn",
")",
":",
"self",
".",
"con",
"=",
"psycopg2",
".",
"connect",
"(",
"dsn",
")",
"self",
".",
"cur",
"=",
"self",
".",
"con",
".",
"cursor",
"(",
"cursor_factory",
"=",
"psycopg2",
".",
"extras",
".",
"Dict... | Connect to DB.
dbname: the database name user: user name used to authenticate password:
password used to authenticate host: database host address (defaults to UNIX
socket if not provided) port: connection port number (defaults to 5432 if not
provided) | [
"Connect",
"to",
"DB",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/management/commands/util/util.py#L114-L126 | train | 45,161 |
genialis/resolwe | resolwe/elastic/viewsets.py | ElasticSearchMixin.order_search | def order_search(self, search):
"""Order given search by the ordering parameter given in request.
:param search: ElasticSearch query object
"""
ordering = self.get_query_param('ordering', self.ordering)
if not ordering:
return search
sort_fields = []
for raw_ordering in ordering.split(','):
ordering_field = raw_ordering.lstrip('-')
if ordering_field not in self.ordering_fields:
raise ParseError('Ordering by `{}` is not supported.'.format(ordering_field))
ordering_field = self.ordering_map.get(ordering_field, ordering_field)
direction = '-' if raw_ordering[0] == '-' else ''
sort_fields.append('{}{}'.format(direction, ordering_field))
return search.sort(*sort_fields) | python | def order_search(self, search):
"""Order given search by the ordering parameter given in request.
:param search: ElasticSearch query object
"""
ordering = self.get_query_param('ordering', self.ordering)
if not ordering:
return search
sort_fields = []
for raw_ordering in ordering.split(','):
ordering_field = raw_ordering.lstrip('-')
if ordering_field not in self.ordering_fields:
raise ParseError('Ordering by `{}` is not supported.'.format(ordering_field))
ordering_field = self.ordering_map.get(ordering_field, ordering_field)
direction = '-' if raw_ordering[0] == '-' else ''
sort_fields.append('{}{}'.format(direction, ordering_field))
return search.sort(*sort_fields) | [
"def",
"order_search",
"(",
"self",
",",
"search",
")",
":",
"ordering",
"=",
"self",
".",
"get_query_param",
"(",
"'ordering'",
",",
"self",
".",
"ordering",
")",
"if",
"not",
"ordering",
":",
"return",
"search",
"sort_fields",
"=",
"[",
"]",
"for",
"ra... | Order given search by the ordering parameter given in request.
:param search: ElasticSearch query object | [
"Order",
"given",
"search",
"by",
"the",
"ordering",
"parameter",
"given",
"in",
"request",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/viewsets.py#L99-L119 | train | 45,162 |
genialis/resolwe | resolwe/elastic/viewsets.py | ElasticSearchMixin.filter_search | def filter_search(self, search):
"""Filter given search by the filter parameter given in request.
:param search: ElasticSearch query object
"""
builder = QueryBuilder(
self.filtering_fields,
self.filtering_map,
self
)
search, unmatched = builder.build(search, self.get_query_params())
# Ensure that no unsupported arguments were used.
for argument in self.get_always_allowed_arguments():
unmatched.pop(argument, None)
if unmatched:
msg = 'Unsupported parameter(s): {}. Please use a combination of: {}.'.format(
', '.join(unmatched),
', '.join(self.filtering_fields),
)
raise ParseError(msg)
return search | python | def filter_search(self, search):
"""Filter given search by the filter parameter given in request.
:param search: ElasticSearch query object
"""
builder = QueryBuilder(
self.filtering_fields,
self.filtering_map,
self
)
search, unmatched = builder.build(search, self.get_query_params())
# Ensure that no unsupported arguments were used.
for argument in self.get_always_allowed_arguments():
unmatched.pop(argument, None)
if unmatched:
msg = 'Unsupported parameter(s): {}. Please use a combination of: {}.'.format(
', '.join(unmatched),
', '.join(self.filtering_fields),
)
raise ParseError(msg)
return search | [
"def",
"filter_search",
"(",
"self",
",",
"search",
")",
":",
"builder",
"=",
"QueryBuilder",
"(",
"self",
".",
"filtering_fields",
",",
"self",
".",
"filtering_map",
",",
"self",
")",
"search",
",",
"unmatched",
"=",
"builder",
".",
"build",
"(",
"search"... | Filter given search by the filter parameter given in request.
:param search: ElasticSearch query object | [
"Filter",
"given",
"search",
"by",
"the",
"filter",
"parameter",
"given",
"in",
"request",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/viewsets.py#L131-L155 | train | 45,163 |
genialis/resolwe | resolwe/elastic/viewsets.py | ElasticSearchMixin.filter_permissions | def filter_permissions(self, search):
"""Filter given query based on permissions of the user in the request.
:param search: ElasticSearch query object
"""
user = self.request.user
if user.is_superuser:
return search
if user.is_anonymous:
user = get_anonymous_user()
filters = [Q('match', users_with_permissions=user.pk)]
filters.extend([
Q('match', groups_with_permissions=group.pk) for group in user.groups.all()
])
filters.append(Q('match', public_permission=True))
# `minimum_should_match` is set to 1 by default
return search.query('bool', should=filters) | python | def filter_permissions(self, search):
"""Filter given query based on permissions of the user in the request.
:param search: ElasticSearch query object
"""
user = self.request.user
if user.is_superuser:
return search
if user.is_anonymous:
user = get_anonymous_user()
filters = [Q('match', users_with_permissions=user.pk)]
filters.extend([
Q('match', groups_with_permissions=group.pk) for group in user.groups.all()
])
filters.append(Q('match', public_permission=True))
# `minimum_should_match` is set to 1 by default
return search.query('bool', should=filters) | [
"def",
"filter_permissions",
"(",
"self",
",",
"search",
")",
":",
"user",
"=",
"self",
".",
"request",
".",
"user",
"if",
"user",
".",
"is_superuser",
":",
"return",
"search",
"if",
"user",
".",
"is_anonymous",
":",
"user",
"=",
"get_anonymous_user",
"(",... | Filter given query based on permissions of the user in the request.
:param search: ElasticSearch query object | [
"Filter",
"given",
"query",
"based",
"on",
"permissions",
"of",
"the",
"user",
"in",
"the",
"request",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/viewsets.py#L157-L176 | train | 45,164 |
genialis/resolwe | resolwe/elastic/viewsets.py | PaginationMixin.paginate_response | def paginate_response(self, queryset, serializers_kwargs={}):
"""Optionally return paginated response.
If pagination parameters are provided in the request, then paginated response
is returned, otherwise response is not paginated.
"""
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True, **serializers_kwargs)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True, **serializers_kwargs)
return Response(serializer.data) | python | def paginate_response(self, queryset, serializers_kwargs={}):
"""Optionally return paginated response.
If pagination parameters are provided in the request, then paginated response
is returned, otherwise response is not paginated.
"""
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True, **serializers_kwargs)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True, **serializers_kwargs)
return Response(serializer.data) | [
"def",
"paginate_response",
"(",
"self",
",",
"queryset",
",",
"serializers_kwargs",
"=",
"{",
"}",
")",
":",
"page",
"=",
"self",
".",
"paginate_queryset",
"(",
"queryset",
")",
"if",
"page",
"is",
"not",
"None",
":",
"serializer",
"=",
"self",
".",
"ge... | Optionally return paginated response.
If pagination parameters are provided in the request, then paginated response
is returned, otherwise response is not paginated. | [
"Optionally",
"return",
"paginated",
"response",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/viewsets.py#L182-L195 | train | 45,165 |
genialis/resolwe | resolwe/elastic/viewsets.py | ElasticSearchBaseViewSet.search | def search(self):
"""Handle the search request."""
search = self.document_class().search() # pylint: disable=not-callable
search = self.custom_filter(search)
search = self.filter_search(search)
search = self.order_search(search)
search = self.filter_permissions(search)
if search.count() > ELASTICSEARCH_SIZE:
limit = self.paginator.get_limit(self.request)
if not limit or limit > ELASTICSEARCH_SIZE:
raise TooManyResults()
search = search.extra(size=ELASTICSEARCH_SIZE)
return search | python | def search(self):
"""Handle the search request."""
search = self.document_class().search() # pylint: disable=not-callable
search = self.custom_filter(search)
search = self.filter_search(search)
search = self.order_search(search)
search = self.filter_permissions(search)
if search.count() > ELASTICSEARCH_SIZE:
limit = self.paginator.get_limit(self.request)
if not limit or limit > ELASTICSEARCH_SIZE:
raise TooManyResults()
search = search.extra(size=ELASTICSEARCH_SIZE)
return search | [
"def",
"search",
"(",
"self",
")",
":",
"search",
"=",
"self",
".",
"document_class",
"(",
")",
".",
"search",
"(",
")",
"# pylint: disable=not-callable",
"search",
"=",
"self",
".",
"custom_filter",
"(",
"search",
")",
"search",
"=",
"self",
".",
"filter_... | Handle the search request. | [
"Handle",
"the",
"search",
"request",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/viewsets.py#L225-L242 | train | 45,166 |
genialis/resolwe | resolwe/elastic/viewsets.py | ElasticSearchCombinedViewSet.list_with_post | def list_with_post(self, request):
"""Endpoint handler."""
if self.is_search_request():
search = self.search()
page = self.paginate_queryset(search)
if page is None:
items = search
else:
items = page
try:
primary_keys = []
order_map_cases = []
for order, item in enumerate(items):
pk = item[self.primary_key_field]
primary_keys.append(pk)
order_map_cases.append(When(pk=pk, then=Value(order)))
queryset = self.get_queryset().filter(
pk__in=primary_keys
).order_by(
Case(*order_map_cases, output_field=IntegerField()).asc()
)
except KeyError:
raise KeyError("Combined viewset requires that your index contains a field with "
"the primary key. By default this field is called 'id', but you "
"can change it by setting primary_key_field.")
# Pagination must be handled differently.
serializer = self.get_serializer(queryset, many=True)
if page is not None:
return self.get_paginated_response(serializer.data)
return Response(serializer.data)
else:
queryset = self.filter_queryset(self.get_queryset())
return self.paginate_response(queryset) | python | def list_with_post(self, request):
"""Endpoint handler."""
if self.is_search_request():
search = self.search()
page = self.paginate_queryset(search)
if page is None:
items = search
else:
items = page
try:
primary_keys = []
order_map_cases = []
for order, item in enumerate(items):
pk = item[self.primary_key_field]
primary_keys.append(pk)
order_map_cases.append(When(pk=pk, then=Value(order)))
queryset = self.get_queryset().filter(
pk__in=primary_keys
).order_by(
Case(*order_map_cases, output_field=IntegerField()).asc()
)
except KeyError:
raise KeyError("Combined viewset requires that your index contains a field with "
"the primary key. By default this field is called 'id', but you "
"can change it by setting primary_key_field.")
# Pagination must be handled differently.
serializer = self.get_serializer(queryset, many=True)
if page is not None:
return self.get_paginated_response(serializer.data)
return Response(serializer.data)
else:
queryset = self.filter_queryset(self.get_queryset())
return self.paginate_response(queryset) | [
"def",
"list_with_post",
"(",
"self",
",",
"request",
")",
":",
"if",
"self",
".",
"is_search_request",
"(",
")",
":",
"search",
"=",
"self",
".",
"search",
"(",
")",
"page",
"=",
"self",
".",
"paginate_queryset",
"(",
"search",
")",
"if",
"page",
"is"... | Endpoint handler. | [
"Endpoint",
"handler",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/viewsets.py#L281-L318 | train | 45,167 |
DataONEorg/d1_python | client_onedrive/src/d1_onedrive/impl/drivers/fuse/callbacks.py | FUSECallbacks.getattr | def getattr(self, path, fh):
"""Called by FUSE when the attributes for a file or directory are required.
Returns a dictionary with keys identical to the stat C structure of stat(2).
st_atime, st_mtime and st_ctime should be floats. On OSX, st_nlink should count
all files inside the directory. On Linux, only the subdirectories are counted.
The 'st_dev' and 'st_blksize' fields are ignored. The 'st_ino' field is ignored
except if the 'use_ino' mount option is given.
This method gets very heavy traffic.
"""
self._raise_error_if_os_special_file(path)
# log.debug(u'getattr(): {0}'.format(path))
attribute = self._get_attributes_through_cache(path)
# log.debug('getattr() returned attribute: {0}'.format(attribute))
return self._stat_from_attributes(attribute) | python | def getattr(self, path, fh):
"""Called by FUSE when the attributes for a file or directory are required.
Returns a dictionary with keys identical to the stat C structure of stat(2).
st_atime, st_mtime and st_ctime should be floats. On OSX, st_nlink should count
all files inside the directory. On Linux, only the subdirectories are counted.
The 'st_dev' and 'st_blksize' fields are ignored. The 'st_ino' field is ignored
except if the 'use_ino' mount option is given.
This method gets very heavy traffic.
"""
self._raise_error_if_os_special_file(path)
# log.debug(u'getattr(): {0}'.format(path))
attribute = self._get_attributes_through_cache(path)
# log.debug('getattr() returned attribute: {0}'.format(attribute))
return self._stat_from_attributes(attribute) | [
"def",
"getattr",
"(",
"self",
",",
"path",
",",
"fh",
")",
":",
"self",
".",
"_raise_error_if_os_special_file",
"(",
"path",
")",
"# log.debug(u'getattr(): {0}'.format(path))",
"attribute",
"=",
"self",
".",
"_get_attributes_through_cache",
"(",
"path",
")",
"# log... | Called by FUSE when the attributes for a file or directory are required.
Returns a dictionary with keys identical to the stat C structure of stat(2).
st_atime, st_mtime and st_ctime should be floats. On OSX, st_nlink should count
all files inside the directory. On Linux, only the subdirectories are counted.
The 'st_dev' and 'st_blksize' fields are ignored. The 'st_ino' field is ignored
except if the 'use_ino' mount option is given.
This method gets very heavy traffic. | [
"Called",
"by",
"FUSE",
"when",
"the",
"attributes",
"for",
"a",
"file",
"or",
"directory",
"are",
"required",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/client_onedrive/src/d1_onedrive/impl/drivers/fuse/callbacks.py#L62-L78 | train | 45,168 |
DataONEorg/d1_python | client_onedrive/src/d1_onedrive/impl/drivers/fuse/callbacks.py | FUSECallbacks.readdir | def readdir(self, path, fh):
"""Called by FUSE when a directory is opened.
Returns a list of file and directory names for the directory.
"""
log.debug('readdir(): {}'.format(path))
try:
dir = self._directory_cache[path]
except KeyError:
dir = self._get_directory(path)
self._directory_cache[path] = dir
return dir | python | def readdir(self, path, fh):
"""Called by FUSE when a directory is opened.
Returns a list of file and directory names for the directory.
"""
log.debug('readdir(): {}'.format(path))
try:
dir = self._directory_cache[path]
except KeyError:
dir = self._get_directory(path)
self._directory_cache[path] = dir
return dir | [
"def",
"readdir",
"(",
"self",
",",
"path",
",",
"fh",
")",
":",
"log",
".",
"debug",
"(",
"'readdir(): {}'",
".",
"format",
"(",
"path",
")",
")",
"try",
":",
"dir",
"=",
"self",
".",
"_directory_cache",
"[",
"path",
"]",
"except",
"KeyError",
":",
... | Called by FUSE when a directory is opened.
Returns a list of file and directory names for the directory. | [
"Called",
"by",
"FUSE",
"when",
"a",
"directory",
"is",
"opened",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/client_onedrive/src/d1_onedrive/impl/drivers/fuse/callbacks.py#L80-L92 | train | 45,169 |
DataONEorg/d1_python | client_onedrive/src/d1_onedrive/impl/drivers/fuse/callbacks.py | FUSECallbacks.open | def open(self, path, flags):
"""Called by FUSE when a file is opened.
Determines if the provided path and open flags are valid.
"""
log.debug('open(): {}'.format(path))
# ONEDrive is currently read only. Anything but read access is denied.
if (flags & self._READ_ONLY_ACCESS_MODE) != os.O_RDONLY:
self._raise_error_permission_denied(path)
# Any file in the filesystem can be opened.
attribute = self._get_attributes_through_cache(path)
return attribute.is_dir() | python | def open(self, path, flags):
"""Called by FUSE when a file is opened.
Determines if the provided path and open flags are valid.
"""
log.debug('open(): {}'.format(path))
# ONEDrive is currently read only. Anything but read access is denied.
if (flags & self._READ_ONLY_ACCESS_MODE) != os.O_RDONLY:
self._raise_error_permission_denied(path)
# Any file in the filesystem can be opened.
attribute = self._get_attributes_through_cache(path)
return attribute.is_dir() | [
"def",
"open",
"(",
"self",
",",
"path",
",",
"flags",
")",
":",
"log",
".",
"debug",
"(",
"'open(): {}'",
".",
"format",
"(",
"path",
")",
")",
"# ONEDrive is currently read only. Anything but read access is denied.",
"if",
"(",
"flags",
"&",
"self",
".",
"_R... | Called by FUSE when a file is opened.
Determines if the provided path and open flags are valid. | [
"Called",
"by",
"FUSE",
"when",
"a",
"file",
"is",
"opened",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/client_onedrive/src/d1_onedrive/impl/drivers/fuse/callbacks.py#L94-L106 | train | 45,170 |
genialis/resolwe | resolwe/flow/expression_engines/base.py | BaseExpressionEngine.get_inline_expression | def get_inline_expression(self, text):
"""Extract an inline expression from the given text."""
text = text.strip()
if not text.startswith(self.inline_tags[0]) or not text.endswith(self.inline_tags[1]):
return
return text[2:-2] | python | def get_inline_expression(self, text):
"""Extract an inline expression from the given text."""
text = text.strip()
if not text.startswith(self.inline_tags[0]) or not text.endswith(self.inline_tags[1]):
return
return text[2:-2] | [
"def",
"get_inline_expression",
"(",
"self",
",",
"text",
")",
":",
"text",
"=",
"text",
".",
"strip",
"(",
")",
"if",
"not",
"text",
".",
"startswith",
"(",
"self",
".",
"inline_tags",
"[",
"0",
"]",
")",
"or",
"not",
"text",
".",
"endswith",
"(",
... | Extract an inline expression from the given text. | [
"Extract",
"an",
"inline",
"expression",
"from",
"the",
"given",
"text",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/expression_engines/base.py#L10-L16 | train | 45,171 |
genialis/resolwe | resolwe/flow/views/relation.py | RelationViewSet._filter_queryset | def _filter_queryset(self, queryset):
"""Filter queryset by entity, label and position.
Due to a bug in django-filter these filters have to be applied
manually:
https://github.com/carltongibson/django-filter/issues/883
"""
entities = self.request.query_params.getlist('entity')
labels = self.request.query_params.getlist('label')
positions = self.request.query_params.getlist('position')
if labels and len(labels) != len(entities):
raise exceptions.ParseError(
'If `labels` query parameter is given, also `entities` '
'must be given and they must be of the same length.'
)
if positions and len(positions) != len(entities):
raise exceptions.ParseError(
'If `positions` query parameter is given, also `entities` '
'must be given and they must be of the same length.'
)
if entities:
for entity, label, position in zip_longest(entities, labels, positions):
filter_params = {'entities__pk': entity}
if label:
filter_params['relationpartition__label'] = label
if position:
filter_params['relationpartition__position'] = position
queryset = queryset.filter(**filter_params)
return queryset | python | def _filter_queryset(self, queryset):
"""Filter queryset by entity, label and position.
Due to a bug in django-filter these filters have to be applied
manually:
https://github.com/carltongibson/django-filter/issues/883
"""
entities = self.request.query_params.getlist('entity')
labels = self.request.query_params.getlist('label')
positions = self.request.query_params.getlist('position')
if labels and len(labels) != len(entities):
raise exceptions.ParseError(
'If `labels` query parameter is given, also `entities` '
'must be given and they must be of the same length.'
)
if positions and len(positions) != len(entities):
raise exceptions.ParseError(
'If `positions` query parameter is given, also `entities` '
'must be given and they must be of the same length.'
)
if entities:
for entity, label, position in zip_longest(entities, labels, positions):
filter_params = {'entities__pk': entity}
if label:
filter_params['relationpartition__label'] = label
if position:
filter_params['relationpartition__position'] = position
queryset = queryset.filter(**filter_params)
return queryset | [
"def",
"_filter_queryset",
"(",
"self",
",",
"queryset",
")",
":",
"entities",
"=",
"self",
".",
"request",
".",
"query_params",
".",
"getlist",
"(",
"'entity'",
")",
"labels",
"=",
"self",
".",
"request",
".",
"query_params",
".",
"getlist",
"(",
"'label'... | Filter queryset by entity, label and position.
Due to a bug in django-filter these filters have to be applied
manually:
https://github.com/carltongibson/django-filter/issues/883 | [
"Filter",
"queryset",
"by",
"entity",
"label",
"and",
"position",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/views/relation.py#L25-L58 | train | 45,172 |
genialis/resolwe | resolwe/flow/views/relation.py | RelationViewSet.update | def update(self, request, *args, **kwargs):
"""Update the ``Relation`` object.
Reject the update if user doesn't have ``EDIT`` permission on
the collection referenced in the ``Relation``.
"""
instance = self.get_object()
if (not request.user.has_perm('edit_collection', instance.collection)
and not request.user.is_superuser):
return Response(status=status.HTTP_401_UNAUTHORIZED)
return super().update(request, *args, **kwargs) | python | def update(self, request, *args, **kwargs):
"""Update the ``Relation`` object.
Reject the update if user doesn't have ``EDIT`` permission on
the collection referenced in the ``Relation``.
"""
instance = self.get_object()
if (not request.user.has_perm('edit_collection', instance.collection)
and not request.user.is_superuser):
return Response(status=status.HTTP_401_UNAUTHORIZED)
return super().update(request, *args, **kwargs) | [
"def",
"update",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"instance",
"=",
"self",
".",
"get_object",
"(",
")",
"if",
"(",
"not",
"request",
".",
"user",
".",
"has_perm",
"(",
"'edit_collection'",
",",
"instan... | Update the ``Relation`` object.
Reject the update if user doesn't have ``EDIT`` permission on
the collection referenced in the ``Relation``. | [
"Update",
"the",
"Relation",
"object",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/views/relation.py#L74-L85 | train | 45,173 |
genialis/resolwe | resolwe/elastic/signals.py | _process_permission | def _process_permission(perm):
"""Rebuild indexes affected by the given permission."""
# XXX: Optimize: rebuild only permissions, not whole document
codename = perm.permission.codename
if not codename.startswith('view') and not codename.startswith('owner'):
return
index_builder.build(perm.content_object) | python | def _process_permission(perm):
"""Rebuild indexes affected by the given permission."""
# XXX: Optimize: rebuild only permissions, not whole document
codename = perm.permission.codename
if not codename.startswith('view') and not codename.startswith('owner'):
return
index_builder.build(perm.content_object) | [
"def",
"_process_permission",
"(",
"perm",
")",
":",
"# XXX: Optimize: rebuild only permissions, not whole document",
"codename",
"=",
"perm",
".",
"permission",
".",
"codename",
"if",
"not",
"codename",
".",
"startswith",
"(",
"'view'",
")",
"and",
"not",
"codename",... | Rebuild indexes affected by the given permission. | [
"Rebuild",
"indexes",
"affected",
"by",
"the",
"given",
"permission",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/signals.py#L16-L23 | train | 45,174 |
DataONEorg/d1_python | lib_common/src/d1_common/multipart.py | parse_response | def parse_response(response, encoding='utf-8'):
"""Parse a multipart Requests.Response into a tuple of BodyPart objects.
Args:
response: Requests.Response
encoding:
The parser will assume that any text in the HTML body is encoded with this
encoding when decoding it for use in the ``text`` attribute.
Returns:
tuple of BodyPart
Members: headers (CaseInsensitiveDict), content (bytes), text (Unicode),
encoding (str).
"""
return requests_toolbelt.multipart.decoder.MultipartDecoder.from_response(
response, encoding
).parts | python | def parse_response(response, encoding='utf-8'):
"""Parse a multipart Requests.Response into a tuple of BodyPart objects.
Args:
response: Requests.Response
encoding:
The parser will assume that any text in the HTML body is encoded with this
encoding when decoding it for use in the ``text`` attribute.
Returns:
tuple of BodyPart
Members: headers (CaseInsensitiveDict), content (bytes), text (Unicode),
encoding (str).
"""
return requests_toolbelt.multipart.decoder.MultipartDecoder.from_response(
response, encoding
).parts | [
"def",
"parse_response",
"(",
"response",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"return",
"requests_toolbelt",
".",
"multipart",
".",
"decoder",
".",
"MultipartDecoder",
".",
"from_response",
"(",
"response",
",",
"encoding",
")",
".",
"parts"
] | Parse a multipart Requests.Response into a tuple of BodyPart objects.
Args:
response: Requests.Response
encoding:
The parser will assume that any text in the HTML body is encoded with this
encoding when decoding it for use in the ``text`` attribute.
Returns:
tuple of BodyPart
Members: headers (CaseInsensitiveDict), content (bytes), text (Unicode),
encoding (str). | [
"Parse",
"a",
"multipart",
"Requests",
".",
"Response",
"into",
"a",
"tuple",
"of",
"BodyPart",
"objects",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/multipart.py#L23-L41 | train | 45,175 |
DataONEorg/d1_python | lib_common/src/d1_common/multipart.py | parse_str | def parse_str(mmp_bytes, content_type, encoding='utf-8'):
"""Parse multipart document bytes into a tuple of BodyPart objects.
Args:
mmp_bytes: bytes
Multipart document.
content_type : str
Must be on the form, ``multipart/form-data; boundary=<BOUNDARY>``, where
``<BOUNDARY>`` is the string that separates the parts of the multipart document
in ``mmp_bytes``. In HTTP requests and responses, it is passed in the
Content-Type header.
encoding : str
The coding used for the text in the HTML body.
Returns:
tuple of BodyPart
Members: headers (CaseInsensitiveDict), content (bytes), text (Unicode),
encoding (str).
"""
return requests_toolbelt.multipart.decoder.MultipartDecoder(
mmp_bytes, content_type, encoding
).parts | python | def parse_str(mmp_bytes, content_type, encoding='utf-8'):
"""Parse multipart document bytes into a tuple of BodyPart objects.
Args:
mmp_bytes: bytes
Multipart document.
content_type : str
Must be on the form, ``multipart/form-data; boundary=<BOUNDARY>``, where
``<BOUNDARY>`` is the string that separates the parts of the multipart document
in ``mmp_bytes``. In HTTP requests and responses, it is passed in the
Content-Type header.
encoding : str
The coding used for the text in the HTML body.
Returns:
tuple of BodyPart
Members: headers (CaseInsensitiveDict), content (bytes), text (Unicode),
encoding (str).
"""
return requests_toolbelt.multipart.decoder.MultipartDecoder(
mmp_bytes, content_type, encoding
).parts | [
"def",
"parse_str",
"(",
"mmp_bytes",
",",
"content_type",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"return",
"requests_toolbelt",
".",
"multipart",
".",
"decoder",
".",
"MultipartDecoder",
"(",
"mmp_bytes",
",",
"content_type",
",",
"encoding",
")",
".",
"p... | Parse multipart document bytes into a tuple of BodyPart objects.
Args:
mmp_bytes: bytes
Multipart document.
content_type : str
Must be on the form, ``multipart/form-data; boundary=<BOUNDARY>``, where
``<BOUNDARY>`` is the string that separates the parts of the multipart document
in ``mmp_bytes``. In HTTP requests and responses, it is passed in the
Content-Type header.
encoding : str
The coding used for the text in the HTML body.
Returns:
tuple of BodyPart
Members: headers (CaseInsensitiveDict), content (bytes), text (Unicode),
encoding (str). | [
"Parse",
"multipart",
"document",
"bytes",
"into",
"a",
"tuple",
"of",
"BodyPart",
"objects",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/multipart.py#L44-L68 | train | 45,176 |
DataONEorg/d1_python | lib_common/src/d1_common/multipart.py | normalize | def normalize(body_part_tup,):
"""Normalize a tuple of BodyPart objects to a string.
Normalization is done by sorting the body_parts by the Content- Disposition headers,
which is typically on the form, ``form-data; name="name_of_part``.
"""
return '\n\n'.join(
[
'{}\n\n{}'.format(
str(p.headers[b'Content-Disposition'], p.encoding), p.text
)
for p in sorted(
body_part_tup, key=lambda p: p.headers[b'Content-Disposition']
)
]
) | python | def normalize(body_part_tup,):
"""Normalize a tuple of BodyPart objects to a string.
Normalization is done by sorting the body_parts by the Content- Disposition headers,
which is typically on the form, ``form-data; name="name_of_part``.
"""
return '\n\n'.join(
[
'{}\n\n{}'.format(
str(p.headers[b'Content-Disposition'], p.encoding), p.text
)
for p in sorted(
body_part_tup, key=lambda p: p.headers[b'Content-Disposition']
)
]
) | [
"def",
"normalize",
"(",
"body_part_tup",
",",
")",
":",
"return",
"'\\n\\n'",
".",
"join",
"(",
"[",
"'{}\\n\\n{}'",
".",
"format",
"(",
"str",
"(",
"p",
".",
"headers",
"[",
"b'Content-Disposition'",
"]",
",",
"p",
".",
"encoding",
")",
",",
"p",
"."... | Normalize a tuple of BodyPart objects to a string.
Normalization is done by sorting the body_parts by the Content- Disposition headers,
which is typically on the form, ``form-data; name="name_of_part``. | [
"Normalize",
"a",
"tuple",
"of",
"BodyPart",
"objects",
"to",
"a",
"string",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/multipart.py#L71-L87 | train | 45,177 |
DataONEorg/d1_python | client_onedrive/src/d1_onedrive/impl/resolver/object_tree_resolver.py | Resolver._generate_readme_text | def _generate_readme_text(self, object_tree_path):
"""Generate a human readable description of the folder in text format."""
wdef_folder = self._object_tree.get_source_tree_folder(object_tree_path)
res = StringIO()
if len(object_tree_path):
folder_name = object_tree_path[-1]
else:
folder_name = 'root'
header = 'ObjectTree Folder "{}"'.format(folder_name)
res.write(header + '\n')
res.write('{}\n\n'.format('=' * len(header)))
res.write(
'The content present in object_tree folders is determined by a list\n'
)
res.write(
'of specific identifiers and by queries applied against the DataONE\n'
)
res.write('search index.\n\n')
res.write('Queries:\n\n')
if len(wdef_folder['queries']):
for query in wdef_folder['queries']:
res.write('- {}\n'.format(query))
else:
res.write('No queries specified at this level.\n')
res.write('\n\n')
res.write('Identifiers:\n\n')
if len(wdef_folder['identifiers']):
for pid in wdef_folder['identifiers']:
res.write('- {}\n'.format(pid))
else:
res.write('No individual identifiers selected at this level.\n')
res.write('\n\n')
res.write('Sub-folders:\n\n')
if len(wdef_folder['collections']):
for f in wdef_folder['collections']:
res.write('- {}\n'.format(f))
else:
res.write('No object_tree sub-folders are specified at this level.\n')
return res.getvalue().encode('utf-8') | python | def _generate_readme_text(self, object_tree_path):
"""Generate a human readable description of the folder in text format."""
wdef_folder = self._object_tree.get_source_tree_folder(object_tree_path)
res = StringIO()
if len(object_tree_path):
folder_name = object_tree_path[-1]
else:
folder_name = 'root'
header = 'ObjectTree Folder "{}"'.format(folder_name)
res.write(header + '\n')
res.write('{}\n\n'.format('=' * len(header)))
res.write(
'The content present in object_tree folders is determined by a list\n'
)
res.write(
'of specific identifiers and by queries applied against the DataONE\n'
)
res.write('search index.\n\n')
res.write('Queries:\n\n')
if len(wdef_folder['queries']):
for query in wdef_folder['queries']:
res.write('- {}\n'.format(query))
else:
res.write('No queries specified at this level.\n')
res.write('\n\n')
res.write('Identifiers:\n\n')
if len(wdef_folder['identifiers']):
for pid in wdef_folder['identifiers']:
res.write('- {}\n'.format(pid))
else:
res.write('No individual identifiers selected at this level.\n')
res.write('\n\n')
res.write('Sub-folders:\n\n')
if len(wdef_folder['collections']):
for f in wdef_folder['collections']:
res.write('- {}\n'.format(f))
else:
res.write('No object_tree sub-folders are specified at this level.\n')
return res.getvalue().encode('utf-8') | [
"def",
"_generate_readme_text",
"(",
"self",
",",
"object_tree_path",
")",
":",
"wdef_folder",
"=",
"self",
".",
"_object_tree",
".",
"get_source_tree_folder",
"(",
"object_tree_path",
")",
"res",
"=",
"StringIO",
"(",
")",
"if",
"len",
"(",
"object_tree_path",
... | Generate a human readable description of the folder in text format. | [
"Generate",
"a",
"human",
"readable",
"description",
"of",
"the",
"folder",
"in",
"text",
"format",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/client_onedrive/src/d1_onedrive/impl/resolver/object_tree_resolver.py#L272-L311 | train | 45,178 |
genialis/resolwe | resolwe/flow/serializers/collection.py | CollectionSerializer._serialize_data | def _serialize_data(self, data):
"""Return serialized data or list of ids, depending on `hydrate_data` query param."""
if self.request and self.request.query_params.get('hydrate_data', False):
serializer = DataSerializer(data, many=True, read_only=True)
serializer.bind('data', self)
return serializer.data
else:
return [d.id for d in data] | python | def _serialize_data(self, data):
"""Return serialized data or list of ids, depending on `hydrate_data` query param."""
if self.request and self.request.query_params.get('hydrate_data', False):
serializer = DataSerializer(data, many=True, read_only=True)
serializer.bind('data', self)
return serializer.data
else:
return [d.id for d in data] | [
"def",
"_serialize_data",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"request",
"and",
"self",
".",
"request",
".",
"query_params",
".",
"get",
"(",
"'hydrate_data'",
",",
"False",
")",
":",
"serializer",
"=",
"DataSerializer",
"(",
"data",
"... | Return serialized data or list of ids, depending on `hydrate_data` query param. | [
"Return",
"serialized",
"data",
"or",
"list",
"of",
"ids",
"depending",
"on",
"hydrate_data",
"query",
"param",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/serializers/collection.py#L47-L54 | train | 45,179 |
genialis/resolwe | resolwe/flow/serializers/collection.py | CollectionSerializer._filter_queryset | def _filter_queryset(self, perms, queryset):
"""Filter object objects by permissions of user in request."""
user = self.request.user if self.request else AnonymousUser()
return get_objects_for_user(user, perms, queryset) | python | def _filter_queryset(self, perms, queryset):
"""Filter object objects by permissions of user in request."""
user = self.request.user if self.request else AnonymousUser()
return get_objects_for_user(user, perms, queryset) | [
"def",
"_filter_queryset",
"(",
"self",
",",
"perms",
",",
"queryset",
")",
":",
"user",
"=",
"self",
".",
"request",
".",
"user",
"if",
"self",
".",
"request",
"else",
"AnonymousUser",
"(",
")",
"return",
"get_objects_for_user",
"(",
"user",
",",
"perms",... | Filter object objects by permissions of user in request. | [
"Filter",
"object",
"objects",
"by",
"permissions",
"of",
"user",
"in",
"request",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/serializers/collection.py#L56-L59 | train | 45,180 |
genialis/resolwe | resolwe/flow/serializers/collection.py | CollectionSerializer.get_data | def get_data(self, collection):
"""Return serialized list of data objects on collection that user has `view` permission on."""
data = self._filter_queryset('view_data', collection.data.all())
return self._serialize_data(data) | python | def get_data(self, collection):
"""Return serialized list of data objects on collection that user has `view` permission on."""
data = self._filter_queryset('view_data', collection.data.all())
return self._serialize_data(data) | [
"def",
"get_data",
"(",
"self",
",",
"collection",
")",
":",
"data",
"=",
"self",
".",
"_filter_queryset",
"(",
"'view_data'",
",",
"collection",
".",
"data",
".",
"all",
"(",
")",
")",
"return",
"self",
".",
"_serialize_data",
"(",
"data",
")"
] | Return serialized list of data objects on collection that user has `view` permission on. | [
"Return",
"serialized",
"list",
"of",
"data",
"objects",
"on",
"collection",
"that",
"user",
"has",
"view",
"permission",
"on",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/serializers/collection.py#L61-L65 | train | 45,181 |
genialis/resolwe | resolwe/flow/engine.py | load_engines | def load_engines(manager, class_name, base_module, engines, class_key='ENGINE', engine_type='engine'):
"""Load engines."""
loaded_engines = {}
for module_name_or_dict in engines:
if not isinstance(module_name_or_dict, dict):
module_name_or_dict = {
class_key: module_name_or_dict
}
try:
module_name = module_name_or_dict[class_key]
engine_settings = module_name_or_dict
except KeyError:
raise ImproperlyConfigured("If {} specification is a dictionary, it must define {}".format(
engine_type, class_key))
try:
engine_module = import_module(module_name)
try:
engine = getattr(engine_module, class_name)(manager=manager, settings=engine_settings)
if not isinstance(engine, BaseEngine):
raise ImproperlyConfigured("{} module {} class {} must extend BaseEngine".format(
engine_type.capitalize(), module_name, class_name))
except AttributeError:
raise ImproperlyConfigured("{} module {} is missing a {} class".format(
engine_type.capitalize(), module_name, class_name))
if engine.get_name() in loaded_engines:
raise ImproperlyConfigured("Duplicated {} {}".format(engine_type, engine.get_name()))
loaded_engines[engine.get_name()] = engine
except ImportError as ex:
# The engine wasn't found. Display a helpful error message listing all possible
# (built-in) engines.
engine_dir = os.path.join(os.path.dirname(upath(__file__)), base_module)
try:
builtin_engines = [name for _, name, _ in pkgutil.iter_modules([engine_dir])]
except EnvironmentError:
builtin_engines = []
if module_name not in ['resolwe.flow.{}.{}'.format(base_module, builtin_engine)
for builtin_engine in builtin_engines]:
engine_reprs = map(repr, sorted(builtin_engines))
error_msg = ("{} isn't an available dataflow {}.\n"
"Try using 'resolwe.flow.{}.XXX', where XXX is one of:\n"
" {}\n"
"Error was: {}".format(
module_name, engine_type, base_module, ", ".join(engine_reprs), ex
))
raise ImproperlyConfigured(error_msg)
else:
# If there's some other error, this must be an error in Django
raise
return loaded_engines | python | def load_engines(manager, class_name, base_module, engines, class_key='ENGINE', engine_type='engine'):
"""Load engines."""
loaded_engines = {}
for module_name_or_dict in engines:
if not isinstance(module_name_or_dict, dict):
module_name_or_dict = {
class_key: module_name_or_dict
}
try:
module_name = module_name_or_dict[class_key]
engine_settings = module_name_or_dict
except KeyError:
raise ImproperlyConfigured("If {} specification is a dictionary, it must define {}".format(
engine_type, class_key))
try:
engine_module = import_module(module_name)
try:
engine = getattr(engine_module, class_name)(manager=manager, settings=engine_settings)
if not isinstance(engine, BaseEngine):
raise ImproperlyConfigured("{} module {} class {} must extend BaseEngine".format(
engine_type.capitalize(), module_name, class_name))
except AttributeError:
raise ImproperlyConfigured("{} module {} is missing a {} class".format(
engine_type.capitalize(), module_name, class_name))
if engine.get_name() in loaded_engines:
raise ImproperlyConfigured("Duplicated {} {}".format(engine_type, engine.get_name()))
loaded_engines[engine.get_name()] = engine
except ImportError as ex:
# The engine wasn't found. Display a helpful error message listing all possible
# (built-in) engines.
engine_dir = os.path.join(os.path.dirname(upath(__file__)), base_module)
try:
builtin_engines = [name for _, name, _ in pkgutil.iter_modules([engine_dir])]
except EnvironmentError:
builtin_engines = []
if module_name not in ['resolwe.flow.{}.{}'.format(base_module, builtin_engine)
for builtin_engine in builtin_engines]:
engine_reprs = map(repr, sorted(builtin_engines))
error_msg = ("{} isn't an available dataflow {}.\n"
"Try using 'resolwe.flow.{}.XXX', where XXX is one of:\n"
" {}\n"
"Error was: {}".format(
module_name, engine_type, base_module, ", ".join(engine_reprs), ex
))
raise ImproperlyConfigured(error_msg)
else:
# If there's some other error, this must be an error in Django
raise
return loaded_engines | [
"def",
"load_engines",
"(",
"manager",
",",
"class_name",
",",
"base_module",
",",
"engines",
",",
"class_key",
"=",
"'ENGINE'",
",",
"engine_type",
"=",
"'engine'",
")",
":",
"loaded_engines",
"=",
"{",
"}",
"for",
"module_name_or_dict",
"in",
"engines",
":",... | Load engines. | [
"Load",
"engines",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/engine.py#L29-L86 | train | 45,182 |
DataONEorg/d1_python | lib_common/src/d1_common/system_metadata.py | normalize_in_place | def normalize_in_place(sysmeta_pyxb, reset_timestamps=False):
"""Normalize SystemMetadata PyXB object in-place.
Args:
sysmeta_pyxb:
SystemMetadata PyXB object to normalize.
reset_timestamps: bool
``True``: Timestamps in the SystemMetadata are set to a standard value so that
objects that are compared after normalization register as equivalent if only
their timestamps differ.
Notes:
The SystemMetadata is normalized by removing any redundant information and
ordering all sections where there are no semantics associated with the order. The
normalized SystemMetadata is intended to be semantically equivalent to the
un-normalized one.
"""
if sysmeta_pyxb.accessPolicy is not None:
sysmeta_pyxb.accessPolicy = d1_common.wrap.access_policy.get_normalized_pyxb(
sysmeta_pyxb.accessPolicy
)
if getattr(sysmeta_pyxb, 'mediaType', False):
d1_common.xml.sort_value_list_pyxb(sysmeta_pyxb.mediaType.property_)
if getattr(sysmeta_pyxb, 'replicationPolicy', False):
d1_common.xml.sort_value_list_pyxb(
sysmeta_pyxb.replicationPolicy.preferredMemberNode
)
d1_common.xml.sort_value_list_pyxb(
sysmeta_pyxb.replicationPolicy.blockedMemberNode
)
d1_common.xml.sort_elements_by_child_values(
sysmeta_pyxb.replica,
['replicaVerified', 'replicaMemberNode', 'replicationStatus'],
)
sysmeta_pyxb.archived = bool(sysmeta_pyxb.archived)
if reset_timestamps:
epoch_dt = datetime.datetime(1970, 1, 1, tzinfo=d1_common.date_time.UTC())
sysmeta_pyxb.dateUploaded = epoch_dt
sysmeta_pyxb.dateSysMetadataModified = epoch_dt
for replica_pyxb in getattr(sysmeta_pyxb, 'replica', []):
replica_pyxb.replicaVerified = epoch_dt
else:
sysmeta_pyxb.dateUploaded = d1_common.date_time.round_to_nearest(
sysmeta_pyxb.dateUploaded
)
sysmeta_pyxb.dateSysMetadataModified = d1_common.date_time.round_to_nearest(
sysmeta_pyxb.dateSysMetadataModified
)
for replica_pyxb in getattr(sysmeta_pyxb, 'replica', []):
replica_pyxb.replicaVerified = d1_common.date_time.round_to_nearest(
replica_pyxb.replicaVerified
) | python | def normalize_in_place(sysmeta_pyxb, reset_timestamps=False):
"""Normalize SystemMetadata PyXB object in-place.
Args:
sysmeta_pyxb:
SystemMetadata PyXB object to normalize.
reset_timestamps: bool
``True``: Timestamps in the SystemMetadata are set to a standard value so that
objects that are compared after normalization register as equivalent if only
their timestamps differ.
Notes:
The SystemMetadata is normalized by removing any redundant information and
ordering all sections where there are no semantics associated with the order. The
normalized SystemMetadata is intended to be semantically equivalent to the
un-normalized one.
"""
if sysmeta_pyxb.accessPolicy is not None:
sysmeta_pyxb.accessPolicy = d1_common.wrap.access_policy.get_normalized_pyxb(
sysmeta_pyxb.accessPolicy
)
if getattr(sysmeta_pyxb, 'mediaType', False):
d1_common.xml.sort_value_list_pyxb(sysmeta_pyxb.mediaType.property_)
if getattr(sysmeta_pyxb, 'replicationPolicy', False):
d1_common.xml.sort_value_list_pyxb(
sysmeta_pyxb.replicationPolicy.preferredMemberNode
)
d1_common.xml.sort_value_list_pyxb(
sysmeta_pyxb.replicationPolicy.blockedMemberNode
)
d1_common.xml.sort_elements_by_child_values(
sysmeta_pyxb.replica,
['replicaVerified', 'replicaMemberNode', 'replicationStatus'],
)
sysmeta_pyxb.archived = bool(sysmeta_pyxb.archived)
if reset_timestamps:
epoch_dt = datetime.datetime(1970, 1, 1, tzinfo=d1_common.date_time.UTC())
sysmeta_pyxb.dateUploaded = epoch_dt
sysmeta_pyxb.dateSysMetadataModified = epoch_dt
for replica_pyxb in getattr(sysmeta_pyxb, 'replica', []):
replica_pyxb.replicaVerified = epoch_dt
else:
sysmeta_pyxb.dateUploaded = d1_common.date_time.round_to_nearest(
sysmeta_pyxb.dateUploaded
)
sysmeta_pyxb.dateSysMetadataModified = d1_common.date_time.round_to_nearest(
sysmeta_pyxb.dateSysMetadataModified
)
for replica_pyxb in getattr(sysmeta_pyxb, 'replica', []):
replica_pyxb.replicaVerified = d1_common.date_time.round_to_nearest(
replica_pyxb.replicaVerified
) | [
"def",
"normalize_in_place",
"(",
"sysmeta_pyxb",
",",
"reset_timestamps",
"=",
"False",
")",
":",
"if",
"sysmeta_pyxb",
".",
"accessPolicy",
"is",
"not",
"None",
":",
"sysmeta_pyxb",
".",
"accessPolicy",
"=",
"d1_common",
".",
"wrap",
".",
"access_policy",
".",... | Normalize SystemMetadata PyXB object in-place.
Args:
sysmeta_pyxb:
SystemMetadata PyXB object to normalize.
reset_timestamps: bool
``True``: Timestamps in the SystemMetadata are set to a standard value so that
objects that are compared after normalization register as equivalent if only
their timestamps differ.
Notes:
The SystemMetadata is normalized by removing any redundant information and
ordering all sections where there are no semantics associated with the order. The
normalized SystemMetadata is intended to be semantically equivalent to the
un-normalized one. | [
"Normalize",
"SystemMetadata",
"PyXB",
"object",
"in",
"-",
"place",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/system_metadata.py#L143-L196 | train | 45,183 |
DataONEorg/d1_python | lib_common/src/d1_common/system_metadata.py | are_equivalent_pyxb | def are_equivalent_pyxb(a_pyxb, b_pyxb, ignore_timestamps=False):
"""Determine if SystemMetadata PyXB objects are semantically equivalent.
Normalize then compare SystemMetadata PyXB objects for equivalency.
Args:
a_pyxb, b_pyxb : SystemMetadata PyXB objects to compare
reset_timestamps: bool
``True``: Timestamps in the SystemMetadata are set to a standard value so that
objects that are compared after normalization register as equivalent if only
their timestamps differ.
Returns:
bool: **True** if SystemMetadata PyXB objects are semantically equivalent.
Notes:
The SystemMetadata is normalized by removing any redundant information and
ordering all sections where there are no semantics associated with the order. The
normalized SystemMetadata is intended to be semantically equivalent to the
un-normalized one.
"""
normalize_in_place(a_pyxb, ignore_timestamps)
normalize_in_place(b_pyxb, ignore_timestamps)
a_xml = d1_common.xml.serialize_to_xml_str(a_pyxb)
b_xml = d1_common.xml.serialize_to_xml_str(b_pyxb)
are_equivalent = d1_common.xml.are_equivalent(a_xml, b_xml)
if not are_equivalent:
logger.debug('XML documents not equivalent:')
logger.debug(d1_common.xml.format_diff_xml(a_xml, b_xml))
return are_equivalent | python | def are_equivalent_pyxb(a_pyxb, b_pyxb, ignore_timestamps=False):
"""Determine if SystemMetadata PyXB objects are semantically equivalent.
Normalize then compare SystemMetadata PyXB objects for equivalency.
Args:
a_pyxb, b_pyxb : SystemMetadata PyXB objects to compare
reset_timestamps: bool
``True``: Timestamps in the SystemMetadata are set to a standard value so that
objects that are compared after normalization register as equivalent if only
their timestamps differ.
Returns:
bool: **True** if SystemMetadata PyXB objects are semantically equivalent.
Notes:
The SystemMetadata is normalized by removing any redundant information and
ordering all sections where there are no semantics associated with the order. The
normalized SystemMetadata is intended to be semantically equivalent to the
un-normalized one.
"""
normalize_in_place(a_pyxb, ignore_timestamps)
normalize_in_place(b_pyxb, ignore_timestamps)
a_xml = d1_common.xml.serialize_to_xml_str(a_pyxb)
b_xml = d1_common.xml.serialize_to_xml_str(b_pyxb)
are_equivalent = d1_common.xml.are_equivalent(a_xml, b_xml)
if not are_equivalent:
logger.debug('XML documents not equivalent:')
logger.debug(d1_common.xml.format_diff_xml(a_xml, b_xml))
return are_equivalent | [
"def",
"are_equivalent_pyxb",
"(",
"a_pyxb",
",",
"b_pyxb",
",",
"ignore_timestamps",
"=",
"False",
")",
":",
"normalize_in_place",
"(",
"a_pyxb",
",",
"ignore_timestamps",
")",
"normalize_in_place",
"(",
"b_pyxb",
",",
"ignore_timestamps",
")",
"a_xml",
"=",
"d1_... | Determine if SystemMetadata PyXB objects are semantically equivalent.
Normalize then compare SystemMetadata PyXB objects for equivalency.
Args:
a_pyxb, b_pyxb : SystemMetadata PyXB objects to compare
reset_timestamps: bool
``True``: Timestamps in the SystemMetadata are set to a standard value so that
objects that are compared after normalization register as equivalent if only
their timestamps differ.
Returns:
bool: **True** if SystemMetadata PyXB objects are semantically equivalent.
Notes:
The SystemMetadata is normalized by removing any redundant information and
ordering all sections where there are no semantics associated with the order. The
normalized SystemMetadata is intended to be semantically equivalent to the
un-normalized one. | [
"Determine",
"if",
"SystemMetadata",
"PyXB",
"objects",
"are",
"semantically",
"equivalent",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/system_metadata.py#L199-L230 | train | 45,184 |
DataONEorg/d1_python | lib_common/src/d1_common/system_metadata.py | are_equivalent_xml | def are_equivalent_xml(a_xml, b_xml, ignore_timestamps=False):
"""Determine if two SystemMetadata XML docs are semantically equivalent.
Normalize then compare SystemMetadata XML docs for equivalency.
Args:
a_xml, b_xml: bytes
UTF-8 encoded SystemMetadata XML docs to compare
ignore_timestamps: bool
``True``: Timestamps in the SystemMetadata are ignored so that objects that are
compared register as equivalent if only their timestamps differ.
Returns:
bool: **True** if SystemMetadata XML docs are semantically equivalent.
Notes:
The SystemMetadata is normalized by removing any redundant information and
ordering all sections where there are no semantics associated with the order. The
normalized SystemMetadata is intended to be semantically equivalent to the
un-normalized one.
"""
"""Normalizes then compares SystemMetadata XML docs for equivalency.
``a_xml`` and ``b_xml`` should be utf-8 encoded DataONE System Metadata XML
documents.
"""
return are_equivalent_pyxb(
d1_common.xml.deserialize(a_xml),
d1_common.xml.deserialize(b_xml),
ignore_timestamps,
) | python | def are_equivalent_xml(a_xml, b_xml, ignore_timestamps=False):
"""Determine if two SystemMetadata XML docs are semantically equivalent.
Normalize then compare SystemMetadata XML docs for equivalency.
Args:
a_xml, b_xml: bytes
UTF-8 encoded SystemMetadata XML docs to compare
ignore_timestamps: bool
``True``: Timestamps in the SystemMetadata are ignored so that objects that are
compared register as equivalent if only their timestamps differ.
Returns:
bool: **True** if SystemMetadata XML docs are semantically equivalent.
Notes:
The SystemMetadata is normalized by removing any redundant information and
ordering all sections where there are no semantics associated with the order. The
normalized SystemMetadata is intended to be semantically equivalent to the
un-normalized one.
"""
"""Normalizes then compares SystemMetadata XML docs for equivalency.
``a_xml`` and ``b_xml`` should be utf-8 encoded DataONE System Metadata XML
documents.
"""
return are_equivalent_pyxb(
d1_common.xml.deserialize(a_xml),
d1_common.xml.deserialize(b_xml),
ignore_timestamps,
) | [
"def",
"are_equivalent_xml",
"(",
"a_xml",
",",
"b_xml",
",",
"ignore_timestamps",
"=",
"False",
")",
":",
"\"\"\"Normalizes then compares SystemMetadata XML docs for equivalency.\n ``a_xml`` and ``b_xml`` should be utf-8 encoded DataONE System Metadata XML\n documents.\n \"\"\"",
"retu... | Determine if two SystemMetadata XML docs are semantically equivalent.
Normalize then compare SystemMetadata XML docs for equivalency.
Args:
a_xml, b_xml: bytes
UTF-8 encoded SystemMetadata XML docs to compare
ignore_timestamps: bool
``True``: Timestamps in the SystemMetadata are ignored so that objects that are
compared register as equivalent if only their timestamps differ.
Returns:
bool: **True** if SystemMetadata XML docs are semantically equivalent.
Notes:
The SystemMetadata is normalized by removing any redundant information and
ordering all sections where there are no semantics associated with the order. The
normalized SystemMetadata is intended to be semantically equivalent to the
un-normalized one. | [
"Determine",
"if",
"two",
"SystemMetadata",
"XML",
"docs",
"are",
"semantically",
"equivalent",
"."
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/system_metadata.py#L233-L265 | train | 45,185 |
DataONEorg/d1_python | lib_common/src/d1_common/system_metadata.py | update_elements | def update_elements(dst_pyxb, src_pyxb, el_list):
"""Copy elements specified in ``el_list`` from ``src_pyxb`` to ``dst_pyxb``
Only elements that are children of root are supported. See
SYSMETA_ROOT_CHILD_LIST.
If an element in ``el_list`` does not exist in ``src_pyxb``, it is removed from
``dst_pyxb``.
"""
invalid_element_set = set(el_list) - set(SYSMETA_ROOT_CHILD_LIST)
if invalid_element_set:
raise ValueError(
'Passed one or more invalid elements. invalid="{}"'.format(
', '.join(sorted(list(invalid_element_set)))
)
)
for el_str in el_list:
setattr(dst_pyxb, el_str, getattr(src_pyxb, el_str, None)) | python | def update_elements(dst_pyxb, src_pyxb, el_list):
"""Copy elements specified in ``el_list`` from ``src_pyxb`` to ``dst_pyxb``
Only elements that are children of root are supported. See
SYSMETA_ROOT_CHILD_LIST.
If an element in ``el_list`` does not exist in ``src_pyxb``, it is removed from
``dst_pyxb``.
"""
invalid_element_set = set(el_list) - set(SYSMETA_ROOT_CHILD_LIST)
if invalid_element_set:
raise ValueError(
'Passed one or more invalid elements. invalid="{}"'.format(
', '.join(sorted(list(invalid_element_set)))
)
)
for el_str in el_list:
setattr(dst_pyxb, el_str, getattr(src_pyxb, el_str, None)) | [
"def",
"update_elements",
"(",
"dst_pyxb",
",",
"src_pyxb",
",",
"el_list",
")",
":",
"invalid_element_set",
"=",
"set",
"(",
"el_list",
")",
"-",
"set",
"(",
"SYSMETA_ROOT_CHILD_LIST",
")",
"if",
"invalid_element_set",
":",
"raise",
"ValueError",
"(",
"'Passed ... | Copy elements specified in ``el_list`` from ``src_pyxb`` to ``dst_pyxb``
Only elements that are children of root are supported. See
SYSMETA_ROOT_CHILD_LIST.
If an element in ``el_list`` does not exist in ``src_pyxb``, it is removed from
``dst_pyxb``. | [
"Copy",
"elements",
"specified",
"in",
"el_list",
"from",
"src_pyxb",
"to",
"dst_pyxb"
] | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/system_metadata.py#L283-L301 | train | 45,186 |
genialis/resolwe | resolwe/permissions/utils.py | get_full_perm | def get_full_perm(perm, obj):
"""Join action with the content type of ``obj``.
Permission is returned in the format of ``<action>_<object_type>``.
"""
ctype = ContentType.objects.get_for_model(obj)
# Camel case class names are converted into a space-separated
# content types, so spaces have to be removed.
ctype = str(ctype).replace(' ', '')
return '{}_{}'.format(perm.lower(), ctype) | python | def get_full_perm(perm, obj):
"""Join action with the content type of ``obj``.
Permission is returned in the format of ``<action>_<object_type>``.
"""
ctype = ContentType.objects.get_for_model(obj)
# Camel case class names are converted into a space-separated
# content types, so spaces have to be removed.
ctype = str(ctype).replace(' ', '')
return '{}_{}'.format(perm.lower(), ctype) | [
"def",
"get_full_perm",
"(",
"perm",
",",
"obj",
")",
":",
"ctype",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"obj",
")",
"# Camel case class names are converted into a space-separated",
"# content types, so spaces have to be removed.",
"ctype",
"=",
... | Join action with the content type of ``obj``.
Permission is returned in the format of ``<action>_<object_type>``. | [
"Join",
"action",
"with",
"the",
"content",
"type",
"of",
"obj",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/permissions/utils.py#L31-L41 | train | 45,187 |
genialis/resolwe | resolwe/permissions/utils.py | copy_permissions | def copy_permissions(src_obj, dest_obj):
"""Copy permissions form ``src_obj`` to ``dest_obj``."""
def _process_permission(codename, user_or_group, dest_obj, relabel):
"""Process single permission."""
if relabel:
codename = change_perm_ctype(codename, dest_obj)
if codename not in dest_all_perms:
return # dest object doesn't have matching permission
assign_perm(codename, user_or_group, dest_obj)
src_obj_ctype = ContentType.objects.get_for_model(src_obj)
dest_obj_ctype = ContentType.objects.get_for_model(dest_obj)
dest_all_perms = get_all_perms(dest_obj)
relabel = (src_obj_ctype != dest_obj_ctype)
for perm in UserObjectPermission.objects.filter(object_pk=src_obj.pk, content_type=src_obj_ctype):
_process_permission(perm.permission.codename, perm.user, dest_obj, relabel)
for perm in GroupObjectPermission.objects.filter(object_pk=src_obj.pk, content_type=src_obj_ctype):
_process_permission(perm.permission.codename, perm.group, dest_obj, relabel) | python | def copy_permissions(src_obj, dest_obj):
"""Copy permissions form ``src_obj`` to ``dest_obj``."""
def _process_permission(codename, user_or_group, dest_obj, relabel):
"""Process single permission."""
if relabel:
codename = change_perm_ctype(codename, dest_obj)
if codename not in dest_all_perms:
return # dest object doesn't have matching permission
assign_perm(codename, user_or_group, dest_obj)
src_obj_ctype = ContentType.objects.get_for_model(src_obj)
dest_obj_ctype = ContentType.objects.get_for_model(dest_obj)
dest_all_perms = get_all_perms(dest_obj)
relabel = (src_obj_ctype != dest_obj_ctype)
for perm in UserObjectPermission.objects.filter(object_pk=src_obj.pk, content_type=src_obj_ctype):
_process_permission(perm.permission.codename, perm.user, dest_obj, relabel)
for perm in GroupObjectPermission.objects.filter(object_pk=src_obj.pk, content_type=src_obj_ctype):
_process_permission(perm.permission.codename, perm.group, dest_obj, relabel) | [
"def",
"copy_permissions",
"(",
"src_obj",
",",
"dest_obj",
")",
":",
"def",
"_process_permission",
"(",
"codename",
",",
"user_or_group",
",",
"dest_obj",
",",
"relabel",
")",
":",
"\"\"\"Process single permission.\"\"\"",
"if",
"relabel",
":",
"codename",
"=",
"... | Copy permissions form ``src_obj`` to ``dest_obj``. | [
"Copy",
"permissions",
"form",
"src_obj",
"to",
"dest_obj",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/permissions/utils.py#L55-L76 | train | 45,188 |
genialis/resolwe | resolwe/permissions/utils.py | fetch_user | def fetch_user(query):
"""Get user by ``pk`` or ``username``. Raise error if it doesn't exist."""
user_filter = {'pk': query} if query.isdigit() else {'username': query}
user_model = get_user_model()
try:
return user_model.objects.get(**user_filter)
except user_model.DoesNotExist:
raise exceptions.ParseError("Unknown user: {}".format(query)) | python | def fetch_user(query):
"""Get user by ``pk`` or ``username``. Raise error if it doesn't exist."""
user_filter = {'pk': query} if query.isdigit() else {'username': query}
user_model = get_user_model()
try:
return user_model.objects.get(**user_filter)
except user_model.DoesNotExist:
raise exceptions.ParseError("Unknown user: {}".format(query)) | [
"def",
"fetch_user",
"(",
"query",
")",
":",
"user_filter",
"=",
"{",
"'pk'",
":",
"query",
"}",
"if",
"query",
".",
"isdigit",
"(",
")",
"else",
"{",
"'username'",
":",
"query",
"}",
"user_model",
"=",
"get_user_model",
"(",
")",
"try",
":",
"return",... | Get user by ``pk`` or ``username``. Raise error if it doesn't exist. | [
"Get",
"user",
"by",
"pk",
"or",
"username",
".",
"Raise",
"error",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/permissions/utils.py#L79-L87 | train | 45,189 |
genialis/resolwe | resolwe/permissions/utils.py | fetch_group | def fetch_group(query):
"""Get group by ``pk`` or ``name``. Raise error if it doesn't exist."""
group_filter = {'pk': query} if query.isdigit() else {'name': query}
try:
return Group.objects.get(**group_filter)
except Group.DoesNotExist:
raise exceptions.ParseError("Unknown group: {}".format(query)) | python | def fetch_group(query):
"""Get group by ``pk`` or ``name``. Raise error if it doesn't exist."""
group_filter = {'pk': query} if query.isdigit() else {'name': query}
try:
return Group.objects.get(**group_filter)
except Group.DoesNotExist:
raise exceptions.ParseError("Unknown group: {}".format(query)) | [
"def",
"fetch_group",
"(",
"query",
")",
":",
"group_filter",
"=",
"{",
"'pk'",
":",
"query",
"}",
"if",
"query",
".",
"isdigit",
"(",
")",
"else",
"{",
"'name'",
":",
"query",
"}",
"try",
":",
"return",
"Group",
".",
"objects",
".",
"get",
"(",
"*... | Get group by ``pk`` or ``name``. Raise error if it doesn't exist. | [
"Get",
"group",
"by",
"pk",
"or",
"name",
".",
"Raise",
"error",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/permissions/utils.py#L90-L97 | train | 45,190 |
genialis/resolwe | resolwe/permissions/utils.py | check_owner_permission | def check_owner_permission(payload, allow_user_owner):
"""Raise ``PermissionDenied``if ``owner`` found in ``data``."""
for entity_type in ['users', 'groups']:
for perm_type in ['add', 'remove']:
for perms in payload.get(entity_type, {}).get(perm_type, {}).values():
if 'owner' in perms:
if entity_type == 'users' and allow_user_owner:
continue
if entity_type == 'groups':
raise exceptions.ParseError("Owner permission cannot be assigned to a group")
raise exceptions.PermissionDenied("Only owners can grant/revoke owner permission") | python | def check_owner_permission(payload, allow_user_owner):
"""Raise ``PermissionDenied``if ``owner`` found in ``data``."""
for entity_type in ['users', 'groups']:
for perm_type in ['add', 'remove']:
for perms in payload.get(entity_type, {}).get(perm_type, {}).values():
if 'owner' in perms:
if entity_type == 'users' and allow_user_owner:
continue
if entity_type == 'groups':
raise exceptions.ParseError("Owner permission cannot be assigned to a group")
raise exceptions.PermissionDenied("Only owners can grant/revoke owner permission") | [
"def",
"check_owner_permission",
"(",
"payload",
",",
"allow_user_owner",
")",
":",
"for",
"entity_type",
"in",
"[",
"'users'",
",",
"'groups'",
"]",
":",
"for",
"perm_type",
"in",
"[",
"'add'",
",",
"'remove'",
"]",
":",
"for",
"perms",
"in",
"payload",
"... | Raise ``PermissionDenied``if ``owner`` found in ``data``. | [
"Raise",
"PermissionDenied",
"if",
"owner",
"found",
"in",
"data",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/permissions/utils.py#L100-L112 | train | 45,191 |
genialis/resolwe | resolwe/permissions/utils.py | check_public_permissions | def check_public_permissions(payload):
"""Raise ``PermissionDenied`` if public permissions are too open."""
allowed_public_permissions = ['view', 'add', 'download']
for perm_type in ['add', 'remove']:
for perm in payload.get('public', {}).get(perm_type, []):
if perm not in allowed_public_permissions:
raise exceptions.PermissionDenied("Permissions for public users are too open") | python | def check_public_permissions(payload):
"""Raise ``PermissionDenied`` if public permissions are too open."""
allowed_public_permissions = ['view', 'add', 'download']
for perm_type in ['add', 'remove']:
for perm in payload.get('public', {}).get(perm_type, []):
if perm not in allowed_public_permissions:
raise exceptions.PermissionDenied("Permissions for public users are too open") | [
"def",
"check_public_permissions",
"(",
"payload",
")",
":",
"allowed_public_permissions",
"=",
"[",
"'view'",
",",
"'add'",
",",
"'download'",
"]",
"for",
"perm_type",
"in",
"[",
"'add'",
",",
"'remove'",
"]",
":",
"for",
"perm",
"in",
"payload",
".",
"get"... | Raise ``PermissionDenied`` if public permissions are too open. | [
"Raise",
"PermissionDenied",
"if",
"public",
"permissions",
"are",
"too",
"open",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/permissions/utils.py#L115-L121 | train | 45,192 |
genialis/resolwe | resolwe/permissions/utils.py | check_user_permissions | def check_user_permissions(payload, user_pk):
"""Raise ``PermissionDenied`` if ``payload`` includes ``user_pk``."""
for perm_type in ['add', 'remove']:
user_pks = payload.get('users', {}).get(perm_type, {}).keys()
if user_pk in user_pks:
raise exceptions.PermissionDenied("You cannot change your own permissions") | python | def check_user_permissions(payload, user_pk):
"""Raise ``PermissionDenied`` if ``payload`` includes ``user_pk``."""
for perm_type in ['add', 'remove']:
user_pks = payload.get('users', {}).get(perm_type, {}).keys()
if user_pk in user_pks:
raise exceptions.PermissionDenied("You cannot change your own permissions") | [
"def",
"check_user_permissions",
"(",
"payload",
",",
"user_pk",
")",
":",
"for",
"perm_type",
"in",
"[",
"'add'",
",",
"'remove'",
"]",
":",
"user_pks",
"=",
"payload",
".",
"get",
"(",
"'users'",
",",
"{",
"}",
")",
".",
"get",
"(",
"perm_type",
",",... | Raise ``PermissionDenied`` if ``payload`` includes ``user_pk``. | [
"Raise",
"PermissionDenied",
"if",
"payload",
"includes",
"user_pk",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/permissions/utils.py#L124-L129 | train | 45,193 |
genialis/resolwe | resolwe/permissions/utils.py | remove_permission | def remove_permission(payload, permission):
"""Remove all occurrences of ``permission`` from ``payload``."""
payload = copy.deepcopy(payload)
for entity_type in ['users', 'groups']:
for perm_type in ['add', 'remove']:
for perms in payload.get(entity_type, {}).get(perm_type, {}).values():
if permission in perms:
perms.remove(permission)
for perm_type in ['add', 'remove']:
perms = payload.get('public', {}).get(perm_type, [])
if permission in perms:
perms.remove(permission)
return payload | python | def remove_permission(payload, permission):
"""Remove all occurrences of ``permission`` from ``payload``."""
payload = copy.deepcopy(payload)
for entity_type in ['users', 'groups']:
for perm_type in ['add', 'remove']:
for perms in payload.get(entity_type, {}).get(perm_type, {}).values():
if permission in perms:
perms.remove(permission)
for perm_type in ['add', 'remove']:
perms = payload.get('public', {}).get(perm_type, [])
if permission in perms:
perms.remove(permission)
return payload | [
"def",
"remove_permission",
"(",
"payload",
",",
"permission",
")",
":",
"payload",
"=",
"copy",
".",
"deepcopy",
"(",
"payload",
")",
"for",
"entity_type",
"in",
"[",
"'users'",
",",
"'groups'",
"]",
":",
"for",
"perm_type",
"in",
"[",
"'add'",
",",
"'r... | Remove all occurrences of ``permission`` from ``payload``. | [
"Remove",
"all",
"occurrences",
"of",
"permission",
"from",
"payload",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/permissions/utils.py#L132-L147 | train | 45,194 |
genialis/resolwe | resolwe/permissions/utils.py | update_permission | def update_permission(obj, data):
"""Update object permissions."""
full_permissions = get_all_perms(obj)
def apply_perm(perm_func, perms, entity):
"""Apply permissions using given ``perm_func``.
``perm_func`` is intended to be ``assign_perms`` or
``remove_perms`` shortcut function from ``django-guardian``, but
can be any function that accepts permission codename,
user/group and object parameters (in this order).
If given permission does not exist, ``exceptions.ParseError`` is
raised.
"ALL" passed as ``perms`` parameter, will call ``perm_function``
with ``full_permissions`` list.
:param func perm_func: Permissions function to be applied
:param list params: list of params to be allpied
:param entity: user or group to be passed to ``perm_func``
:type entity: `~django.contrib.auth.models.User` or
`~django.contrib.auth.models.Group`
"""
if perms == 'ALL':
perms = full_permissions
for perm in perms:
perm_codename = get_full_perm(perm, obj)
if perm_codename not in full_permissions:
raise exceptions.ParseError("Unknown permission: {}".format(perm))
perm_func(perm_codename, entity, obj)
def set_permissions(entity_type, perm_type):
"""Set object permissions."""
perm_func = assign_perm if perm_type == 'add' else remove_perm
fetch_fn = fetch_user if entity_type == 'users' else fetch_group
for entity_id in data.get(entity_type, {}).get(perm_type, []):
entity = fetch_fn(entity_id)
if entity:
perms = data[entity_type][perm_type][entity_id]
apply_perm(perm_func, perms, entity)
def set_public_permissions(perm_type):
"""Set public permissions."""
perm_func = assign_perm if perm_type == 'add' else remove_perm
user = AnonymousUser()
perms = data.get('public', {}).get(perm_type, [])
apply_perm(perm_func, perms, user)
with transaction.atomic():
set_permissions('users', 'add')
set_permissions('users', 'remove')
set_permissions('groups', 'add')
set_permissions('groups', 'remove')
set_public_permissions('add')
set_public_permissions('remove') | python | def update_permission(obj, data):
"""Update object permissions."""
full_permissions = get_all_perms(obj)
def apply_perm(perm_func, perms, entity):
"""Apply permissions using given ``perm_func``.
``perm_func`` is intended to be ``assign_perms`` or
``remove_perms`` shortcut function from ``django-guardian``, but
can be any function that accepts permission codename,
user/group and object parameters (in this order).
If given permission does not exist, ``exceptions.ParseError`` is
raised.
"ALL" passed as ``perms`` parameter, will call ``perm_function``
with ``full_permissions`` list.
:param func perm_func: Permissions function to be applied
:param list params: list of params to be allpied
:param entity: user or group to be passed to ``perm_func``
:type entity: `~django.contrib.auth.models.User` or
`~django.contrib.auth.models.Group`
"""
if perms == 'ALL':
perms = full_permissions
for perm in perms:
perm_codename = get_full_perm(perm, obj)
if perm_codename not in full_permissions:
raise exceptions.ParseError("Unknown permission: {}".format(perm))
perm_func(perm_codename, entity, obj)
def set_permissions(entity_type, perm_type):
"""Set object permissions."""
perm_func = assign_perm if perm_type == 'add' else remove_perm
fetch_fn = fetch_user if entity_type == 'users' else fetch_group
for entity_id in data.get(entity_type, {}).get(perm_type, []):
entity = fetch_fn(entity_id)
if entity:
perms = data[entity_type][perm_type][entity_id]
apply_perm(perm_func, perms, entity)
def set_public_permissions(perm_type):
"""Set public permissions."""
perm_func = assign_perm if perm_type == 'add' else remove_perm
user = AnonymousUser()
perms = data.get('public', {}).get(perm_type, [])
apply_perm(perm_func, perms, user)
with transaction.atomic():
set_permissions('users', 'add')
set_permissions('users', 'remove')
set_permissions('groups', 'add')
set_permissions('groups', 'remove')
set_public_permissions('add')
set_public_permissions('remove') | [
"def",
"update_permission",
"(",
"obj",
",",
"data",
")",
":",
"full_permissions",
"=",
"get_all_perms",
"(",
"obj",
")",
"def",
"apply_perm",
"(",
"perm_func",
",",
"perms",
",",
"entity",
")",
":",
"\"\"\"Apply permissions using given ``perm_func``.\n\n ``per... | Update object permissions. | [
"Update",
"object",
"permissions",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/permissions/utils.py#L150-L207 | train | 45,195 |
genialis/resolwe | resolwe/permissions/utils.py | assign_contributor_permissions | def assign_contributor_permissions(obj, contributor=None):
"""Assign all permissions to object's contributor."""
for permission in get_all_perms(obj):
assign_perm(permission, contributor if contributor else obj.contributor, obj) | python | def assign_contributor_permissions(obj, contributor=None):
"""Assign all permissions to object's contributor."""
for permission in get_all_perms(obj):
assign_perm(permission, contributor if contributor else obj.contributor, obj) | [
"def",
"assign_contributor_permissions",
"(",
"obj",
",",
"contributor",
"=",
"None",
")",
":",
"for",
"permission",
"in",
"get_all_perms",
"(",
"obj",
")",
":",
"assign_perm",
"(",
"permission",
",",
"contributor",
"if",
"contributor",
"else",
"obj",
".",
"co... | Assign all permissions to object's contributor. | [
"Assign",
"all",
"permissions",
"to",
"object",
"s",
"contributor",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/permissions/utils.py#L210-L213 | train | 45,196 |
genialis/resolwe | resolwe/flow/managers/listener.py | ExecutorListener._make_connection | async def _make_connection(self):
"""Construct a connection to Redis."""
return await aioredis.create_redis(
'redis://{}:{}'.format(
self._redis_params.get('host', 'localhost'),
self._redis_params.get('port', 6379)
),
db=int(self._redis_params.get('db', 1))
) | python | async def _make_connection(self):
"""Construct a connection to Redis."""
return await aioredis.create_redis(
'redis://{}:{}'.format(
self._redis_params.get('host', 'localhost'),
self._redis_params.get('port', 6379)
),
db=int(self._redis_params.get('db', 1))
) | [
"async",
"def",
"_make_connection",
"(",
"self",
")",
":",
"return",
"await",
"aioredis",
".",
"create_redis",
"(",
"'redis://{}:{}'",
".",
"format",
"(",
"self",
".",
"_redis_params",
".",
"get",
"(",
"'host'",
",",
"'localhost'",
")",
",",
"self",
".",
"... | Construct a connection to Redis. | [
"Construct",
"a",
"connection",
"to",
"Redis",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/managers/listener.py#L84-L92 | train | 45,197 |
genialis/resolwe | resolwe/flow/managers/listener.py | ExecutorListener._call_redis | async def _call_redis(self, meth, *args, **kwargs):
"""Perform a Redis call and handle connection dropping."""
while True:
try:
if not self._redis:
self._redis = await self._make_connection()
return await meth(self._redis, *args, **kwargs)
except aioredis.RedisError:
logger.exception("Redis connection error")
if self._redis:
self._redis.close()
await self._redis.wait_closed()
self._redis = None
await asyncio.sleep(3) | python | async def _call_redis(self, meth, *args, **kwargs):
"""Perform a Redis call and handle connection dropping."""
while True:
try:
if not self._redis:
self._redis = await self._make_connection()
return await meth(self._redis, *args, **kwargs)
except aioredis.RedisError:
logger.exception("Redis connection error")
if self._redis:
self._redis.close()
await self._redis.wait_closed()
self._redis = None
await asyncio.sleep(3) | [
"async",
"def",
"_call_redis",
"(",
"self",
",",
"meth",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"while",
"True",
":",
"try",
":",
"if",
"not",
"self",
".",
"_redis",
":",
"self",
".",
"_redis",
"=",
"await",
"self",
".",
"_make_connec... | Perform a Redis call and handle connection dropping. | [
"Perform",
"a",
"Redis",
"call",
"and",
"handle",
"connection",
"dropping",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/managers/listener.py#L94-L107 | train | 45,198 |
genialis/resolwe | resolwe/flow/managers/listener.py | ExecutorListener.clear_queue | async def clear_queue(self):
"""Reset the executor queue channel to an empty state."""
conn = await self._make_connection()
try:
script = """
local keys = redis.call('KEYS', ARGV[1])
redis.call('DEL', unpack(keys))
"""
await conn.eval(
script,
keys=[],
args=['*{}*'.format(settings.FLOW_MANAGER['REDIS_PREFIX'])],
)
finally:
conn.close() | python | async def clear_queue(self):
"""Reset the executor queue channel to an empty state."""
conn = await self._make_connection()
try:
script = """
local keys = redis.call('KEYS', ARGV[1])
redis.call('DEL', unpack(keys))
"""
await conn.eval(
script,
keys=[],
args=['*{}*'.format(settings.FLOW_MANAGER['REDIS_PREFIX'])],
)
finally:
conn.close() | [
"async",
"def",
"clear_queue",
"(",
"self",
")",
":",
"conn",
"=",
"await",
"self",
".",
"_make_connection",
"(",
")",
"try",
":",
"script",
"=",
"\"\"\"\n local keys = redis.call('KEYS', ARGV[1])\n redis.call('DEL', unpack(keys))\n \"\"... | Reset the executor queue channel to an empty state. | [
"Reset",
"the",
"executor",
"queue",
"channel",
"to",
"an",
"empty",
"state",
"."
] | f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86 | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/managers/listener.py#L109-L123 | train | 45,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.