output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Return a dictionary of all modules. | Here you have a function in Python 3, explain what it does
def modules(self):
if not self.get_objects_by_type('module'):
self.inventory()
return {int(c.index): c for c in self.get_objects_by_type('module')} | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a dictionary of all ports. | Here you have a function in Python 3, explain what it does
def ports(self):
if not self.get_objects_by_type('port'):
self.inventory()
return {int(p.index.split('/')[1]): p for p in self.get_objects_by_type('port')} | As a Python code translator, you convert algorithms and pseudocode into Python. |
This is a wrapper around the cyclotron run method. It will run the main loop and loop forever. | Given the following Python 3 function, write the documentation
def run(entry_point, drivers, loop = None):
''' This is a runner wrapping the cyclotron "run" implementation. It takes
an additional parameter to provide a custom asyncio mainloop.
'''
program = setup(entry_point, drivers)
dispose = prog... | You are a Python code generator, capable of creating scripts from specifications. |
Return a boolean if a user has edit access to the glitter object or page this object is on. | Can you generate a brief explanation for the following Python 3 code
def has_glitter_edit_permission(self, request, obj):
# We're testing for the edit permission here with the glitter object - not the current
# object, not the change permission. Once a user has edit access to an object they can edit
... | As a python code expert, you are capable of creating scripts from specifications. |
The change admin view for this model. | Make a summary of the following Python 3 code
def change_view(self, request, object_id, form_url='', extra_context=None):
obj = self.get_object(request, unquote(object_id))
if obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {
'name... | You are a Python code analyst, evaluating scripts for potential improvements. |
def response_change(self, request, obj):
"""Determine the HttpResponse for the change_view stage."""
opts = self.opts.app_label, self.opts.model_name
pk_value = obj._get_pk_val()
if '_continue' in request.POST:
msg = _(
'The %(name)s block was changed success... | Write a Python 3 function that can
determine the HttpResponse for the change_view stage. | As a python code expert, you are capable of creating scripts from specifications. |
Get the filter string for a term. | Can you tell what is the following Python 3 function doing
def get_filter_item(name: str, operation: bytes, value: bytes) -> bytes:
assert isinstance(name, str)
assert isinstance(value, bytes)
if operation is None:
return filter_format(b"(%s=%s)", [name, value])
elif operation == "contains":
... | You are a Python code generator, capable of creating scripts from specifications. |
def get_filter(q: tldap.Q, fields: Dict[str, tldap.fields.Field], pk: str):
"""
Translate the Q tree into a filter string to search for, or None
if no results possible.
"""
# check the details are valid
if q.negated and len(q.children) == 1:
op = b"!"
elif q.connector == tldap.Q.AND:... | Create a Python 3 function for
translating the Q tree into a filter string to search for. | You are a Python code architect, reviewing and designing scalable and efficient code |
Checks if the node corresponds to the code result = | Can you tell what is the following Python 3 function doing
def node_is_result_assignment(node: ast.AST) -> bool:
# `.first_token` is added by asttokens
token = node.first_token # type: ignore
return token.line.strip().startswith('result =') | As a Python code composer, you craft elegant and concise scripts. |
Function does nothing - is just pass or docstring. | How would you explain what the following Python 3 function does
def function_is_noop(function_node: ast.FunctionDef) -> bool:
return all(node_is_noop(n) for n in function_node.body) | As a Python code composer, you craft elegant and concise scripts. |
def add_node_parents(root: ast.AST) -> None:
"""
Adds "parent" attribute to all child nodes of passed node.
Code taken from https://stackoverflow.com/a/43311383/1286705
"""
for node in ast.walk(root):
for child in ast.iter_child_nodes(node):
child.parent = node | Create a Python 3 function to
add parent attribute to all child nodes of passed node. | You are a Python code generator, capable of creating scripts from specifications. |
Generates a list of lines that the passed node covers relative to the first line number. | Can you tell what is the following Python 3 function doing
def build_footprint(node: ast.AST, first_line_no: int) -> Set[int]:
return set(
range(
get_first_token(node).start[0] - first_line_no,
get_last_token(node).end[0] - first_line_no + 1,
)
) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def filter_arrange_nodes(nodes: List[ast.stmt], max_line_number: int) -> List[ast.stmt]:
"""
Finds all nodes that are before the ``max_line_number`` and are not
docstrings or ``pass``.
"""
return [
node for node in nodes if node.lineno < max_line_number and not isinstance(node, ast.Pass)
... | How would you implement a function in Python 3 that
returns a list of nodes that are not at max_line_number. | You are a Python code generator, capable of creating scripts from specifications. |
Find all nodes that are after the given line number. | Given the following Python 3 function, write the documentation
def filter_assert_nodes(nodes: List[ast.stmt], min_line_number: int) -> List[ast.stmt]:
return [node for node in nodes if node.lineno > min_line_number] | As a Python code analyst, you investigate and solve complex coding mysteries |
Find all lines that contain a string in a tree. | Given the following Python 3 function, write the documentation
def find_stringy_lines(tree: ast.AST, first_line_no: int) -> Set[int]:
str_footprints = set()
for node in ast.walk(tree):
if isinstance(node, ast.Str):
str_footprints.update(build_footprint(node, first_line_no))
return str_fo... | You are a Python code analyst, evaluating scripts for potential improvements. |
def check_all(self) -> Generator[AAAError, None, None]:
"""
Run everything required for checking this function.
Returns:
A generator of errors.
Raises:
ValidationError: A non-recoverable linting error is found.
"""
# Function def
if funct... | Can you write a function in Python 3 where it
runs everything required for checking this function. | As a Python code analyst, you investigate and solve complex coding mysteries |
Load the ActNode from the node. | Can you generate the documentation for the following Python 3 function
def load_act_node(self) -> ActNode:
act_nodes = ActNode.build_body(self.node.body)
if not act_nodes:
raise ValidationError(self.first_line_no, self.node.col_offset, 'AAA01 no Act block found in test')
# Allow `p... | As a python code expert, you are capable of creating scripts from specifications. |
def get_line_relative_to_node(self, target_node: ast.AST, offset: int) -> str:
"""
Raises:
IndexError: when ``offset`` takes the request out of bounds of this
Function's lines.
"""
return self.lines[target_node.lineno - self.node.lineno + offset] | Implement a Python 3 function for
returning the line number relative to the given node. | As a Python code analyst, you investigate and solve complex coding mysteries |
Mark this function s definition lines into the line_markers attribute. | Make a summary of the following Python 3 code
def mark_def(self) -> int:
first_line = get_first_token(self.node).start[0] - self.first_line_no # Should usually be 0
try:
end_token = get_last_token(self.node.args.args[-1])
except IndexError:
# Fn has no args, so end of fu... | As a Python code composer, you craft elegant and concise scripts. |
Mark unprocessed lines that have no content and no string nodes and no string nodes and no string nodes and no string nodes and no string nodes are blank line BL. | How would you explain what the following Python 3 function does
def mark_bl(self) -> int:
counter = 0
stringy_lines = find_stringy_lines(self.node, self.first_line_no)
for relative_line_number, line in enumerate(self.lines):
if relative_line_number not in stringy_lines and line.strip... | As a Python code analyst, you investigate and solve complex coding mysteries |
Function enhance
Enhance the object with new item or enhanced items
| Explain what the following Python 3 code does
def enhance(self):
self.update({'puppetclasses':
SubDict(self.api, self.objName,
self.payloadObj, self.key,
SubItemPuppetClasses)})
self.update({'parameters':
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Function getParamFromEnv
Search a parameter in the host environment and return the value | Explain what the following Python 3 code does
def getParamFromEnv(self, var, default=''):
if self.getParam(var):
return self.getParam(var)
if self.hostgroup:
if self.hostgroup.getParam(var):
return self.hostgroup.getParam(var)
if self.domain.getParam('pass... | You are a Python code analyst, evaluating scripts for potential improvements. |
def getUserData(self,
hostgroup,
domain,
defaultPwd='',
defaultSshKey='',
proxyHostname='',
tplFolder='metadata/templates/'):
""" Function getUserData
Generate a userdata script for me... | How would you implement a function in Python 3 that
functions getUserData Generate a userdata script for the user from the Foreman API. | You are a Python code architect, reviewing and designing scalable and efficient code |
def register_payload(self, *payloads, flavour: ModuleType):
"""Queue one or more payload for execution after its runner is started"""
for payload in payloads:
self._logger.debug('registering payload %s (%s)', NameRepr(payload), NameRepr(flavour))
self.runners[flavour].register_pa... | Write a Python 3 script to
queue one or more payloads for execution after its runner is started | You are a Python code architect, reviewing and designing scalable and efficient code |
Execute one payload after its runner is started and return its output | Make a summary of the following Python 3 code
def run_payload(self, payload, *, flavour: ModuleType):
return self.runners[flavour].run_payload(payload) | You are a Python code analyst, evaluating scripts for potential improvements. |
Run all runners blocking until completion or error | Can you generate the documentation for the following Python 3 function
def run(self):
self._logger.info('starting all runners')
try:
with self._lock:
assert not self.running.set(), 'cannot re-run: %s' % self
self.running.set()
thread_runner = self.... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Hook for specifying the form Field instance for a given database Field. | Can you generate a brief explanation for the following Python 3 code
def formfield_for_dbfield(self, db_field, **kwargs):
formfield = super().formfield_for_dbfield(db_field, **kwargs)
if db_field.name == 'image':
formfield.widget = ImageRelatedFieldWidgetWrapper(
ImageSelect(... | You are a Python code architect, reviewing and designing scalable and efficient code |
Compares two structures that represents JSON schemas. | Can you tell what is the following Python 3 function doing
def compare_schemas(one, two):
one = _normalize_string_type(one)
two = _normalize_string_type(two)
_assert_same_types(one, two)
if isinstance(one, list):
return _compare_lists(one, two)
elif isinstance(one, dict):
return _c... | As a python code expert, you are capable of creating scripts from specifications. |
def is_ecma_regex(regex):
"""Check if given regex is of type ECMA 262 or not.
:rtype: bool
"""
parts = regex.split('/')
if len(parts) == 1:
return False
if len(parts) < 3:
raise ValueError('Given regex isn\'t ECMA regex nor Python regex.')
parts.pop()
parts.append('')... | How would you implement a function in Python 3 that
checks if given regex is of type ECMA 262 or not. | You are a Python code analyst, evaluating scripts for potential improvements. |
def convert_ecma_regex_to_python(value):
"""Convert ECMA 262 regex to Python tuple with regex and flags.
If given value is already Python regex it will be returned unchanged.
:param string value: ECMA regex.
:return: 2-tuple with `regex` and `flags`
:rtype: namedtuple
"""
if not is_ecma_r... | Implement a function in Python 3 to
convert ECMA 262 regex to Python tuple with regex and flags. | You are a Python code analyst, evaluating scripts for potential improvements. |
Convert Python regex to ECMA 262 regex. | Can you generate a brief explanation for the following Python 3 code
def convert_python_regex_to_ecma(value, flags=[]):
if is_ecma_regex(value):
return value
result_flags = [PYTHON_TO_ECMA_FLAGS[f] for f in flags]
result_flags = ''.join(result_flags)
return '/{value}/{flags}'.format(value=valu... | You are a Python code architect, reviewing and designing scalable and efficient code |
Populate values to fields. Skip non - existing. | Can you tell what is the following Python 3 function doing
def populate(self, **values):
values = values.copy()
fields = list(self.iterate_with_name())
for _, structure_name, field in fields:
if structure_name in values:
field.__set__(self, values.pop(structure_name))... | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_field(self, field_name):
"""Get field associated with given attribute."""
for attr_name, field in self:
if field_name == attr_name:
return field
raise errors.FieldNotFound('Field not found', field_name) | Write a Python 3 script to
get the field associated with given attribute. | You are a Python code generator, capable of creating scripts from specifications. |
Explicitly validate all the fields. | Can you generate a brief explanation for the following Python 3 code
def validate(self):
for name, field in self:
try:
field.validate_for_object(self)
except ValidationError as error:
raise ValidationError(
"Error for field '{name}'.".f... | You are a Python code analyst, evaluating scripts for potential improvements. |
Iterate through fields as attribute_name field_instance. | Given the following Python 3 function, write the documentation
def iterate_over_fields(cls):
for attr in dir(cls):
clsattr = getattr(cls, attr)
if isinstance(clsattr, BaseField):
yield attr, clsattr | As a Python code composer, you craft elegant and concise scripts. |
Iterate over fields but also give structure_name. | Here you have a function in Python 3, explain what it does
def iterate_with_name(cls):
for attr_name, field in cls.iterate_over_fields():
structure_name = field.structue_name(attr_name)
yield attr_name, structure_name, field | You are a Python code analyst, evaluating scripts for potential improvements. |
def parse_value(self, value):
"""Cast value to `int`, e.g. from string or long"""
parsed = super(IntField, self).parse_value(value)
if parsed is None:
return parsed
return int(parsed) | Implement a function in Python 3 to
cast value to int e. g. from string or long | As a python code expert, you are capable of creating scripts from specifications. |
Cast value to bool. | Make a summary of the following Python 3 code
def parse_value(self, value):
parsed = super(BoolField, self).parse_value(value)
return bool(parsed) if parsed is not None else None | As a Python code composer, you craft elegant and concise scripts. |
Cast value to proper collection. | Can you tell what is the following Python 3 function doing
def parse_value(self, values):
result = self.get_default_value()
if not values:
return result
if not isinstance(values, list):
return values
return [self._cast_value(value) for value in values] | You are a Python code generator, capable of creating scripts from specifications. |
Parse value to proper model type. | Can you generate a brief explanation for the following Python 3 code
def parse_value(self, value):
if not isinstance(value, dict):
return value
embed_type = self._get_embed_type()
return embed_type(**value) | You are a Python code analyst, evaluating scripts for potential improvements. |
def to_struct(self, value):
"""Cast `time` object to string."""
if self.str_format:
return value.strftime(self.str_format)
return value.isoformat() | Write a Python 3 script to
cast time object to string. | You are a Python code analyst, evaluating scripts for potential improvements. |
Parse string into instance of time. | Make a summary of the following Python 3 code
def parse_value(self, value):
if value is None:
return value
if isinstance(value, datetime.time):
return value
return parse(value).timetz() | As a python code expert, you are capable of creating scripts from specifications. |
Cast date object to string. | Can you generate the documentation for the following Python 3 function
def to_struct(self, value):
if self.str_format:
return value.strftime(self.str_format)
return value.strftime(self.default_format) | You are a Python code analyst, evaluating scripts for potential improvements. |
def parse_value(self, value):
"""Parse string into instance of `datetime`."""
if isinstance(value, datetime.datetime):
return value
if value:
return parse(value)
else:
return None | Implement a function in Python 3 to
parse string into instance of datetime. datetime. | As a Python code analyst, you investigate and solve complex coding mysteries |
Modify the field schema. | Can you generate a brief explanation for the following Python 3 code
def modify_schema(self, field_schema):
field_schema['pattern'] = utilities.convert_python_regex_to_ecma(
self.pattern, self.flags) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Cast instance of model to python structure. | Here you have a function in Python 3, explain what it does
def to_struct(model):
model.validate()
resp = {}
for _, name, field in model.iterate_with_name():
value = field.__get__(model)
if value is None:
continue
value = field.to_struct(value)
resp[name] = value... | You are a Python code generator, capable of creating scripts from specifications. |
def run_from_argv(self, argv):
"""
Set up any environment changes requested (e.g., Python path
and Django settings), then run this command. If the
command raises a ``CommandError``, intercept it and print it sensibly
to stderr.
"""
parser = self.create_parser(argv... | Can you implement a function in Python 3 that
runs the command from the command line. | As a python code expert, you are capable of creating scripts from specifications. |
def create_parser(self, prog_name, subcommand):
"""
Create and return the ``OptionParser`` which will be used to
parse the arguments to this command.
"""
parser = argparse.ArgumentParser(prog='%s %s' % (prog_name, subcommand), description=self.help)
parser.add_argument(... | Write a Python 3 function for
creating and return the option parser which will be used to parse the arguments to this command. | You are a Python code architect, reviewing and designing scalable and efficient code |
def rst(filename):
'''
Load rst file and sanitize it for PyPI.
Remove unsupported github tags:
- code-block directive
- travis ci build badge
'''
content = codecs.open(filename, encoding='utf-8').read()
for regex, replacement in PYPI_RST_FILTERS:
content = re.sub(regex, replace... | Write a Python 3 script to
load rst file and sanitize it for PyPI. | You are a Python code analyst, evaluating scripts for potential improvements. |
A shortcut to render a script tag for the packaged jQuery | Can you tell what is the following Python 3 function doing
def jquery_js(version=None, migrate=False):
'''A shortcut to render a ``script`` tag for the packaged jQuery'''
version = version or settings.JQUERY_VERSION
suffix = '.min' if not settings.DEBUG else ''
libs = [js_lib('jquery-%s%s.js' % (version... | As a Python code analyst, you investigate and solve complex coding mysteries |
Include Django. js javascript library in the page | Here you have a function in Python 3, explain what it does
def django_js(context, jquery=True, i18n=True, csrf=True, init=True):
'''Include Django.js javascript library in the page'''
return {
'js': {
'minified': not settings.DEBUG,
'jquery': _boolean(jquery),
'i18n':... | You are a Python code analyst, evaluating scripts for potential improvements. |
def django_js_init(context, jquery=False, i18n=True, csrf=True, init=True):
'''Include Django.js javascript library initialization in the page'''
return {
'js': {
'jquery': _boolean(jquery),
'i18n': _boolean(i18n),
'csrf': _boolean(csrf),
'init': _boolean(... | Implement a Python 3 function for
including Django. js javascript library initialization in the page | You are a Python code analyst, evaluating scripts for potential improvements. |
def as_dict(self):
'''
Serialize the context as a dictionnary from a given request.
'''
data = {}
if settings.JS_CONTEXT_ENABLED:
for context in RequestContext(self.request):
for key, value in six.iteritems(context):
if settings.JS_... | Write a Python 3 script for
serializing the context as a dictionnary from a given request. | You are a Python code analyst, evaluating scripts for potential improvements. |
Process the language code when set to non included default en and add the extra variables LANGUAGE_NAME and LANGUAGE_NAME_LOCAL. | Explain what the following Python 3 code does
def process_LANGUAGE_CODE(self, language_code, data):
'''
Fix language code when set to non included default `en`
and add the extra variables ``LANGUAGE_NAME`` and ``LANGUAGE_NAME_LOCAL``.
'''
# Dirty hack to fix non included default
... | As a Python code composer, you craft elegant and concise scripts. |
Insert user informations in data | Can you generate the documentation for the following Python 3 function
def handle_user(self, data):
'''
Insert user informations in data
Override it to add extra user attributes.
'''
# Default to unauthenticated anonymous user
data['user'] = {
'username': '',... | You are a Python code analyst, evaluating scripts for potential improvements. |
Get a python class object from its name | Here you have a function in Python 3, explain what it does
def class_from_string(name):
'''
Get a python class object from its name
'''
module_name, class_name = name.rsplit('.', 1)
__import__(module_name)
module = sys.modules[module_name]
return getattr(module, class_name) | You are a Python code architect, reviewing and designing scalable and efficient code |
Glob a pattern or a list of pattern static storage relative ( s. | Can you generate the documentation for the following Python 3 function
def glob(cls, files=None):
'''
Glob a pattern or a list of pattern static storage relative(s).
'''
files = files or []
if isinstance(files, str):
files = os.path.normpath(files)
matches... | You are a Python code generator, capable of creating scripts from specifications. |
def execute(self, command):
'''
Execute a subprocess yielding output lines
'''
process = Popen(command, stdout=PIPE, stderr=STDOUT, universal_newlines=True)
while True:
if process.poll() is not None:
self.returncode = process.returncode # pylint: disa... | Can you implement a function in Python 3 that
executes a subprocess yielding output lines | You are a Python code architect, reviewing and designing scalable and efficient code |
def phantomjs(self, *args, **kwargs):
'''
Execute PhantomJS by giving ``args`` as command line arguments.
If test are run in verbose mode (``-v/--verbosity`` = 2), it output:
- the title as header (with separators before and after)
- modules and test names
- assert... | Write a Python 3 function that can
execute PhantomJS by giving args as command line arguments and keyword arguments as keyword arguments. | You are a Python code architect, reviewing and designing scalable and efficient code |
def run_suite(self):
'''
Run a phantomjs test suite.
- ``phantomjs_runner`` is mandatory.
- Either ``url`` or ``url_name`` needs to be defined.
'''
if not self.phantomjs_runner:
raise JsTestException('phantomjs_runner need to be defined')
url = sel... | Write a Python 3 script for
running a phantomjs test suite. | As a Python code analyst, you investigate and solve complex coding mysteries |
Write rows to table. | Given the following Python 3 function, write the documentation
def write(self, rows, keyed=False):
for row in rows:
keyed_row = row
if not keyed:
keyed_row = dict(zip(self.__schema.field_names, row))
keyed_row = self.__convert_row(keyed_row)
if sel... | You are a Python code architect, reviewing and designing scalable and efficient code |
def __prepare_bloom(self):
"""Prepare bloom for existing checks
"""
self.__bloom = pybloom_live.ScalableBloomFilter()
columns = [getattr(self.__table.c, key) for key in self.__update_keys]
keys = select(columns).execution_options(stream_results=True).execute()
for key in ... | Write a Python 3 function for
preparing bloom for existing checks | You are a Python code generator, capable of creating scripts from specifications. |
Insert rows to table
| Given the following Python 3 function, write the documentation
def __insert(self):
if len(self.__buffer) > 0:
# Insert data
statement = self.__table.insert()
if self.__autoincrement:
statement = statement.returning(
getattr(self.__table.c, ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Update rows in table
| How would you explain what the following Python 3 function does
def __update(self, row):
expr = self.__table.update().values(row)
for key in self.__update_keys:
expr = expr.where(getattr(self.__table.c, key) == row[key])
if self.__autoincrement:
expr = expr.returning(geta... | You are a Python code architect, reviewing and designing scalable and efficient code |
Check if row exists in table
| Explain what the following Python 3 code does
def __check_existing(self, row):
if self.__update_keys is not None:
key = tuple(row[key] for key in self.__update_keys)
if key in self.__bloom:
return True
self.__bloom.add(key)
return False
ret... | You are a Python code analyst, evaluating scripts for potential improvements. |
def buckets(self):
"""https://github.com/frictionlessdata/tableschema-sql-py#storage
"""
buckets = []
for table in self.__metadata.sorted_tables:
bucket = self.__mapper.restore_bucket(table.name)
if bucket is not None:
buckets.append(bucket)
... | Implement a function in Python 3 to
return a list of all buckets in the database. | You are a Python code analyst, evaluating scripts for potential improvements. |
def create(self, bucket, descriptor, force=False, indexes_fields=None):
"""https://github.com/frictionlessdata/tableschema-sql-py#storage
"""
# Make lists
buckets = bucket
if isinstance(bucket, six.string_types):
buckets = [bucket]
descriptors = descriptor
... | Can you write a function in Python 3 where it
creates a new entry in the database. | You are a Python code architect, reviewing and designing scalable and efficient code |
def delete(self, bucket=None, ignore=False):
"""https://github.com/frictionlessdata/tableschema-sql-py#storage
"""
# Make lists
buckets = bucket
if isinstance(bucket, six.string_types):
buckets = [bucket]
elif bucket is None:
buckets = reversed(se... | Create a Python 3 function to
delete the object from the specified bucket. | As a Python code analyst, you investigate and solve complex coding mysteries |
Get or set the descriptor for a specific bucket. | Explain what the following Python 3 code does
def describe(self, bucket, descriptor=None):
# Set descriptor
if descriptor is not None:
self.__descriptors[bucket] = descriptor
# Get descriptor
else:
descriptor = self.__descriptors.get(bucket)
if descr... | As a python code expert, you are capable of creating scripts from specifications. |
def iter(self, bucket):
"""https://github.com/frictionlessdata/tableschema-sql-py#storage
"""
# Get table and fallbacks
table = self.__get_table(bucket)
schema = tableschema.Schema(self.describe(bucket))
# Open and close transaction
with self.__connection.begin(... | How would you code a function in Python 3 to
iterate over the items in the specified bucket. | As a Python code analyst, you investigate and solve complex coding mysteries |
Write rows to table with key and return a generator of the new entries. | Make a summary of the following Python 3 code
def write(self, bucket, rows, keyed=False, as_generator=False, update_keys=None):
# Check update keys
if update_keys is not None and len(update_keys) == 0:
message = 'Argument "update_keys" cannot be an empty list'
raise tableschema.... | As a Python code analyst, you investigate and solve complex coding mysteries |
def __get_table(self, bucket):
"""Get table by bucket
"""
table_name = self.__mapper.convert_bucket(bucket)
if self.__dbschema:
table_name = '.'.join((self.__dbschema, table_name))
return self.__metadata.tables[table_name] | Create a Python 3 function to
get table by bucket | You are a Python code analyst, evaluating scripts for potential improvements. |
def __reflect(self):
"""Reflect metadata
"""
def only(name, _):
return self.__only(name) and self.__mapper.restore_bucket(name) is not None
self.__metadata.reflect(only=only) | How would you code a function in Python 3 to
reflect the metadata object. | You are a Python code analyst, evaluating scripts for potential improvements. |
Create SQL comment from field s title and description. | Given the following Python 3 function, write the documentation
def _get_field_comment(field, separator=' - '):
title = field.descriptor.get('title') or ''
description = field.descriptor.get('description') or ''
return _get_comment(description, title, separator) | You are a Python code generator, capable of creating scripts from specifications. |
def convert_descriptor(self, bucket, descriptor, index_fields=[], autoincrement=None):
"""Convert descriptor to SQL
"""
# Prepare
columns = []
indexes = []
fallbacks = []
constraints = []
column_mapping = {}
table_name = self.convert_bucket(bucket... | Write a Python 3 function for
converting a descriptor to SQL SQL | You are a Python code generator, capable of creating scripts from specifications. |
def convert_row(self, keyed_row, schema, fallbacks):
"""Convert row to SQL
"""
for key, value in list(keyed_row.items()):
field = schema.get_field(key)
if not field:
del keyed_row[key]
if key in fallbacks:
value = _uncast_value(... | Can you create a Python 3 function that
converts a row from SQL to SQL | As a Python code composer, you craft elegant and concise scripts. |
def convert_type(self, type):
"""Convert type to SQL
"""
# Default dialect
mapping = {
'any': sa.Text,
'array': None,
'boolean': sa.Boolean,
'date': sa.Date,
'datetime': sa.DateTime,
'duration': None,
'g... | Implement a Python 3 function for
converting type to SQL | As a python code expert, you are capable of creating scripts from specifications. |
Restore bucket from SQL
| Given the following Python 3 function, write the documentation
def restore_bucket(self, table_name):
if table_name.startswith(self.__prefix):
return table_name.replace(self.__prefix, '', 1)
return None | You are a Python code analyst, evaluating scripts for potential improvements. |
def restore_descriptor(self, table_name, columns, constraints, autoincrement_column=None):
"""Restore descriptor from SQL
"""
# Fields
fields = []
for column in columns:
if column.name == autoincrement_column:
continue
field_type = self.re... | Can you implement a function in Python 3 that
restores descriptor from SQL SQL | As a Python code analyst, you investigate and solve complex coding mysteries |
Restore row from SQL
| Explain what the following Python 3 code does
def restore_row(self, row, schema):
row = list(row)
for index, field in enumerate(schema.fields):
if self.__dialect == 'postgresql':
if field.type in ['array', 'object']:
continue
row[index] = field... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def restore_type(self, type):
"""Restore type from SQL
"""
# All dialects
mapping = {
ARRAY: 'array',
sa.Boolean: 'boolean',
sa.Date: 'date',
sa.DateTime: 'datetime',
sa.Float: 'number',
sa.Integer: 'integer',
... | Write a Python 3 script for
restoring type from SQL | You are a Python code architect, reviewing and designing scalable and efficient code |
Open a new hierarchy. | Make a summary of the following Python 3 code
def open_hierarchy(self, path, relative_to_object_id, object_id, create_file_type=0):
try:
return(self.process.OpenHierarchy(path, relative_to_object_id, "", create_file_type))
except Exception as e:
print(e)
print("Could... | You are a Python code architect, reviewing and designing scalable and efficient code |
def create_new_page (self, section_id, new_page_style=0):
"""
NewPageStyle
0 - Create a Page that has Default Page Style
1 - Create a blank page with no title
2 - Createa blank page that has no title
"""
try:
self.process.CreateNewPage(section_... | Can you write a function in Python 3 where it
creates a new page in the specified section. | As a Python code composer, you craft elegant and concise scripts. |
Publish a single element of the hierarchy. | Make a summary of the following Python 3 code
def publish(self, hierarchy_id, target_file_path, publish_format, clsid_of_exporter=""):
try:
self.process.Publish(hierarchy_id, target_file_path, publish_format, clsid_of_exporter)
except Exception as e:
print(e)
print("... | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_special_location(self, special_location=0):
"""
SpecialLocation
0 - Gets the path to the Backup Folders folder location.
1 - Gets the path to the Unfiled Notes folder location.
2 - Gets the path to the Default Notebook folder location.
"""
try:
... | Implement a Python 3 function for
getting the special location of the current process. | You are a Python code architect, reviewing and designing scalable and efficient code |
def memory():
"""Determine memory specifications of the machine.
Returns
-------
mem_info : dictonary
Holds the current values for the total, free and used memory of the system.
"""
mem_info = dict()
for k, v in psutil.virtual_memory()._asdict().items():
mem_info[k] = i... | Create a Python 3 function to
return a dictionary of the current values for the total free and used memory of the machine. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_chunk_size(N, n):
"""Given a two-dimensional array with a dimension of size 'N',
determine the number of rows or columns that can fit into memory.
Parameters
----------
N : int
The size of one of the dimensions of a two-dimensional array.
n : int
The number of ar... | Can you implement a function in Python 3 that
gives a two - dimensional array with a dimension of size N determine the number of rows or columns that can fit into memory. | As a python code expert, you are capable of creating scripts from specifications. |
Determine whether or not to use a compression on the array stored in
a hierarchical data format and which compression library to use to use to the HDF5 file size. | Here you have a function in Python 3, explain what it does
def get_compression_filter(byte_counts):
assert isinstance(byte_counts, numbers.Integral) and byte_counts > 0
if 2 * byte_counts > 1000 * memory()['free']:
try:
FILTERS = tables.filters(complevel = 5, complib = 'blosc',
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Return the adjacency matrix to a hypergraph in sparse matrix representation. | Make a summary of the following Python 3 code
def build_hypergraph_adjacency(cluster_runs):
N_runs = cluster_runs.shape[0]
hypergraph_adjacency = create_membership_matrix(cluster_runs[0])
for i in range(1, N_runs):
hypergraph_adjacency = scipy.sparse.vstack([hypergraph_adjacency,
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def store_hypergraph_adjacency(hypergraph_adjacency, hdf5_file_name):
"""Write an hypergraph adjacency to disk to disk in an HDF5 data structure.
Parameters
----------
hypergraph_adjacency : compressed sparse row matrix
hdf5_file_name : file handle or string
"""
assert(hypergra... | Write a Python 3 function for
writing an adjacency matrix to disk in an HDF5 file. | You are a Python code analyst, evaluating scripts for potential improvements. |
Loads the sparse row matrix of the next hypergraph from the given hdf5 file. | Explain what the following Python 3 code does
def load_hypergraph_adjacency(hdf5_file_name):
with tables.open_file(hdf5_file_name, 'r+') as fileh:
pars = []
for par in ('data', 'indices', 'indptr', 'shape'):
pars.append(getattr(fileh.root.consensus_group, par).read())
hypergraph_ad... | You are a Python code generator, capable of creating scripts from specifications. |
def ceEvalMutual(cluster_runs, cluster_ensemble = None, verbose = False):
"""Compute a weighted average of the mutual information with the known labels,
the weights being proportional to the fraction of known labels.
Parameters
----------
cluster_runs : array of shape (n_partitions, n_samples)... | Implement a Python 3 function for
computing a weighted average of the mutual information between the ensemble and the cluster_runs. | You are a Python code analyst, evaluating scripts for potential improvements. |
Checks that a given cluster labelling is in a valid format. | Can you generate a brief explanation for the following Python 3 code
def checkcl(cluster_run, verbose = False):
cluster_run = np.asanyarray(cluster_run)
if cluster_run.size == 0:
raise ValueError("\nERROR: Cluster_Ensembles: checkcl: "
"empty vector provided as input.\n")
... | As a python code expert, you are capable of creating scripts from specifications. |
def one_to_max(array_in):
"""Alter a vector of cluster labels to a dense mapping.
Given that this function is herein always called after passing
a vector to the function checkcl, one_to_max relies on the assumption
that cluster_run does not contain any NaN entries.
Parameters
---... | Can you implement a function in Python 3 that
alters a vector of cluster labels to a dense mapping. Given that this function is herein always called after passing a vector to the function checkcl, one_to_max relies on the assumption that cluster_run does not contain any NaN entries. Parameters ---------- array_in : a l... | As a Python code composer, you craft elegant and concise scripts. |
Check that a matrix is a proper similarity matrix and bring
appropriate changes if applicable. | Here you have a function in Python 3, explain what it does
def checks(similarities, verbose = False):
if similarities.size == 0:
raise ValueError("\nERROR: Cluster_Ensembles: checks: the similarities "
"matrix provided as input happens to be empty.\n")
elif np.where(np.isna... | You are a Python code generator, capable of creating scripts from specifications. |
def hmetis(hdf5_file_name, N_clusters_max, w = None):
"""Gives cluster labels ranging from 1 to N_clusters_max for
hypergraph partitioning required for HGPA.
Parameters
----------
hdf5_file_name : file handle or string
N_clusters_max : int
w : array, optional (default = None)... | Can you implement a function in Python 3 that
gives cluster labels ranging from 1 to N_clusters_max for hypergraph partitioning required for HGPA. Parameters ---------- hdf5_file_name : file handle or string N_clusters_max : int w : array, optional (default = None) Returns ------- labels : array of shape (n_samples,) A... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def wgraph(hdf5_file_name, w = None, method = 0):
"""Write a graph file in a format apposite to later use by METIS or HMETIS.
Parameters
----------
hdf5_file_name : file handle or string
w : list or array, optional (default = None)
method : int, optional (default = 0)
Ret... | Write a Python 3 function for
writing a graph file in a format apposite to later use by METIS or HMETIS. | You are a Python code generator, capable of creating scripts from specifications. |
Runs METIS or HMETIS and returns the labels found by those EVEN clustering algorithms. | Given the following Python 3 function, write the documentation
def sgraph(N_clusters_max, file_name):
if file_name == 'DO_NOT_PROCESS':
return []
print('\n#')
k = str(N_clusters_max)
out_name = file_name + '.part.' + k
if file_name == 'wgraph_HGPA':
print("INFO: Cluster_Ensembles:... | You are a Python code generator, capable of creating scripts from specifications. |
def overlap_matrix(hdf5_file_name, consensus_labels, cluster_runs):
"""Writes on disk (in an HDF5 file whose handle is provided as the first
argument to this function) a stack of matrices, each describing
for a particular run the overlap of cluster ID's that are matching
each of the cluster ID... | Write a Python 3 script to
create an adjacency matrix that contains the overlap of each cluster ID and the mutual informations between each of the clusterings that are associated with the ensemble. | As a python code expert, you are capable of creating scripts from specifications. |
def obfuscate(p, action):
"""Obfuscate the auth details to avoid easy snatching.
It's best to use a throw away account for these alerts to avoid having
your authentication put at risk by storing it locally.
"""
key = "ru7sll3uQrGtDPcIW3okutpFLo6YYtd5bWSpbZJIopYQ0Du0a1WlhvJOaZEH"
s = list()
... | How would you implement a function in Python 3 that
obfuscates the auth details to avoid easy snatching. | As a Python code analyst, you investigate and solve complex coding mysteries |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.