output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Saves the current configuration to a folder | Make a summary of the following Python 3 code
def save(self, folder_path='', configuration_type='running', vrf_management_name=None, return_artifact=False):
if hasattr(self.resource_config, "vrf_management_name"):
vrf_management_name = vrf_management_name or self.resource_config.vrf_management_name... | You are a Python code analyst, evaluating scripts for potential improvements. |
Restore configuration on device from provided path | Can you tell what is the following Python 3 function doing
def restore(self, path, configuration_type="running", restore_method="override", vrf_management_name=None):
if hasattr(self.resource_config, "vrf_management_name"):
vrf_management_name = vrf_management_name or self.resource_config.vrf_manag... | You are a Python code architect, reviewing and designing scalable and efficient code |
Orchestration Save command
:param mode:
:param custom_params: json with all required action to configure or remove vlans from certain port
:return Serialized OrchestrationSavedArtifact to json
:rtype json | Given the following Python 3 function, write the documentation
def orchestration_save(self, mode="shallow", custom_params=None):
save_params = {'folder_path': '', 'configuration_type': 'running', 'return_artifact': True}
params = dict()
if custom_params:
params = jsonpickle.decode(c... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Orchestration restore on the device. | Can you generate a brief explanation for the following Python 3 code
def orchestration_restore(self, saved_artifact_info, custom_params=None):
if saved_artifact_info is None or saved_artifact_info == '':
raise Exception('ConfigurationOperations', 'saved_artifact_info is None or empty')
sav... | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_path(self, path=''):
"""
Validate incoming path, if path is empty, build it from resource attributes,
If path is invalid - raise exception
:param path: path to remote file storage
:return: valid path or :raise Exception:
"""
if not path:
host... | Create a Python 3 function for
validating incoming path and build path url from resource attributes | As a Python code translator, you convert algorithms and pseudocode into Python. |
Validate configuration type
:param configuration_type: configuration_type, should be Startup or Running
:raise Exception: | Make a summary of the following Python 3 code
def _validate_configuration_type(self, configuration_type):
if configuration_type.lower() != 'running' and configuration_type.lower() != 'startup':
raise Exception(self.__class__.__name__, 'Configuration Type is invalid. Should be startup or running') | As a Python code analyst, you investigate and solve complex coding mysteries |
Validate OrchestrationSavedArtifactInfo object for key components
| Given the following Python 3 function, write the documentation
def _validate_artifact_info(self, saved_config):
is_fail = False
fail_attribute = ''
for class_attribute in self.REQUIRED_SAVE_ATTRIBUTES_LIST:
if type(class_attribute) is tuple:
if not hasattr(saved_confi... | As a Python code analyst, you investigate and solve complex coding mysteries |
Adds resolver to global container | Given the following Python 3 function, write the documentation
def register(key, initializer: callable, param=None):
'''Adds resolver to global container'''
get_current_scope().container.register(key, initializer, param) | You are a Python code architect, reviewing and designing scalable and efficient code |
Generates resolver to return singleton value and adds it to global container | Can you tell what is the following Python 3 function doing
def register_single(key, value, param=None):
'''Generates resolver to return singleton value and adds it to global container'''
get_current_scope().container.register(key, lambda: value, param) | As a Python code analyst, you investigate and solve complex coding mysteries |
def wrap_with_scope(func, scope_name=None):
'''Wraps function with scope. If scope_name is None current scope is used'''
if scope_name is None:
scope_name = get_current_scope().name
return lambda *args, scope=scope_name, **kwargs: \
_call_with_scope(func, scope, args, kwargs) | How would you implement a function in Python 3 that
wraps function with scope. | As a Python code composer, you craft elegant and concise scripts. |
def inject(*injections):
'''Resolves dependencies using global container and passed it with optional parameters'''
def _decorate(func):
def _decorated(*args, **kwargs):
args = list(args)
keys_to_inject = [name for name in injections if name not in kwargs]
for key in k... | Write a Python 3 script to
resolve dependencies using global container and passed it with optional parameters | As a Python code analyst, you investigate and solve complex coding mysteries |
Add resolver to container | Can you generate the documentation for the following Python 3 function
def register(self, key, initializer: callable, param=None):
'''Add resolver to container'''
if not callable(initializer):
raise DependencyError('Initializer {0} is not callable'.format(initializer))
if key not in ... | You are a Python code generator, capable of creating scripts from specifications. |
Handle a Flask HTTP request. | How would you explain what the following Python 3 function does
def handle_http(handler: Resource, args: Tuple, kwargs: Dict, logic: Callable):
try:
# We are checking mimetype here instead of content_type because
# mimetype is just the content-type, where as content_type can
# contain encodi... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Convert the confusion matrix to Matthews correlation coefficient. | How would you explain what the following Python 3 function does
def confusion_to_mcc(*args):
if len(args) is 1:
tn, fp, fn, tp = args[0].ravel().astype(float)
elif len(args) is 4:
tn, fp, fn, tp = [float(a) for a in args]
else:
raise Exception((
"Input argument is not an ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Creates node from xml node using namespace as module and tag name as class name | Given the following Python 3 function, write the documentation
def create_node(xml_node: XmlNode, **init_args):
'''Creates node from xml node using namespace as module and tag name as class name'''
inst_type = get_inst_type(xml_node)
init_args['xml_node'] = xml_node
inst = create_inst(inst_type, **init_... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_inst_type(xml_node: XmlNode):
'''Returns type by xml node'''
(module_path, class_name) = (xml_node.namespace, xml_node.name)
try:
return import_module(module_path).__dict__[class_name]
except (KeyError, ImportError, ModuleNotFoundError):
message = 'Import "{0}.{1}" is failed.'.fo... | Write a Python 3 function for
returning type by xml node | You are a Python code architect, reviewing and designing scalable and efficient code |
Creates class instance with args | Make a summary of the following Python 3 code
def create_inst(inst_type, **init_args):
'''Creates class instance with args'''
args, kwargs = get_init_args(inst_type, init_args)
return inst_type(*args, **kwargs) | As a python code expert, you are capable of creating scripts from specifications. |
Returns tuple with args and kwargs to pass it to inst_type constructor | How would you explain what the following Python 3 function does
def get_init_args(inst_type, init_args: dict, add_kwargs=False) -> Tuple[List, Dict]:
'''Returns tuple with args and kwargs to pass it to inst_type constructor'''
try:
parameters = signature(inst_type).parameters.values()
args_keys ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Wraps passed instance with InstanceNode | Make a summary of the following Python 3 code
def convert_to_node(instance, xml_node: XmlNode, node_globals: InheritedDict = None)\
-> InstanceNode:
'''Wraps passed instance with InstanceNode'''
return InstanceNode(instance, xml_node, node_globals) | You are a Python code analyst, evaluating scripts for potential improvements. |
Create QS Logger for command context AutoLoadCommandContext ResourceCommandContext or ResourceRemoteCommandContext with thread name
. | Explain what the following Python 3 code does
def get_logger_with_thread_id(context):
logger = LoggingSessionContext.get_logger_for_context(context)
child = logger.getChild(threading.currentThread().name)
for handler in logger.handlers:
child.addHandler(handler)
child.level = logger.level
fo... | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_snmp_parameters_from_command_context(resource_config, api, force_decrypt=False):
"""
:param ResourceCommandContext resource_config: command context
:return:
"""
if '3' in resource_config.snmp_version:
return SNMPV3Parameters(ip=resource_config.address,
... | Write a Python 3 script to
get the SNMPV3Parameters object from the command context. | You are a Python code architect, reviewing and designing scalable and efficient code |
def add(self, target, args=None, kwargs=None, **options):
"""Add an Async job to this context.
Like Context.add(): creates an Async and adds it to our list of tasks.
but also calls _auto_insert_check() to add tasks to queues
automatically.
"""
# In superclass, add new t... | How would you implement a function in Python 3 that
adds an Async job to this context. | You are a Python code generator, capable of creating scripts from specifications. |
Automatically insert tasks asynchronously. Depending on batch_size insert or wait until next call. | Explain what the following Python 3 code does
def _auto_insert_check(self):
if not self.batch_size:
return
if len(self._tasks) >= self.batch_size:
self._handle_tasks() | You are a Python code architect, reviewing and designing scalable and efficient code |
Get all Instructions that are derived from cls. | Here you have a function in Python 3, explain what it does
def get_insns(cls = None):
insns = []
if cls is None:
cls = Instruction
if "_mnemonic" in cls.__dict__.keys():
insns = [cls]
for subcls in cls.__subclasses__():
insns += get_insns(subcls)
return insns | As a Python code composer, you craft elegant and concise scripts. |
Find instruction that matches the mnemonic. | Can you generate the documentation for the following Python 3 function
def reverse_lookup(mnemonic: str):
for i in get_insns():
if "_mnemonic" in i.__dict__ and i._mnemonic == mnemonic:
return i
return None | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_value_from_schema(schema, definition: dict, key: str,
definition_key: str):
"""Gets a value from a schema and definition.
If the value has references it will recursively attempt to resolve them.
:param ResourceSchema schema: The resource schema.
:param dict definition... | Implement a Python 3 function for
getting a value from a schema and definition. | As a Python code composer, you craft elegant and concise scripts. |
Returns the json and native python type based on the json_type input. | Can you generate the documentation for the following Python 3 function
def get_types(json_type: StrOrList) -> typing.Tuple[str, str]:
# If the type is a list, use the first non 'null' value as the type.
if isinstance(json_type, list):
for j_type in json_type:
if j_type != 'null':
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Create a type object from a json schema file. | Make a summary of the following Python 3 code
def json_schema_type(schema_file: str, **kwargs) -> typing.Type:
# Importing here to avoid circular dependencies
from doctor.resource import ResourceSchema
schema = ResourceSchema.from_file(schema_file)
kwargs['schema'] = schema
# Look up the descriptio... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Create a new string type. | Can you generate the documentation for the following Python 3 function
def string(description: str, **kwargs) -> typing.Type:
kwargs['description'] = description
return type('String', (String,), kwargs) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Create a new integer type. | Can you generate the documentation for the following Python 3 function
def integer(description, **kwargs) -> typing.Type:
kwargs['description'] = description
return type('Integer', (Integer,), kwargs) | As a Python code composer, you craft elegant and concise scripts. |
Create a number type. | Explain what the following Python 3 code does
def number(description, **kwargs) -> typing.Type:
kwargs['description'] = description
return type('Number', (Number,), kwargs) | As a Python code analyst, you investigate and solve complex coding mysteries |
def boolean(description, **kwargs) -> typing.Type:
"""Create a :class:`~doctor.types.Boolean` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.Boolean`
"""
kwargs['description'] = description
return type('Bool... | Implement a Python 3 function for
creating a type with the given description. | As a Python code analyst, you investigate and solve complex coding mysteries |
def enum(description, **kwargs) -> typing.Type:
"""Create a :class:`~doctor.types.Enum` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.Enum`
"""
kwargs['description'] = description
return type('Enum', (Enum,... | Write a Python 3 script for
creating a new Enum type. | You are a Python code generator, capable of creating scripts from specifications. |
Create a new Array type. | How would you explain what the following Python 3 function does
def array(description, **kwargs) -> typing.Type:
kwargs['description'] = description
return type('Array', (Array,), kwargs) | You are a Python code generator, capable of creating scripts from specifications. |
def new_type(cls, **kwargs) -> typing.Type:
"""Create a user defined type.
The new type will contain all attributes of the `cls` type passed in.
Any attribute's value can be overwritten using kwargs.
:param kwargs: Can include any attribute defined in
the provided user defined type.
"""
... | Can you create a Python 3 function that
creates a new user defined type. | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_example(cls) -> dict:
"""Returns an example value for the Dict type.
If an example isn't a defined attribute on the class we return
a dict of example values based on each property's annotation.
"""
if cls.example is not None:
return cls.example
return... | Implement a Python 3 function for
returning an example value for the Dict type. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_example(cls) -> list:
"""Returns an example value for the Array type.
If an example isn't a defined attribute on the class we return
a list of 1 item containing the example value of the `items` attribute.
If `items` is None we simply return a `[1]`.
"""
if cls.ex... | Can you implement a function in Python 3 that
returns an example value for the Array type. | As a Python code analyst, you investigate and solve complex coding mysteries |
Renders node from xml node | Can you generate a brief explanation for the following Python 3 code
def render_node(xml_node: XmlNode, **args) -> Node:
try:
node = create_node(xml_node, **args)
pipeline = get_pipeline(node)
run_steps(node, pipeline, **args)
return node
except CoreError as error:
error.... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Gets rendering pipeline for passed node | Given the following Python 3 function, write the documentation
def get_pipeline(node: Node) -> RenderingPipeline:
pipeline = _get_registered_pipeline(node)
if pipeline is None:
msg = _get_pipeline_registration_error_message(node)
raise RenderingError(msg)
return pipeline | You are a Python code generator, capable of creating scripts from specifications. |
def run_steps(node: Node, pipeline: RenderingPipeline, **args):
"""Runs instance node rendering steps"""
for step in pipeline.steps:
result = step(node, pipeline=pipeline, **args)
if isinstance(result, dict):
args = {**args, **result} | Write a Python 3 function for
running the node rendering steps | You are a Python code architect, reviewing and designing scalable and efficient code |
def apply_attributes(node: Node, **_):
"""Applies xml attributes to instance node and setups bindings"""
for attr in node.xml_node.attrs:
apply_attribute(node, attr) | Create a Python 3 function for
applying xml attributes to instance node and setups bindings | You are a Python code analyst, evaluating scripts for potential improvements. |
def apply_attribute(node: Node, attr: XmlAttr):
"""Maps xml attribute to instance node property and setups bindings"""
setter = get_setter(attr)
stripped_value = attr.value.strip() if attr.value else ''
if is_expression(stripped_value):
(binding_type, expr_body) = parse_expression(stripped_value... | Can you write a function in Python 3 where it
maps xml attribute to instance node property and setups bindings | You are a Python code analyst, evaluating scripts for potential improvements. |
Return a list of all columns. | Can you generate a brief explanation for the following Python 3 code
def all_columns(self):
columns = set()
for values in self._parts:
for value in values._parts:
columns.add(value.column_name)
return sorted(columns) | As a python code expert, you are capable of creating scripts from specifications. |
def get_annotation(cls, fn):
"""Find the _schema_annotation attribute for the given function.
This will descend through decorators until it finds something that has
the attribute. If it doesn't find it anywhere, it will return None.
:param func fn: Find the attribute on this function.
... | Can you implement a function in Python 3 that
finds the _schema_annotation attribute for the given function. | As a Python code composer, you craft elegant and concise scripts. |
def _create_request_schema(self, params, required):
"""Create a JSON schema for a request.
:param list params: A list of keys specifying which definitions from
the base schema should be allowed in the request.
:param list required: A subset of the params that the requester must
... | Create a Python 3 function for
creating a JSON schema for a request. | You are a Python code generator, capable of creating scripts from specifications. |
def update_note(note_id: NoteId, body: Body=None, done: Done=None) -> Note:
"""Update an existing note."""
if note_id != 1:
raise NotFoundError('Note does not exist')
new_note = note.copy()
if body is not None:
new_note['body'] = body
if done is not None:
new_note['done'] = d... | How would you implement a function in Python 3 that
updates an existing note. | As a Python code analyst, you investigate and solve complex coding mysteries |
Return a Task object representing this message. | Here you have a function in Python 3, explain what it does
def to_task(self):
from google.appengine.api.taskqueue import Task
task_args = self.get_task_args().copy()
payload = None
if 'payload' in task_args:
payload = task_args.pop('payload')
kwargs = {
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def insert(self):
"""Insert the pull task into the requested queue, 'default' if non
given.
"""
from google.appengine.api.taskqueue import Queue
task = self.to_task()
Queue(name=self.get_queue()).add(task) | Can you write a function in Python 3 where it
inserts the pull task into the requested queue. | As a python code expert, you are capable of creating scripts from specifications. |
def to_dict(self):
"""Return this message as a dict suitable for json encoding."""
import copy
options = copy.deepcopy(self._options)
# JSON don't like datetimes.
eta = options.get('task_args', {}).get('eta')
if eta:
options['task_args']['eta'] = time.mktime... | How would you code a function in Python 3 to
return this message as a dict suitable for json encoding. | You are a Python code analyst, evaluating scripts for potential improvements. |
Get the id of this message. | Make a summary of the following Python 3 code
def _get_id(self):
id = self._options.get('id')
if id:
return id
id = uuid.uuid4().hex
self.update_options(id=id)
return id | You are a Python code generator, capable of creating scripts from specifications. |
def from_dict(cls, message):
"""Return an message from a dict output by Async.to_dict."""
message_options = message.copy()
# JSON don't like datetimes.
eta = message_options.get('task_args', {}).get('eta')
if eta:
from datetime import datetime
message_o... | Can you create a Python 3 function that
returns an Async message from a dict output by Async. to_dict. | As a Python code analyst, you investigate and solve complex coding mysteries |
Return a task object representing this MessageProcessor job. | Here you have a function in Python 3, explain what it does
def to_task(self):
task_args = self.get_task_args()
# check for name in task args
name = task_args.get('name', MESSAGE_PROCESSOR_NAME)
# if the countdown isn't in the task_args set it to the frequency
if not 'countdown'... | As a Python code composer, you craft elegant and concise scripts. |
def current_batch(self):
"""Return the batch id for the tag.
:return: :class: `int` current batch id
"""
current_batch = memcache.get(self.group_key)
if not current_batch:
memcache.add(self.group_key, 1)
current_batch = 1
return current_batch | Create a Python 3 function to
return the current batch id for the tag. | As a python code expert, you are capable of creating scripts from specifications. |
def fetch_messages(self):
"""Fetch messages from the specified pull-queue.
This should only be called a single time by a given MessageIterator
object. If the MessageIterator is iterated over again, it should
return the originally leased messages.
"""
if self._fetched:
... | Implement a Python 3 function for
fetching the messages from the specified pull - queue. | As a Python code analyst, you investigate and solve complex coding mysteries |
Get the next batch of messages from the previously fetched messages. | Can you tell what is the following Python 3 function doing
def next(self):
if not self._messages:
if self.auto_delete:
self.delete_messages()
raise StopIteration
message = self._messages.pop(0)
self._processed_messages.append(message)
return json.... | As a Python code composer, you craft elegant and concise scripts. |
Delete the messages previously leased. | Can you generate a brief explanation for the following Python 3 code
def delete_messages(self, only_processed=True):
messages = self._processed_messages
if not only_processed:
messages += self._messages
if messages:
try:
self.queue.delete_tasks(messages)
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def copy_func(func: Callable) -> Callable:
"""Returns a copy of a function.
:param func: The function to copy.
:returns: The copied function.
"""
copied = types.FunctionType(
func.__code__, func.__globals__, name=func.__name__,
argdefs=func.__defaults__, closure=func.__closure__)
... | How would you implement a function in Python 3 that
returns a copy of a function. | You are a Python code analyst, evaluating scripts for potential improvements. |
Gets all parameters from a function signature. | Can you generate the documentation for the following Python 3 function
def get_params_from_func(func: Callable, signature: Signature=None) -> Params:
if signature is None:
# Check if the function already parsed the signature
signature = getattr(func, '_doctor_signature', None)
# Otherwise pa... | You are a Python code analyst, evaluating scripts for potential improvements. |
Adds parameter annotations to a logic function. | Can you tell what is the following Python 3 function doing
def add_param_annotations(
logic: Callable, params: List[RequestParamAnnotation]) -> Callable:
"""Adds parameter annotations to a logic function.
This adds additional required and/or optional parameters to the logic
function that are not pa... | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_module_attr(module_filename, module_attr, namespace=None):
"""Get an attribute from a module.
This uses exec to load the module with a private namespace, and then
plucks and returns the given attribute from that module's namespace.
Note that, while this method doesn't have any explicit unit te... | How would you code a function in Python 3 to
get an attribute from a module. | You are a Python code generator, capable of creating scripts from specifications. |
Extract the description from the given docstring. | How would you explain what the following Python 3 function does
def get_description_lines(docstring):
if prepare_docstring is None:
raise ImportError('sphinx must be installed to use this function.')
if not isinstance(docstring, str):
return []
lines = []
for line in prepare_docstring(d... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_valid_class_name(s: str) -> str:
"""Return the given string converted so that it can be used for a class name
Remove leading and trailing spaces; removes spaces and capitalizes each
word; and remove anything that is not alphanumeric. Returns a pep8
compatible class name.
:param s: The str... | Can you create a Python 3 function that
returns the given string converted so that it can be used for a class name. | As a python code expert, you are capable of creating scripts from specifications. |
Instantiate a new _ExecutionContext and store a reference to it in the global async context. | Can you tell what is the following Python 3 function doing
def execution_context_from_async(async):
local_context = _local.get_local_context()
if local_context._executing_async_context:
raise errors.ContextExistsError
execution_context = _ExecutionContext(async)
local_context._executing_async_... | As a Python code analyst, you investigate and solve complex coding mysteries |
Use cli. get_session to open CLI connection and switch into required mode
| Can you generate the documentation for the following Python 3 function
def get_cli_service(self, command_mode):
return self._cli.get_session(self._new_sessions(), command_mode, self._logger) | As a Python code composer, you craft elegant and concise scripts. |
Function that identifies whether two crystals are equivalent | Make a summary of the following Python 3 code
def check_crystal_equivalence(crystal_a, crystal_b):
# getting symmetry datasets for both crystals
cryst_a = spglib.get_symmetry_dataset(ase_to_spgcell(crystal_a), symprec=1e-5, angle_tolerance=-1.0, hall_number=0)
cryst_b = spglib.get_symmetry_dataset(ase_to_s... | As a Python code composer, you craft elegant and concise scripts. |
def add_view_info(self, view_info: ViewInfo):
'''Adds view information to error message'''
try:
next(info for info in self._view_infos if info.view == view_info.view)
except StopIteration:
indent = len(self._view_infos) * '\t'
self._view_infos.append(view_info... | Write a Python 3 script to
add view information to error message | As a python code expert, you are capable of creating scripts from specifications. |
def add_info(self, header, message):
'''Adds "header: message" line to error message'''
current_message = self.args[0]
message = current_message + self._format_info(header, message)
self.args = (message,) + self.args[1:] | Implement a Python 3 function for
adding header line to error message | You are a Python code analyst, evaluating scripts for potential improvements. |
Adds cause error to error message | Here you have a function in Python 3, explain what it does
def add_cause(self, error: Exception):
'''Adds cause error to error message'''
self.add_info('Cause error', '{0} - {1}'.format(type(error).__name__, error)) | As a Python code analyst, you investigate and solve complex coding mysteries |
def process_async_task(headers, request_body):
"""Process an Async task and execute the requested function."""
async_options = json.loads(request_body)
async = async_from_options(async_options)
_log_task_info(headers,
extra_task_info=async.get_options().get('_extra_task_info'))
... | Write a Python 3 script for
processing an Async task and execute the requested function. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _log_task_info(headers, extra_task_info=None):
"""Processes the header from task requests to log analytical data."""
ran_at = time.time()
task_eta = float(headers.get('X-Appengine-Tasketa', 0.0))
task_info = {
'retry_count': headers.get('X-Appengine-Taskretrycount', ''),
'execution_c... | Can you write a function in Python 3 where it
processes the header from task requests to log analytical data. | As a python code expert, you are capable of creating scripts from specifications. |
Load firmware from given path and update firmware version on device. | Can you generate the documentation for the following Python 3 function
def load_firmware(self, path, vrf_management_name=None):
url = UrlParser.parse_url(path)
required_keys = [UrlParser.FILENAME, UrlParser.HOSTNAME, UrlParser.SCHEME]
if not url or not all(key in url for key in required_keys):... | As a Python code composer, you craft elegant and concise scripts. |
Parse the ports string into the list
| Make a summary of the following Python 3 code
def _parse_ports(self, ports):
if not ports:
return []
return [tuple(port_pair.split("::")) for port_pair in ports.strip(";").split(";")] | You are a Python code architect, reviewing and designing scalable and efficient code |
SDN Controller enable trunk ports return list of tuple | Can you tell what is the following Python 3 function doing
def add_trunk_ports(self):
ports = self.attributes.get("{}Enable Full Trunk Ports".format(self.namespace_prefix), None)
return self._parse_ports(ports=ports) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _validate_build_resource_structure(autoload_resource):
"""Validate resource structure
:param dict autoload_resource:
:return correct autoload resource structure
:rtype: dict
"""
result = {}
for resource_prefix, resources in autoload_resource.iteritems():
... | Write a Python 3 function for
validating the autoload resource structure. | As a python code expert, you are capable of creating scripts from specifications. |
Build autoload details
:param autoload_data: dict:
:param relative_path: str: full relative path of current autoload resource | Given the following Python 3 function, write the documentation
def _build_autoload_details(self, autoload_data, relative_path=""):
self._autoload_details.attributes.extend([AutoLoadAttribute(relative_address=relative_path,
attribute_name=attri... | As a python code expert, you are capable of creating scripts from specifications. |
def set_attr(self, key: str, value):
"""Sets node attribute. Can be customized by attr_setter property"""
self.attr_setter(self, key, value) | How would you implement a function in Python 3 that
sets the attribute of the node. Can be customized by attr_setter property. | You are a Python code generator, capable of creating scripts from specifications. |
Destroys the current instance of the class. | How would you explain what the following Python 3 function does
def destroy(self):
self.destroy_children()
self.destroy_bindings()
if self.on_destroy:
self.on_destroy(self) | You are a Python code generator, capable of creating scripts from specifications. |
def set(self, value):
"""Sets value"""
self._value = self._setter(self._node, value, self._value) if self._setter else value | Can you write a function in Python 3 where it
sets the value of the node. | You are a Python code generator, capable of creating scripts from specifications. |
def new(self, node: Node):
"""Creates property for node"""
return Property(self.name, self._setter, node) | How would you implement a function in Python 3 that
creates a new property for node | You are a Python code architect, reviewing and designing scalable and efficient code |
def corr_vs_pval(r, pval, plim=0.01, rlim=0.4, dpi=96):
"""Histogram for correlation coefficients and its p-values (colored)
Parameters:
-----------
r : np.ndarray
Correlation coefficient matrix.
The upper triangular elements are extracted if a NxN is provided.
Otherwise provide... | Can you implement a function in Python 3 that
plots a histogram of correlation coefficients and its p - values. | As a python code expert, you are capable of creating scripts from specifications. |
Create an instance of TrafficGeneratorVBladeResource from the given context. | Make a summary of the following Python 3 code
def from_context(cls, context, shell_type=None, shell_name=None):
return cls(address=context.resource.address,
family=context.resource.family,
shell_type=shell_type,
shell_name=shell_name,
f... | As a python code expert, you are capable of creating scripts from specifications. |
Helper. Updates the filter dict for a queryset. | Explain what the following Python 3 code does
def update_filter_dict(d, user, status):
if user is not None:
if not user.id:
return None
d['user'] = user
if status is not None:
d['status'] = status | As a Python code composer, you craft elegant and concise scripts. |
Returns a dictionary with flag objects associated with the given model classes. | Can you generate the documentation for the following Python 3 function
def get_flags_for_types(cls, mdl_classes, user=None, status=None, allow_empty=True):
return get_model_class_from_string(MODEL_FLAG).get_flags_for_types(
mdl_classes, user=user, status=status, allow_empty=allow_empty) | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_flags_for_objects(cls, objects_list, user=None, status=None):
"""Returns a dictionary with flag objects associated with the given model objects.
The dictionary is indexed by objects IDs.
Each dict entry contains a list of associated flag objects.
:param list, QuerySet objects_li... | Write a Python 3 function for
returning a dictionary with flag objects associated with the given model objects. | You are a Python code generator, capable of creating scripts from specifications. |
def get_flags(self, user=None, status=None):
"""Returns flags for the object optionally filtered by status.
:param User user: Optional user filter
:param int status: Optional status filter
:rtype: QuerySet
"""
filter_kwargs = {}
update_filter_dict(filter_kwargs, ... | Write a Python 3 script for
returning a QuerySet containing only the flags for the object optionally filtered by status. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def set_flag(self, user, note=None, status=None):
"""Flags the object.
:param User user:
:param str note: User-defined note for this flag.
:param int status: Optional status integer (the meaning is defined by a developer).
:return:
"""
if not user.id:
... | How would you implement a function in Python 3 that
flags the object. :param User user: :param str note: User-defined note for this flag. :param int status: Optional status integer (the meaning is defined by a developer). :return: | As a Python code translator, you convert algorithms and pseudocode into Python. |
Removes flag from the object. | Explain what the following Python 3 code does
def remove_flag(self, user=None, status=None):
filter_kwargs = {
'content_type': ContentType.objects.get_for_model(self),
'object_id': self.id
}
update_filter_dict(filter_kwargs, user, status)
get_flag_model().objects.... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def is_flagged(self, user=None, status=None):
"""Returns boolean whether the objects is flagged by a user.
:param User user: Optional user filter
:param int status: Optional status filter
:return:
"""
filter_kwargs = {
'content_type': ContentType.objects.get_... | Write a Python 3 function for
returning whether the objects is flagged by a user. | You are a Python code generator, capable of creating scripts from specifications. |
def set_backend(database):
"""
Configure used database, so sqlpuzzle can generate queries which are needed.
For now there is only support of MySQL and PostgreSQL.
"""
new_backend = BACKENDS.get(database.lower())
if not new_backend:
raise Exception('Backend {} is not supported.'.format(da... | Can you create a Python 3 function that
configures used database so sqlpuzzle can generate queries which are needed. | As a python code expert, you are capable of creating scripts from specifications. |
def health_check(self):
""" Verify that device is accessible over CLI by sending ENTER for cli session """
api_response = 'Online'
result = 'Health check on resource {}'.format(self._resource_name)
try:
health_check_flow = RunCommandFlow(self.cli_handler, self._logger)
... | Write a Python 3 script to
verify that the device is accessible over CLI by sending ENTER for CLI session. | As a Python code analyst, you investigate and solve complex coding mysteries |
Convert as reference on column. | Can you tell what is the following Python 3 function doing
def reference(cls, value):
from sqlpuzzle._common.utils import force_text
value = force_text(value)
parts = re.split(r'{quote}([^{quote}]+){quote}|\.'.format(quote=cls.reference_quote), value)
parts = ('{quote}{i}{quote}'.format(... | As a Python code analyst, you investigate and solve complex coding mysteries |
Convert a reference to a string path. | Make a summary of the following Python 3 code
def reference_to_path(reference):
# Try to pop the options off whatever they passed in.
if isinstance(reference, basestring):
# This is an object path name in str form.
import re
if not re.match(r'^[^\d\W]([a-zA-Z._]|((?<!\.)\d))+$', referenc... | As a Python code composer, you craft elegant and concise scripts. |
def path_to_reference(path):
"""Convert an object path reference to a reference."""
# By default JSON decodes strings as unicode. The Python __import__ does
# not like that choice. So we'll just cast all function paths to a string.
# NOTE: that there is no corresponding unit test for the classmethod
... | Write a Python 3 script to
convert an object path reference to a reference. | You are a Python code generator, capable of creating scripts from specifications. |
Encode callbacks to a dict suitable for JSON encoding. | Make a summary of the following Python 3 code
def encode_callbacks(callbacks):
from furious.async import Async
if not callbacks:
return
encoded_callbacks = {}
for event, callback in callbacks.iteritems():
if callable(callback):
callback, _ = get_function_path_and_options(ca... | You are a Python code analyst, evaluating scripts for potential improvements. |
def decode_callbacks(encoded_callbacks):
"""Decode the callbacks to an executable form."""
from furious.async import Async
callbacks = {}
for event, callback in encoded_callbacks.iteritems():
if isinstance(callback, dict):
async_type = Async
if '_type' in callback:
... | Implement a Python 3 function for
decoding the callbacks to an executable form. | You are a Python code analyst, evaluating scripts for potential improvements. |
Formats a stack for use in error messages. | Given the following Python 3 function, write the documentation
def _format_stack(self, stack, current=None):
if current is not None:
stack = stack + [current]
if len(stack) > 1:
prefix = os.path.commonprefix(stack)
if prefix.endswith('/'):
prefix = pre... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def resolve(self, ref, document=None):
"""Resolve a fragment within the schema.
If the resolved value contains a $ref, it will attempt to resolve that
as well, until it gets something that is not a reference. Circular
references will raise a SchemaError.
:param str ref: URI to ... | Implement a Python 3 function for
resolving a fragment within the schema. | As a python code expert, you are capable of creating scripts from specifications. |
def resolve_remote(self, uri):
"""Add support to load YAML files.
This will attempt to load a YAML file first, and then go back to the
default behavior.
:param str uri: the URI to resolve
:returns: the retrieved document
"""
if uri.startswith('file://'):
... | Can you write a function in Python 3 where it
adds support to load YAML files. | You are a Python code analyst, evaluating scripts for potential improvements. |
Get a jsonschema validator. | Make a summary of the following Python 3 code
def get_validator(self, schema=None):
schema = schema if schema is not None else self.schema
return jsonschema.Draft4Validator(
schema, resolver=self.resolver,
format_checker=jsonschema.draft4_format_checker) | You are a Python code architect, reviewing and designing scalable and efficient code |
def resolve(self, ref, document=None):
"""Resolve a ref within the schema.
This is just a convenience method, since RefResolver returns both a URI
and the resolved value, and we usually just need the resolved value.
:param str ref: URI to resolve.
:param dict document: Optional... | Can you implement a function in Python 3 that
resolves a ref within the schema. | As a Python code composer, you craft elegant and concise scripts. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.