code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
while True: # Discover primary key to limit the current chunk. This is required because delete # cannot be called on a sliced queryset due to ordering requirement. with transaction.atomic(): # Get offset of last item (needed because it may be less tha...
def _delete_chunked(queryset, chunk_size=500)
Chunked delete, which should be used if deleting many objects. The reason why this method is needed is that deleting a lot of Data objects requires Django to fetch all of them into memory (fast path is not used) and this causes huge memory usage (and possibly OOM). :param chunk_size: O...
5.98462
6.247002
0.957999
bundle = [ {'original': data, 'copy': data.duplicate(contributor=contributor)} for data in self ] bundle = rewire_inputs(bundle) duplicated = [item['copy'] for item in bundle] return duplicated
def duplicate(self, contributor=None)
Duplicate (make a copy) ``Data`` objects. :param contributor: Duplication user
9.830378
9.816167
1.001448
for field_schema, fields in iterate_fields(instance, schema): name = field_schema['name'] value = fields[name] if field_schema.get('type', '').startswith('basic:json:'): if value and not self.pk: raise ValidationError( ...
def save_storage(self, instance, schema)
Save basic:json values to a Storage collection.
4.169903
3.985395
1.046296
secrets = {} for field_schema, fields in iterate_fields(self.input, self.process.input_schema): # pylint: disable=no-member if not field_schema.get('type', '').startswith('basic:secret:'): continue name = field_schema['name'] value = fields[...
def resolve_secrets(self)
Retrieve handles for all basic:secret: fields on input. The process must have the ``secrets`` resource requirement specified in order to access any secrets. Otherwise this method will raise a ``PermissionDenied`` exception. :return: A dictionary of secrets where key is the secret handl...
4.63238
3.963962
1.168624
def add_dependency(value): try: DataDependency.objects.update_or_create( parent=Data.objects.get(pk=value), child=self, defaults={'kind': DataDependency.KIND_IO}, ) except Da...
def save_dependencies(self, instance, schema)
Save data: and list:data: references as parents.
3.562764
3.272763
1.088611
entity_type = self.process.entity_type # pylint: disable=no-member entity_descriptor_schema = self.process.entity_descriptor_schema # pylint: disable=no-member entity_input = self.process.entity_input # pylint: disable=no-member if entity_type: data_filter = {} ...
def create_entity(self)
Create entity if `flow_collection` is defined in process. Following rules applies for adding `Data` object to `Entity`: * Only add `Data object` to `Entity` if process has defined `flow_collection` field * Add object to existing `Entity`, if all parents that are part of it (but ...
2.780629
2.741313
1.014342
self.named_by_user = True create = self.pk is None if create: fill_with_defaults(self.input, self.process.input_schema) # pylint: disable=no-member if not self.name: self._render_name() else: self.named_by_user = True ...
def save(self, render_name=False, *args, **kwargs): # pylint: disable=keyword-arg-before-vararg if self.name != self._original_name
Save the data model.
3.899683
3.805296
1.024804
# Store ids in memory as relations are also deleted with the Data object. storage_ids = list(self.storages.values_list('pk', flat=True)) # pylint: disable=no-member super().delete(*args, **kwargs) Storage.objects.filter(pk__in=storage_ids, data=None).delete()
def delete(self, *args, **kwargs)
Delete the data model.
6.209875
5.695576
1.090298
if self.status not in [self.STATUS_DONE, self.STATUS_ERROR]: raise ValidationError('Data object must have done or error status to be duplicated') duplicate = Data.objects.get(id=self.id) duplicate.pk = None duplicate.slug = None duplicate.name = 'Copy of {}'...
def duplicate(self, contributor=None)
Duplicate (make a copy).
2.764666
2.717388
1.017398
if not self.process.data_name or self.named_by_user: # pylint: disable=no-member return inputs = copy.deepcopy(self.input) hydrate_input_references(inputs, self.process.input_schema, hydrate_values=False) # pylint: disable=no-member template_context = inputs ...
def _render_name(self)
Render data name. The rendering is based on name template (`process.data_name`) and input context.
5.225809
4.4252
1.180921
prefix = prefix or settings.FLOW_EXECUTOR['DATA_DIR'] path = os.path.join(prefix, self.subpath) if filename: path = os.path.join(path, filename) return path
def get_path(self, prefix=None, filename=None)
Compose data location path.
4.239848
4.005684
1.058458
return self.get_path(prefix=settings.FLOW_EXECUTOR['RUNTIME_DIR'], filename=filename)
def get_runtime_path(self, filename=None)
Compose data runtime location path.
11.377709
10.03527
1.133772
data = self._filter_queryset('view_data', entity.data.all()) return self._serialize_data(data)
def get_data(self, entity)
Return serialized list of data objects on entity that user has `view` permission on.
11.985815
6.917908
1.732578
required_fields = ('slug', 'name', 'process_type', 'version') for field in required_fields: if getattr(self.metadata, field, None) is None: raise ValidationError("process '{}' is missing required meta attribute: {}".format( self.metadata.slug or '...
def validate(self)
Validate process descriptor.
3.598148
3.195824
1.125891
process_type = self.metadata.process_type if not process_type.endswith(':'): process_type = '{}:'.format(process_type) schema = { 'slug': self.metadata.slug, 'name': self.metadata.name, 'type': process_type, 'version': self.me...
def to_schema(self)
Return process schema for this process.
1.942063
1.899419
1.022451
if not getattr(settings, 'FLOW_DOCKER_DONT_PULL', False): call_command('list_docker_images', pull=True, verbosity=verbosity)
def post_register_hook(self, verbosity=1)
Pull Docker images needed by processes after registering.
9.877641
6.535314
1.511426
if data is None: return constants.DATA_ALL_VOLUME # Prefix MUST be set because ``get_path`` uses Django's settings, # if prefix is not set, to get path prefix. But the executor # shouldn't use Django's settings directly, so prefix is set # via a constant. ...
def resolve_data_path(self, data=None, filename=None)
Resolve data path for use with the executor. :param data: Data object instance :param filename: Filename to resolve :return: Resolved filename, which can be used to access the given data file in programs executed using this executor
14.177547
13.871718
1.022047
if filename is None: return constants.UPLOAD_VOLUME return os.path.join(constants.UPLOAD_VOLUME, filename)
def resolve_upload_path(self, filename=None)
Resolve upload path for use with the executor. :param filename: Filename to resolve :return: Resolved filename, which can be used to access the given uploaded file in programs executed using this executor
5.362951
6.890439
0.778318
ra_dt = round_to_nearest(a_dt, round_sec) rb_dt = round_to_nearest(b_dt, round_sec) logger.debug('Rounded:') logger.debug('{} -> {}'.format(a_dt, ra_dt)) logger.debug('{} -> {}'.format(b_dt, rb_dt)) return normalize_datetime_to_utc(ra_dt) == normalize_datetime_to_utc(rb_dt)
def are_equal(a_dt, b_dt, round_sec=1)
Determine if two datetimes are equal with fuzz factor. A naive datetime (no timezone information) is assumed to be in in UTC. Args: a_dt: datetime Timestamp to compare. b_dt: datetime Timestamp to compare. round_sec: int or float Round the timestamps to the closest ...
2.342394
2.975742
0.787163
epoch_seconds = ts_from_dt(dt) return email.utils.formatdate(epoch_seconds, localtime=False, usegmt=True)
def http_datetime_str_from_dt(dt)
Format datetime to HTTP Full Date format. Args: dt : datetime - tz-aware: Used in the formatted string. - tz-naive: Assumed to be in UTC. Returns: str The returned format is a is fixed-length subset of that defined by RFC 1123 and is the preferred format fo...
3.660542
5.678878
0.644589
date_parts = list(email.utils.parsedate(http_full_datetime)[:6]) year = date_parts[0] if year <= 99: year = year + 2000 if year < 50 else year + 1900 return create_utc_datetime(year, *date_parts[1:])
def dt_from_http_datetime_str(http_full_datetime)
Parse HTTP Full Date formats and return as datetime. Args: http_full_datetime : str Each of the allowed formats are supported: - Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123 - Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036 - Sun Nov 6 08:49:...
2.898768
3.293057
0.880267
return datetime.datetime( *dt.utctimetuple()[:6], microsecond=dt.microsecond, tzinfo=datetime.timezone.utc )
def normalize_datetime_to_utc(dt)
Adjust datetime to UTC. Apply the timezone offset to the datetime and set the timezone to UTC. This is a no-op if the datetime is already in UTC. Args: dt : datetime - tz-aware: Used in the formatted string. - tz-naive: Assumed to be in UTC. Returns: datetime The ...
3.807482
5.723043
0.66529
if has_tz(dt): return dt return dt.replace(tzinfo=tz)
def cast_naive_datetime_to_tz(dt, tz=UTC())
If datetime is tz-naive, set it to ``tz``. If datetime is tz-aware, return it unmodified. Args: dt : datetime tz-naive or tz-aware datetime. tz : datetime.tzinfo The timezone to which to adjust tz-naive datetime. Returns: datetime tz-aware datetime. Warning:...
4.074772
10.754475
0.378891
ts = ts_from_dt(strip_timezone(dt)) + n_round_sec / 2.0 res = dt_from_ts(ts - (ts % n_round_sec)) return res.replace(tzinfo=dt.tzinfo)
def round_to_nearest(dt, n_round_sec=1.0)
Round datetime up or down to nearest divisor. Round datetime up or down to nearest number of seconds that divides evenly by the divisor. Any timezone is preserved but ignored in the rounding. Args: dt: datetime n_round_sec : int or float Divisor for rounding Examples: ...
4.317701
6.150438
0.702015
limits = data.process.get_resource_limits() logger.debug(__( "Connector '{}' running for Data with id {} ({}).", self.__class__.__module__, data.id, repr(argv) )) # Compute target partition. partition = getattr(settings, '...
def submit(self, data, runtime_dir, argv)
Run process with SLURM. For details, see :meth:`~resolwe.flow.managers.workload_connectors.base.BaseConnector.submit`.
3.168909
3.035315
1.044013
def remove_file(fn, paths): while fn: for i in range(len(paths) - 1, -1, -1): if fn == paths[i]: paths.pop(i) fn, _ = os.path.split(fn) def remove_tree(fn, paths): for i in range(len(paths) - 1, -1, -1): ...
def get_purge_files(root, output, output_schema, descriptor, descriptor_schema)
Get files to purge.
2.036459
2.020453
1.007922
try: location = DataLocation.objects.get(id=location_id) except DataLocation.DoesNotExist: logger.warning("Data location does not exist", extra={'location_id': location_id}) return unreferenced_files = set() purged_data = Data.objects.none() referenced_by_data = locatio...
def location_purge(location_id, delete=False, verbosity=0)
Print and conditionally delete files not referenced by meta data. :param location_id: Id of the :class:`~resolwe.flow.models.DataLocation` model that data objects reference to. :param delete: If ``True``, then delete unreferenced files.
2.868045
2.718759
1.05491
if DataLocation.objects.exists(): for location in DataLocation.objects.filter(Q(purged=False) | Q(data=None)): location_purge(location.id, delete, verbosity) else: logger.info("No data locations")
def _location_purge_all(delete=False, verbosity=0)
Purge all data locations.
4.016821
3.736993
1.074881
orphaned_storages = Storage.objects.filter(data=None) if verbosity >= 1: if orphaned_storages.exists(): logger.info(__("Unreferenced storages ({}):", orphaned_storages.count())) for storage_id in orphaned_storages.values_list('id', flat=True): logger.info(__...
def _storage_purge_all(delete=False, verbosity=0)
Purge unreferenced storages.
2.739088
2.53691
1.079694
_location_purge_all(delete, verbosity) _storage_purge_all(delete, verbosity)
def purge_all(delete=False, verbosity=0)
Purge all data locations.
6.077614
4.966905
1.223622
if not isinstance(node, ast.Str): raise TypeError("must be a string literal") return node.s
def get_value(self, node)
Convert value from an AST node.
5.630569
4.36246
1.290687
if not isinstance(node, ast.Attribute): raise TypeError("must be an attribute") if node.value.id != self.choices.__name__: raise TypeError("must be an attribute of {}".format(self.choices.__name__)) return getattr(self.choices, node.attr)
def get_value(self, node)
Convert value from an AST node.
3.646357
3.37043
1.081867
if not isinstance(node, ast.Dict): raise TypeError("must be a dictionary") evaluator = SafeEvaluator() try: value = evaluator.run(node) except Exception as ex: # TODO: Handle errors. raise ex try: # Ensure val...
def get_value(self, node)
Convert value from an AST node.
4.384039
4.185285
1.047489
discovered_fields = collections.OrderedDict() field_groups = {} for node in item.body: if isinstance(node, ast.ClassDef): field_groups[node.name] = self.visit_field_class(node) continue if not isinstance(node, ast.Assign): ...
def visit_field_class(self, item, descriptor=None, fields=None)
Visit a class node containing a list of field definitions.
3.303917
3.18563
1.037131
# Cover `from resolwe.process import ...`. if isinstance(base, ast.Name) and isinstance(base.ctx, ast.Load): base = getattr(runtime, base.id, None) # Cover `from resolwe import process`. elif isinstance(base, ast.Attribute) and isinstance(base.ctx, ast.Loa...
def visit_ClassDef(self, node): # pylint: disable=invalid-name # Resolve everything as root scope contains everything from the process module. for base in node.bases
Visit top-level classes.
2.834114
2.834131
0.999994
root = ast.parse(self._source) visitor = ProcessVisitor(source=self._source) visitor.visit(root) return visitor.processes
def parse(self)
Parse process. :return: A list of discovered process descriptors
7.462641
7.169626
1.040869
def load_permissions(permissions_name): try: return import_module('{}'.format(permissions_name)).ResolwePermissions except AttributeError: raise AttributeError("'ResolwePermissions' class not found in {} module.".format( permissions_name)) ...
def get_permissions_class(permissions_name=None)
Load and cache permissions class. If ``permissions_name`` is not given, it defaults to permissions class set in Django ``FLOW_API['PERMISSIONS']`` setting.
3.476531
3.329141
1.044273
name_max_len = self._meta.get_field('name').max_length if len(self.name) > name_max_len: self.name = self.name[:(name_max_len - 3)] + '...' for _ in range(MAX_SLUG_RETRIES): try: # Attempt to save the model. It may fail due to slug conflict. ...
def save(self, *args, **kwargs)
Save the model.
3.098429
3.046256
1.017127
pid = d1_common.xml.get_opt_val(sysmeta_pyxb, 'identifier') sid = d1_common.xml.get_opt_val(sysmeta_pyxb, 'seriesId') obsoletes_pid = d1_common.xml.get_opt_val(sysmeta_pyxb, 'obsoletes') obsoleted_by_pid = d1_common.xml.get_opt_val(sysmeta_pyxb, 'obsoletedBy') return pid, sid, obsoletes_pid, ob...
def get_identifiers(sysmeta_pyxb)
Get set of identifiers that provide revision context for SciObj. Returns: tuple: PID, SID, OBSOLETES_PID, OBSOLETED_BY_PID
1.851921
1.606825
1.152534
sorted_list = [] sorted_set = set() found = True unconnected_dict = unsorted_dict.copy() while found: found = False for pid, obsoletes_pid in list(unconnected_dict.items()): if obsoletes_pid is None or obsoletes_pid in sorted_set: found = True ...
def topological_sort(unsorted_dict)
Sort objects by dependency. Sort a dict of obsoleting PID to obsoleted PID to a list of PIDs in order of obsolescence. Args: unsorted_dict : dict Dict that holds obsolescence information. Each ``key/value`` pair establishes that the PID in ``key`` identifies an object that obsoletes ...
2.753332
2.303854
1.195098
def _req(p): return d1_common.xml.get_req_val(p) def _opt(p, a): return d1_common.xml.get_opt_val(p, a) sysmeta_pyxb = client.getSystemMetadata(did) # Walk to tail while _opt(sysmeta_pyxb, 'obsoletes'): sysmeta_pyxb = client.getSystemMetadata(_opt(sysmeta_pyxb, 'obsol...
def get_pids_in_revision_chain(client, did)
Args: client: d1_client.cnclient.CoordinatingNodeClient or d1_client.mnclient.MemberNodeClient. did : str SID or a PID of any object in a revision chain. Returns: list of str: All PIDs in the chain. The returned list is in the same order as the chain. The initial PID is typ...
2.7147
2.590396
1.047987
parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter ) parser.add_argument("path", nargs="+", help="File or directory path") parser.add_argument("--exclude", nargs="+", help="Exclude glob patterns") parser.add_argument( "--n...
def main()
Remove unused imports Unsafe! Only tested on our codebase, which uses simple absolute imports on the form, "import a.b.c".
2.628603
2.651929
0.991204
docstr_list = [] for n in red.find_all("string"): if n.value.startswith('"""'): docstr_list.append(n) return docstr_list
def get_docstr_list(red)
Find all triple-quoted docstrings in module.
4.214272
2.967764
1.420016
def get_indent(): if line_str.startswith('"""'): return node_indent return len(re.match(r"^( *)", line_str).group(1)) def finish_block(): if block_list: unwrap_list.append( (block_indent, (" ".join([v.strip() for v in block_list])).strip()) ...
def unwrap(s, node_indent)
Group lines of a docstring to blocks. For now, only groups markdown list sections. A block designates a list of consequtive lines that all start at the same indentation level. The lines of the docstring are iterated top to bottom. Each line is added to `block_list` until a line is encountered tha...
3.819499
3.638318
1.049798
with io.StringIO() as str_buf: is_rest_block = unwrap_str.startswith(("- ", "* ")) while unwrap_str: cut_pos = (unwrap_str + " ").rfind(" ", 0, WRAP_MARGIN_INT - indent_int) if cut_pos == -1: cut_pos = WRAP_MARGIN_INT this_str, unwrap_str =...
def wrap(indent_int, unwrap_str)
Wrap a single line to one or more lines that start at indent_int and end at the last word that will fit before WRAP_MARGIN_INT. If there are no word breaks (spaces) before WRAP_MARGIN_INT, force a break at WRAP_MARGIN_INT.
3.038221
2.941187
1.032991
ore = ResourceMap() ore.initialize(ore_pid) ore.addMetadataDocument(scimeta_pid) ore.addDataDocuments(sciobj_pid_list, scimeta_pid) return ore
def createSimpleResourceMap(ore_pid, scimeta_pid, sciobj_pid_list)
Create a simple OAI-ORE Resource Map with one Science Metadata document and any number of Science Data objects. This creates a document that establishes an association between a Science Metadata object and any number of Science Data objects. The Science Metadata object contains information that is inde...
3.32754
3.612255
0.921181
pids = [] for line in in_stream: pid = line.strip() if pid == "#" or pid.startswith("# "): continue if len(pids) < 2: raise ValueError("Insufficient numbers of identifiers provided.") logging.info("Read {} identifiers".format(len(pids))) ore = ResourceMap(b...
def createResourceMapFromStream(in_stream, base_url=d1_common.const.URL_DATAONE_ROOT)
Create a simple OAI-ORE Resource Map with one Science Metadata document and any number of Science Data objects, using a stream of PIDs. Args: in_stream: The first non-blank line is the PID of the resource map itself. Second line is the science metadata PID and remaining lines are science ...
3.882124
3.285742
1.181506
# Set nice prefixes for the namespaces for k in list(d1_common.const.ORE_NAMESPACE_DICT.keys()): self.bind(k, d1_common.const.ORE_NAMESPACE_DICT[k]) # Create the ORE entity oid = self._pid_to_id(pid) ore = rdflib.URIRef(oid) self.add((ore, rdflib.RDF....
def initialize(self, pid, ore_software_id=d1_common.const.ORE_SOFTWARE_ID)
Create the basic ORE document structure.
3.119544
2.933664
1.063361
return super(ResourceMap, self).serialize( format=doc_format, encoding="utf-8", *args, **kwargs )
def serialize_to_transport(self, doc_format="xml", *args, **kwargs)
Serialize ResourceMap to UTF-8 encoded XML document. Args: doc_format: str One of: ``xml``, ``n3``, ``turtle``, ``nt``, ``pretty-xml``, ``trix``, ``trig`` and ``nquads``. args and kwargs: Optional arguments forwarded to rdflib.ConjunctiveGraph.serialize(...
5.520313
5.121001
1.077975
return ( super(ResourceMap, self) .serialize(format=doc_format, encoding=None, *args, **kwargs) .decode("utf-8") )
def serialize_to_display(self, doc_format="pretty-xml", *args, **kwargs)
Serialize ResourceMap to an XML doc that is pretty printed for display. Args: doc_format: str One of: ``xml``, ``n3``, ``turtle``, ``nt``, ``pretty-xml``, ``trix``, ``trig`` and ``nquads``. args and kwargs: Optional arguments forwarded to rdflib.Conjunct...
4.440308
4.639251
0.957117
self.parse(*args, **kwargs) self._ore_initialized = True
def deserialize(self, *args, **kwargs)
Deserialize Resource Map XML doc. The source is specified using one of source, location, file or data. Args: source: InputSource, file-like object, or string In the case of a string the string is the location of the source. location: str String indicating t...
18.049404
29.273767
0.616573
self._check_initialized() return [ o for o in self.subjects(predicate=rdflib.RDF.type, object=ORE.Aggregation) ][0]
def getAggregation(self)
Returns: str : URIRef of the Aggregation entity
9.593882
7.20135
1.332234
self._check_initialized() opid = rdflib.term.Literal(pid) res = [o for o in self.subjects(predicate=DCTERMS.identifier, object=opid)] return res[0]
def getObjectByPid(self, pid)
Args: pid : str Returns: str : URIRef of the entry identified by ``pid``.
5.028191
5.712842
0.880156
self._check_initialized() try: # is entry already in place? self.getObjectByPid(pid) return except IndexError: pass # Entry not present, add it to the graph oid = self._pid_to_id(pid) obj = rdflib.URIRef(oid) ...
def addResource(self, pid)
Add a resource to the Resource Map. Args: pid : str
4.428957
4.800781
0.922549
self._check_initialized() documenting_id = self.getObjectByPid(documenting_pid) documented_id = self.getObjectByPid(documented_pid) self.add((documenting_id, CITO.documents, documented_id))
def setDocuments(self, documenting_pid, documented_pid)
Add a CiTO, the Citation Typing Ontology, triple asserting that ``documenting_pid`` documents ``documented_pid``. Adds assertion: ``documenting_pid cito:documents documented_pid`` Args: documenting_pid: str PID of a Science Object that documents ``documented_pid``. ...
4.013898
3.20085
1.25401
self._check_initialized() documented_id = self.getObjectByPid(documented_pid) documenting_id = self.getObjectByPid(documenting_pid) self.add((documented_id, CITO.isDocumentedBy, documenting_id))
def setDocumentedBy(self, documented_pid, documenting_pid)
Add a CiTO, the Citation Typing Ontology, triple asserting that ``documented_pid`` isDocumentedBy ``documenting_pid``. Adds assertion: ``documented_pid cito:isDocumentedBy documenting_pid`` Args: documented_pid: str PID of a Science Object that is documented by ``document...
3.873883
3.139022
1.234105
mpids = self.getAggregatedScienceMetadataPids() if scimeta_pid is None: if len(mpids) > 1: raise ValueError( "No metadata PID specified and more than one choice available." ) scimeta_pid = mpids[0] else: ...
def addDataDocuments(self, scidata_pid_list, scimeta_pid=None)
Add Science Data object(s) Args: scidata_pid_list : list of str List of one or more PIDs of Science Data objects scimeta_pid: str PID of a Science Metadata object that documents the Science Data objects.
3.265679
3.401203
0.960154
ore = [ o for o in self.subjects(predicate=rdflib.RDF.type, object=ORE.ResourceMap) ][0] pid = [str(o) for o in self.objects(predicate=DCTERMS.identifier, subject=ore)][ 0 ] return pid
def getResourceMapPid(self)
Returns: str : PID of the Resource Map itself.
4.270431
3.98849
1.070689
return [(str(s), str(p), str(o)) for s, p, o in self]
def getAllTriples(self)
Returns: list of tuples : Each tuple holds a subject, predicate, object triple
4.106622
4.260124
0.963968
return sorted( set( [ (str(s), str(o)) for s, o in self.subject_objects(rdflib.term.URIRef(predicate)) ] ) )
def getSubjectObjectsByPredicate(self, predicate)
Args: predicate : str Predicate for which to return subject, object tuples. Returns: list of subject, object tuples: All subject/objects with ``predicate``. Notes: Equivalent SPARQL: .. highlight: sql :: SELECT DISTINCT ?s ?o WHERE {{ ?s {0} ...
3.566087
4.295975
0.830099
self.parse(data=doc_str, format=format) self._ore_initialized = True return self
def parseDoc(self, doc_str, format="xml")
Parse a OAI-ORE Resource Maps document. See Also: ``rdflib.ConjunctiveGraph.parse`` for documentation on arguments.
8.671199
8.394583
1.032952
return d1_common.url.joinPathElements( self._base_url, self._version_tag, "resolve", d1_common.url.encodePathElement(pid), )
def _pid_to_id(self, pid)
Converts a pid to a URI that can be used as an OAI-ORE identifier.
6.721458
4.625638
1.453088
if not os.path.exists('./hash_check'): os.mkdir('./hash_check') with open('./hash_check/curl.sh', 'w') as curl_f, open( './hash_check/md5.txt', 'w' ) as md5_f, open('./hash_check/sha1.txt', 'w') as sha1_f: curl_f.write('#!/usr/bin/env bash\n\n') for stats_dict in stat...
def make_checksum_validation_script(stats_list)
Make batch files required for checking checksums from another machine.
2.476011
2.47094
1.002052
kwargs.update({ 'max_value': 90, 'min_value': -90, }) return super(LatitudeField, self).formfield(**kwargs)
def formfield(self, **kwargs)
:returns: A :class:`~django.forms.FloatField` with ``max_value`` 90 and ``min_value`` -90.
3.374472
2.170654
1.554588
kwargs.update({ 'max_value': 180, 'min_value': -180, }) return super(LongitudeField, self).formfield(**kwargs)
def formfield(self, **kwargs)
:returns: A :class:`~django.forms.FloatField` with ``max_value`` 180 and ``min_value`` -180.
3.278773
2.054395
1.59598
widget_kwargs = { 'lat_field': self.latitude_field_name, 'lon_field': self.longitude_field_name, } if self.data_field_name: widget_kwargs['data_field'] = self.data_field_name defaults = { 'form_class': OSMFormField, '...
def formfield(self, **kwargs)
:returns: A :class:`~osm_field.forms.OSMFormField` with a :class:`~osm_field.widgets.OSMWidget`.
2.209137
1.996872
1.106299
if self._lat_field_name is None: self._lat_field_name = self.name + '_lat' return self._lat_field_name
def latitude_field_name(self)
The name of the related :class:`LatitudeField`.
2.663977
2.308747
1.153863
if self._lon_field_name is None: self._lon_field_name = self.name + '_lon' return self._lon_field_name
def longitude_field_name(self)
The name of the related :class:`LongitudeField`.
2.77509
2.363016
1.174385
DataDependency = apps.get_model('flow', 'DataDependency') for dependency in DataDependency.objects.all(): # Assume dependency is of subprocess kind. dependency.kind = 'subprocess' # Check child inputs to determine if this is an IO dependency. child = dependency.child ...
def update_dependency_kinds(apps, schema_editor)
Update historical dependency kinds as they may be wrong.
3.897481
3.919715
0.994328
value = soft_unicode(value) if self._engine._escape is None: # pylint: disable=protected-access return value return self._engine._escape(value)
def escape(self, value)
Escape given value.
5.68851
5.409602
1.051558
def wrapper(*args, **kwargs): try: return function(*args, **kwargs) except Exception: # pylint: disable=broad-except return NestedUndefined() # Copy over Jinja filter decoration attributes. for attribute in dir(funct...
def _wrap_jinja_filter(self, function)
Propagate exceptions as undefined values filter.
4.099543
3.48652
1.175826
custom_filters = self.settings.get('CUSTOM_FILTERS', []) if not isinstance(custom_filters, list): raise KeyError("`CUSTOM_FILTERS` setting must be a list.") for filter_module_name in custom_filters: try: filter_module = import_module(filter_modul...
def _register_custom_filters(self)
Register any custom filter modules.
2.191934
2.098305
1.044621
self._escape = escape self._safe_wrapper = safe_wrapper try: yield finally: self._escape = None self._safe_wrapper = None
def _evaluation_context(self, escape, safe_wrapper)
Configure the evaluation context.
2.597863
2.462453
1.05499
if context is None: context = {} try: with self._evaluation_context(escape, safe_wrapper): template = self._environment.from_string(template) return template.render(**context) except jinja2.TemplateError as error: rais...
def evaluate_block(self, template, context=None, escape=None, safe_wrapper=None)
Evaluate a template block.
3.199337
3.183932
1.004838
if context is None: context = {} try: with self._evaluation_context(escape, safe_wrapper): compiled = self._environment.compile_expression(expression) return compiled(**context) except jinja2.TemplateError as error: ra...
def evaluate_inline(self, expression, context=None, escape=None, safe_wrapper=None)
Evaluate an inline expression.
3.654125
3.593641
1.016831
with tempfile.NamedTemporaryFile() as tmp_file: tmp_file.write(redbaron_tree_to_module_str(redbaron_tree)) tmp_file.seek(0) if are_files_equal(module_path, tmp_file.name): logging.debug('Source unchanged') return False logging.debug('Source modified') ...
def update_module_file(redbaron_tree, module_path, show_diff=False, dry_run=False)
Set show_diff to False to overwrite module_path with a new file generated from ``redbaron_tree``. Returns True if tree is different from source.
3.087926
3.098483
0.996593
repo = git.Repo(path, search_parent_directories=True) repo_path = repo.git.rev_parse('--show-toplevel') logging.info('Repository: {}'.format(repo_path)) return repo_path
def find_repo_root_by_path(path)
Given a path to an item in a git repository, find the root of the repository.
2.463757
2.357637
1.045011
v = self._find_value(operation, key) if v == "NOT_FOUND": return [] if not isinstance(v, list): v = [v] if not len(v): v = [None] key = key + ":" lines = [] for s in v: # Access control rules are stored in t...
def _format_value(self, operation, key, indent)
A value that exists in the operation but has value None is displayed. A value that does not exist in the operation is left out entirely. The value name in the operation must match the value name in the template, but the location does not have to match.
3.970049
4.149588
0.956733
opt_method_list = ",".join(request.allowed_method_list + ["OPTIONS"]) response["Allow"] = opt_method_list response["Access-Control-Allow-Methods"] = opt_method_list response["Access-Control-Allow-Origin"] = request.META.get("Origin", "*") response["Access-Control-Allow-Headers"] = "Authorizatio...
def add_cors_headers(response, request)
Add Cross-Origin Resource Sharing (CORS) headers to response. - ``method_list`` is a list of HTTP methods that are allowed for the endpoint that was called. It should not include "OPTIONS", which is included automatically since it's allowed for all endpoints.
2.759638
2.718049
1.015301
def export_files(value): if isinstance(value, str) and os.path.isfile(value): # TODO: Use the protocol to export files and get the # process schema to check field type. print("export {}".format(value)) elif isinstance(...
def run_process(self, slug, inputs)
Run a new process from a running process.
4.697703
4.854555
0.96769
report = resolwe_runtime_utils.info(' '.join([str(x) for x in args])) # TODO: Use the protocol to report progress. print(report)
def info(self, *args)
Log informational message.
13.121863
11.777064
1.114188
resolwe_host = os.environ.get('RESOLWE_HOST_URL') url = urllib.parse.urljoin(resolwe_host, '/api/data?slug={}&fields=id'.format(slug)) with urllib.request.urlopen(url, timeout=60) as f: data = json.loads(f.read().decode('utf-8')) if len(data) == 1: retu...
def get_data_id_by_slug(self, slug)
Find data object ID for given slug. This method queries the Resolwe API and requires network access.
2.402724
2.292133
1.048248
class dotdict(dict): # pylint: disable=invalid-name def __getattr__(self, attr): value = self.get(attr) return dotdict(value) if isinstance(value, dict) else value return dotdict(self._meta.metadata.requirements)
def requirements(self)
Process requirements.
5.841602
4.920354
1.187232
self.logger.info("Process is starting") outputs = Outputs(self._meta.outputs) self.logger.info("Process is running") try: self.run(inputs.freeze(), outputs) return outputs.freeze() except Exception as error: self.logger.exception("Ex...
def start(self, inputs)
Start the process. :param inputs: An instance of `Inputs` describing the process inputs :return: An instance of `Outputs` describing the process outputs
4.086611
3.80812
1.073131
if not path.lower().endswith('.py'): return [] parser = SafeParser(open(path).read()) processes = parser.parse() return [process.to_schema() for process in processes]
def discover_process(self, path)
Perform process discovery in given path. This method will be called during process registration and should return a list of dictionaries with discovered process schemas.
6.024302
5.57162
1.081248
return 'PYTHONPATH="{runtime}" python3 -u -m resolwe.process {program} --slug {slug} --inputs {inputs}'.format( runtime=PYTHON_RUNTIME_VOLUME, program=PYTHON_PROGRAM_VOLUME, slug=shlex.quote(data.process.slug), inputs=PYTHON_INPUTS_VOLUME, )
def evaluate(self, data)
Evaluate the code needed to compute a given Data object.
7.815466
7.567794
1.032727
# Copy over Python process runtime (resolwe.process). import resolwe.process as runtime_package src_dir = os.path.dirname(inspect.getsourcefile(runtime_package)) dest_package_dir = os.path.join(runtime_dir, PYTHON_RUNTIME_DIRNAME, 'resolwe', 'process') shutil.copytree(s...
def prepare_runtime(self, runtime_dir, data)
Prepare runtime directory.
3.494015
3.495468
0.999585
try: jwt_dict = validate_and_decode(jwt_bu64, cert_obj) except JwtException as e: return log_jwt_bu64_info(logging.error, str(e), jwt_bu64) try: return jwt_dict['sub'] except LookupError: log_jwt_dict_info(logging.error, 'Missing "sub" key', jwt_dict)
def get_subject_with_local_validation(jwt_bu64, cert_obj)
Validate the JWT and return the subject it contains. - The JWT is validated by checking that it was signed with a CN certificate. - The returned subject can be trusted for authz and authn operations. - Possible validation errors include: - A trusted (TLS/SSL) connection could not be made to the C...
3.486612
3.81922
0.912912
cert_obj = d1_common.cert.x509.download_as_obj(base_url) return get_subject_with_local_validation(jwt_bu64, cert_obj)
def get_subject_with_remote_validation(jwt_bu64, base_url)
Same as get_subject_with_local_validation() except that the signing certificate is automatically downloaded from the CN. - Additional possible validations errors: - The certificate could not be retrieved from the root CN.
4.921267
5.304195
0.927807
cert_obj = d1_common.cert.x509.deserialize_pem_file(cert_path) return get_subject_with_local_validation(jwt_bu64, cert_obj)
def get_subject_with_file_validation(jwt_bu64, cert_path)
Same as get_subject_with_local_validation() except that the signing certificate is read from a local PEM file.
3.905489
3.013459
1.296015
try: jwt_dict = get_jwt_dict(jwt_bu64) except JwtException as e: return log_jwt_bu64_info(logging.error, str(e), jwt_bu64) try: return jwt_dict['sub'] except LookupError: log_jwt_dict_info(logging.error, 'Missing "sub" key', jwt_dict)
def get_subject_without_validation(jwt_bu64)
Extract subject from the JWT without validating the JWT. - The extracted subject cannot be trusted for authn or authz. Args: jwt_bu64: bytes JWT, encoded using a a URL safe flavor of Base64. Returns: str: The subject contained in the JWT.
3.312035
3.731154
0.88767
jwt_tup = get_jwt_tup(jwt_bu64) try: jwt_dict = json.loads(jwt_tup[0].decode('utf-8')) jwt_dict.update(json.loads(jwt_tup[1].decode('utf-8'))) jwt_dict['_sig_sha1'] = hashlib.sha1(jwt_tup[2]).hexdigest() except TypeError as e: raise JwtException('Decode failed. error="{}...
def get_jwt_dict(jwt_bu64)
Parse Base64 encoded JWT and return as a dict. - JWTs contain a set of values serialized to a JSON dict. This decodes the JWT and returns it as a dict containing Unicode strings. - In addition, a SHA1 hash is added to the dict for convenience. Args: jwt_bu64: bytes JWT, encoded using a...
3.111432
3.146034
0.989001
try: return jwt.decode( jwt_bu64.strip(), cert_obj.public_key(), algorithms=['RS256'], verify=True ) except jwt.InvalidTokenError as e: raise JwtException('Signature is invalid. error="{}"'.format(str(e)))
def validate_and_decode(jwt_bu64, cert_obj)
Validate the JWT and return as a dict. - JWTs contain a set of values serialized to a JSON dict. This decodes the JWT and returns it as a dict. Args: jwt_bu64: bytes The JWT encoded using a a URL safe flavor of Base64. cert_obj: cryptography.Certificate Public certificate us...
3.250763
3.583876
0.907052
d = ts_to_str(jwt_dict) # Log known items in specific order, then the rest just sorted log_list = [(b, d.pop(a)) for a, b, c in CLAIM_LIST if a in d] + [ (k, d[k]) for k in sorted(d) ] list( map( log, ['{}:'.format(msg_str)] + [' {}: {}'.format(k, v) for...
def log_jwt_dict_info(log, msg_str, jwt_dict)
Dump JWT to log. Args: log: Logger Logger to which to write the message. msg_str: str A message to write to the log before the JWT values. jwt_dict: dict JWT containing values to log. Returns: None
5.737477
6.762678
0.848403
d = ts_to_dt(jwt_dict) for k, v in list(d.items()): if isinstance(v, datetime.datetime): d[k] = v.isoformat().replace('T', ' ') return d
def ts_to_str(jwt_dict)
Convert timestamps in JWT to human readable dates. Args: jwt_dict: dict JWT with some keys containing timestamps. Returns: dict: Copy of input dict where timestamps have been replaced with human readable dates.
2.903605
3.14556
0.92308
d = jwt_dict.copy() for k, v in [v[:2] for v in CLAIM_LIST if v[2]]: if k in jwt_dict: d[k] = d1_common.date_time.dt_from_ts(jwt_dict[k]) return d
def ts_to_dt(jwt_dict)
Convert timestamps in JWT to datetime objects. Args: jwt_dict: dict JWT with some keys containing timestamps. Returns: dict: Copy of input dict where timestamps have been replaced with datetime.datetime() objects.
4.381521
4.633629
0.945592
s = base64.standard_b64encode(b) s = s.rstrip('=') s = s.replace('+', '-') s = s.replace('/', '_') return s
def encode_bu64(b)
Encode bytes to a URL safe flavor of Base64 used by JWTs. - Reverse of decode_bu64(). Args: b: bytes Bytes to Base64 encode. Returns: bytes: URL safe Base64 encoded version of input.
2.250406
2.565234
0.877271
s = b s = s.replace(b'-', b'+') s = s.replace(b'_', b'/') p = len(s) % 4 if p == 0: pass elif p == 2: s += b'==' elif p == 3: s += b'=' else: raise ValueError('Illegal Base64url string') return base64.standard_b64decode(s)
def decode_bu64(b)
Encode bytes to a URL safe flavor of Base64 used by JWTs. - Reverse of encode_bu64(). Args: b: bytes URL safe Base64 encoded bytes to encode. Returns: bytes: Decoded bytes.
2.302405
2.31758
0.993452
try: inputs = copy.deepcopy(data.input) hydrate_input_references(inputs, data.process.input_schema) hydrate_input_uploads(inputs, data.process.input_schema) # Include special 'proc' variable in the context. inputs['proc'] = { ...
def evaluate(self, data)
Evaluate the code needed to compute a given Data object.
6.157507
6.071404
1.014182
if isinstance(value, SafeString): return value return shellescape.quote(value)
def _escape(self, value)
Escape given value unless it is safe.
10.151877
6.599706
1.538232