code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
obj_pyxb.sort(key=lambda x: [get_auto(getattr(x, n)) for n in child_name_list])
def sort_elements_by_child_values(obj_pyxb, child_name_list)
In-place sort simple or complex elements in a PyXB object by values they contain in child elements. Args: obj_pyxb: PyXB object child_name_list: list of str List of element names that are direct children of the PyXB object.
4.760674
6.384637
0.745645
return '\n'.join( difflib.ndiff( serialize_to_xml_str(a_pyxb).splitlines(), serialize_to_xml_str(b_pyxb).splitlines(), ) )
def format_diff_pyxb(a_pyxb, b_pyxb)
Create a diff between two PyXB objects. Args: a_pyxb: PyXB object b_pyxb: PyXB object Returns: str : `Differ`-style delta
2.415821
3.070676
0.786739
return '\n'.join( difflib.ndiff( reformat_to_pretty_xml(a_xml).splitlines(), reformat_to_pretty_xml(b_xml).splitlines(), ) )
def format_diff_xml(a_xml, b_xml)
Create a diff between two XML documents. Args: a_xml: str b_xml: str Returns: str : `Differ`-style delta
2.685943
3.528938
0.761119
v = getattr(obj_pyxb, attr_str, default_val) return v if v is not None else default_val
def get_opt_attr(obj_pyxb, attr_str, default_val=None)
Get an optional attribute value from a PyXB element. The attributes for elements that are optional according to the schema and not set in the PyXB object are present and set to None. PyXB validation will fail if required elements are missing. Args: obj_pyxb: PyXB object attr_str: str ...
2.652152
4.013228
0.660852
try: return get_req_val(getattr(obj_pyxb, attr_str)) except (ValueError, AttributeError): return default_val
def get_opt_val(obj_pyxb, attr_str, default_val=None)
Get an optional Simple Content value from a PyXB element. The attributes for elements that are optional according to the schema and not set in the PyXB object are present and set to None. PyXB validation will fail if required elements are missing. Args: obj_pyxb: PyXB object attr_str: st...
3.694216
5.014246
0.736744
response = exception_handler(exc, context) if isinstance(exc, ValidationError): if response is None: response = Response({}) response.status_code = 400 response.data['error'] = exc.message return response
def resolwe_exception_handler(exc, context)
Handle exceptions raised in API and make them nicer. To enable this, you have to add it to the settings: .. code:: python REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'resolwe.flow.utils.exceptions.resolwe_exception_handler', }
3.021506
3.623486
0.833867
public_key = cert_obj.public_key() message = '.'.join(d1_common.cert.jwt.get_bu64_tup(jwt_bu64)[:2]) signature = d1_common.cert.jwt.get_jwt_tup(jwt_bu64)[2] try: public_key.verify( signature, message, cryptography.hazmat.primitives.asymmetric.padding.PKCS...
def validate_and_decode(jwt_bu64, cert_obj)
Example for validating the signature of a JWT using only the cryptography library. Note that this does NOT validate the claims in the claim set.
2.399363
2.507352
0.956931
for cert_file_name in cert_file_name_list: cert_pem = '' # self.test_files.load_utf8_to_str(cert_file_name) cert_obj = d1_common.cert.x509.deserialize_pem(cert_pem) # d1_common.cert.x509.log_cert_info(logging.info, 'CERT', cert_obj) for jwt_file_name in jwt_file_name_list: ...
def find_valid_combinations(cert_file_name_list, jwt_file_name_list)
Given a list of cert and JWT file names, print a list showing each combination along with indicators for combinations where the JWT signature was successfully validated with the cert.
2.53596
2.530414
1.002192
scheme, netloc, url, params, query, fragment = urllib.parse.urlparse(url) query_dict = { k: sorted(v) if len(v) > 1 else v[0] for k, v in list(urllib.parse.parse_qs(query).items()) } return { 'scheme': scheme, 'netloc': netloc, 'url': url, 'params': p...
def parseUrl(url)
Return a dict containing scheme, netloc, url, params, query, fragment keys. query is a dict where the values are always lists. If the query key appears only once in the URL, the list will have a single value.
2.002512
1.776731
1.127077
return urllib.parse.quote( ( element.encode('utf-8') if isinstance(element, str) else str(element) if isinstance(element, int) else element ), safe=d1_common.const.URL_PATHELEMENT_SAFE_CHARS, )
def encodePathElement(element)
Encode a URL path element according to RFC3986.
3.374725
3.347098
1.008254
return urllib.parse.quote( ( element.encode('utf-8') if isinstance(element, str) else str(element) if isinstance(element, int) else element ), safe=d1_common.const.URL_QUERYELEMENT_SAFE_CHARS, )
def encodeQueryElement(element)
Encode a URL query element according to RFC3986.
3.352796
3.303687
1.014865
if hasattr(query, "items"): # Remove None parameters from query. Dictionaries are mutable, so we can # remove the the items directly. dict.keys() creates a copy of the # dictionary keys, making it safe to remove elements from the dictionary # while iterating. for k in li...
def urlencode(query, doseq=0)
Modified version of the standard urllib.urlencode that is conforms to RFC3986. The urllib version encodes spaces as '+' which can lead to inconsistency. This version will always encode spaces as '%20'. Encode a sequence of two-element tuples or dictionary into a URL query string. If any values in the ...
3.34732
3.301139
1.013989
o = urllib.parse.urlparse(url, scheme=d1_common.const.DEFAULT_CN_PROTOCOL) if o.netloc and o.path: netloc = o.netloc path = o.path elif o.netloc: netloc = o.netloc path = d1_common.const.DEFAULT_CN_PATH elif o.path: s = o.path.split('/', 1) netloc = s...
def makeCNBaseURL(url)
Attempt to create a valid CN BaseURL when one or more sections of the URL are missing.
1.71759
1.743596
0.985085
o = urllib.parse.urlparse(url, scheme=d1_common.const.DEFAULT_MN_PROTOCOL) if o.netloc and o.path: netloc = o.netloc path = o.path elif o.netloc: netloc = o.netloc path = d1_common.const.DEFAULT_MN_PATH elif o.path: s = o.path.split('/', 1) netloc = s...
def makeMNBaseURL(url)
Attempt to create a valid MN BaseURL when one or more sections of the URL are missing.
1.727863
1.737745
0.994313
diff_list = [] a_parts = urllib.parse.urlparse(a_url) b_parts = urllib.parse.urlparse(b_url) # scheme if a_parts.scheme.lower() != b_parts.scheme.lower(): diff_list.append( 'Schemes differ. a="{}" b="{}" differ'.format( a_parts.scheme.lower(), b_parts.scheme....
def find_url_mismatches(a_url, b_url)
Given two URLs, return a list of any mismatches. If the list is empty, the URLs are equivalent. Implemented by parsing and comparing the elements. See RFC 1738 for details.
1.441246
1.438752
1.001734
args = parse_arguments() ext = os.path.splitext(args.input_file)[-1].lower() with gzip.open(args.output_file, mode='wt') as outfile: csvwriter = csv.writer(outfile, delimiter=str('\t'), lineterminator='\n') try: if ext in ('.tab', '.txt', '.tsv'): with open...
def main()
Run the program.
2.243608
2.221203
1.010087
if self._session.get(d1_cli.impl.session.QUERY_ENGINE_NAME) == "solr": return self._search_solr(line) raise d1_cli.impl.exceptions.InvalidArguments( "Unsupported query engine: {}".format( self._session.get(d1_cli.impl.session.QUERY_ENGINE_NAME) ...
def search(self, line)
CN search.
3.729569
3.648796
1.022137
client = d1_cli.impl.client.CLICNClient( **self._cn_client_connect_params_from_session() ) object_location_list_pyxb = client.resolve(pid) for location in object_location_list_pyxb.objectLocation: d1_cli.impl.util.print_info(location.url)
def resolve(self, pid)
Get Object Locations for Object.
6.902953
6.141154
1.124048
mn_client = d1_cli.impl.client.CLIMNClient( **self._mn_client_connect_params_from_session() ) try: response = mn_client.get(pid) except d1_common.types.exceptions.DataONEException: pass else: self._output(response, path) ...
def science_object_get(self, pid, path)
First try the MN set in the session. Then try to resolve via the CN set in the session.
2.483369
2.280071
1.089163
self._queue_science_object_create(pid, path, format_id)
def science_object_create(self, pid, path, format_id=None)
Create a new Science Object on a Member Node.
4.90522
6.162417
0.79599
self._queue_science_object_update(pid_old, path, pid_new, format_id)
def science_object_update(self, pid_old, path, pid_new, format_id=None)
Obsolete a Science Object on a Member Node with a different one.
3.420385
3.351037
1.020695
if not path: self._output_to_display(file_like_object) else: self._output_to_file(file_like_object, path)
def _output(self, file_like_object, path=None)
Display or save file like object.
2.679844
2.204824
1.215445
try: query_str = self._create_solr_query(line) client = d1_cli.impl.client.CLICNClient( **self._cn_client_connect_params_from_session() ) object_list_pyxb = client.search( queryType=d1_common.const.DEFAULT_SEARCH_ENGINE, ...
def _search_solr(self, line)
Perform a SOLR search.
3.432875
3.424922
1.002322
p0 = "" if line: p0 = line.strip() p1 = self._query_string_to_solr_filter(line) p2 = self._object_format_to_solr_filter(line) p3 = self._time_span_to_solr_filter() result = p0 + p1 + p2 + p3 return result.strip()
def _create_solr_query(self, line)
Actual search - easier to test.
3.753002
3.586825
1.04633
if isinstance(obj, (list, tuple)): return [func(item) for item in obj] return func(obj)
def apply_filter_list(func, obj)
Apply `func` to list or tuple `obj` element-wise and directly otherwise.
2.587831
2.193507
1.179769
if isinstance(data, dict): # `Data` object's id is hydrated as `__id` in expression engine data = data['__id'] data_obj = Data.objects.get(id=data) return getattr(data_obj, attr)
def _get_data_attr(data, attr)
Get data object field.
8.697351
7.605856
1.143507
data_obj = Data.objects.get(id=data['__id']) inputs = copy.deepcopy(data_obj.input) # XXX: Optimize by hydrating only the required field (major refactoring). hydrate_input_references(inputs, data_obj.process.input_schema) hydrate_input_uploads(inputs, data_obj.process.input_schema) return...
def input_(data, field_path)
Return a hydrated value of the ``input`` field.
7.571592
6.762482
1.119647
# Get only file path if whole file object is given. if isinstance(field, str) and hasattr(field, 'file_name'): # field is already actually a HydratedPath object return field if isinstance(field, dict) and 'file' in field: hydrated_path = field['file'] if not hasattr(hydrat...
def _get_hydrated_path(field)
Return HydratedPath object for file-type field.
5.561528
4.489708
1.238728
hydrated_path = _get_hydrated_path(field) base_url = getattr(settings, 'RESOLWE_HOST_URL', 'localhost') return "{}/data/{}/{}".format(base_url, hydrated_path.data_id, hydrated_path.file_name)
def get_url(field)
Return file's url based on base url set in settings.
4.752645
4.358572
1.090413
if isinstance(obj, dict): # Current object is hydrated, so we need to get descriptor from # dict representation. desc = obj['__descriptor'] else: desc = obj.descriptor resp = dict_dot(desc, path) if isinstance(resp, list) or isinstance(resp, dict): return j...
def descriptor(obj, path='')
Return descriptor of given object. If ``path`` is specified, only the content on that path is returned.
5.788188
6.231341
0.928883
date_ranges = (('beginDate', 'endDate'),) for begin, end in date_ranges: if begin in record and end in record: return elif begin in record: record[end] = record[begin] elif end in record: record[begin] = record[...
def _close_open_date_ranges(self, record)
If a date range is missing the start or end date, close it by copying the date from the existing value.
2.71899
2.511546
1.082596
reserved = [ '+', '-', '&', '|', '!', '(', ')', '{', '}', '[', ']', '^', '"', '~', '*', '?', ':', ...
def escapeQueryTerm(self, term)
+ - && || ! ( ) { } [ ] ^ " ~ * ? : \
2.317497
2.037908
1.137194
if term == "*": return term addstar = False if term[len(term) - 1] == '*': addstar = True term = term[0 : len(term) - 1] term = self.escapeQueryTerm(term) if addstar: term = '%s*' % term if self.getSolrType(field) i...
def prepareQueryTerm(self, field, term)
Prepare a query term for inclusion in a query. This escapes the term and if necessary, wraps the term in quotes.
3.176637
3.105787
1.022812
if value is None: return None if ftype == 'string': return str(value) elif ftype == 'text': return str(value) elif ftype == 'int': try: v = int(value) return str(v) except Exception: ...
def coerceType(self, ftype, value)
Returns unicode(value) after trying to coerce it into the SOLR field type. @param ftype(string) The SOLR field type for the value @param value(any) The value that is to be represented as Unicode text.
1.789629
1.852864
0.965872
ftype = 'string' try: ftype = self.fieldtypes[field] return ftype except Exception: pass fta = field.split('_') if len(fta) > 1: ft = fta[len(fta) - 1] try: ftype = self.fieldtypes[ft] ...
def getSolrType(self, field)
Returns the SOLR type of the specified field name. Assumes the convention of dynamic fields using an underscore + type character code for the field name.
3.143931
3.142681
1.000398
lst = ['<add>'] for fields in docs: self.__add(lst, fields) lst.append('</add>') xstr = ''.join(lst) return self.doUpdateXML(xstr)
def addDocs(self, docs)
docs is a list of fields that are a dictionary of name:value for a record.
6.395068
6.122314
1.044551
params = {'q': q, 'rows': '0'} if fq is not None: params['fq'] = fq res = self.search(params) hits = res['response']['numFound'] return hits
def count(self, q='*:*', fq=None)
Return the number of entries that match query.
2.449692
2.384668
1.027268
params = {'q': query, 'start': str(start), 'rows': str(rows), 'wt': 'python'} if fq is not None: params['fq'] = fq request = urllib.parse.urlencode(params, doseq=True) data = None response = {'matches': 0, 'start': start, 'failed': True, 'ids': []} tr...
def getIds(self, query='*:*', fq=None, start=0, rows=1000)
Returns a dictionary of: matches: number of matches failed: if true, then an exception was thrown start: starting index ids: [id, id, ...] See also the SOLRSearchResponseIterator class
2.778691
2.602106
1.067862
params = {'q': 'id:%s' % str(id), 'wt': 'python'} request = urllib.parse.urlencode(params, doseq=True) data = None try: rsp = self.doPost(self.solrBase + '', request, self.formheaders) data = eval(rsp.read()) except Exception: pass ...
def get(self, id)
Retrieves the specified document.
4.114136
3.965731
1.037422
if self._fields is not None: return self._fields params = {'numTerms': str(numTerms), 'wt': 'python'} request = urllib.parse.urlencode(params, doseq=True) rsp = self.doPost(self.solrBase + '/admin/luke', request, self.formheaders) data = eval(rsp.read()) ...
def getFields(self, numTerms=1)
Retrieve a list of fields. The response looks something like: { 'responseHeader':{ 'status':0, 'QTime':44}, 'index':{ 'numDocs':2000, 'maxDoc':2000, 'numTerms':23791, 'version':1227298371173, 'optimized':True, 'current':True, 'hasDeletions':False, 'directory':'org.apache.lucen...
4.625407
5.170517
0.894573
params = { 'q': q, 'rows': '0', 'facet': 'true', 'facet.field': name, 'facet.limit': str(maxvalues), 'facet.zeros': 'false', 'wt': 'python', 'facet.sort': 'false', } if fq is not None: ...
def fieldValues(self, name, q="*:*", fq=None, maxvalues=-1)
Retrieve the unique values for a field, along with their usage counts. http://localhost:8080/solr/select/?q=*:*&rows=0&facet=true&inde nt=on&wt=python&facet.field=genus_s&facet.limit=10&facet.zeros=false&fa cet.sort=false. @param name(string) Name of field to retrieve values for ...
3.080583
2.54191
1.211917
minmax = [None, None] oldpersist = self.persistent self.persistent = True params = { 'q': q, 'rows': 1, 'fl': name, 'sort': '%s asc' % name, 'wt': 'python', } if fq is not None: params['fq'] ...
def fieldMinMax(self, name, q='*:*', fq=None)
Returns the minimum and maximum values of the specified field. This requires two search calls to the service, each requesting a single value of a single field. @param name(string) Name of the field @param q(string) Query identifying range of records for min and max values @param...
2.269094
2.478139
0.915645
fields = self.getFields() try: fld = fields['fields'][name] except Exception: return str if fld['type'] in ['string', 'text', 'stext', 'text_ws']: return str if fld['type'] in ['sint', 'integer', 'long', 'slong']: return in...
def getftype(self, name)
Returns the python type for the specified field name. The field list is cached so multiple calls do not invoke a getFields request each time. @param name(string) The name of the SOLR field @returns Python type of the field.
3.38583
3.117823
1.08596
oldpersist = self.persistent self.persistent = True ftype = self.getftype(name) if ftype == str: ##handle text histograms over here bins = self.fieldAlphaHistogram( name, q=q, fq=fq, nbins=nbins, includequeries=includequeries )...
def fieldHistogram( self, name, q="*:*", fq=None, nbins=10, minmax=None, includequeries=True )
Generates a histogram of values. Expects the field to be integer or floating point. @param name(string) Name of the field to compute @param q(string) The query identifying the set of records for the histogram @param fq(string) Filter query to restrict application of query @param...
2.33803
2.314234
1.010283
self.logger.debug("Iterator crecord=%s" % str(self.crecord)) params = { 'q': self.q, 'start': str(offset), 'rows': str(self.pagesize), 'fl': self.fields, 'explainOther': '', 'hl.fl': '', } if self.fq is not ...
def _nextPage(self, offset)
Retrieves the next set of results from the service.
4.284767
4.284723
1.00001
self.logger.debug("Iterator crecord=%s" % str(self.crecord)) params = { 'q': self.q, 'rows': '0', 'facet': 'true', 'facet.field': self.field, 'facet.limit': str(self.pagesize), 'facet.offset': str(offset), 'fac...
def _nextPage(self, offset)
Retrieves the next set of results from the service.
3.644775
3.656154
0.996888
response = d1_gmn.app.views.util.http_response_with_boolean_true_type() d1_gmn.app.views.headers.add_http_date_header(response) return response
def get_monitor_ping(request)
MNCore.ping() → Boolean.
7.505424
8.309451
0.90324
query = d1_gmn.app.models.EventLog.objects.all().order_by('timestamp', 'id') if not d1_gmn.app.auth.is_trusted_subject(request): query = d1_gmn.app.db_filter.add_access_policy_filter( request, query, 'sciobj__id' ) query = d1_gmn.app.db_filter.add_redact_annotation(reque...
def get_log(request)
MNCore.getLogRecords(session[, fromDate][, toDate][, idFilter][, event] [, start=0][, count=1000]) → Log Sorted by timestamp, id.
2.4963
2.456771
1.01609
api_major_int = 2 if d1_gmn.app.views.util.is_v2_api(request) else 1 node_pretty_xml = d1_gmn.app.node.get_pretty_xml(api_major_int) return django.http.HttpResponse(node_pretty_xml, d1_common.const.CONTENT_TYPE_XML)
def get_node(request)
MNCore.getCapabilities() → Node.
4.280892
4.735185
0.90406
sciobj = d1_gmn.app.models.ScienceObject.objects.get(pid__did=pid) content_type_str = d1_gmn.app.object_format_cache.get_content_type( sciobj.format.format ) # Return local or proxied SciObj bytes response = django.http.StreamingHttpResponse( _get_sciobj_iter(sciobj), content_ty...
def get_object(request, pid)
MNRead.get(session, did) → OctetStream.
4.535278
4.654851
0.974312
d1_gmn.app.event_log.log_read_event(pid, request) return django.http.HttpResponse( d1_gmn.app.views.util.generate_sysmeta_xml_matching_api_version(request, pid), d1_common.const.CONTENT_TYPE_XML, )
def get_meta(request, pid)
MNRead.getSystemMetadata(session, pid) → SystemMetadata.
5.045934
5.068337
0.99558
sciobj = d1_gmn.app.models.ScienceObject.objects.get(pid__did=pid) response = django.http.HttpResponse() d1_gmn.app.views.headers.add_sciobj_properties_headers_to_response(response, sciobj) d1_gmn.app.event_log.log_read_event(pid, request) return response
def head_object(request, pid)
MNRead.describe(session, did) → DescribeResponse.
3.913303
4.542655
0.861457
# MNRead.getChecksum() requires that a new checksum be calculated. Cannot # simply return the checksum from the sysmeta. # # If the checksumAlgorithm argument was not provided, it defaults to # the system wide default checksum algorithm. algorithm = request.GET.get( 'checksumAlgorit...
def get_checksum(request, pid)
MNRead.getChecksum(session, did[, checksumAlgorithm]) → Checksum.
4.343811
4.032005
1.077333
d1_gmn.app.views.assert_db.post_has_mime_parts(request, (('file', 'message'),)) try: synchronization_failed = d1_gmn.app.views.util.deserialize( request.FILES['message'] ) except d1_common.types.exceptions.DataONEException as e: # In v1, MNRead.synchronizationFailed(...
def post_error(request)
MNRead.synchronizationFailed(session, message)
5.497197
4.904506
1.120846
_assert_node_is_authorized(request, pid) sciobj = d1_gmn.app.models.ScienceObject.objects.get(pid__did=pid) content_type_str = d1_gmn.app.object_format_cache.get_content_type( sciobj.format.format ) # Replica is always a local file that can be handled with FileResponse() response = ...
def get_replica(request, pid)
MNReplication.getReplica(session, did) → OctetStream.
4.498991
4.702277
0.956769
if django.conf.settings.REQUIRE_WHITELIST_FOR_UPDATE: d1_gmn.app.auth.assert_create_update_delete_permission(request) d1_gmn.app.util.coerce_put_post(request) d1_gmn.app.views.assert_db.post_has_mime_parts( request, (('field', 'pid'), ('file', 'sysmeta')) ) pid = request.POST['p...
def put_meta(request)
MNStorage.updateSystemMetadata(session, pid, sysmeta) → boolean. TODO: Currently, this call allows making breaking changes to SysMeta. We need to clarify what can be modified and what the behavior should be when working with SIDs and chains.
4.110976
4.18635
0.981995
if 'action' not in request.GET: raise d1_common.types.exceptions.InvalidRequest( 0, 'Missing required parameter. required="action"' ) # Convert action string to action level. Raises InvalidRequest if the # action string is not valid. level = d1_gmn.app.auth.action_to_lev...
def get_is_authorized(request, pid)
MNAuthorization.isAuthorized(did, action) -> Boolean.
4.443791
4.401344
1.009644
d1_gmn.app.views.assert_db.post_has_mime_parts( request, ( ('field', 'pid'), ('field', 'serialVersion'), ('field', 'dateSysMetaLastModified'), ), ) d1_gmn.app.views.assert_db.is_existing_object(request.POST['pid']) d1_gmn.app.models.sysmet...
def post_refresh_system_metadata(request)
MNStorage.systemMetadataChanged(session, did, serialVersion, dateSysMetaLastModified) → boolean.
5.404886
4.801567
1.12565
d1_gmn.app.views.assert_db.post_has_mime_parts( request, (('field', 'pid'), ('file', 'object'), ('file', 'sysmeta')) ) url_pid = request.POST['pid'] sysmeta_pyxb = d1_gmn.app.sysmeta.deserialize(request.FILES['sysmeta']) d1_gmn.app.views.assert_sysmeta.obsoletes_not_specified(sysmeta_py...
def post_object_list(request)
MNStorage.create(session, did, object, sysmeta) → Identifier.
4.248558
3.930028
1.08105
if django.conf.settings.REQUIRE_WHITELIST_FOR_UPDATE: d1_gmn.app.auth.assert_create_update_delete_permission(request) d1_gmn.app.util.coerce_put_post(request) d1_gmn.app.views.assert_db.post_has_mime_parts( request, (('field', 'newPid'), ('file', 'object'), ('file', 'sysmeta')) ) ...
def put_object(request, old_pid)
MNStorage.update(session, pid, object, newPid, sysmeta) → Identifier.
3.623089
3.579222
1.012256
d1_gmn.app.views.assert_db.post_has_mime_parts(request, (('field', 'scheme'),)) if request.POST['scheme'] != 'UUID': raise d1_common.types.exceptions.InvalidRequest( 0, 'Only the UUID scheme is currently supported' ) fragment = request.POST.get('fragment', None) while Tr...
def post_generate_identifier(request)
MNStorage.generateIdentifier(session, scheme[, fragment]) → Identifier.
6.006196
5.874226
1.022466
d1_gmn.app.views.assert_db.is_not_replica(pid) d1_gmn.app.views.assert_db.is_not_archived(pid) d1_gmn.app.sysmeta.archive_sciobj(pid) return pid
def put_archive(request, pid)
MNStorage.archive(session, did) → Identifier.
5.146131
5.094132
1.010208
d1_gmn.app.views.assert_db.post_has_mime_parts( request, (('field', 'sourceNode'), ('file', 'sysmeta')) ) sysmeta_pyxb = d1_gmn.app.sysmeta.deserialize(request.FILES['sysmeta']) d1_gmn.app.local_replica.assert_request_complies_with_replication_policy( sysmeta_pyxb ) pid = d1...
def post_replicate(request)
MNReplication.replicate(session, sysmeta, sourceNode) → boolean.
5.257557
4.742857
1.108521
self.name = name self.process = process fields[name] = self
def contribute_to_class(self, process, fields, name)
Register this field with a specific process. :param process: Process descriptor instance :param fields: Fields registry to use :param name: Field name
4.56568
5.043519
0.905257
if not self.name or not self.process: raise ValueError("field is not registered with process") schema = { 'name': self.name, 'type': self.get_field_type(), } if self.required is not None: schema['required'] = self.required ...
def to_schema(self)
Return field schema for this field.
2.064338
1.888872
1.092894
if self.required and value is None: raise ValidationError("field is required") if value is not None and self.choices is not None: choices = [choice for choice, _ in self.choices] if value not in choices: raise ValidationError("field must be o...
def validate(self, value)
Validate field value.
2.697589
2.573463
1.048233
if value is None: value = self.default try: value = self.to_python(value) self.validate(value) except ValidationError as error: raise ValidationError("invalid value for {}: {}".format( self.name, error.args...
def clean(self, value)
Run validators and return the clean value.
2.974086
2.736416
1.086854
if value is not None and not isinstance(value, str): raise ValidationError("field must be a string") super().validate(value)
def validate(self, value)
Validate field value.
4.179592
3.485853
1.199016
if value is not None and not isinstance(value, bool): raise ValidationError("field must be a boolean") super().validate(value)
def validate(self, value)
Validate field value.
4.358795
3.619452
1.204269
return json.loads(resolwe_runtime_utils.save(self.name, str(value)))
def to_output(self, value)
Convert value to process output format.
22.177603
19.883512
1.115377
if isinstance(value, str): return value elif isinstance(value, dict): try: value = value['url'] except KeyError: raise ValidationError("dictionary must contain an 'url' element") if not isinstance(value, str): ...
def to_python(self, value)
Convert value if needed.
3.298661
3.271301
1.008364
if not hasattr(resolwe_runtime_utils, 'import_file'): raise RuntimeError('Requires resolwe-runtime-utils >= 2.0.0') if imported_format is None: imported_format = resolwe_runtime_utils.ImportedFormat.BOTH return resolwe_runtime_utils.import_file( src...
def import_file(self, imported_format=None, progress_from=0.0, progress_to=None)
Import field source file to working directory. :param imported_format: Import file format (extracted, compressed or both) :param progress_from: Initial progress value :param progress_to: Final progress value :return: Destination file path (if extracted and compressed, extracted path giv...
3.274963
3.428161
0.955312
if isinstance(value, FileDescriptor): return value elif isinstance(value, str): return FileDescriptor(value) elif isinstance(value, dict): try: path = value['file'] except KeyError: raise ValidationError("di...
def to_python(self, value)
Convert value if needed.
1.799141
1.787663
1.006421
return json.loads(resolwe_runtime_utils.save_file(self.name, value.path, *value.refs))
def to_output(self, value)
Convert value to process output format.
24.825335
24.726328
1.004004
if isinstance(value, DirDescriptor): return value elif isinstance(value, str): return DirDescriptor(value) elif isinstance(value, dict): try: path = value['dir'] except KeyError: raise ValidationError("dicti...
def to_python(self, value)
Convert value if needed.
2.112442
2.102147
1.004897
super().contribute_to_class(process, fields, name) self.inner.name = name self.inner.process = process
def contribute_to_class(self, process, fields, name)
Register this field with a specific process. :param process: Process descriptor instance :param fields: Fields registry to use :param name: Field name
3.908642
5.524185
0.707551
return {self.name: [self.inner.to_output(v)[self.name] for v in value]}
def to_output(self, value)
Convert value to process output format.
6.82809
6.523723
1.046655
if value is not None: if not isinstance(value, list): raise ValidationError("field must be a list") for index, element in enumerate(value): try: self.inner.validate(element) except ValidationError as error: ...
def validate(self, value)
Validate field value.
2.823823
2.680156
1.053604
self._populate_cache() if key not in self._cache: raise AttributeError("DataField has no member {}".format(key)) return self._cache[key]
def _get(self, key)
Return given key from cache.
6.380534
5.60918
1.137516
cache = None if value is None: return None if isinstance(value, DataDescriptor): return value elif isinstance(value, dict): # Allow pre-hydrated data objects. cache = value try: value = cache['__id'] ...
def to_python(self, value)
Convert value if needed.
6.006753
5.877813
1.021937
# Use order-preserving definition namespace (__dict__) to respect the # order of GroupField's fields definition. for field_name in self.field_group.__dict__: if field_name.startswith('_'): continue field = getattr(self.field_group, field_name) ...
def contribute_to_class(self, process, fields, name)
Register this field with a specific process. :param process: Process descriptor instance :param fields: Fields registry to use :param name: Field name
4.624007
5.304072
0.871784
if isinstance(value, GroupDescriptor): value = value._value # pylint: disable=protected-access result = {} for name, field in self.fields.items(): result[name] = field.to_python(value.get(name, None)) return GroupDescriptor(result)
def to_python(self, value)
Convert value if needed.
3.214084
2.990041
1.074929
schema = super().to_schema() if self.disabled is not None: schema['disabled'] = self.disabled if self.collapsed is not None: schema['collapsed'] = self.collapsed group = [] for field in self.fields.values(): group.append(field.to_sche...
def to_schema(self)
Return field schema for this field.
2.713575
2.529499
1.072772
global MANAGER_CONTROL_CHANNEL, MANAGER_EXECUTOR_CHANNELS # pylint: disable=global-statement global MANAGER_LISTENER_STATS, MANAGER_STATE_PREFIX # pylint: disable=global-statement redis_prefix = getattr(settings, 'FLOW_MANAGER', {}).get('REDIS_PREFIX', '') MANAGER_CONTROL_CHANNEL = '{}.control'....
def update_constants()
Recreate channel name constants with changed settings. This kludge is mostly needed due to the way Django settings are patched for testing and how modules need to be imported throughout the project. On import time, settings are not patched yet, but some of the code needs static values immediately. Upda...
3.29719
3.369018
0.97868
for item_name in dir(self): item = getattr(self, item_name) if isinstance(item, self.RedisAtomicBase): self.redis.delete(item.item_name)
def destroy_channels(self)
Destroy Redis channels managed by this state instance.
5.544019
4.589719
1.207921
self._render_type = "file" self._tree.render( file_name=image_out_path, w=width_pixels, h=height_pixels, dpi=dpi, units="px", tree_style=self._get_tree_style(), )
def render_to_image_file( self, image_out_path, width_pixels=None, height_pixels=None, dpi=90 )
Render the SubjectInfo to an image file. Args: image_out_path : str Path to where image image will be written. Valid extensions are ``.svg,`` ``.pdf``, and ``.png``. width_pixels : int Width of image to write. height_pixels :...
3.46721
3.593528
0.964848
self._render_type = "browse" self._tree.show(tree_style=self._get_tree_style())
def browse_in_qt5_ui(self)
Browse and edit the SubjectInfo in a simple Qt5 based UI.
17.259893
15.040576
1.147555
for si_node in subject_info_tree.child_list: if si_node.type_str == TYPE_NODE_TAG: child = self._add_type_node(node, si_node.label_str) elif si_node.type_str == SUBJECT_NODE_TAG: child = self._add_subject_node(node, si_node.label_str) ...
def _gen_etetoolkit_tree(self, node, subject_info_tree)
Copy SubjectInfoTree to a ETE Tree.
2.779366
2.699248
1.029681
child = node.add_child(name=label) child.add_feature(TYPE_NODE_TAG, True) return child
def _add_type_node(self, node, label)
Add a node representing a SubjectInfo type.
6.965929
7.055712
0.987275
child = node.add_child(name=subj_str) child.add_feature(SUBJECT_NODE_TAG, True) return child
def _add_subject_node(self, node, subj_str)
Add a node containing a subject string.
6.675506
6.692063
0.997526
path = [] while node.up: path.append(node.name) node = node.up return list(reversed(path))
def _get_node_path(self, node)
Return the path from the root to ``node`` as a list of node names.
3.661031
2.86842
1.276323
def set_edge_style(): node_style = ete3.NodeStyle() node_style["vt_line_color"] = EDGE_COLOR node_style["hz_line_color"] = EDGE_COLOR node_style["vt_line_width"] = EDGE_WIDTH node_style["hz_line_width"] = EDGE_WIDTH n...
def _layout(self, node)
ETE calls this function to style each node before rendering. - ETE terms: - A Style is a specification for how to render the node itself - A Face defines extra information that is rendered outside of the node - Face objects are used here to provide more control on how to draw the nodes.
2.462105
2.328626
1.057321
process = Data.objects.get(pk=data_id).process if process.requirements.get('resources', {}).get('secrets', False): raise PermissionDenied( "Process which requires access to secrets cannot be run using the local executor" ) return super().extend_s...
def extend_settings(self, data_id, files, secrets)
Prevent processes requiring access to secrets from being run.
6.315183
4.802934
1.31486
finder_class = import_string(import_path) if not issubclass(finder_class, BaseProcessesFinder): raise ImproperlyConfigured( 'Finder "{}" is not a subclass of "{}"'.format(finder_class, BaseProcessesFinder)) return finder_class()
def get_finder(import_path)
Get a process finder.
3.143806
2.771599
1.134293
found_folders = [] for app_config in apps.get_app_configs(): folder_path = os.path.join(app_config.path, folder_name) if os.path.isdir(folder_path): found_folders.append(folder_path) return found_folders
def _find_folders(self, folder_name)
Return a list of sub-directories.
2.070051
1.947602
1.062872
_does_not_contain_replica_sections(sysmeta_pyxb) _is_not_archived(sysmeta_pyxb) _obsoleted_by_not_specified(sysmeta_pyxb) if 'HTTP_VENDOR_GMN_REMOTE_URL' in request.META: return _has_correct_file_size(request, sysmeta_pyxb) _is_supported_checksum_algorithm(sysmeta_pyxb) _is_corr...
def sanity(request, sysmeta_pyxb)
Check that sysmeta_pyxb is suitable for creating a new object and matches the uploaded sciobj bytes.
5.265505
5.329917
0.987915
sid = d1_common.xml.get_opt_val(sysmeta_pyxb, 'seriesId') if not d1_gmn.app.did.is_valid_sid_for_new_standalone(sid): raise d1_common.types.exceptions.IdentifierNotUnique( 0, 'Identifier is already in use as {}. did="{}"'.format( d1_gmn.app.did.classify_ident...
def is_valid_sid_for_new_standalone(sysmeta_pyxb)
Assert that any SID in ``sysmeta_pyxb`` can be assigned to a new standalone object.
3.930212
4.205337
0.934577
if not d1_gmn.app.did.is_valid_sid_for_chain(pid, sid): existing_sid = d1_gmn.app.revision.get_sid_by_pid(pid) raise d1_common.types.exceptions.IdentifierNotUnique( 0, 'A different SID is already assigned to the revision chain to which ' 'the object being cre...
def is_valid_sid_for_chain(pid, sid)
Assert that ``sid`` can be assigned to the single object ``pid`` or to the chain to which ``pid`` belongs. - If the chain does not have a SID, the new SID must be previously unused. - If the chain already has a SID, the new SID must match the existing SID.
4.185012
4.017262
1.041757
if len(getattr(sysmeta_pyxb, 'replica', [])): raise d1_common.types.exceptions.InvalidSystemMetadata( 0, 'A replica section was included. A new object object created via ' 'create() or update() cannot already have replicas. pid="{}"'.format( d1_common...
def _does_not_contain_replica_sections(sysmeta_pyxb)
Assert that ``sysmeta_pyxb`` does not contain any replica information.
4.921159
4.851364
1.014387
if _is_archived(sysmeta_pyxb): raise d1_common.types.exceptions.InvalidSystemMetadata( 0, 'Archived flag was set. A new object created via create() or update() ' 'cannot already be archived. pid="{}"'.format( d1_common.xml.get_req_val(sysmeta_pyxb.ide...
def _is_not_archived(sysmeta_pyxb)
Assert that ``sysmeta_pyxb`` does not have have the archived flag set.
4.005499
3.785487
1.05812