output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Prepare connection for ElasticSearch.
Can you tell what is the following Python 3 function doing def prepare_connection(): elasticsearch_host = getattr(settings, 'ELASTICSEARCH_HOST', 'localhost') elasticsearch_port = getattr(settings, 'ELASTICSEARCH_PORT', 9200) connections.create_connection(hosts=['{}:{}'.format(elasticsearch_host, elasticsea...
You are a Python code analyst, evaluating scripts for potential improvements.
Log an operation that was performed on a sciobj.
Make a summary of the following Python 3 code def _log(pid, request, event, timestamp=None): # Support logging events that are not associated with an object. sciobj_model = None if pid is not None: try: sciobj_model = d1_gmn.app.models.ScienceObject.objects.filter(pid__did=pid)[ ...
You are a Python code architect, reviewing and designing scalable and efficient code
Return True if this read event was generated by an automated process and if the user has specified the LOG_IGNORE settings.
Can you generate a brief explanation for the following Python 3 code def _is_ignored_read_event(request): if ( django.conf.settings.LOG_IGNORE_TRUSTED_SUBJECT and d1_gmn.app.auth.is_trusted_subject(request) ): return True if ( django.conf.settings.LOG_IGNORE_NODE_SUBJECT ...
As a Python code analyst, you investigate and solve complex coding mysteries
Map action name to action level.
Given the following Python 3 function, write the documentation def action_to_level(action): try: return ACTION_LEVEL_MAP[action] except LookupError: raise d1_common.types.exceptions.InvalidRequest( 0, 'Unknown action. action="{}"'.format(action) )
As a Python code translator, you convert algorithms and pseudocode into Python.
Map action level to action name.
Can you generate the documentation for the following Python 3 function def level_to_action(level): try: return LEVEL_ACTION_MAP[level] except LookupError: raise d1_common.types.exceptions.InvalidRequest( 0, 'Unknown action level. level="{}"'.format(level) )
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_trusted_subjects(): """Get set of subjects that have unlimited access to all SciObj and APIs on this node.""" cert_subj = _get_client_side_certificate_subject() return ( d1_gmn.app.node_registry.get_cn_subjects() | django.conf.settings.DATAONE_TRUSTED_SUBJECTS | {cert_sub...
Write a Python 3 function for getting set of subjects that have unlimited access to all SciObj and APIs on this node.
You are a Python code analyst, evaluating scripts for potential improvements.
def is_trusted_subject(request): """Determine if calling subject is fully trusted.""" logging.debug('Active subjects: {}'.format(', '.join(request.all_subjects_set))) logging.debug('Trusted subjects: {}'.format(', '.join(get_trusted_subjects()))) return not request.all_subjects_set.isdisjoint(get_truste...
Can you implement a function in Python 3 that determines if calling subject is fully trusted.
You are a Python code analyst, evaluating scripts for potential improvements.
Return the DN from the client side certificate as a D1 subject if a client side cert has been configured. Otherwise return None.
Here you have a function in Python 3, explain what it does def _get_client_side_certificate_subject(): subject = django.core.cache.cache.get('client_side_certificate_subject') if subject is not None: return subject cert_pem = _get_client_side_certificate_pem() if cert_pem is None: return...
You are a Python code generator, capable of creating scripts from specifications.
Check if one or more subjects are allowed to perform action level on object.
Can you generate a brief explanation for the following Python 3 code def is_allowed(request, level, pid): if is_trusted_subject(request): return True return d1_gmn.app.models.Permission.objects.filter( sciobj__pid__did=pid, subject__subject__in=request.all_subjects_set, level__gt...
As a Python code translator, you convert algorithms and pseudocode into Python.
Access only by subjects with Create Update and Delete permission and by trusted infrastructure ( CNs ).
Can you generate a brief explanation for the following Python 3 code def assert_create_update_delete_permission(request): if not has_create_update_delete_permission(request): raise d1_common.types.exceptions.NotAuthorized( 0, 'Access allowed only for subjects with Create/Update/Delet...
As a Python code composer, you craft elegant and concise scripts.
Assert that one or more subjects are allowed to perform action on object.
Here you have a function in Python 3, explain what it does def assert_allowed(request, level, pid): if not d1_gmn.app.models.ScienceObject.objects.filter(pid__did=pid).exists(): raise d1_common.types.exceptions.NotFound( 0, 'Attempted to perform operation on non-existing object. pid=...
You are a Python code generator, capable of creating scripts from specifications.
Create a string listing active subjects for this connection suitable for appending to authentication error messages.
Explain what the following Python 3 code does def format_active_subjects(request): decorated_subject_list = [request.primary_subject_str + ' (primary)'] for subject in request.all_subjects_set: if subject != request.primary_subject_str: decorated_subject_list.append(subject) return ', '....
You are a Python code architect, reviewing and designing scalable and efficient code
def main(): """Remove unused imports Unsafe! Only tested on our codebase, which uses simple absolute imports on the form, "import a.b.c". """ parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter ) parser.add_argument("path", na...
Can you create a Python 3 function that removes unused imports Unsafe! Only tested on our codebase, which uses simple absolute imports on the form, "import a.b.c".
As a Python code translator, you convert algorithms and pseudocode into Python.
def comment_import(r, unused_dot_list): """Comment out import for {dot_str}.""" unused_dot_str = ".".join(unused_dot_list) for n in r("ImportNode"): if n.names()[0] == unused_dot_str: # The "!" is inserted so that this line doesn't show up when searching for # the comment pat...
Implement a Python 3 function for commenting out import for unused_dot_list.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_atomtrailer_list(r): """Capture only the leading dotted name list. A full sequence typically includes function calls and parameters. pkga.pkgb.pkgc.one_call(arg1, arg2, arg3=4) """ dot_set = set() for n in r.find_all(("atomtrailers",)): name_list = [] for x in n.value: ...
Implement a Python 3 function for capturing only the leading dotted name list.
As a Python code composer, you craft elegant and concise scripts.
Support general query using the text attribute.
Make a summary of the following Python 3 code def custom_filter_text(self, value, search): if isinstance(value, list): value = ' '.join(value) should = [ Q('match', slug={'query': value, 'operator': 'and', 'boost': 10.0}), Q('match', **{'slug.ngrams': {'query': value...
As a python code expert, you are capable of creating scripts from specifications.
Apply permissions to data objects and entities in Collection.
Can you generate the documentation for the following Python 3 function def set_content_permissions(self, user, obj, payload): for entity in obj.entity_set.all(): if user.has_perm('share_entity', entity): update_permission(entity, payload) # Data doesn't have "ADD" permission...
As a Python code composer, you craft elegant and concise scripts.
Only authenticated usesr can create new collections.
Make a summary of the following Python 3 code def create(self, request, *args, **kwargs): if not request.user.is_authenticated: raise exceptions.NotFound return super().create(request, *args, **kwargs)
You are a Python code architect, reviewing and designing scalable and efficient code
def destroy(self, request, *args, **kwargs): """Destroy a model instance. If ``delete_content`` flag is set in query parameters, also all Data objects and Entities, on which user has ``EDIT`` permission, contained in collection will be deleted. """ obj = self.get_object(...
Write a Python 3 function for destroying a model instance.
You are a Python code analyst, evaluating scripts for potential improvements.
def add_data(self, request, pk=None): """Add data to collection.""" collection = self.get_object() if 'ids' not in request.data: return Response({"error": "`ids`parameter is required"}, status=status.HTTP_400_BAD_REQUEST) missing = [] for data_id in request.data['id...
How would you code a function in Python 3 to add data to collection.
As a Python code analyst, you investigate and solve complex coding mysteries
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']: ...
Write a Python 3 function for removing data from collection.
As a Python code composer, you craft elegant and concise scripts.
def duplicate(self, request, *args, **kwargs): """Duplicate (make copy of) ``Collection`` models.""" if not request.user.is_authenticated: raise exceptions.NotFound ids = self.get_ids(request.data) queryset = get_objects_for_user(request.user, 'view_collection', Collection.o...
Create a Python 3 function for duplicating ( make copy of ) Collection models.
As a python code expert, you are capable of creating scripts from specifications.
async def is_object_synced_to_cn(self, client, pid): """Check if object with {pid} has successfully synced to the CN. CNRead.describe() is used as it's a light-weight HTTP HEAD request. This assumes that the call is being made over a connection that has been authenticated and has read ...
Can you write a function in Python 3 where it checks if an object with pid has successfully synced to CN.
As a Python code composer, you craft elegant and concise scripts.
Apply lookup expression to search query.
Can you tell what is the following Python 3 function doing def apply(self, search, field, value): return search.query( self.query_type( # pylint: disable=not-callable **{ field: { self.operator: self.get_value_query(value) ...
As a Python code analyst, you investigate and solve complex coding mysteries
Apply lookup expression to search query.
Given the following Python 3 function, write the documentation def apply(self, search, field, value): if not isinstance(value, list): value = [x for x in value.strip().split(',') if x] filters = [Q('match', **{field: item}) for item in value] return search.query('bool', should=filte...
You are a Python code architect, reviewing and designing scalable and efficient code
Apply lookup expression to search query.
Given the following Python 3 function, write the documentation def apply(self, search, field, value): # We assume that the field in question has a "raw" counterpart. return search.query('match', **{'{}.raw'.format(field): value})
As a Python code composer, you craft elegant and concise scripts.
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))
Write a Python 3 function for looking up a lookup.
As a Python code analyst, you investigate and solve complex coding mysteries
Build query. :param search: Search query instance :param raw_query: Raw query arguments dictionary
Can you generate the documentation for the following Python 3 function def build(self, search, raw_query): unmatched_items = {} for expression, value in raw_query.items(): # Parse query expression into tokens. tokens = expression.split(TOKEN_SEPARATOR) field = tokens...
You are a Python code architect, reviewing and designing scalable and efficient code
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 th...
Implement a function in Python 3 to 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. E...
As a Python code composer, you craft elegant and concise scripts.
Decorator that decodes a DID from URL path segment by Django.
Can you generate the documentation for the following Python 3 function def decode_did(f): @functools.wraps(f) def wrapper(request, did, *args, **kwargs): return f(request, decode_path_segment(did), *args, **kwargs) return wrapper
As a Python code analyst, you investigate and solve complex coding mysteries
Access only by D1 infrastructure.
Can you tell what is the following Python 3 function doing def trusted_permission(f): @functools.wraps(f) def wrapper(request, *args, **kwargs): trusted(request) return f(request, *args, **kwargs) return wrapper
As a Python code translator, you convert algorithms and pseudocode into Python.
Decorator to allow access to listObjects() controlled by settings. PUBLIC_OBJECT_LIST.
Explain what the following Python 3 code does def list_objects_access(f): @functools.wraps(f) def wrapper(request, *args, **kwargs): if not django.conf.settings.PUBLIC_OBJECT_LIST: trusted(request) return f(request, *args, **kwargs) return wrapper
You are a Python code analyst, evaluating scripts for potential improvements.
Decorator to allow access to the log records of the current page.
Can you generate a brief explanation for the following Python 3 code def get_log_records_access(f): @functools.wraps(f) def wrapper(request, *args, **kwargs): if not django.conf.settings.PUBLIC_LOG_RECORDS: trusted(request) return f(request, *args, **kwargs) return wrapper
As a python code expert, you are capable of creating scripts from specifications.
def assert_create_update_delete_permission(f): """Access only by subjects with Create/Update/Delete permission and by trusted infrastructure (CNs).""" @functools.wraps(f) def wrapper(request, *args, **kwargs): d1_gmn.app.auth.assert_create_update_delete_permission(request) return f(requ...
Write a Python 3 function that can access only by subjects with Create/Update/Delete permission and by trusted infrastructure (CNs).
As a Python code analyst, you investigate and solve complex coding mysteries
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 a...
Can you implement a function in Python 3 that accesses only with a valid session.
You are a Python code architect, reviewing and designing scalable and efficient code
Decorator that asserts that subject has access at given level or higher for object.
Here you have a function in Python 3, explain what it does def required_permission(f, level): @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
As a python code expert, you are capable of creating scripts from specifications.
Given a response body try to create an instance of a DataONE type.
Can you generate the documentation for the following Python 3 function def _read_and_deserialize_dataone_type(self, response): try: return d1_common.xml.deserialize(response.content) except ValueError as e: self._raise_service_failure_invalid_dataone_type(response, e)
You are a Python code generator, capable of creating scripts from specifications.
def get(self, pid, stream=False, vendorSpecific=None): """Initiate a MNRead.get(). Return a Requests Response object from which the object bytes can be retrieved. When ``stream`` is False, Requests buffers the entire object in memory before returning the Response. This can exhaust avail...
Implement a function in Python 3 to initiate a MNRead. get. Return a Requests Response object from which the object bytes can be retrieved.
As a python code expert, you are capable of creating scripts from specifications.
def get_and_save( self, pid, sciobj_stream, create_missing_dirs=False, vendorSpecific=None ): """Like MNRead.get(), but also retrieve the object bytes and store them in a stream. This method does not have the potential issue with excessive memory usage that get() with ``stream``=Fals...
Can you implement a function in Python 3 that likes MNRead. get but also retrieve the object bytes and store them in aSciObjStream.
You are a Python code analyst, evaluating scripts for potential improvements.
Returns a dictionary of the metadata for the specified resource ID.
Can you generate a brief explanation for the following Python 3 code def describe(self, pid, vendorSpecific=None): response = self.describeResponse(pid, vendorSpecific=vendorSpecific) return self._read_header_response(response)
You are a Python code architect, reviewing and designing scalable and efficient code
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)
Create a Python 3 function to return True if user is allowed to perform action on pid else False.
As a Python code analyst, you investigate and solve complex coding mysteries
Filter fields based on request query parameters.
Can you tell what is the following Python 3 function doing def fields(self): fields = super().fields return apply_subfield_projection(self, copy.copy(fields))
As a Python code composer, you craft elegant and concise scripts.
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 ov...
How would you code a function in Python 3 to iterate over all field values sub - fields.
You are a Python code architect, reviewing and designing scalable and efficient code
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 :typ...
Create a Python 3 function to iterate over all schema sub - fields.
You are a Python code analyst, evaluating scripts for potential improvements.
Iterate over a nested dictionary.
Can you generate the documentation for the following Python 3 function def iterate_dict(container, exclude=None, path=None): if path is None: path = [] for key, value in container.items(): if callable(exclude) and exclude(key, value): continue if isinstance(value, collectio...
You are a Python code architect, reviewing and designing scalable and efficient code
Get all subjects in the certificate.
Given the following Python 3 function, write the documentation def get_subjects(request): 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( ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Return primary subject and set of equivalents authenticated by certificate.
Explain what the following Python 3 code does def get_authenticated_subjects(cert_pem): if isinstance(cert_pem, str): cert_pem = cert_pem.encode('utf-8') return d1_common.cert.subjects.extract_subjects(cert_pem)
You are a Python code analyst, evaluating scripts for potential improvements.
Augment base serializer class.
Can you tell what is the following Python 3 function doing def get_serializer_class(self): base_class = super().get_serializer_class() class SerializerWithPermissions(base_class): """Augment serializer class.""" def get_fields(serializer_self): # pylint: disable=no-self-argume...
As a python code expert, you are capable of creating scripts from specifications.
Get or set permissions API endpoint.
Can you tell what is the following Python 3 function doing def detail_permissions(self, request, pk=None): obj = self.get_object() if request.method == 'POST': content_type = ContentType.objects.get_for_model(obj) payload = request.data share_content = strtobool(payl...
As a python code expert, you are capable of creating scripts from specifications.
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 ...
Create a Python 3 function for performing descriptor validation and save object.
You are a Python code architect, reviewing and designing scalable and efficient code
Duplicate the current instance.
Can you tell what is the following Python 3 function doing def duplicate(self, contributor=None): duplicate = Collection.objects.get(id=self.id) duplicate.pk = None duplicate.slug = None duplicate.name = 'Copy of {}'.format(self.name) duplicate.duplicated = now() if contr...
As a Python code translator, you convert algorithms and pseudocode into Python.
Convert a dictionary with scalar elements and string indices _1234 to a dictionary of arrays. Unspecified entries are np. nan.
Can you tell what is the following Python 3 function doing def _scalar2array(d): 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: ...
You are a Python code architect, reviewing and designing scalable and efficient code
To get rid of NaNs produced by _scalar2array symmetrize operators where C_ijkl = C_klij
Here you have a function in Python 3, explain what it does def _symm_current(C): nans = np.isnan(C) C[nans] = np.einsum('klij', C)[nans] return C
You are a Python code analyst, evaluating scripts for potential improvements.
Antisymmetrize the first two indices of operators where C_ijkl = - C_jikl
Can you generate the documentation for the following Python 3 function def _antisymm_12(C): nans = np.isnan(C) C[nans] = -np.einsum('jikl', C)[nans] return C
As a Python code translator, you convert algorithms and pseudocode into 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()}
Write a Python 3 function for undoing the scaling applied in scale_dict_wet.
As a Python code composer, you craft elegant and concise scripts.
Writes a list of requests to a file
Explain what the following Python 3 code does def write_reqs(req_path, req_list): with open(req_path, 'w') as f: f.write('\n'.join(req_list) + "\n")
As a Python code translator, you convert algorithms and pseudocode into 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__.__mod...
Write a Python 3 script for submitting a new process locally.
You are a Python code generator, capable of creating scripts from specifications.
Calculate the checksum of a file - like object.
How would you explain what the following Python 3 function does def create_checksum_object_from_stream( f, algorithm=d1_common.const.DEFAULT_CHECKSUM_ALGORITHM ): """Calculate the checksum of a stream. Args: f: file-like object Only requirement is a ``read()`` method that returns ``bytes``. ...
You are a Python code generator, capable of creating scripts from specifications.
def create_checksum_object_from_iterator( itr, algorithm=d1_common.const.DEFAULT_CHECKSUM_ALGORITHM ): """Calculate the checksum of an iterator. Args: itr: iterable Object which supports the iterator protocol. algorithm: str Checksum algorithm, ``MD5`` or ``SHA1`` / ``SHA-1``. ...
Write a Python 3 script for calculating the checksum of an iterator.
As a python code expert, you are capable of creating scripts from specifications.
def create_checksum_object_from_bytes( b, algorithm=d1_common.const.DEFAULT_CHECKSUM_ALGORITHM ): """Calculate the checksum of ``bytes``. Warning: This method requires the entire object to be buffered in (virtual) memory, which should normally be avoided in production code. Args: b: ...
Write a Python 3 script to calculate the checksum of the bytes b and return a PyXB Checksum object.
You are a Python code architect, reviewing and designing scalable and efficient code
Calculate the checksum of a file - like object.
Given the following Python 3 function, write the documentation def calculate_checksum_on_stream( f, algorithm=d1_common.const.DEFAULT_CHECKSUM_ALGORITHM, chunk_size=DEFAULT_CHUNK_SIZE, ): """Calculate the checksum of a stream. Args: f: file-like object Only requirement is a ``read()``...
As a Python code analyst, you investigate and solve complex coding mysteries
def calculate_checksum_on_iterator( itr, algorithm=d1_common.const.DEFAULT_CHECKSUM_ALGORITHM ): """Calculate the checksum of an iterator. Args: itr: iterable Object which supports the iterator protocol. algorithm: str Checksum algorithm, ``MD5`` or ``SHA1`` / ``SHA-1``. R...
Implement a Python 3 function for calculating the checksum of an iterator.
As a python code expert, you are capable of creating scripts from specifications.
Calculate the checksum of the given bytes.
Can you tell what is the following Python 3 function doing def calculate_checksum_on_bytes( b, algorithm=d1_common.const.DEFAULT_CHECKSUM_ALGORITHM ): """Calculate the checksum of ``bytes``. Warning: This method requires the entire object to be buffered in (virtual) memory, which should normally be avo...
You are a Python code analyst, evaluating scripts for potential improvements.
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 algo...
Create a Python 3 function for returning True if checksums are equal.
As a Python code analyst, you investigate and solve complex coding mysteries
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.va...
Write a Python 3 function that can return a string representation of a PyXB Checksum object.
As a Python code composer, you craft elegant and concise scripts.
Run the executor listener. This method never returns.
Explain what the following Python 3 code does def handle(self, *args, **kwargs): listener = ExecutorListener(redis_params=getattr(settings, 'FLOW_MANAGER', {}).get('REDIS_CONNECTION', {})) def _killer(signum, frame): """Kill the listener on receipt of a signal.""" listener.termi...
You are a Python code architect, reviewing and designing scalable and efficient code
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: di...
Implement a function in Python 3 to apply a projection to a single resource.
You are a Python code analyst, evaluating scripts for potential improvements.
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-dic...
Write a Python 3 script for applying a projection to the value.
You are a Python code generator, capable of creating scripts from specifications.
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(): ...
Write a Python 3 script to create Relation object and add partitions of Entities.
As a Python code composer, you craft elegant and concise scripts.
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()...
How would you implement a function in Python 3 that updates the relation with the given data.
As a python code expert, you are capable of creating scripts from specifications.
Display or save file like object.
Here you have a function in Python 3, explain what it does def output(file_like_object, path, verbose=False): if not path: for line in file_like_object: if verbose: print_info(line.rstrip()) else: print(line.rstrip()) else: try: ...
You are a Python code generator, capable of creating scripts from specifications.
Print the information in Unicode safe manner.
Explain what the following Python 3 code does def _print_level(level, msg): for l in str(msg.rstrip()).split("\n"): print("{0:<9s}{1}".format(level, str(l)))
As a Python code composer, you craft elegant and concise scripts.
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:...
Write a Python 3 script for finding the first line of process definition.
As a python code expert, you are capable of creating scripts from specifications.
Find processes in a directory and return a dictionary of processes where keys are URLs pointing to processes source code and values are processes definitions parsed from YAML files.
Explain what the following Python 3 code does 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_extensions = ['*.yaml', '*.yml'] for root, _, filena...
You are a Python code architect, reviewing and designing scalable and efficient code
Register directives. When sphinx loads the extension (= imports the extension module) it also executes the setup() function. Setup is the way extension informs Sphinx about everything that the extension enables: which config_values are introduced, which custom nodes/directives/roles and which event...
Explain what the following Python 3 code does def setup(app): 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) ...
You are a Python code architect, reviewing and designing scalable and efficient code
Fill content into nodes. field instance with given name and body.
Can you generate a brief explanation for the following Python 3 code def make_field(self, field_name, field_body): 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 jus...
As a Python code composer, you craft elegant and concise scripts.
Fill the given field into a properties list and return it.
Can you generate a brief explanation for the following Python 3 code 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', 'type', 'description'...
You are a Python code generator, capable of creating scripts from specifications.
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 ...
Write a Python 3 function that can generate a process definition header.
As a Python code analyst, you investigate and solve complex coding mysteries
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 ...
Implement a function in Python 3 to fill the content of the process definiton node.
As a Python code composer, you craft elegant and concise scripts.
Create a list of process definitions.
Here you have a function in Python 3, explain what it does def run(self): 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...
You are a Python code architect, reviewing and designing scalable and efficient code
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')) categorize...
Implement a function in Python 3 to create a category tree.
As a Python code analyst, you investigate and solve complex coding mysteries
Create a type list.
Here you have a function in Python 3, explain what it does def run(self): 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')) ...
You are a Python code generator, capable of creating scripts from specifications.
MNRead. get - Retrieve the SciObj bytes and write them to a stream.
Can you generate a brief explanation for the following Python 3 code async def get(self, file_stream, pid, vendor_specific=None): async with await self._retry_request( "get", ["object", pid], vendor_specific=vendor_specific ) as response: self._assert_valid_response(response) ...
You are a Python code analyst, evaluating scripts for potential improvements.
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, )
How would you implement a function in Python 3 that sends an object synchronization request to the CN.
You are a Python code generator, capable of creating scripts from specifications.
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()) }
Create a Python 3 function to encode any datetime query parameters to ISO8601.
As a Python code translator, you convert algorithms and pseudocode into Python.
Project outgoing native value.
Can you generate a brief explanation for the following Python 3 code def to_representation(self, value): value = apply_subfield_projection(self, value, deep=True) return super().to_representation(value)
You are a Python code generator, capable of creating scripts from specifications.
CNRead. synchronize - POST / synchronize. pid - PID of the current session Returns True if successful False otherwise
Can you generate the documentation for the following Python 3 function def synchronizeResponse(self, pid, vendorSpecific=None): mmp_dict = {'pid': pid} return self.POST(['synchronize'], fields=mmp_dict, headers=vendorSpecific)
As a Python code composer, you craft elegant and concise scripts.
def synchronize(self, pid, vendorSpecific=None): """See Also: synchronizeResponse() Args: pid: vendorSpecific: Returns: """ response = self.synchronizeResponse(pid, vendorSpecific) return self._read_boolean_response(response)
How would you code a function in Python 3 to see Also : synchronizeResponse
You are a Python code generator, capable of creating scripts from specifications.
Check if a BagIt file is valid.
Explain what the following Python 3 code does 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_checksums(bagit_zip, manifest_info_list) return True
You are a Python code analyst, evaluating scripts for potential improvements.
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 L...
Create a Python 3 function to create a stream containing a BagIt zip archive.
As a python code expert, you are capable of creating scripts from specifications.
Add a key with the path to each payload_info_dict.
Here you have a function in Python 3, explain what it does 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['path'] = d1_common.utils.filesystem.gen_safe_path( d...
You are a Python code generator, capable of creating scripts from specifications.
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_i...
Write a Python 3 script to add the payload files to the zip.
You are a Python code generator, capable of creating scripts from specifications.
Generate the tag files and add them to the zip.
Given the following Python 3 function, write the documentation 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_fi...
As a python code expert, you are capable of creating scripts from specifications.
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, ...
Create a Python 3 function for generating the manifest files and add them to the zip.
As a python code expert, you are capable of creating scripts from specifications.
Generate the tag manifest file and add it to the zip.
How would you explain what the following Python 3 function does 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) )
As a Python code composer, you craft elegant and concise scripts.
Add a tag file to zip_file and record info for the tag manifest file.
Explain what the following Python 3 code does 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, tag_name) tag_iter = _create_and_add_tag_iter(zip_file, tag_path, tag_str) tag_info_list.append( ...
As a Python code analyst, you investigate and solve complex coding mysteries
Convert a node_list_pyxb to a dict.
Given the following Python 3 function, write the documentation def pyxb_to_dict(node_list_pyxb): f_dict = {} for f_pyxb in sorted(node_list_pyxb.node, key=lambda x: x.identifier.value()): f_dict[f_pyxb.identifier.value()] = { 'name': f_pyxb.name, 'description': f_pyxb.description...
As a python code expert, you are capable of creating scripts from specifications.
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_ma...
Implement a function in Python 3 to check if the user has permission to edit the object.
You are a Python code generator, capable of creating scripts from specifications.
Get a set containing all subjects for which the current connection has been successfully authenticated.
Can you generate a brief explanation for the following Python 3 code 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.META: request.META[ ...
As a Python code analyst, you investigate and solve complex coding mysteries
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.
Here you have a function in Python 3, explain what it does def log_setup(debug_bool): level = logging.DEBUG if debug_bool else logging.INFO logging.config.dictConfig( { "version": 1, "disable_existing_loggers": False, "formatters": { "verbose": { ...
You are a Python code architect, reviewing and designing scalable and efficient code