output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def add_to_collection(self, request, pk=None):
"""Add Entity to a collection."""
entity = self.get_object()
# TODO use `self.get_ids` (and elsewhere). Backwards
# incompatible because raised error's response contains
# ``detail`` instead of ``error``).
if 'ids' not in re... | Write a Python 3 script to
add Entity to a collection. | You are a Python code architect, reviewing and designing scalable and efficient code |
def add_data(self, request, pk=None):
"""Add data to Entity and it's collection."""
# add data to entity
resp = super().add_data(request, pk)
# add data to collections in which entity is
entity = self.get_object()
for collection in entity.collections.all():
c... | How would you implement a function in Python 3 that
adds data to Entity and its collection. | You are a Python code generator, capable of creating scripts from specifications. |
def move_to_collection(self, request, *args, **kwargs):
"""Move samples from source to destination collection."""
ids = self.get_ids(request.data)
src_collection_id = self.get_id(request.data, 'source_collection')
dst_collection_id = self.get_id(request.data, 'destination_collection')
... | Can you create a Python 3 function that
moves samples from source to destination collection. | As a Python code analyst, you investigate and solve complex coding mysteries |
def update(self, request, *args, **kwargs):
"""Update an entity.
Original queryset produces a temporary database table whose rows
cannot be selected for an update. As a workaround, we patch
get_queryset function to return only Entity objects without
additional data that is not n... | Create a Python 3 function to
update an entity. Original queryset produces a temporary database table whose rows cannot be selected for an update. As a workaround, we patch get_queryset function to return only Entity objects without additional data that is not needed for the update. | As a Python code translator, you convert algorithms and pseudocode into Python. |
async def start(self):
"""Start process execution."""
# arguments passed to the Docker command
command_args = {
'command': self.command,
'container_image': self.requirements.get('image', constants.DEFAULT_CONTAINER_IMAGE),
}
# Get limit defaults.
... | Implement a Python 3 function for
starting the process execution. | As a Python code analyst, you investigate and solve complex coding mysteries |
Execute the script and save results. | Here you have a function in Python 3, explain what it does
async def run_script(self, script):
# Create a Bash command to add all the tools to PATH.
tools_paths = ':'.join([map_["dest"] for map_ in self.tools_volumes])
add_tools_path = 'export PATH=$PATH:{}'.format(tools_paths)
# Spawn a... | As a Python code composer, you craft elegant and concise scripts. |
async def terminate(self):
"""Terminate a running script."""
# Workaround for pylint issue #1469
# (https://github.com/PyCQA/pylint/issues/1469).
cmd = await subprocess.create_subprocess_exec( # pylint: disable=no-member
*shlex.split('{} rm -f {}'.format(self.command, self._... | Write a Python 3 function that can
terminate a running script. | You are a Python code analyst, evaluating scripts for potential improvements. |
async def _send_manager_command(self, *args, **kwargs):
"""Send an update to manager and terminate the process if it fails."""
resp = await send_manager_command(*args, **kwargs)
if resp is False:
await self.terminate() | Write a Python 3 script to
send an update to manager and terminate the process if it fails. | As a Python code translator, you convert algorithms and pseudocode into Python. |
async def update_data_status(self, **kwargs):
"""Update (PATCH) Data object.
:param kwargs: The dictionary of
:class:`~resolwe.flow.models.Data` attributes to be changed.
"""
await self._send_manager_command(ExecutorProtocol.UPDATE, extra_fields={
ExecutorProtoco... | Implement a function in Python 3 to
update the status of the current data object. | You are a Python code generator, capable of creating scripts from specifications. |
async def run(self, data_id, script):
"""Execute the script and save results."""
logger.debug("Executor for Data with id {} has started.".format(data_id))
try:
finish_fields = await self._run(data_id, script)
except SystemExit as ex:
raise ex
except Except... | Can you write a function in Python 3 where it
executes the script and save the results. | As a python code expert, you are capable of creating scripts from specifications. |
def _create_file(self, filename):
"""Ensure a new file is created and opened for writing."""
file_descriptor = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
return os.fdopen(file_descriptor, 'w') | Create a Python 3 function to
ensure a new file is created and opened for writing. | You are a Python code analyst, evaluating scripts for potential improvements. |
Execute the script and save the results. | Can you generate a brief explanation for the following Python 3 code
async def _run(self, data_id, script):
self.data_id = data_id
# Fetch data instance to get any executor requirements.
self.process = PROCESS
requirements = self.process['requirements']
self.requirements = requi... | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_total_size_of_queued_replicas():
"""Return the total number of bytes of requested, unprocessed replicas."""
return (
d1_gmn.app.models.ReplicationQueue.objects.filter(
local_replica__info__status__status='queued'
).aggregate(Sum('size'))['size__sum']
or 0
) | Implement a function in Python 3 to
return the total number of bytes of requested unprocessed replicas. | As a python code expert, you are capable of creating scripts from specifications. |
Add a replication request issued by a CN to a queue that is processed asynchronously. | Here you have a function in Python 3, explain what it does
def add_to_replication_queue(source_node_urn, sysmeta_pyxb):
replica_info_model = d1_gmn.app.models.replica_info(
status_str='queued', source_node_urn=source_node_urn
)
local_replica_model = d1_gmn.app.models.local_replica(
pid=d1_co... | As a Python code analyst, you investigate and solve complex coding mysteries |
def add_arguments(parser, doc_str, add_base_url=True):
"""Add standard arguments for DataONE utilities to a command line parser."""
parser.description = doc_str
parser.formatter_class = argparse.RawDescriptionHelpFormatter
parser.add_argument("--debug", action="store_true", help="Debug level logging")
... | Can you create a Python 3 function that
adds standard arguments for DataONE utilities to a command line parser. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_resource_map_members(pid):
"""``pid`` is the PID of a Resource Map or the PID of a member of a Resource Map."""
if d1_gmn.app.did.is_resource_map_db(pid):
return get_resource_map_members_by_map(pid)
elif d1_gmn.app.did.is_resource_map_member(pid):
return get_resource_map_members_by_m... | Implement a Python 3 function for
getting a list of all members of a Resource Map. | As a python code expert, you are capable of creating scripts from specifications. |
Convert user supplied string to Python type. | Make a summary of the following Python 3 code
def set_with_conversion(self, variable, value_string):
self._assert_valid_variable(variable)
try:
v = ast.literal_eval(value_string)
except (ValueError, SyntaxError):
v = value_string
if v is None or v == "none":
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Setup a standardized log format for the DataONE Python stack. | Explain what the following Python 3 code does
def log_setup(is_debug=False, is_multiprocess=False):
format_str = (
'%(asctime)s %(name)s %(module)s:%(lineno)d %(process)4d %(levelname)-8s %(message)s'
if is_multiprocess
else '%(asctime)s %(name)s %(module)s:%(lineno)d %(levelname)-8s %(messa... | As a python code expert, you are capable of creating scripts from specifications. |
Extract the MIME type value from a content type string. | Can you tell what is the following Python 3 function doing
def get_content_type(content_type):
m = email.message.Message()
m['Content-Type'] = content_type
return m.get_content_type() | You are a Python code analyst, evaluating scripts for potential improvements. |
def nested_update(d, u):
"""Merge two nested dicts.
Nested dicts are sometimes used for representing various recursive structures. When
updating such a structure, it may be convenient to present the updated data as a
corresponding recursive structure. This function will then apply the update.
Args... | Create a Python 3 function for
merging two nested dicts. | As a python code expert, you are capable of creating scripts from specifications. |
Context manager that temporarily suppress additional information such as timestamps
when writing to loggers. | How would you explain what the following Python 3 function does
def print_logging():
root_logger = logging.getLogger()
old_level_list = [h.level for h in root_logger.handlers]
for h in root_logger.handlers:
h.setLevel(logging.WARN)
log_format = logging.Formatter('%(message)s')
stream_handler... | You are a Python code analyst, evaluating scripts for potential improvements. |
Serialize a native object to JSON and save it normalized pretty printed to a
file. | Here you have a function in Python 3, explain what it does
def save_json(py_obj, json_path):
with open(json_path, 'w', encoding='utf-8') as f:
f.write(serialize_to_normalized_pretty_json(py_obj)) | As a python code expert, you are capable of creating scripts from specifications. |
def serialize_to_normalized_pretty_json(py_obj):
"""Serialize a native object to normalized, pretty printed JSON.
The JSON string is normalized by sorting any dictionary keys.
Args:
py_obj: object
Any object that can be represented in JSON. Some types, such as datetimes are
automatic... | Create a Python 3 function to
serialize a native object to normalized pretty printed JSON. | You are a Python code generator, capable of creating scripts from specifications. |
Serialize a native object to normalized compact JSON. | Make a summary of the following Python 3 code
def serialize_to_normalized_compact_json(py_obj):
return json.dumps(
py_obj, sort_keys=True, separators=(',', ':'), cls=ToJsonCompatibleTypes
) | You are a Python code analyst, evaluating scripts for potential improvements. |
Format seconds to days hours minutes. | Can you generate the documentation for the following Python 3 function
def format_sec_to_dhm(sec):
rem_int, s_int = divmod(int(sec), 60)
rem_int, m_int, = divmod(rem_int, 60)
d_int, h_int, = divmod(rem_int, 24)
return '{}d{:02d}h{:02d}m'.format(d_int, h_int, m_int) | You are a Python code analyst, evaluating scripts for potential improvements. |
Counts the number of times an event occurs in the event dict. | Here you have a function in Python 3, explain what it does
def count(self, event_str, inc_int=1):
self._event_dict.setdefault(event_str, 0)
self._event_dict[event_str] += inc_int | As a Python code translator, you convert algorithms and pseudocode into Python. |
def log_and_count(self, event_str, msg_str=None, inc_int=None):
"""Count an event and write a message to a logger.
Args:
event_str: str
The name of an event to count. Used as a key in the event dict. The same
name will be used in the summary. This also becomes a part o... | Can you create a Python 3 function that
counts an event and write a message to a logger. | You are a Python code analyst, evaluating scripts for potential improvements. |
Write summary to logger. | How would you explain what the following Python 3 function does
def dump_to_log(self):
if self._event_dict:
logger.info('Events:')
for event_str, count_int in sorted(self._event_dict.items()):
logger.info(' {}: {}'.format(event_str, count_int))
else:
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def delete_all_from_db():
"""Clear the database.
Used for testing and debugging.
"""
# The models.CASCADE property is set on all ForeignKey fields, so tables can
# be deleted in any order without breaking constraints.
for model in django.apps.apps.get_models():
model.objects.all().dele... | Can you implement a function in Python 3 that
clears the database. Used for testing and debugging. | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_query_param(request, key):
"""Get query parameter uniformly for GET and POST requests."""
value = request.query_params.get(key) or request.data.get(key)
if value is None:
raise KeyError()
return value | Write a Python 3 function for
getting a query parameter uniformly for GET and POST requests. | As a Python code translator, you convert algorithms and pseudocode into Python. |
2to3 uses AST, not Baron. | Given the following Python 3 function, write the documentation
def futurize_module(module_path, show_diff, write_update):
logging.info('Futurizing module... path="{}"'.format(module_path))
ast_tree = back_to_the_futurize(module_path)
return d1_dev.util.update_module_file_ast(
ast_tree, module_path, ... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _remove_single_line_import_comments(r):
"""We previously used more groups for the import statements and named each group."""
logging.info('Removing single line import comments')
import_r, remaining_r = split_by_last_import(r)
new_import_r = redbaron.NodeList()
for i, v in enumerate(import_r):
... | Implement a Python 3 function for
removing comments from a single line import statement. | You are a Python code generator, capable of creating scripts from specifications. |
Add or update __all__ in __init__. py file. | Can you generate a brief explanation for the following Python 3 code
def _update_init_all(module_path, r):
module_dir_path = os.path.split(module_path)[0]
module_list = []
for item_name in os.listdir(module_dir_path):
item_path = os.path.join(module_dir_path, item_name)
if os.path.isfile(ite... | You are a Python code generator, capable of creating scripts from specifications. |
def _remove_init_all(r):
"""Remove any __all__ in __init__.py file."""
new_r = redbaron.NodeList()
for n in r.node_list:
if n.type == 'assignment' and n.target.value == '__all__':
pass
else:
new_r.append(n)
return new_r | Can you create a Python 3 function that
removes any __all__ in __init__. py file. | As a Python code composer, you craft elegant and concise scripts. |
Return a JSON representation of the object list. | Can you generate a brief explanation for the following Python 3 code
def get_object_list_json(request):
# TODO: Add to documentation
if "f" in request.GET:
field_list = request.GET.getlist("f")
else:
field_list = None
result_dict = d1_gmn.app.views.util.query_object_list(request, "objec... | As a Python code analyst, you investigate and solve complex coding mysteries |
def configure_logging(emit_list):
"""Configure logging to send log records to the master."""
if 'sphinx' in sys.modules:
module_base = 'resolwe.flow.executors'
else:
module_base = 'executors'
logging_config = dict(
version=1,
formatters={
'json_formatter': {
... | Write a Python 3 function that can
configure logging to send log records to the master. | As a python code expert, you are capable of creating scripts from specifications. |
Dump the record to JSON. | Here you have a function in Python 3, explain what it does
def format(self, record):
data = record.__dict__.copy()
data['data_id'] = DATA['id']
data['data_location_id'] = DATA_LOCATION['id']
data['hostname'] = socket.gethostname()
# Get relative path, so listener can reconstruc... | As a Python code composer, you craft elegant and concise scripts. |
def emit(self, record):
"""Send log message to the listener."""
future = asyncio.ensure_future(send_manager_command(
ExecutorProtocol.LOG,
extra_fields={
ExecutorProtocol.LOG_MESSAGE: self.format(record),
},
expect_reply=False
))
... | How would you code a function in Python 3 to
send log message to the listener. | You are a Python code generator, capable of creating scripts from specifications. |
Check if object with pid has successfully synced to CN. | How would you explain what the following Python 3 function does
async def is_object_synced_to_cn(self, client, pid):
status = await client.describe(pid)
if status == 200:
self.progress_logger.event("SciObj already synced on CN")
return True
elif status == 404:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
async def send_synchronization_request(self, client, pid):
"""Issue a notification and request for sync for object with {pid} to the CN."""
# Skip CN call for debugging
# status = 200
status = await client.synchronize(pid)
if status == 200:
self.progress_logger.event(... | Can you implement a function in Python 3 that
issues a notification and request for sync for object with pid to the CN. | As a python code expert, you are capable of creating scripts from specifications. |
def create_secret(self, value, contributor, metadata=None, expires=None):
"""Create a new secret, returning its handle.
:param value: Secret value to store
:param contributor: User owning the secret
:param metadata: Optional metadata dictionary (must be JSON serializable)
:param... | Implement a function in Python 3 to
create a new secret returning its handle. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_secret(self, handle, contributor):
"""Retrieve an existing secret's value.
:param handle: Secret handle
:param contributor: User instance to perform contributor validation,
which means that only secrets for the given contributor will be
looked up.
"""
... | Write a Python 3 function that can
retrieve an existing secret s value. | As a python code expert, you are capable of creating scripts from specifications. |
def validation_schema(name):
"""Return json schema for json validation."""
schemas = {
'processor': 'processSchema.json',
'descriptor': 'descriptorSchema.json',
'field': 'fieldSchema.json',
'type': 'typeSchema.json',
}
if name not in schemas:
raise ValueError()
... | Write a Python 3 function for
returning json schema for json validation. | As a python code expert, you are capable of creating scripts from specifications. |
Validate that the given instance and schema are consistent with our data types. | Can you generate the documentation for the following Python 3 function
def validate_schema(instance, schema, test_required=True, data_location=None,
skip_missing_data=False):
"""Check if DictField values are consistent with our data types.
Perform basic JSON schema validation and our custom... | You are a Python code analyst, evaluating scripts for potential improvements. |
Hydrate basic file and basic. json values. | Can you tell what is the following Python 3 function doing
def _hydrate_values(output, output_schema, data):
def hydrate_path(file_name):
"""Hydrate file paths."""
from resolwe.flow.managers import manager
class HydratedPath(str):
"""String wrapper, which also stores the origina... | As a Python code analyst, you investigate and solve complex coding mysteries |
Hydrate input_ with linked data. | Can you generate the documentation for the following Python 3 function
def hydrate_input_references(input_, input_schema, hydrate_values=True):
from .data import Data # prevent circular import
for field_schema, fields in iterate_fields(input_, input_schema):
name = field_schema['name']
value =... | As a python code expert, you are capable of creating scripts from specifications. |
Hydrate input basic : upload types with upload location. | How would you explain what the following Python 3 function does
def hydrate_input_uploads(input_, input_schema, hydrate_values=True):
from resolwe.flow.managers import manager
files = []
for field_schema, fields in iterate_fields(input_, input_schema):
name = field_schema['name']
value = fi... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Populates the size of all files and directories of all objects in the object. | Can you generate a brief explanation for the following Python 3 code
def hydrate_size(data, force=False):
from .data import Data # prevent circular import
def get_dir_size(path):
"""Get directory size."""
total_size = 0
for dirpath, _, filenames in os.walk(path):
for file_n... | You are a Python code generator, capable of creating scripts from specifications. |
Render data descriptor.
The rendering is based on descriptor schema and input context.
:param data: data instance
:type data: :class:`resolwe.flow.models.Data` or :class:`dict` | How would you explain what the following Python 3 function does
def render_descriptor(data):
if not data.descriptor_schema:
return
# Set default values
for field_schema, field, path in iterate_schema(data.descriptor, data.descriptor_schema.schema, 'descriptor'):
if 'default' in field_schema... | As a python code expert, you are capable of creating scripts from specifications. |
Render a template using the specified expression engine. | Make a summary of the following Python 3 code
def render_template(process, template_string, context):
from resolwe.flow.managers import manager
# Get the appropriate expression engine. If none is defined, do not evaluate
# any expressions.
expression_engine = process.requirements.get('expression-engine... | You are a Python code analyst, evaluating scripts for potential improvements. |
Convert a JSON path to individual path components. | Can you tell what is the following Python 3 function doing
def json_path_components(path):
if isinstance(path, str):
path = path.split('.')
return list(path) | You are a Python code generator, capable of creating scripts from specifications. |
Perform process subtype validation. | Explain what the following Python 3 code does
def validate_process_subtype(supertype_name, supertype, subtype_name, subtype):
errors = []
for item in supertype:
# Ensure that the item exists in subtype and has the same schema.
for subitem in subtype:
if item['name'] != subitem['name'... | You are a Python code generator, capable of creating scripts from specifications. |
def validate_process_types(queryset=None):
"""Perform process type validation.
:param queryset: Optional process queryset to validate
:return: A list of validation error strings
"""
if not queryset:
from .process import Process
queryset = Process.objects.all()
processes = {}
... | Create a Python 3 function to
perform process type validation. | As a python code expert, you are capable of creating scripts from specifications. |
def fill_with_defaults(process_input, input_schema):
"""Fill empty optional fields in input with default values."""
for field_schema, fields, path in iterate_schema(process_input, input_schema):
if 'default' in field_schema and field_schema['name'] not in fields:
dict_dot(process_input, path... | Write a Python 3 function for
filling empty optional fields in input with default values. | You are a Python code architect, reviewing and designing scalable and efficient code |
def to_internal_value(self, data):
"""Format the internal value."""
# When setting the contributor, it may be passed as an integer.
if isinstance(data, dict) and isinstance(data.get('id', None), int):
data = data['id']
elif isinstance(data, int):
pass
else... | Implement a function in Python 3 to
format the internal value. | As a Python code analyst, you investigate and solve complex coding mysteries |
Extract data from the descriptor. | Can you generate the documentation for the following Python 3 function
def extract_descriptor(self, obj):
descriptor = []
def flatten(current):
"""Flatten descriptor."""
if isinstance(current, dict):
for key in current:
flatten(current[key])
... | As a python code expert, you are capable of creating scripts from specifications. |
Return serialized items or list of ids depending on hydrate_XXX query param. | Make a summary of the following Python 3 code
def _serialize_items(self, serializer, kind, items):
if self.request and self.request.query_params.get('hydrate_{}'.format(kind), False):
serializer = serializer(items, many=True, read_only=True)
serializer.bind(kind, self)
return... | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_entity_names(self, data):
"""Return serialized list of entity names on data that user has `view` permission on."""
entities = self._filter_queryset('view_entity', data.entity_set.all())
return list(entities.values_list('name', flat=True)) | Can you write a function in Python 3 where it
returns serialized list of entity names on data that user has view permission on. | As a python code expert, you are capable of creating scripts from specifications. |
def get_collections(self, data):
"""Return serialized list of collection objects on data that user has `view` permission on."""
collections = self._filter_queryset('view_collection', data.collection_set.all())
from .collection import CollectionSerializer
class CollectionWithoutDataSeri... | How would you implement a function in Python 3 that
returns serialized list of collection objects on data that user has view permission on. | As a Python code composer, you craft elegant and concise scripts. |
def get_entities(self, data):
"""Return serialized list of entity objects on data that user has `view` permission on."""
entities = self._filter_queryset('view_entity', data.entity_set.all())
from .entity import EntitySerializer
class EntityWithoutDataSerializer(WithoutDataSerializerMi... | Write a Python 3 function that can
return serialized list of entity objects on data that user has view permission on. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def handle(self, *args, **options):
"""Handle command list_docker_images."""
verbosity = int(options.get('verbosity'))
# Check that the specified output format is valid
if options['format'] != 'plain' and options['format'] != 'yaml':
raise CommandError("Unknown output format... | How would you code a function in Python 3 to
handle the list_docker_images command. | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_or_create(self, request, *args, **kwargs):
"""Get ``Data`` object if similar already exists, otherwise create it."""
kwargs['get_or_create'] = True
return self.create(request, *args, **kwargs) | Can you implement a function in Python 3 that
gets or create a Data object if similar already exists otherwise create it. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def perform_get_or_create(self, request, *args, **kwargs):
"""Perform "get_or_create" - return existing object if found."""
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
process = serializer.validated_data.get('process')
process_inp... | Create a Python 3 function to
perform get_or_create - return existing object if found. | You are a Python code generator, capable of creating scripts from specifications. |
Called once per Django process instance. | Explain what the following Python 3 code does
def ready(self):
# Stop the startup code from running automatically from pytest unit tests.
# When running tests in parallel with xdist, an instance of GMN is launched
# before thread specific settings have been applied.
# if hasattr(sys, '_l... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _assert_dirs_exist(self, setting_name):
"""Check that the dirs leading up to the given file path exist.
Does not check if the file exists.
"""
v = self._get_setting(setting_name)
if (not os.path.isdir(os.path.split(v)[0])) or os.path.isdir(v):
self.raise_config_... | Write a Python 3 function for
checking that the dirs leading up to the given file path exist. | You are a Python code architect, reviewing and designing scalable and efficient code |
Warn on settings that are not safe for production. | Here you have a function in Python 3, explain what it does
def _warn_unsafe_for_prod(self):
safe_settings_list = [
('DEBUG', False),
('DEBUG_GMN', False),
('STAND_ALONE', False),
('DATABASES.default.ATOMIC_REQUESTS', True),
('SECRET_KEY', '<Do not modi... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _get_setting(self, setting_dotted_name, default=None):
"""Return the value of a potentially nested dict setting.
E.g., 'DATABASES.default.NAME
"""
name_list = setting_dotted_name.split('.')
setting_obj = getattr(django.conf.settings, name_list[0], default)
# if len(... | Create a Python 3 function to
get a potentially nested dict setting. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _refresh_connection(self):
"""Refresh connection to Elasticsearch when worker is started.
File descriptors (sockets) can be shared between multiple
threads. If same connection is used by multiple threads at the
same time, this can cause timeouts in some of the pushes. So
con... | Write a Python 3 script for
refreshing the connection to Elasticsearch when worker is started. | As a Python code analyst, you investigate and solve complex coding mysteries |
def generate_id(self, obj):
"""Generate unique document id for ElasticSearch."""
object_type = type(obj).__name__.lower()
return '{}_{}'.format(object_type, self.get_object_id(obj)) | Can you write a function in Python 3 where it
generates unique document id for ElasticSearch. | As a Python code analyst, you investigate and solve complex coding mysteries |
Process the current object and push it to the ElasticSearch index. | Make a summary of the following Python 3 code
def process_object(self, obj):
document = self.document_class(meta={'id': self.generate_id(obj)})
for field in document._doc_type.mapping: # pylint: disable=protected-access
if field in ['users_with_permissions', 'groups_with_permissions', 'pub... | As a Python code analyst, you investigate and solve complex coding mysteries |
def create_mapping(self):
"""Create the mappings in elasticsearch."""
try:
self.document_class.init()
self._mapping_created = True
except IllegalOperation as error:
if error.args[0].startswith('You cannot update analysis configuration'):
# Igno... | Create a Python 3 function to
create the mappings in elasticsearch. | You are a Python code architect, reviewing and designing scalable and efficient code |
def push(self):
"""Push built documents to ElasticSearch."""
self._refresh_connection()
# Check if we need to update mappings as this needs to be done
# before we push anything to the Elasticsearch server.
# This must be done even if the queue is empty, as otherwise ES
#... | Write a Python 3 function that can
push built documents to Elasticsearch server. | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_permissions(self, obj):
"""Return users and groups with ``view`` permission on the current object.
Return a dict with two keys - ``users`` and ``groups`` - which
contain list of ids of users/groups with ``view`` permission.
"""
# TODO: Optimize this for bulk running
... | Can you create a Python 3 function that
returns users and groups with view permission on the current object. | You are a Python code analyst, evaluating scripts for potential improvements. |
Remove current object from the ElasticSearch index. | Make a summary of the following Python 3 code
def remove_object(self, obj):
obj_id = self.generate_id(obj)
es_obj = self.document_class.get(obj_id, ignore=[404])
# Object may not exist in this index.
if es_obj:
es_obj.delete(refresh=True) | You are a Python code analyst, evaluating scripts for potential improvements. |
def generate_pyxb_binding(self, args):
"""Args:
args:
"""
pyxbgen_args = []
pyxbgen_args.append('--schema-root=\'{}\''.format(self.schema_dir))
pyxbgen_args.append('--binding-root=\'{}\''.format(self.binding_dir))
pyxbgen_args.append(
'--schema-strip... | Can you write a function in Python 3 where it
generates a new entry point for the current locale. | You are a Python code generator, capable of creating scripts from specifications. |
Given a DataONE schema generates a file that contains version information
about the schema. | How would you explain what the following Python 3 function does
def generate_version_file(self, schema_filename, binding_filename):
version_filename = binding_filename + '_version.txt'
version_path = os.path.join(self.binding_dir, version_filename)
schema_path = os.path.join(self.schema_dir, sch... | As a Python code analyst, you investigate and solve complex coding mysteries |
def set_data_location(apps, schema_editor):
"""Create DataLocation for each Data."""
Data = apps.get_model('flow', 'Data')
DataLocation = apps.get_model('flow', 'DataLocation')
for data in Data.objects.all():
if os.path.isdir(os.path.join(settings.FLOW_EXECUTOR['DATA_DIR'], str(data.id))):
... | Can you implement a function in Python 3 that
creates DataLocation for each Data. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _loadMore(self, start=0, trys=0, validation=True):
"""Retrieves the next page of results."""
self._log.debug("Loading page starting from %d" % start)
self._czero = start
self._pageoffs = 0
try:
pyxb.RequireValidWhenParsing(validation)
self._object_list... | Write a Python 3 script to
retrieve the next page of results. | You are a Python code generator, capable of creating scripts from specifications. |
def parse_mime_type(mime_type):
"""Carves up a mime-type and returns a tuple of the (type, subtype, params) where
'params' is a dictionary of all the parameters for the media range. For example, the
media range 'application/xhtml;q=0.5' would get parsed into:
('application', 'xhtml', {'q', '0.5'})
... | Write a Python 3 script for
carving up a mime - type and returns a tuple of the type subtype and params. | You are a Python code analyst, evaluating scripts for potential improvements. |
def best_match(supported, header):
"""Takes a list of supported mime-types and finds the best match for all the media-
ranges listed in header. The value of header must be a string that conforms to the
format of the HTTP Accept: header. The value of 'supported' is a list of mime-types.
>>> best_match([... | Can you implement a function in Python 3 that
takes a list of supported mime - types and finds the best match for all the media - types listed in header. | As a Python code translator, you convert algorithms and pseudocode into Python. |
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 memo... | Implement a Python 3 function for
chunking 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: ... | As a Python code composer, you craft elegant and concise scripts. |
Duplicate ( make a copy ) Data objects. | Can you tell what is the following Python 3 function doing
def duplicate(self, contributor=None):
bundle = [
{'original': data, 'copy': data.duplicate(contributor=contributor)}
for data in self
]
bundle = rewire_inputs(bundle)
duplicated = [item['copy'] for item ... | You are a Python code architect, reviewing and designing scalable and efficient code |
Save basic : json values to a Storage collection. | Explain what the following Python 3 code does
def save_storage(self, instance, schema):
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... | As a Python code composer, you craft elegant and concise scripts. |
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... | Create a Python 3 function to
retrieve handles for all basic : secret fields on input. | As a python code expert, you are capable of creating scripts from specifications. |
def save_dependencies(self, instance, schema):
"""Save data: and list:data: references as parents."""
def add_dependency(value):
"""Add parent Data dependency."""
try:
DataDependency.objects.update_or_create(
parent=Data.objects.get(pk=value),
... | Can you create a Python 3 function that
saves data and list : data references as parents. | As a Python code translator, you convert algorithms and pseudocode into Python. |
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 paren... | Implement a function in Python 3 to
create a new entity if flow_collection is defined in process. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def save(self, render_name=False, *args, **kwargs): # pylint: disable=keyword-arg-before-vararg
"""Save the data model."""
if self.name != self._original_name:
self.named_by_user = True
create = self.pk is None
if create:
fill_with_defaults(self.input, self.proc... | How would you code a function in Python 3 to
save the data model. | You are a Python code analyst, evaluating scripts for potential improvements. |
def delete(self, *args, **kwargs):
"""Delete the data model."""
# 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.... | Can you create a Python 3 function that
deletes the data model. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def duplicate(self, contributor=None):
"""Duplicate (make a copy)."""
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 = Non... | Create a Python 3 function to
create a duplicate of this data object. | As a python code expert, you are capable of creating scripts from specifications. |
def _render_name(self):
"""Render data name.
The rendering is based on name template (`process.data_name`) and
input context.
"""
if not self.process.data_name or self.named_by_user: # pylint: disable=no-member
return
inputs = copy.deepcopy(self.input)
... | Implement a Python 3 function for
rendering data name. The rendering is based on name template (`process.data_name`) and input context. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_path(self, prefix=None, filename=None):
"""Compose data location path."""
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 | Create a Python 3 function for
composing data location path. | You are a Python code generator, capable of creating scripts from specifications. |
def get_runtime_path(self, filename=None):
"""Compose data runtime location path."""
return self.get_path(prefix=settings.FLOW_EXECUTOR['RUNTIME_DIR'], filename=filename) | Can you create a Python 3 function that
composes data runtime location path. | As a python code expert, you are capable of creating scripts from specifications. |
def get_data(self, entity):
"""Return serialized list of data objects on entity that user has `view` permission on."""
data = self._filter_queryset('view_data', entity.data.all())
return self._serialize_data(data) | Can you implement a function in Python 3 that
returns serialized list of data objects on entity that user has view permission on. | You are a Python code analyst, evaluating scripts for potential improvements. |
Return the process schema for this process. | Can you generate a brief explanation for the following Python 3 code
def to_schema(self):
process_type = self.metadata.process_type
if not process_type.endswith(':'):
process_type = '{}:'.format(process_type)
schema = {
'slug': self.metadata.slug,
'name': sel... | As a Python code analyst, you investigate and solve complex coding mysteries |
Pull Docker images needed by processes after registering. | Can you tell what is the following Python 3 function doing
def post_register_hook(self, verbosity=1):
if not getattr(settings, 'FLOW_DOCKER_DONT_PULL', False):
call_command('list_docker_images', pull=True, verbosity=verbosity) | You are a Python code architect, reviewing and designing scalable and efficient code |
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 usin... | Can you implement a function in Python 3 that
resolves the data path for use with the executor. | You are a Python code analyst, evaluating scripts for potential improvements. |
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
"""
... | Implement a function in Python 3 to
resolve the upload path for use with the executor. | As a python code expert, you are capable of creating scripts from specifications. |
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 flo... | Implement a Python 3 function for
determining if two datetimes are equal with fuzz factor. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Format datetime to HTTP Full Date format. | Given the following Python 3 function, write the documentation
def http_datetime_str_from_dt(dt):
epoch_seconds = ts_from_dt(dt)
return email.utils.formatdate(epoch_seconds, localtime=False, usegmt=True) | As a Python code translator, you convert algorithms and pseudocode into Python. |
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 ; ... | Create a Python 3 function for
parsing the HTTP Full Date formats and return as datetime. | You are a Python code analyst, evaluating scripts for potential improvements. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.