output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Get a template into an xml template | How would you explain what the following Python 3 function does
def get_template_as_xml(template_id,**kwargs):
template_xml = etree.Element("template_definition")
template_i = db.DBSession.query(Template).filter(
Template.id==template_id).options(
#joinedload_all('templatetypes.type... | As a python code expert, you are capable of creating scripts from specifications. |
def import_template_json(template_json_string,allow_update=True, **kwargs):
"""
Add the template, type and typeattrs described
in a JSON file.
Delete type, typeattr entries in the DB that are not in the XML file
The assumption is that they have been deleted and are no longer require... | Implement a Python 3 function for
importing a template from a JSON string. | As a python code expert, you are capable of creating scripts from specifications. |
def import_template_xml(template_xml, allow_update=True, **kwargs):
"""
Add the template, type and typeattrs described
in an XML file.
Delete type, typeattr entries in the DB that are not in the XML file
The assumption is that they have been deleted and are no longer required.
"... | How would you implement a function in Python 3 that
imports a template XML file into the database. | As a Python code composer, you craft elegant and concise scripts. |
def apply_template_to_network(template_id, network_id, **kwargs):
"""
For each node and link in a network, check whether it matches
a type in a given template. If so, assign the type to the node / link.
"""
net_i = db.DBSession.query(Network).filter(Network.id==network_id).one()
#There ... | Write a Python 3 function for
applying a template to a network. | You are a Python code architect, reviewing and designing scalable and efficient code |
This function is used to set a template to a network. | Explain what the following Python 3 code does
def set_network_template(template_id, network_id, **kwargs):
resource_types = []
#There should only ever be one matching type, but if there are more,
#all we can do is pick the first one.
try:
network_type = db.DBSession.query(ResourceType).filter(... | You are a Python code analyst, evaluating scripts for potential improvements. |
Removes a template from a network. | How would you explain what the following Python 3 function does
def remove_template_from_network(network_id, template_id, remove_attrs, **kwargs):
try:
network = db.DBSession.query(Network).filter(Network.id==network_id).one()
except NoResultFound:
raise HydraError("Network %s not found"%networ... | As a Python code analyst, you investigate and solve complex coding mysteries |
Identify the resources which can be removed from the tree. | Can you generate a brief explanation for the following Python 3 code
def _get_resources_to_remove(resource, template):
type_ids = [tmpltype.id for tmpltype in template.templatetypes]
node_attr_ids = dict([(ra.attr_id, ra) for ra in resource.attributes])
attrs_to_remove = []
attrs_to_keep = []
for... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get the possible types of a resource by checking its attributes
against all available types. | Given the following Python 3 function, write the documentation
def get_matching_resource_types(resource_type, resource_id,**kwargs):
resource_i = None
if resource_type == 'NETWORK':
resource_i = db.DBSession.query(Network).filter(Network.id==resource_id).one()
elif resource_type == 'NODE':
r... | You are a Python code generator, capable of creating scripts from specifications. |
def assign_types_to_resources(resource_types,**kwargs):
"""
Assign new types to list of resources.
This function checks if the necessary
attributes are present and adds them if needed. Non existing attributes
are also added when the type is already assigned. This means that this
... | How would you implement a function in Python 3 that
assigns new types to resources. | You are a Python code architect, reviewing and designing scalable and efficient code |
def check_type_compatibility(type_1_id, type_2_id):
"""
When applying a type to a resource, it may be the case that the resource already
has an attribute specified in the new type, but the template which defines this
pre-existing attribute has a different unit specification to the new templa... | Can you implement a function in Python 3 that
checks if the type_1_id and type_2_id are compatible with the resource type. | As a python code expert, you are capable of creating scripts from specifications. |
def assign_type_to_resource(type_id, resource_type, resource_id,**kwargs):
"""Assign new type to a resource. This function checks if the necessary
attributes are present and adds them if needed. Non existing attributes
are also added when the type is already assigned. This means that this
function can a... | Write a Python 3 script for
assigning a new type to a resource. | You are a Python code analyst, evaluating scripts for potential improvements. |
Set this resource to a certain type. | Make a summary of the following Python 3 code
def set_resource_type(resource, type_id, types={}, **kwargs):
ref_key = resource.ref_key
existing_attr_ids = []
for res_attr in resource.attributes:
existing_attr_ids.append(res_attr.attr_id)
if type_id in types:
type_i = types[type_id]
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def remove_type_from_resource( type_id, resource_type, resource_id,**kwargs):
"""
Remove a resource type trom a resource
"""
node_id = resource_id if resource_type == 'NODE' else None
link_id = resource_id if resource_type == 'LINK' else None
group_id = resource_id if resource_type == 'GROUP... | Write a Python 3 script to
remove a resource type from a resource | As a Python code translator, you convert algorithms and pseudocode into Python. |
Add a template and a type and typeattrs. | Can you generate a brief explanation for the following Python 3 code
def add_template(template, **kwargs):
tmpl = Template()
tmpl.name = template.name
if template.description:
tmpl.description = template.description
if template.layout:
tmpl.layout = get_layout_as_string(template.layout)
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def update_template(template,**kwargs):
"""
Update template and a type and typeattrs.
"""
tmpl = db.DBSession.query(Template).filter(Template.id==template.id).one()
tmpl.name = template.name
if template.description:
tmpl.description = template.description
#Lazy load the rest of ... | Create a Python 3 function to
update the template and a type and typeattrs. | You are a Python code generator, capable of creating scripts from specifications. |
Delete a template and its type and typeattrs. | Can you generate the documentation for the following Python 3 function
def delete_template(template_id,**kwargs):
try:
tmpl = db.DBSession.query(Template).filter(Template.id==template_id).one()
except NoResultFound:
raise ResourceNotFoundError("Template %s not found"%(template_id,))
db.DBSes... | As a python code expert, you are capable of creating scripts from specifications. |
Get all templates.
Args:
load_all Boolean: Returns just the template entry or the full template structure (template types and type attrs)
Returns:
List of Template objects | Can you generate a brief explanation for the following Python 3 code
def get_templates(load_all=True, **kwargs):
if load_all is False:
templates = db.DBSession.query(Template).all()
else:
templates = db.DBSession.query(Template).options(joinedload_all('templatetypes.typeattrs')).all()
retur... | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_template(template_id,**kwargs):
"""
Get a specific resource template template, by ID.
"""
try:
tmpl_i = db.DBSession.query(Template).filter(Template.id==template_id).options(joinedload_all('templatetypes.typeattrs.default_dataset.metadata')).one()
#Load the attributes.
... | Write a Python 3 script for
getting a specific resource template by ID. | You are a Python code generator, capable of creating scripts from specifications. |
def get_template_by_name(name,**kwargs):
"""
Get a specific resource template, by name.
"""
try:
tmpl_i = db.DBSession.query(Template).filter(Template.name == name).options(joinedload_all('templatetypes.typeattrs.default_dataset.metadata')).one()
return tmpl_i
except NoResultFoun... | How would you code a function in Python 3 to
get a specific resource template by name. | You are a Python code analyst, evaluating scripts for potential improvements. |
def add_templatetype(templatetype,**kwargs):
"""
Add a template type with typeattrs.
"""
type_i = _update_templatetype(templatetype)
db.DBSession.flush()
return type_i | How would you code a function in Python 3 to
add a template type to the hierarchy. | You are a Python code generator, capable of creating scripts from specifications. |
def update_templatetype(templatetype,**kwargs):
"""
Update a resource type and its typeattrs.
New typeattrs will be added. typeattrs not sent will be ignored.
To delete typeattrs, call delete_typeattr
"""
tmpltype_i = db.DBSession.query(TemplateType).filter(TemplateType.id == templa... | How would you implement a function in Python 3 that
updates a resource type and its typeattrs. | You are a Python code architect, reviewing and designing scalable and efficient code |
Sets the type attributes of the current node. | Here you have a function in Python 3, explain what it does
def _set_typeattr(typeattr, existing_ta = None):
if existing_ta is None:
ta = TypeAttr(attr_id=typeattr.attr_id)
else:
ta = existing_ta
ta.unit_id = typeattr.unit_id
ta.type_id = typeattr.type_id
ta.data_type = typeattr.data... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _update_templatetype(templatetype, existing_tt=None):
"""
Add or update a templatetype. If an existing template type is passed in,
update that one. Otherwise search for an existing one. If not found, add.
"""
if existing_tt is None:
if "id" in templatetype and templatetype.id is ... | Implement a Python 3 function for
updating a template type in the database. | As a Python code analyst, you investigate and solve complex coding mysteries |
def delete_templatetype(type_id,template_i=None, **kwargs):
"""
Delete a template type and its typeattrs.
"""
try:
tmpltype_i = db.DBSession.query(TemplateType).filter(TemplateType.id == type_id).one()
except NoResultFound:
raise ResourceNotFoundError("Template Type %s not found"... | Write a Python 3 script to
delete a template type and its typeattrs. | As a python code expert, you are capable of creating scripts from specifications. |
Get a specific resource type by ID. | Can you tell what is the following Python 3 function doing
def get_templatetype(type_id,**kwargs):
templatetype = db.DBSession.query(TemplateType).filter(
TemplateType.id==type_id).options(
joinedload_all("typeattrs")).one()
return templatetype | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get a specific resource type by name. | Make a summary of the following Python 3 code
def get_templatetype_by_name(template_id, type_name,**kwargs):
try:
templatetype = db.DBSession.query(TemplateType).filter(TemplateType.id==template_id, TemplateType.name==type_name).one()
except NoResultFound:
raise HydraError("%s is not a valid id... | You are a Python code generator, capable of creating scripts from specifications. |
def add_typeattr(typeattr,**kwargs):
"""
Add an typeattr to an existing type.
"""
tmpltype = get_templatetype(typeattr.type_id, user_id=kwargs.get('user_id'))
ta = _set_typeattr(typeattr)
tmpltype.typeattrs.append(ta)
db.DBSession.flush()
return ta | Write a Python 3 script to
add an typeattr to an existing type. | As a Python code composer, you craft elegant and concise scripts. |
Remove an typeattr from an existing type
| Here you have a function in Python 3, explain what it does
def delete_typeattr(typeattr,**kwargs):
tmpltype = get_templatetype(typeattr.type_id, user_id=kwargs.get('user_id'))
ta = db.DBSession.query(TypeAttr).filter(TypeAttr.type_id == typeattr.type_id,
TypeAttr.attr... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def validate_attr(resource_attr_id, scenario_id, template_id=None):
"""
Check that a resource attribute satisfies the requirements of all the types of the
resource.
"""
rs = db.DBSession.query(ResourceScenario).\
filter(ResourceScenario.resource_attr_id==resource_attr... | Can you implement a function in Python 3 that
validates a resource attribute against the resource scenario. | As a python code expert, you are capable of creating scripts from specifications. |
Check that multiple resource attribute ids satisfy the requirements of the types of resources to the scenario. | Here you have a function in Python 3, explain what it does
def validate_attrs(resource_attr_ids, scenario_id, template_id=None):
multi_rs = db.DBSession.query(ResourceScenario).\
filter(ResourceScenario.resource_attr_id.in_(resource_attr_ids),\
Resource... | As a python code expert, you are capable of creating scripts from specifications. |
Perform a check to ensure a resource scenario s datasets are correct given what the resource attribute of that resource is specified. | Make a summary of the following Python 3 code
def _do_validate_resourcescenario(resourcescenario, template_id=None):
res = resourcescenario.resourceattr.get_resource()
types = res.types
dataset = resourcescenario.dataset
if len(types) == 0:
return
if template_id is not None:
if t... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def validate_network(network_id, template_id, scenario_id=None):
"""
Given a network, scenario and template, ensure that all the nodes, links & groups
in the network have the correct resource attributes as defined by the types in the template.
Also ensure valid entries in tresourcetype.
... | Can you create a Python 3 function that
gives a network, scenario and template, ensure that all the nodes, links & groups in the network have the correct resource attributes as defined by the types in the template. Also ensure valid entries in tresourcetype. This validation will not fail if a resource has more than the... | As a Python code composer, you craft elegant and concise scripts. |
def get_network_as_xml_template(network_id,**kwargs):
"""
Turn an existing network into an xml template
using its attributes.
If an optional scenario ID is passed in, default
values will be populated from that scenario.
"""
template_xml = etree.Element("template_definition")
... | Implement a function in Python 3 to
get an existing network into an xml template. | As a Python code translator, you convert algorithms and pseudocode into Python. |
This function creates an attribute element from a type_attr element. | Can you generate the documentation for the following Python 3 function
def _make_attr_element_from_typeattr(parent, type_attr_i):
attr = _make_attr_element(parent, type_attr_i.attr)
if type_attr_i.unit_id is not None:
attr_unit = etree.SubElement(attr, 'unit')
attr_unit.text = units.get_uni... | You are a Python code generator, capable of creating scripts from specifications. |
This function creates an attribute element from a resource attribute. | Here you have a function in Python 3, explain what it does
def _make_attr_element_from_resourceattr(parent, resource_attr_i):
attr = _make_attr_element(parent, resource_attr_i.attr)
attr_is_var = etree.SubElement(attr, 'is_var')
attr_is_var.text = resource_attr_i.attr_is_var
return attr | As a python code expert, you are capable of creating scripts from specifications. |
Create an attribute element from an attribute DB object | Here you have a function in Python 3, explain what it does
def _make_attr_element(parent, attr_i):
attr = etree.SubElement(parent, "attribute")
attr_name = etree.SubElement(attr, 'name')
attr_name.text = attr_i.name
attr_desc = etree.SubElement(attr, 'description')
attr_desc.text = attr_... | As a Python code analyst, you investigate and solve complex coding mysteries |
Convert a layout tree to a dict. | Can you generate the documentation for the following Python 3 function
def get_etree_layout_as_dict(layout_tree):
layout_dict = dict()
for item in layout_tree.findall('item'):
name = item.find('name').text
val_element = item.find('value')
value = val_element.text.strip()
if val... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _get_layout_as_etree(layout_dict):
"""
Convert something that looks like this:
{
'color' : ['red'],
'shapefile' : ['blah.shp']
}
Into something that looks like this:
<layout>
<item>
<name>color</name>
<value>red</value>
</item>
... | Implement a function in Python 3 to
convert a dict to an etree. Element | You are a Python code architect, reviewing and designing scalable and efficient code |
Return the value contained by dataset argument after casting to
correct type and performing type - specific validation. | Make a summary of the following Python 3 code
def valueFromDataset(cls, datatype, value, metadata=None, tmap=None):
if tmap is None:
tmap = typemap
obj = cls.fromDataset(datatype, value, metadata=metadata, tmap=tmap)
return obj.value | You are a Python code architect, reviewing and designing scalable and efficient code |
def fromDataset(datatype, value, metadata=None, tmap=None):
"""
Return a representation of dataset argument as an instance
of the class corresponding to its datatype
"""
if tmap is None:
tmap = typemap
return tmap[datatype.upper()].fromDataset(value, meta... | Can you implement a function in Python 3 that
returns an instance of the class corresponding to the specified datatype and value. | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns True if the dimension exists False otherwise. | Can you generate a brief explanation for the following Python 3 code
def exists_dimension(dimension_name,**kwargs):
try:
dimension = db.DBSession.query(Dimension).filter(Dimension.name==dimension_name).one()
# At this point the dimension exists
return True
except NoResultFound:
#... | You are a Python code analyst, evaluating scripts for potential improvements. |
def convert_units(values, source_measure_or_unit_abbreviation, target_measure_or_unit_abbreviation,**kwargs):
"""
Convert a value from one unit to another one.
Example::
>>> cli = PluginLib.connect()
>>> cli.service.convert_units(20.0, 'm', 'km')
0.02
Pa... | How would you implement a function in Python 3 that
converts a value from one unit to another unit. | As a Python code analyst, you investigate and solve complex coding mysteries |
Convert a value or a list of values from an unit to another one. | Given the following Python 3 function, write the documentation
def convert(values, source_measure_or_unit_abbreviation, target_measure_or_unit_abbreviation):
source_dimension = get_dimension_by_unit_measure_or_abbreviation(source_measure_or_unit_abbreviation)
target_dimension = get_dimension_by_unit_measure_or... | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns an empty dimension object initialized with empty values | How would you explain what the following Python 3 function does
def get_empty_dimension(**kwargs):
dimension = JSONObject(Dimension())
dimension.id = None
dimension.name = ''
dimension.description = ''
dimension.project_id = None
dimension.units = []
return dimension | As a Python code translator, you convert algorithms and pseudocode into Python. |
Given a dimension id returns all its data
| How would you explain what the following Python 3 function does
def get_dimension(dimension_id, do_accept_dimension_id_none=False,**kwargs):
if do_accept_dimension_id_none == True and dimension_id is None:
# In this special case, the method returns a dimension with id None
return get_empty_dimension... | As a python code expert, you are capable of creating scripts from specifications. |
def get_dimensions(**kwargs):
"""
Returns a list of objects describing all the dimensions with all the units.
"""
dimensions_list = db.DBSession.query(Dimension).options(load_only("id")).all()
return_list = []
for dimension in dimensions_list:
return_list.append(get_dimension(dimensi... | Can you implement a function in Python 3 that
returns a list of objects describing all the dimensions with all the units. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns all the data for a given dimension name. | Here you have a function in Python 3, explain what it does
def get_dimension_by_name(dimension_name,**kwargs):
try:
if dimension_name is None:
dimension_name = ''
dimension = db.DBSession.query(Dimension).filter(func.lower(Dimension.name)==func.lower(dimension_name.strip())).one()
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a single unit | Can you generate the documentation for the following Python 3 function
def get_unit(unit_id, **kwargs):
try:
unit = db.DBSession.query(Unit).filter(Unit.id==unit_id).one()
return JSONObject(unit)
except NoResultFound:
# The dimension does not exist
raise ResourceNotFoundError("Un... | As a Python code composer, you craft elegant and concise scripts. |
Returns all the units in the database | How would you explain what the following Python 3 function does
def get_units(**kwargs):
units_list = db.DBSession.query(Unit).all()
units = []
for unit in units_list:
new_unit = JSONObject(unit)
units.append(new_unit)
return units | You are a Python code generator, capable of creating scripts from specifications. |
def get_dimension_by_unit_measure_or_abbreviation(measure_or_unit_abbreviation,**kwargs):
"""
Return the physical dimension a given unit abbreviation of a measure, or the measure itself, refers to.
The search key is the abbreviation or the full measure
"""
unit_abbreviation, factor = _parse... | Can you write a function in Python 3 where it
returns the physical dimension a given unit abbreviation of a measure or the measure itself refers to. | As a python code expert, you are capable of creating scripts from specifications. |
Returns the Dimension a given unit id refers to. | Can you generate the documentation for the following Python 3 function
def get_dimension_by_unit_id(unit_id, do_accept_unit_id_none=False, **kwargs):
if do_accept_unit_id_none == True and unit_id is None:
# In this special case, the method returns a dimension with id None
return get_empty_dimension(... | You are a Python code generator, capable of creating scripts from specifications. |
Returns a single unit by abbreviation. Used as utility function to resolve string to id
| Explain what the following Python 3 code does
def get_unit_by_abbreviation(unit_abbreviation, **kwargs):
try:
if unit_abbreviation is None:
unit_abbreviation = ''
unit_i = db.DBSession.query(Unit).filter(Unit.abbreviation==unit_abbreviation.strip()).one()
return JSONObject(unit_i... | You are a Python code architect, reviewing and designing scalable and efficient code |
def add_dimension(dimension,**kwargs):
"""
Add the dimension defined into the object "dimension" to the DB
If dimension["project_id"] is None it means that the dimension is global, otherwise is property of a project
If the dimension exists emits an exception
"""
if numpy.isscalar(dim... | How would you implement a function in Python 3 that
adds a dimension to the DB | You are a Python code architect, reviewing and designing scalable and efficient code |
Update a dimension in the DB. | Can you generate the documentation for the following Python 3 function
def update_dimension(dimension,**kwargs):
db_dimension = None
dimension = JSONObject(dimension)
try:
db_dimension = db.DBSession.query(Dimension).filter(Dimension.id==dimension.id).filter().one()
if "description" in dime... | As a Python code composer, you craft elegant and concise scripts. |
Delete a dimension from the DB. Raises and exception if the dimension does not exist. | Can you generate a brief explanation for the following Python 3 code
def delete_dimension(dimension_id,**kwargs):
try:
dimension = db.DBSession.query(Dimension).filter(Dimension.id==dimension_id).one()
db.DBSession.query(Unit).filter(Unit.dimension_id==dimension.id).delete()
db.DBSession.d... | As a python code expert, you are capable of creating scripts from specifications. |
def bulk_add_dimensions(dimension_list, **kwargs):
"""
Save all the dimensions contained in the passed list.
"""
added_dimensions = []
for dimension in dimension_list:
added_dimensions.append(add_dimension(dimension, **kwargs))
return JSONObject({"dimensions": added_dimensions}) | Can you write a function in Python 3 where it
adds all the dimensions contained in the passed list to the current node. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def add_unit(unit,**kwargs):
"""
Add the unit defined into the object "unit" to the DB
If unit["project_id"] is None it means that the unit is global, otherwise is property of a project
If the unit exists emits an exception
A minimal example:
.. code-block:: python
... | How would you code a function in Python 3 to
add a unit to the DB. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Add all the units contained in the passed list to the current page. | How would you explain what the following Python 3 function does
def bulk_add_units(unit_list, **kwargs):
# for unit in unit_list:
# add_unit(unit, **kwargs)
added_units = []
for unit in unit_list:
added_units.append(add_unit(unit, **kwargs))
return JSONObject({"units": added_units}) | As a Python code composer, you craft elegant and concise scripts. |
def delete_unit(unit_id, **kwargs):
"""
Delete a unit from the DB.
Raises and exception if the unit does not exist
"""
try:
db_unit = db.DBSession.query(Unit).filter(Unit.id==unit_id).one()
db.DBSession.delete(db_unit)
db.DBSession.flush()
return True
ex... | Write a Python 3 function that can
delete a unit from the DB. Raises and exception if the unit does not exist | As a Python code analyst, you investigate and solve complex coding mysteries |
Update a unit in the DB. | How would you explain what the following Python 3 function does
def update_unit(unit, **kwargs):
try:
db_unit = db.DBSession.query(Unit).join(Dimension).filter(Unit.id==unit["id"]).filter().one()
db_unit.name = unit["name"]
# Needed to uniform into to description
db_unit.abbreviat... | As a Python code composer, you craft elegant and concise scripts. |
Convert a whole dataset to a new unit. | Can you generate the documentation for the following Python 3 function
def convert_dataset(dataset_id, target_unit_abbreviation,**kwargs):
ds_i = db.DBSession.query(Dataset).filter(Dataset.id==dataset_id).one()
dataset_type = ds_i.type
dsval = ds_i.get_val()
source_unit_abbreviation = get_unit(ds_i.u... | You are a Python code analyst, evaluating scripts for potential improvements. |
def validate_resource_attributes(resource, attributes, template, check_unit=True, exact_match=False,**kwargs):
"""
Validate that the resource provided matches the template.
Only passes if the resource contains ONLY the attributes specified
in the template.
The template should take t... | Create a Python 3 function for
validating that the resource and attributes in the template are in the data. | As a Python code composer, you craft elegant and concise scripts. |
Encodes the given data using the specified encoding that is specified
. | Make a summary of the following Python 3 code
def encode(encoding, data):
data = ensure_bytes(data, 'utf8')
try:
return ENCODINGS_LOOKUP[encoding].code + ENCODINGS_LOOKUP[encoding].converter.encode(data)
except KeyError:
raise ValueError('Encoding {} not supported.'.format(encoding)) | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_codec(data):
"""
Returns the codec used to encode the given data
:param data: multibase encoded data
:type data: str or bytes
:return: the :py:obj:`multibase.Encoding` object for the data's codec
:raises ValueError: if the codec is not supported
"""
try:
key = ensure_byt... | How would you code a function in Python 3 to
return the codec used to encode the given data. | As a Python code analyst, you investigate and solve complex coding mysteries |
def decode(data):
"""
Decode the multibase decoded data
:param data: multibase encoded data
:type data: str or bytes
:return: decoded data
:rtype: str
:raises ValueError: if the data is not multibase encoded
"""
data = ensure_bytes(data, 'utf8')
codec = get_codec(data)
return... | Can you create a Python 3 function that
decodes the multibase encoded data | As a Python code analyst, you investigate and solve complex coding mysteries |
def ed25519_generate_key_pair_from_secret(secret):
"""
Generate a new key pair.
Args:
secret (:class:`string`): A secret that serves as a seed
Returns:
A tuple of (private_key, public_key) encoded in base58.
"""
# if you want to do this correctly, use a key derivation function!
... | Can you write a function in Python 3 where it
generates a new key pair from a secret. | As a Python code analyst, you investigate and solve complex coding mysteries |
def generate_key_pair(secret=None):
"""Generates a cryptographic key pair.
Args:
secret (:class:`string`): A secret that serves as a seed
Returns:
:class:`~bigchaindb.common.crypto.CryptoKeypair`: A
:obj:`collections.namedtuple` with named fields
:attr:`~bigchaindb.common.cry... | Write a Python 3 function for
generating a cryptographic key pair. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _get_role_arn():
"""
Return role arn from X-Role-ARN header,
lookup role arn from source IP,
or fall back to command line default.
"""
role_arn = bottle.request.headers.get('X-Role-ARN')
if not role_arn:
role_arn = _lookup_ip_role_arn(bottle.request.environ.get('REMOTE_ADDR'))
... | Implement a Python 3 function for
getting the role arn from X - Role - ARN header and REMOTE -ADDR. | You are a Python code generator, capable of creating scripts from specifications. |
def _chunk_with_padding(self, iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# _chunk_with_padding('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue) | Implement a function in Python 3 to
collect data into fixed - length chunks or blocks | As a Python code composer, you craft elegant and concise scripts. |
Marshall a dict into something DynamoDB likes. | Make a summary of the following Python 3 code
def marshall(values):
serialized = {}
for key in values:
serialized[key] = _marshall_value(values[key])
return serialized | As a Python code translator, you convert algorithms and pseudocode into Python. |
def unmarshall(values):
"""
Transform a response payload from DynamoDB to a native dict
:param dict values: The response payload from DynamoDB
:rtype: dict
:raises ValueError: if an unsupported type code is encountered
"""
unmarshalled = {}
for key in values:
unmarshalled[key] ... | Can you implement a function in Python 3 that
transforms a response payload from DynamoDB to a native dict | As a Python code analyst, you investigate and solve complex coding mysteries |
def _marshall_value(value):
"""
Recursively transform `value` into an AttributeValue `dict`
:param mixed value: The value to encode
:rtype: dict
:raises ValueError: for unsupported types
Return the value as dict indicating the data type and transform or
recursively process the value if req... | Can you write a function in Python 3 where it
transforms a value into a AttributeValue dict | As a Python code analyst, you investigate and solve complex coding mysteries |
Unwrap a request response and return only the response data. | Here you have a function in Python 3, explain what it does
def _unwrap_result(action, result):
if not result:
return
elif action in {'DeleteItem', 'PutItem', 'UpdateItem'}:
return _unwrap_delete_put_update_item(result)
elif action == 'GetItem':
return _unwrap_get_item(result)
eli... | As a Python code analyst, you investigate and solve complex coding mysteries |
def list_tables(self, exclusive_start_table_name=None, limit=None):
"""
Invoke the `ListTables`_ function.
Returns an array of table names associated with the current account
and endpoint. The output from *ListTables* is paginated, with each page
returning a maximum of ``100`` t... | Write a Python 3 script to
invoke the `ListTables`_ function. Returns an array of table names associated with the current account and endpoint. The output from *ListTables* is paginated, with each page returning a maximum of ``100`` table names. :param str exclusive_start_table_name: The first table name that this oper... | You are a Python code analyst, evaluating scripts for potential improvements. |
Invoke the PutItem method in DynamoDB to add or replace an existing item. | Make a summary of the following Python 3 code
def put_item(self, table_name, item,
condition_expression=None,
expression_attribute_names=None,
expression_attribute_values=None,
return_consumed_capacity=None,
return_item_collection_metr... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_item(self, table_name, key_dict,
consistent_read=False,
expression_attribute_names=None,
projection_expression=None,
return_consumed_capacity=None):
"""
Invoke the `GetItem`_ function.
:param str table_name: table to re... | Create a Python 3 function to
invoke the `GetItem`_ function. :param str table_name: table to retrieve the item from :param dict key_dict: key to use for retrieval. This will be marshalled for you so a native :class:`dict` works. :param bool consistent_read: Determines the read consistency model: If set to :py:data`Tru... | You are a Python code architect, reviewing and designing scalable and efficient code |
def update_item(self, table_name, key_dict,
condition_expression=None,
update_expression=None,
expression_attribute_names=None,
expression_attribute_values=None,
return_consumed_capacity=None,
return_... | Write a Python 3 function for
invoking the `UpdateItem`_ function. Edits an existing item's attributes, or adds a new item to the table if it does not already exist. You can put, delete, or add attribute values. You can also perform a conditional update on an existing item (insert a new attribute name-value pair if it ... | As a Python code composer, you craft elegant and concise scripts. |
A Query operation uses the primary key of a table or secondary index to directly access items from that table or index. | Can you tell what is the following Python 3 function doing
def query(self, table_name,
index_name=None,
consistent_read=None,
key_condition_expression=None,
filter_expression=None,
expression_attribute_names=None,
expression_attribute_v... | As a Python code composer, you craft elegant and concise scripts. |
This operation scans the table and returns one or more items and item attributes in a secondary index. | Given the following Python 3 function, write the documentation
def scan(self,
table_name,
index_name=None,
consistent_read=None,
projection_expression=None,
filter_expression=None,
expression_attribute_names=None,
expression_attr... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def execute(self, action, parameters):
"""
Execute a DynamoDB action with the given parameters. The method will
retry requests that failed due to OS level errors or when being
throttled by DynamoDB.
:param str action: DynamoDB action to invoke
:param dict parameters: par... | Create a Python 3 function to
execute a DynamoDB action with the given parameters. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Assign a method to invoke when a request has encountered an ancillary unrecoverable error in an action execution. | Here you have a function in Python 3, explain what it does
def set_error_callback(self, callback):
self.logger.debug('Setting error callback: %r', callback)
self._on_error = callback | As a Python code composer, you craft elegant and concise scripts. |
def set_instrumentation_callback(self, callback):
"""Assign a method to invoke when a request has completed gathering
measurements.
:param method callback: The method to invoke
"""
self.logger.debug('Setting instrumentation callback: %r', callback)
self._instrumentation... | How would you implement a function in Python 3 that
assigns a method to invoke when a request has completed gathering measurements. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Invoke a DynamoDB action and return a concurrent. Future that will be completed when the action completes. | Can you generate the documentation for the following Python 3 function
def _execute(self, action, parameters, attempt, measurements):
future = concurrent.Future()
start = time.time()
def handle_response(request):
"""Invoked by the IOLoop when fetch has a response to process.
... | You are a Python code generator, capable of creating scripts from specifications. |
def _on_response(self, action, table, attempt, start, response, future,
measurements):
"""Invoked when the HTTP request to the DynamoDB has returned and
is responsible for setting the future result or exception based upon
the HTTP response provided.
:param str actio... | Can you create a Python 3 function that
invokes when the HTTP request to the DynamoDB has returned and sets the future result or exception based upon the response. | As a Python code composer, you craft elegant and concise scripts. |
Process the response from DynamoDB returning either the mapped exception
COOKIE or deserialized response. | Can you generate a brief explanation for the following Python 3 code
def _process_response(response):
error = response.exception()
if error:
if isinstance(error, aws_exceptions.AWSError):
if error.args[1]['type'] in exceptions.MAP:
raise exceptions.MAP[err... | As a Python code composer, you craft elegant and concise scripts. |
Write and return the id of the transaction that created the object. | Make a summary of the following Python 3 code
def write(self, obj, resource_id=None):
if resource_id is not None:
if self.read(resource_id):
raise ValueError("There are one object already with this id.")
obj['_id'] = resource_id
prepared_creation_tx = self.driver.... | You are a Python code generator, capable of creating scripts from specifications. |
Read and obj in bdb using the tx_id. | Make a summary of the following Python 3 code
def _get(self, tx_id):
# tx_id=self._find_tx_id(resource_id)
value = [
{
'data': transaction['metadata'],
'id': transaction['id']
}
for transaction in self.driver.instance.transactions.get(a... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Update and obj in bdb using the tx_id. | Here you have a function in Python 3, explain what it does
def _update(self, metadata, tx_id, resource_id):
try:
if not tx_id:
sent_tx = self.write(metadata, resource_id)
self.logger.debug('bdb::put::{}'.format(sent_tx['id']))
return sent_tx
... | As a Python code composer, you craft elegant and concise scripts. |
def list(self, search_from=None, search_to=None, limit=None):
"""List all the objects saved in the namespace.
:param search_from: TBI
:param search_to: TBI
:param offset: TBI
:param limit: max number of values to be shows.
:return: list with transactions.
"... | Implement a Python 3 function for
listing all the objects saved in the namespace. | You are a Python code architect, reviewing and designing scalable and efficient code |
List all the objects saved in the namespace. | Can you generate a brief explanation for the following Python 3 code
def _list(self):
all = self.driver.instance.metadata.get(search=self.namespace)
list = []
for id in all:
try:
if not self._get(id['id']) in list:
list.append(self._get(id['id']))
... | You are a Python code generator, capable of creating scripts from specifications. |
Query to bdb namespace. | Can you generate the documentation for the following Python 3 function
def query(self, search_model: QueryModel):
self.logger.debug('bdb::get::{}'.format(search_model.query))
assets = json.loads(requests.post("http://localhost:4000/query", data=search_model.query).content)['data']
self.logger.de... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Delete a transaction. Read documentation about CRAB model in https://blog.bigchaindb.com/crab-create-retrieve-append-burn-b9f6d111f460.
:param tx_id: transaction id
:return: | Here you have a function in Python 3, explain what it does
def _delete(self, tx_id):
txs = self.driver.instance.transactions.get(asset_id=self.get_asset_id(tx_id))
unspent = txs[-1]
output_index = 0
output = unspent['outputs'][output_index]
transfer_input = {
'fulfil... | As a python code expert, you are capable of creating scripts from specifications. |
Return the asset id of the first transaction. | Can you generate the documentation for the following Python 3 function
def get_asset_id(self, tx_id):
tx = self.driver.instance.transactions.retrieve(txid=tx_id)
assert tx is not None
return tx['id'] if tx['operation'] == 'CREATE' else tx['asset']['id'] | You are a Python code architect, reviewing and designing scalable and efficient code |
Writes ENVI header files | How would you explain what the following Python 3 function does
def hdr(data, filename):
hdrobj = data if isinstance(data, HDRobject) else HDRobject(data)
hdrobj.write(filename) | As a Python code translator, you convert algorithms and pseudocode into Python. |
read a HDR file into a dictionary | Make a summary of the following Python 3 code
def __hdr2dict(self):
with open(self.filename, 'r') as infile:
lines = infile.readlines()
i = 0
out = dict()
while i < len(lines):
line = lines[i].strip('\r\n')
if '=' in line:
if '{' in lin... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def write(self, filename='same'):
"""
write object to an ENVI header file
"""
if filename == 'same':
filename = self.filename
if not filename.endswith('.hdr'):
filename += '.hdr'
with open(filename, 'w') as out:
out.write(self.__str__()... | Create a Python 3 function for
writing object to an ENVI header file | As a python code expert, you are capable of creating scripts from specifications. |
def GoZero(self, speed):
' Go to Zero position '
self.ReleaseSW()
spi.SPI_write_byte(self.CS, 0x82 | (self.Dir & 1)) # Go to Zero
spi.SPI_write_byte(self.CS, 0x00)
spi.SPI_write_byte(self.CS, speed)
while self.IsBusy():
pass
time.sleep(0.3)
... | Can you create a Python 3 function that
goes to Zero position | You are a Python code generator, capable of creating scripts from specifications. |
Move some distance units from current position | Given the following Python 3 function, write the documentation
def Move(self, units):
' Move some distance units from current position '
steps = units * self.SPU # translate units to steps
if steps > 0: # look for direction
spi.SPI_write_byt... | As a python code expert, you are capable of creating scripts from specifications. |
Report given status bit | Can you generate the documentation for the following Python 3 function
def ReadStatusBit(self, bit):
' Report given status bit '
spi.SPI_write_byte(self.CS, 0x39) # Read from address 0x19 (STATUS)
spi.SPI_write_byte(self.CS, 0x00)
data0 = spi.SPI_read_byte() # 1st byte
... | As a Python code composer, you craft elegant and concise scripts. |
Writes a data to a SPI device selected by chipselect bit. | Explain what the following Python 3 code does
def SPI_write_byte(self, chip_select, data):
'Writes a data to a SPI device selected by chipselect bit. '
self.bus.write_byte_data(self.address, chip_select, data) | 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.