output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Connect to the database. | Make a summary of the following Python 3 code
def connect(self, dsn):
self.con = psycopg2.connect(dsn)
self.cur = self.con.cursor(cursor_factory=psycopg2.extras.DictCursor)
# autocommit: Disable automatic transactions
self.con.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOC... | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_query_param(self, key, default=None):
"""Get query parameter uniformly for GET and POST requests."""
value = self.request.query_params.get(key, None)
if value is None:
value = self.request.data.get(key, None)
if value is None:
value = default
retur... | Implement a Python 3 function for
getting a query parameter uniformly for GET and POST requests. | You are a Python code generator, capable of creating scripts from specifications. |
def get_query_params(self):
"""Get combined query parameters (GET and POST)."""
params = self.request.query_params.copy()
params.update(self.request.data)
return params | Implement a function in Python 3 to
get combined query parameters. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def order_search(self, search):
"""Order given search by the ordering parameter given in request.
:param search: ElasticSearch query object
"""
ordering = self.get_query_param('ordering', self.ordering)
if not ordering:
return search
sort_fields = []
... | Create a Python 3 function for
ordering given search by the ordering parameter given in request. | You are a Python code generator, capable of creating scripts from specifications. |
def filter_search(self, search):
"""Filter given search by the filter parameter given in request.
:param search: ElasticSearch query object
"""
builder = QueryBuilder(
self.filtering_fields,
self.filtering_map,
self
)
search, unmatche... | Write a Python 3 function for
filtering given search by the filter parameter given in request. | You are a Python code architect, reviewing and designing scalable and efficient code |
def filter_permissions(self, search):
"""Filter given query based on permissions of the user in the request.
:param search: ElasticSearch query object
"""
user = self.request.user
if user.is_superuser:
return search
if user.is_anonymous:
user = g... | Can you create a Python 3 function that
filters given query based on permissions of the user in the request. | As a python code expert, you are capable of creating scripts from specifications. |
Optionally return paginated response. | Can you generate the documentation for the following Python 3 function
def paginate_response(self, queryset, serializers_kwargs={}):
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True, **serializers_kwargs)
return self.ge... | You are a Python code analyst, evaluating scripts for potential improvements. |
Handle the search request. | Make a summary of the following Python 3 code
def search(self):
search = self.document_class().search() # pylint: disable=not-callable
search = self.custom_filter(search)
search = self.filter_search(search)
search = self.order_search(search)
search = self.filter_permissions(se... | You are a Python code architect, reviewing and designing scalable and efficient code |
def getattr(self, path, fh):
"""Called by FUSE when the attributes for a file or directory are required.
Returns a dictionary with keys identical to the stat C structure of stat(2).
st_atime, st_mtime and st_ctime should be floats. On OSX, st_nlink should count
all files inside the dire... | Write a Python 3 function for
calling by FUSE when the attributes for a file or directory are required. | You are a Python code analyst, evaluating scripts for potential improvements. |
def readdir(self, path, fh):
"""Called by FUSE when a directory is opened.
Returns a list of file and directory names for the directory.
"""
log.debug('readdir(): {}'.format(path))
try:
dir = self._directory_cache[path]
except KeyError:
dir = sel... | Write a Python 3 script to
call by FUSE when a directory is opened. Returns a list of file and directory names for the directory. | As a Python code composer, you craft elegant and concise scripts. |
def open(self, path, flags):
"""Called by FUSE when a file is opened.
Determines if the provided path and open flags are valid.
"""
log.debug('open(): {}'.format(path))
# ONEDrive is currently read only. Anything but read access is denied.
if (flags & self._READ_ONLY_AC... | Create a Python 3 function to
call by FUSE when a file is opened. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_inline_expression(self, text):
"""Extract an inline expression from the given text."""
text = text.strip()
if not text.startswith(self.inline_tags[0]) or not text.endswith(self.inline_tags[1]):
return
return text[2:-2] | Write a Python 3 script for
extracting an inline expression from the given text. | You are a Python code generator, capable of creating scripts from specifications. |
def _filter_queryset(self, queryset):
"""Filter queryset by entity, label and position.
Due to a bug in django-filter these filters have to be applied
manually:
https://github.com/carltongibson/django-filter/issues/883
"""
entities = self.request.query_params.getlist('en... | Implement a Python 3 function for
filtering queryset by entity label and position. | As a Python code composer, you craft elegant and concise scripts. |
Update the relation object. | Make a summary of the following Python 3 code
def update(self, request, *args, **kwargs):
instance = self.get_object()
if (not request.user.has_perm('edit_collection', instance.collection)
and not request.user.is_superuser):
return Response(status=status.HTTP_401_UNAUTHORIZED... | As a Python code composer, you craft elegant and concise scripts. |
def _process_permission(perm):
"""Rebuild indexes affected by the given permission."""
# XXX: Optimize: rebuild only permissions, not whole document
codename = perm.permission.codename
if not codename.startswith('view') and not codename.startswith('owner'):
return
index_builder.build(perm.c... | Write a Python 3 script for
rebuilding indexes affected by the given permission. | You are a Python code generator, capable of creating scripts from specifications. |
Parse a multipart Requests. Response into a tuple of BodyPart objects. | Explain what the following Python 3 code does
def parse_response(response, encoding='utf-8'):
return requests_toolbelt.multipart.decoder.MultipartDecoder.from_response(
response, encoding
).parts | As a Python code analyst, you investigate and solve complex coding mysteries |
def parse_str(mmp_bytes, content_type, encoding='utf-8'):
"""Parse multipart document bytes into a tuple of BodyPart objects.
Args:
mmp_bytes: bytes
Multipart document.
content_type : str
Must be on the form, ``multipart/form-data; boundary=<BOUNDARY>``, where
``<BOUNDARY>`... | Implement a Python 3 function for
parsing a string representation of a multipart document into a tuple of BodyPart objects. | You are a Python code generator, capable of creating scripts from specifications. |
def normalize(body_part_tup,):
"""Normalize a tuple of BodyPart objects to a string.
Normalization is done by sorting the body_parts by the Content- Disposition headers,
which is typically on the form, ``form-data; name="name_of_part``.
"""
return '\n\n'.join(
[
'{}\n\n{}'.form... | How would you implement a function in Python 3 that
normalizes a tuple of BodyPart objects to a string. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Checks if the given dict contains a Content - Type key that starts with multipart. | Explain what the following Python 3 code does
def is_multipart(header_dict):
return (
{k.lower(): v for k, v in header_dict.items()}
.get('content-type', '')
.startswith('multipart')
) | As a Python code composer, you craft elegant and concise scripts. |
Split the path by reserved name. | Can you generate the documentation for the following Python 3 function
def _split_path_by_reserved_name(self, path):
for i, e in enumerate(path):
if e in self._resolvers or e == self._get_readme_filename():
return path[:i], path[i], path[i + 1 :]
raise d1_onedrive.impl.onedri... | You are a Python code generator, capable of creating scripts from specifications. |
def _generate_readme_text(self, object_tree_path):
"""Generate a human readable description of the folder in text format."""
wdef_folder = self._object_tree.get_source_tree_folder(object_tree_path)
res = StringIO()
if len(object_tree_path):
folder_name = object_tree_path[-1]... | Write a Python 3 function that can
generate a human readable description of the folder in text format. | As a python code expert, you are capable of creating scripts from specifications. |
def _serialize_data(self, data):
"""Return serialized data or list of ids, depending on `hydrate_data` query param."""
if self.request and self.request.query_params.get('hydrate_data', False):
serializer = DataSerializer(data, many=True, read_only=True)
serializer.bind('data', se... | Write a Python 3 function for
returning serialized data or list of ids depending on hydrate_data query param. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _filter_queryset(self, perms, queryset):
"""Filter object objects by permissions of user in request."""
user = self.request.user if self.request else AnonymousUser()
return get_objects_for_user(user, perms, queryset) | Create a Python 3 function to
filter object objects by permissions of user in request. | You are a Python code generator, capable of creating scripts from specifications. |
Return serialized list of data objects on collection that user has view permission on. | Here you have a function in Python 3, explain what it does
def get_data(self, collection):
data = self._filter_queryset('view_data', collection.data.all())
return self._serialize_data(data) | As a python code expert, you are capable of creating scripts from specifications. |
Dynamically adapt fields based on the current request. | Given the following Python 3 function, write the documentation
def get_fields(self):
fields = super(CollectionSerializer, self).get_fields()
if self.request.method == "GET":
fields['data'] = serializers.SerializerMethodField()
else:
fields['data'] = serializers.PrimaryKe... | You are a Python code generator, capable of creating scripts from specifications. |
def is_sysmeta_pyxb(sysmeta_pyxb):
"""Args: sysmeta_pyxb: Object that may or may not be a SystemMetadata PyXB object.
Returns:
bool:
- ``True`` if ``sysmeta_pyxb`` is a SystemMetadata PyXB object.
- ``False`` if ``sysmeta_pyxb`` is not a PyXB object or is a PyXB object of a
type... | Can you create a Python 3 function that
returns True if sysmeta_pyxb is a SystemMetadata PyXB object. | You are a Python code architect, reviewing and designing scalable and efficient code |
Normalizes SystemMetadata PyXB object in - place. | Can you generate the documentation for the following Python 3 function
def normalize_in_place(sysmeta_pyxb, reset_timestamps=False):
if sysmeta_pyxb.accessPolicy is not None:
sysmeta_pyxb.accessPolicy = d1_common.wrap.access_policy.get_normalized_pyxb(
sysmeta_pyxb.accessPolicy
)
if ... | As a Python code composer, you craft elegant and concise scripts. |
Determine if two SystemMetadata PyXB objects are semantically equivalent. | Make a summary of the following Python 3 code
def are_equivalent_pyxb(a_pyxb, b_pyxb, ignore_timestamps=False):
normalize_in_place(a_pyxb, ignore_timestamps)
normalize_in_place(b_pyxb, ignore_timestamps)
a_xml = d1_common.xml.serialize_to_xml_str(a_pyxb)
b_xml = d1_common.xml.serialize_to_xml_str(b_pyxb... | As a python code expert, you are capable of creating scripts from specifications. |
def are_equivalent_xml(a_xml, b_xml, ignore_timestamps=False):
"""Determine if two SystemMetadata XML docs are semantically equivalent.
Normalize then compare SystemMetadata XML docs for equivalency.
Args:
a_xml, b_xml: bytes
UTF-8 encoded SystemMetadata XML docs to compare
ignore_tim... | How would you implement a function in Python 3 that
determines if two SystemMetadata XML docs are semantically equivalent. | You are a Python code analyst, evaluating scripts for potential improvements. |
def clear_elements(sysmeta_pyxb, clear_replica=True, clear_serial_version=True):
"""{clear_replica} causes any replica information to be removed from the object.
{clear_replica} ignores any differences in replica information, as this information
is often different between MN and CN.
"""
if clear_r... | Can you implement a function in Python 3 that
clears the sysmeta_pyxb s elements. | As a Python code analyst, you investigate and solve complex coding mysteries |
def update_elements(dst_pyxb, src_pyxb, el_list):
"""Copy elements specified in ``el_list`` from ``src_pyxb`` to ``dst_pyxb``
Only elements that are children of root are supported. See
SYSMETA_ROOT_CHILD_LIST.
If an element in ``el_list`` does not exist in ``src_pyxb``, it is removed from
``dst_py... | Can you create a Python 3 function that
copies elements specified in el_list from src_pyxb to dst_pyxb. | As a python code expert, you are capable of creating scripts from specifications. |
def get_full_perm(perm, obj):
"""Join action with the content type of ``obj``.
Permission is returned in the format of ``<action>_<object_type>``.
"""
ctype = ContentType.objects.get_for_model(obj)
# Camel case class names are converted into a space-separated
# content types, so spaces have to ... | Implement a Python 3 function for
joining action with the content type of obj. | You are a Python code generator, capable of creating scripts from specifications. |
Copy permissions from src_obj to dest_obj. | Can you generate a brief explanation for the following Python 3 code
def copy_permissions(src_obj, dest_obj):
def _process_permission(codename, user_or_group, dest_obj, relabel):
"""Process single permission."""
if relabel:
codename = change_perm_ctype(codename, dest_obj)
if ... | You are a Python code generator, capable of creating scripts from specifications. |
def fetch_user(query):
"""Get user by ``pk`` or ``username``. Raise error if it doesn't exist."""
user_filter = {'pk': query} if query.isdigit() else {'username': query}
user_model = get_user_model()
try:
return user_model.objects.get(**user_filter)
except user_model.DoesNotExist:
r... | Write a Python 3 function that can
get user by pk or username. Raise error if it doesn t exist. | You are a Python code analyst, evaluating scripts for potential improvements. |
def fetch_group(query):
"""Get group by ``pk`` or ``name``. Raise error if it doesn't exist."""
group_filter = {'pk': query} if query.isdigit() else {'name': query}
try:
return Group.objects.get(**group_filter)
except Group.DoesNotExist:
raise exceptions.ParseError("Unknown group: {}".f... | Write a Python 3 function for
getting group by pk or name. Raise error if it doesn t exist. | As a Python code analyst, you investigate and solve complex coding mysteries |
Raise PermissionDenied if owner is not allowed. | Given the following Python 3 function, write the documentation
def check_owner_permission(payload, allow_user_owner):
for entity_type in ['users', 'groups']:
for perm_type in ['add', 'remove']:
for perms in payload.get(entity_type, {}).get(perm_type, {}).values():
if 'owner' in p... | You are a Python code analyst, evaluating scripts for potential improvements. |
Raise PermissionDenied if public permissions are too open. | Given the following Python 3 function, write the documentation
def check_public_permissions(payload):
allowed_public_permissions = ['view', 'add', 'download']
for perm_type in ['add', 'remove']:
for perm in payload.get('public', {}).get(perm_type, []):
if perm not in allowed_public_permissio... | As a Python code composer, you craft elegant and concise scripts. |
def check_user_permissions(payload, user_pk):
"""Raise ``PermissionDenied`` if ``payload`` includes ``user_pk``."""
for perm_type in ['add', 'remove']:
user_pks = payload.get('users', {}).get(perm_type, {}).keys()
if user_pk in user_pks:
raise exceptions.PermissionDenied("You cannot ... | Write a Python 3 function for
raising PermissionDenied if user_pk is not in the payload. | As a Python code composer, you craft elegant and concise scripts. |
def remove_permission(payload, permission):
"""Remove all occurrences of ``permission`` from ``payload``."""
payload = copy.deepcopy(payload)
for entity_type in ['users', 'groups']:
for perm_type in ['add', 'remove']:
for perms in payload.get(entity_type, {}).get(perm_type, {}).values()... | Write a Python 3 function that can
remove all occurrences of permission from payload. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Update object s permissions using given data. | How would you explain what the following Python 3 function does
def update_permission(obj, data):
full_permissions = get_all_perms(obj)
def apply_perm(perm_func, perms, entity):
"""Apply permissions using given ``perm_func``.
``perm_func`` is intended to be ``assign_perms`` or
``remove... | As a Python code composer, you craft elegant and concise scripts. |
Assign all permissions to object s contributor. | Explain what the following Python 3 code does
def assign_contributor_permissions(obj, contributor=None):
for permission in get_all_perms(obj):
assign_perm(permission, contributor if contributor else obj.contributor, obj) | You are a Python code architect, reviewing and designing scalable and efficient code |
async def run_script(self, script):
"""Execute the script and save results."""
script = os.linesep.join(['set -x', 'set +B', script, 'exit']) + os.linesep
self.proc.stdin.write(script.encode('utf-8'))
await self.proc.stdin.drain()
self.proc.stdin.close() | Can you implement a function in Python 3 that
executes the script and save results. | You are a Python code generator, capable of creating scripts from specifications. |
Terminate a running script. | Here you have a function in Python 3, explain what it does
async def terminate(self):
self.proc.terminate()
await asyncio.wait_for(self.proc.wait(), self.kill_delay)
if self.proc.returncode is None:
self.proc.kill()
await self.proc.wait()
await super().terminate() | You are a Python code architect, reviewing and designing scalable and efficient code |
async def _make_connection(self):
"""Construct a connection to Redis."""
return await aioredis.create_redis(
'redis://{}:{}'.format(
self._redis_params.get('host', 'localhost'),
self._redis_params.get('port', 6379)
),
db=int(self._redis... | How would you implement a function in Python 3 that
constructs a connection to Redis. | You are a Python code analyst, evaluating scripts for potential improvements. |
async def _call_redis(self, meth, *args, **kwargs):
"""Perform a Redis call and handle connection dropping."""
while True:
try:
if not self._redis:
self._redis = await self._make_connection()
return await meth(self._redis, *args, **kwargs)
... | Can you create a Python 3 function that
performs a Redis call and handle connection dropping. | As a Python code translator, you convert algorithms and pseudocode into Python. |
async def clear_queue(self):
"""Reset the executor queue channel to an empty state."""
conn = await self._make_connection()
try:
script = """
local keys = redis.call('KEYS', ARGV[1])
redis.call('DEL', unpack(keys))
"""
await con... | Can you implement a function in Python 3 that
clears the executor queue channel. | You are a Python code generator, capable of creating scripts from specifications. |
Stop the standalone manager. | Can you generate a brief explanation for the following Python 3 code
def terminate(self):
logger.info(__(
"Terminating Resolwe listener on channel '{}'.",
state.MANAGER_EXECUTOR_CHANNELS.queue
))
self._should_stop = True | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _queue_response_channel(self, obj):
"""Generate the feedback channel name from the object's id.
:param obj: The Channels message object.
"""
return '{}.{}'.format(state.MANAGER_EXECUTOR_CHANNELS.queue_response, obj[ExecutorProtocol.DATA_ID]) | Create a Python 3 function to
generate the feedback channel name from the object s id. | As a python code expert, you are capable of creating scripts from specifications. |
async def _send_reply(self, obj, reply):
"""Send a reply with added standard fields back to executor.
:param obj: The original Channels message object to which we're
replying.
:param reply: The message contents dictionary. The data id is
added automatically (``reply`` is... | Write a Python 3 script to
send a reply to the executor. | You are a Python code generator, capable of creating scripts from specifications. |
def hydrate_spawned_files(self, exported_files_mapper, filename, data_id):
"""Pop the given file's map from the exported files mapping.
:param exported_files_mapper: The dict of file mappings this
process produced.
:param filename: The filename to format and remove from the
... | Write a Python 3 script to
pop the given file s map from the exported files mapping. | You are a Python code architect, reviewing and designing scalable and efficient code |
Handles an incoming update request. | Here you have a function in Python 3, explain what it does
def handle_update(self, obj, internal_call=False):
data_id = obj[ExecutorProtocol.DATA_ID]
changeset = obj[ExecutorProtocol.UPDATE_CHANGESET]
if not internal_call:
logger.debug(
__("Handling update for Data wi... | As a python code expert, you are capable of creating scripts from specifications. |
def handle_finish(self, obj):
"""Handle an incoming ``Data`` finished processing request.
:param obj: The Channels message object. Command object format:
.. code-block:: none
{
'command': 'finish',
'data_id': [id of the :class:`~reso... | Can you create a Python 3 function that
handles an incoming Data finished processing request. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Handle an incoming Abort processing request. | Can you tell what is the following Python 3 function doing
def handle_abort(self, obj):
async_to_sync(consumer.send_event)({
WorkerProtocol.COMMAND: WorkerProtocol.ABORT,
WorkerProtocol.DATA_ID: obj[ExecutorProtocol.DATA_ID],
WorkerProtocol.FINISH_COMMUNICATE_EXTRA: {
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def handle_log(self, obj):
"""Handle an incoming log processing request.
:param obj: The Channels message object. Command object format:
.. code-block:: none
{
'command': 'log',
'message': [log message]
}
"""
... | Can you write a function in Python 3 where it
handles an incoming log processing request. | As a Python code translator, you convert algorithms and pseudocode into Python. |
async def push_stats(self):
"""Push current stats to Redis."""
snapshot = self._make_stats()
try:
serialized = json.dumps(snapshot)
await self._call_redis(aioredis.Redis.set, state.MANAGER_LISTENER_STATS, serialized)
await self._call_redis(aioredis.Redis.expir... | Write a Python 3 script for
pushing current stats to Redis. | You are a Python code analyst, evaluating scripts for potential improvements. |
def check_critical_load(self):
"""Check for critical load and log an error if necessary."""
if self.load_avg.intervals['1m'].value > 1:
if self.last_load_level == 1 and time.time() - self.last_load_log < 30:
return
self.last_load_log = time.time()
self... | How would you implement a function in Python 3 that
checks for critical load and log an error if necessary. | You are a Python code architect, reviewing and designing scalable and efficient code |
async def run(self):
"""Run the main listener run loop.
Doesn't return until :meth:`terminate` is called.
"""
logger.info(__(
"Starting Resolwe listener on channel '{}'.",
state.MANAGER_EXECUTOR_CHANNELS.queue
))
while not self._should_stop:
... | Implement a function in Python 3 to
run the main listener run loop. Doesn't return until :meth:`terminate` is called. | You are a Python code analyst, evaluating scripts for potential improvements. |
Issue callback to start dokan drive. | Can you generate the documentation for the following Python 3 function
def dokanMain(self, dokanOptions, dokanOperations):
return int(
self.dokanDLL.DokanMain(
PDOKAN_OPTIONS(dokanOptions), PDOKAN_OPERATIONS(dokanOperations)
)
) | As a Python code composer, you craft elegant and concise scripts. |
Creates a file in the cache. | Explain what the following Python 3 code does
def createFile(
self,
fileName,
desiredAccess,
shareMode,
creationDisposition,
flagsAndAttributes,
dokanFileInfo,
):
"""Creates a file.
:param fileName: name of file to create
:type fileNam... | As a Python code composer, you craft elegant and concise scripts. |
def readFile(
self,
fileName,
buffer,
numberOfBytesToRead,
numberOfBytesRead,
offset,
dokanFileInfo,
):
"""Read a file.
:param fileName: name of file to read
:type fileName: ctypes.c_wchar_p
:param buffer: buffer for content re... | Implement a Python 3 function for
reading a file from the Dokan and returns the size of the file. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def writeFile(
self,
fileName,
buffer,
numberOfBytesToWrite,
numberOfBytesWritten,
offset,
dokanFileInfo,
):
"""Read a file.
:param fileName: name of file to write
:type fileName: ctypes.c_wchar_p
:param buffer: buffer to write... | Can you implement a function in Python 3 that
writes a file from the cache. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def findFilesWithPattern(
self, fileName, searchPattern, fillFindData, dokanFileInfo
):
"""Find files in a certain path that match the search pattern.
:param fileName: path to search
:type fileName: ctypes.c_wchar_p
:param searchPattern: pattern to search for
:type s... | Create a Python 3 function for
finding files in a certain path that match the search pattern. :param fileName: path to search :type fileName: ctypes.c_wchar_p :param searchPattern: pattern to search for :type searchPattern: ctypes.c_wchar_p :param fillFindData: function pointer for populating search results :type fillF... | You are a Python code generator, capable of creating scripts from specifications. |
Set the file time values for a specific file. | Here you have a function in Python 3, explain what it does
def setFileTime(
self, fileName, creationTime, lastAccessTime, lastWriteTime, dokanFileInfo
):
"""Set time values for a file.
:param fileName: name of file to set time values for
:type fileName: ctypes.c_wchar_p
:par... | As a Python code analyst, you investigate and solve complex coding mysteries |
Move a file.
:param existingFileName: name of file to move
:type existingFileName: ctypes.c_wchar_p
:param newFileName: new name of file
:type newFileName: ctypes.c_wchar_p
:param replaceExisting: flag to indicate replacement of existing file
:type replaceExisting: ctype... | Explain what the following Python 3 code does
def moveFile(self, existingFileName, newFileName, replaceExisiting, dokanFileInfo):
return self.operations('moveFile', existingFileName, newFileName) | You are a Python code architect, reviewing and designing scalable and efficient code |
Lock a file.
:param fileName: name of file to lock
:type fileName: ctypes.c_wchar_p
:param byteOffset: location to start lock
:type byteOffset: ctypes.c_longlong
:param length: number of bytes to lock
:type length: ctypes.c_longlong
:param dokanFileInfo: used by ... | Explain what the following Python 3 code does
def lockFile(self, fileName, byteOffset, length, dokanFileInfo):
return self.operations('lockFile', fileName, byteOffset, length) | As a python code expert, you are capable of creating scripts from specifications. |
def unlockFile(self, fileName, byteOffset, length, dokanFileInfo):
"""Unlock a file.
:param fileName: name of file to unlock
:type fileName: ctypes.c_wchar_p
:param byteOffset: location to start unlock
:type byteOffset: ctypes.c_longlong
:param length: number of bytes to... | How would you implement a function in Python 3 that
unlocks a file. :param fileName: name of file to unlock :type fileName: ctypes.c_wchar_p :param byteOffset: location to start unlock :type byteOffset: ctypes.c_longlong :param length: number of bytes to unlock :type length: ctypes.c_longlong :param dokanFileInfo: used... | As a Python code analyst, you investigate and solve complex coding mysteries |
This method returns the amount of free space on this volume. | Make a summary of the following Python 3 code
def getDiskFreeSpace(
self,
freeBytesAvailable,
totalNumberOfBytes,
totalNumberOfFreeBytes,
dokanFileInfo,
):
"""Get the amount of free space on this volume.
:param freeBytesAvailable: pointer for free bytes avail... | You are a Python code architect, reviewing and designing scalable and efficient code |
def getVolumeInformation(
self,
volumeNameBuffer,
volumeNameSize,
volumeSerialNumber,
maximumComponentLength,
fileSystemFlags,
fileSystemNameBuffer,
fileSystemNameSize,
dokanFileInfo,
):
"""Get information about the volume.
:pa... | Create a Python 3 function to
get information about the volume. :param volumeNameBuffer: buffer for volume name :type volumeNameBuffer: ctypes.c_void_p :param volumeNameSize: volume name buffer size :type volumeNameSize: ctypes.c_ulong :param volumeSerialNumber: buffer for volume serial number :type volumeSerialNumber:... | As a Python code analyst, you investigate and solve complex coding mysteries |
Get security attributes of a file. | Can you tell what is the following Python 3 function doing
def getFileSecurity(
self,
fileName,
securityInformation,
securityDescriptor,
lengthSecurityDescriptorBuffer,
lengthNeeded,
dokanFileInfo,
):
"""Get security attributes of a file.
:par... | As a Python code composer, you craft elegant and concise scripts. |
def setFileSecurity(
self,
fileName,
securityInformation,
securityDescriptor,
lengthSecurityDescriptorBuffer,
dokanFileInfo,
):
"""Set security attributes of a file.
:param fileName: name of file to set security for
:type fileName: ctypes.c_wc... | Write a Python 3 function that can
set security attributes of a file. | As a Python code analyst, you investigate and solve complex coding mysteries |
def createSimpleResourceMap(ore_pid, sci_meta_pid, data_pids):
"""Create a simple resource map with one metadata document and n data objects."""
ore = ResourceMap()
ore.initialize(ore_pid)
ore.addMetadataDocument(sci_meta_pid)
ore.addDataDocuments(data_pids, sci_meta_pid)
return ore | Can you create a Python 3 function that
creates a simple resource map with one metadata document and n data objects. | You are a Python code generator, capable of creating scripts from specifications. |
def pids2ore(in_stream, fmt='xml', base_url='https://cn.dataone.org/cn'):
"""read pids from in_stream and generate a resource map.
first pid is the ore_pid second is the sci meta pid remainder are data pids
"""
pids = []
for line in in_stream:
pid = line.strip()
if len(pid) > 0:
... | Write a Python 3 function for
reading pids from in_stream and generate a resource map. | As a Python code analyst, you investigate and solve complex coding mysteries |
Submit a new process. | Make a summary of the following Python 3 code
def submit(self, data, runtime_dir, argv):
queue = 'ordinary'
if data.process.scheduling_class == Process.SCHEDULING_CLASS_INTERACTIVE:
queue = 'hipri'
logger.debug(__(
"Connector '{}' running for Data with id {} ({}) in cele... | As a python code expert, you are capable of creating scripts from specifications. |
def refresh(self):
"""Synchronize the local tree of Solr records for DataONE identifiers and
queries with the reference tree."""
if self._source_tree.cache_is_stale():
self._source_tree.refresh()
logging.info('Refreshing object tree')
self._init_cache()
... | Create a Python 3 function to
synchronize the local tree of Solr records for DataONE identifiers and queries with the reference tree. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get an object record from the object tree. | How would you explain what the following Python 3 function does
def get_object_record(self, pid):
try:
return self._cache['records'][pid]
except KeyError:
raise d1_onedrive.impl.onedrive_exceptions.ONEDriveException('Unknown PID') | As a Python code composer, you craft elegant and concise scripts. |
Get an object record with sync. | Given the following Python 3 function, write the documentation
def get_object_record_with_sync(self, pid):
try:
return self._cache['records'][pid]
except KeyError:
return self._get_uncached_object_record(pid) | As a Python code composer, you craft elegant and concise scripts. |
def _create_cache_item_for_pid(self, cache_folder, pid):
"""The source tree can contain identifiers that are no longer valid (or were
never valid).
Any items for which a Solr record cannot be retrieved are silently skipped.
"""
try:
record = self._solr_client.get_so... | Can you write a function in Python 3 where it
creates a cache item for a given PID. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def dependency_status(data):
"""Return abstracted status of dependencies.
- ``STATUS_ERROR`` .. one dependency has error status or was deleted
- ``STATUS_DONE`` .. all dependencies have done status
- ``None`` .. other
"""
parents_statuses = set(
DataDependency.objects.filter(
... | How would you code a function in Python 3 to
return abstracted status of dependencies. | You are a Python code generator, capable of creating scripts from specifications. |
Discover configured engines.
:param executor: Optional executor module override | Can you generate the documentation for the following Python 3 function
def discover_engines(self, executor=None):
if executor is None:
executor = getattr(settings, 'FLOW_EXECUTOR', {}).get('NAME', 'resolwe.flow.executors.local')
self.executor = self.load_executor(executor)
logger.inf... | You are a Python code architect, reviewing and designing scalable and efficient code |
Reset the shared state and drain Django Channels. | Can you tell what is the following Python 3 function doing
def reset(self, keep_state=False):
if not keep_state:
self.state = state.ManagerState(state.MANAGER_STATE_PREFIX)
self.state.reset()
async_to_sync(consumer.run_consumer)(timeout=1)
async_to_sync(self.sync_counter.... | As a python code expert, you are capable of creating scripts from specifications. |
def _marshal_settings(self):
"""Marshal Django settings into a serializable object.
:return: The serialized settings.
:rtype: dict
"""
result = {}
for key in dir(settings):
if any(map(key.startswith, ['FLOW_', 'RESOLWE_', 'CELERY_'])):
result[... | Implement a Python 3 function for
marshaling Django settings into a serializable object. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def run(self, data, runtime_dir, argv):
"""Select a concrete connector and run the process through it.
:param data: The :class:`~resolwe.flow.models.Data` object that
is to be run.
:param runtime_dir: The directory the executor is run from.
:param argv: The argument vector u... | Implement a function in Python 3 to
select a concrete connector and run the process through it. | You are a Python code generator, capable of creating scripts from specifications. |
Extend the given base directory with a per - data component. | Can you tell what is the following Python 3 function doing
def _get_per_data_dir(self, dir_base, subpath):
# Use Django settings here, because the state must be preserved
# across events. This also implies the directory settings can't
# be patched outside the manager and then just sent along in ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _prepare_data_dir(self, data):
"""Prepare destination directory where the data will live.
:param data: The :class:`~resolwe.flow.models.Data` object for
which to prepare the private execution directory.
:return: The prepared data directory path.
:rtype: str
"""
... | Can you write a function in Python 3 where it
prepares the private execution directory for the given data object. | As a python code expert, you are capable of creating scripts from specifications. |
def _prepare_context(self, data_id, data_dir, runtime_dir, **kwargs):
"""Prepare settings and constants JSONs for the executor.
Settings and constants provided by other ``resolwe`` modules and
:class:`~django.conf.settings` are all inaccessible in the
executor once it is deployed, so th... | Write a Python 3 function that can
prepare the context for the executor. | You are a Python code architect, reviewing and designing scalable and efficient code |
Prepare the executor class for the given data object. | Make a summary of the following Python 3 code
def _prepare_executor(self, data, executor):
logger.debug(__("Preparing executor for Data with id {}", data.id))
# Both of these imports are here only to get the packages' paths.
import resolwe.flow.executors as executor_package
exec_dir = ... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _prepare_script(self, dest_dir, program):
"""Copy the script into the destination directory.
:param dest_dir: The target directory where the script will be
saved.
:param program: The script text to be saved.
:return: The name of the script file.
:rtype: str
... | Can you implement a function in Python 3 that
copies the script into the destination directory. | You are a Python code generator, capable of creating scripts from specifications. |
Handle an event from the Channels layer callback do not call directly. | How would you explain what the following Python 3 function does
async def handle_control_event(self, message):
cmd = message[WorkerProtocol.COMMAND]
logger.debug(__("Manager worker got channel command '{}'.", cmd))
# Prepare settings for use; Django overlaid by state overlaid by
# anyth... | As a Python code analyst, you investigate and solve complex coding mysteries |
Ensure the sync counter is a valid non - dummy object. | Make a summary of the following Python 3 code
def _ensure_counter(self):
if not isinstance(self.sync_counter, self._SynchronizationManager):
self.sync_counter = self._SynchronizationManager() | As a Python code analyst, you investigate and solve complex coding mysteries |
Wait for all executors to finish. | Explain what the following Python 3 code does
async def execution_barrier(self):
async def _barrier():
"""Enter the sync block and exit the app afterwards."""
async with self.sync_counter:
pass
await consumer.exit_consumer()
self._ensure_counter()
... | You are a Python code architect, reviewing and designing scalable and efficient code |
This method is used to send a COMMUNICATE command to the manager s channel workers. | Make a summary of the following Python 3 code
async def communicate(self, data_id=None, run_sync=False, save_settings=True):
executor = getattr(settings, 'FLOW_EXECUTOR', {}).get('NAME', 'resolwe.flow.executors.local')
logger.debug(__(
"Manager sending communicate command on '{}' triggered b... | As a Python code analyst, you investigate and solve complex coding mysteries |
Execute the data object. | Here you have a function in Python 3, explain what it does
def _data_execute(self, data, program, executor):
if not program:
return
logger.debug(__("Manager preparing Data with id {} for processing.", data.id))
# Prepare the executor's environment.
try:
executor... | As a Python code composer, you craft elegant and concise scripts. |
def _data_scan(self, data_id=None, executor='resolwe.flow.executors.local', **kwargs):
"""Scan for new Data objects and execute them.
:param data_id: Optional id of Data object which (+ its
children) should be scanned. If it is not given, all
resolving objects are processed.
... | Can you create a Python 3 function that
scans for new Data objects and execute them. | As a Python code composer, you craft elegant and concise scripts. |
def get_expression_engine(self, name):
"""Return an expression engine instance."""
try:
return self.expression_engines[name]
except KeyError:
raise InvalidEngineError("Unsupported expression engine: {}".format(name)) | Create a Python 3 function to
return an expression engine instance. | As a Python code composer, you craft elegant and concise scripts. |
def get_execution_engine(self, name):
"""Return an execution engine instance."""
try:
return self.execution_engines[name]
except KeyError:
raise InvalidEngineError("Unsupported execution engine: {}".format(name)) | Can you write a function in Python 3 where it
returns an execution engine instance. | You are a Python code architect, reviewing and designing scalable and efficient code |
def extract_subjects(cert_pem):
"""Extract subjects from a DataONE PEM (Base64) encoded X.509 v3 certificate.
Args:
cert_pem: str or bytes
PEM (Base64) encoded X.509 v3 certificate
Returns:
2-tuple:
- The primary subject string, extracted from the certificate DN.
- A se... | Write a Python 3 script to
extract subjects from a DataONE PEM encoded X. 509 certificate. | As a python code expert, you are capable of creating scripts from specifications. |
Check that collection exists and user has add permission. | Can you generate a brief explanation for the following Python 3 code
def _get_collection_for_user(self, collection_id, user):
collection_query = Collection.objects.filter(pk=collection_id)
if not collection_query.exists():
raise exceptions.ValidationError('Collection id does not exist')
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return entities queryset based on provided entity ids. | How would you explain what the following Python 3 function does
def _get_entities(self, user, ids):
queryset = get_objects_for_user(user, 'view_entity', Entity.objects.filter(id__in=ids))
actual_ids = queryset.values_list('id', flat=True)
missing_ids = list(set(ids) - set(actual_ids))
if... | As a Python code composer, you craft elegant and concise scripts. |
def set_content_permissions(self, user, obj, payload):
"""Apply permissions to data objects in ``Entity``."""
# Data doesn't have "ADD" permission, so it has to be removed
payload = remove_permission(payload, 'add')
for data in obj.data.all():
if user.has_perm('share_data', ... | Write a Python 3 function that can
apply permissions to data objects in Entity. | You are a Python code generator, capable of creating scripts from specifications. |
def destroy(self, request, *args, **kwargs):
"""Destroy a model instance.
If ``delete_content`` flag is set in query parameters, also all
Data objects contained in entity will be deleted.
"""
obj = self.get_object()
user = request.user
if strtobool(request.query... | Create a Python 3 function for
destroying a model instance. | You are a Python code generator, capable of creating scripts from specifications. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.