repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
hydraplatform/hydra-base
hydra_base/lib/template.py
get_types_by_attr
def get_types_by_attr(resource, template_id=None): """ Using the attributes of the resource, get all the types that this resource matches. @returns a dictionary, keyed on the template name, with the value being the list of type names which match the resources attributes. """ resource_type_templates = [] #Create a list of all of this resources attributes. attr_ids = [] for res_attr in resource.attributes: attr_ids.append(res_attr.attr_id) all_resource_attr_ids = set(attr_ids) all_types = db.DBSession.query(TemplateType).options(joinedload_all('typeattrs')).filter(TemplateType.resource_type==resource.ref_key) if template_id is not None: all_types = all_types.filter(TemplateType.template_id==template_id) all_types = all_types.all() #tmpl type attrs must be a subset of the resource's attrs for ttype in all_types: type_attr_ids = [] for typeattr in ttype.typeattrs: type_attr_ids.append(typeattr.attr_id) if set(type_attr_ids).issubset(all_resource_attr_ids): resource_type_templates.append(ttype) return resource_type_templates
python
def get_types_by_attr(resource, template_id=None): """ Using the attributes of the resource, get all the types that this resource matches. @returns a dictionary, keyed on the template name, with the value being the list of type names which match the resources attributes. """ resource_type_templates = [] #Create a list of all of this resources attributes. attr_ids = [] for res_attr in resource.attributes: attr_ids.append(res_attr.attr_id) all_resource_attr_ids = set(attr_ids) all_types = db.DBSession.query(TemplateType).options(joinedload_all('typeattrs')).filter(TemplateType.resource_type==resource.ref_key) if template_id is not None: all_types = all_types.filter(TemplateType.template_id==template_id) all_types = all_types.all() #tmpl type attrs must be a subset of the resource's attrs for ttype in all_types: type_attr_ids = [] for typeattr in ttype.typeattrs: type_attr_ids.append(typeattr.attr_id) if set(type_attr_ids).issubset(all_resource_attr_ids): resource_type_templates.append(ttype) return resource_type_templates
[ "def", "get_types_by_attr", "(", "resource", ",", "template_id", "=", "None", ")", ":", "resource_type_templates", "=", "[", "]", "#Create a list of all of this resources attributes.", "attr_ids", "=", "[", "]", "for", "res_attr", "in", "resource", ".", "attributes", ...
Using the attributes of the resource, get all the types that this resource matches. @returns a dictionary, keyed on the template name, with the value being the list of type names which match the resources attributes.
[ "Using", "the", "attributes", "of", "the", "resource", "get", "all", "the", "types", "that", "this", "resource", "matches", "." ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L71-L102
train
46,100
hydraplatform/hydra-base
hydra_base/lib/template.py
_get_attr_by_name_and_dimension
def _get_attr_by_name_and_dimension(name, dimension_id): """ Search for an attribute with the given name and dimension_id. If such an attribute does not exist, create one. """ attr = db.DBSession.query(Attr).filter(Attr.name==name, Attr.dimension_id==dimension_id).first() if attr is None: # In this case the attr does not exists so we must create it attr = Attr() attr.dimension_id = dimension_id attr.name = name log.debug("Attribute not found, creating new attribute: name:%s, dimen:%s", attr.name, attr.dimension_id) db.DBSession.add(attr) return attr
python
def _get_attr_by_name_and_dimension(name, dimension_id): """ Search for an attribute with the given name and dimension_id. If such an attribute does not exist, create one. """ attr = db.DBSession.query(Attr).filter(Attr.name==name, Attr.dimension_id==dimension_id).first() if attr is None: # In this case the attr does not exists so we must create it attr = Attr() attr.dimension_id = dimension_id attr.name = name log.debug("Attribute not found, creating new attribute: name:%s, dimen:%s", attr.name, attr.dimension_id) db.DBSession.add(attr) return attr
[ "def", "_get_attr_by_name_and_dimension", "(", "name", ",", "dimension_id", ")", ":", "attr", "=", "db", ".", "DBSession", ".", "query", "(", "Attr", ")", ".", "filter", "(", "Attr", ".", "name", "==", "name", ",", "Attr", ".", "dimension_id", "==", "dim...
Search for an attribute with the given name and dimension_id. If such an attribute does not exist, create one.
[ "Search", "for", "an", "attribute", "with", "the", "given", "name", "and", "dimension_id", ".", "If", "such", "an", "attribute", "does", "not", "exist", "create", "one", "." ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L104-L123
train
46,101
hydraplatform/hydra-base
hydra_base/lib/template.py
get_template_as_xml
def get_template_as_xml(template_id,**kwargs): """ Turn a template into an xml template """ template_xml = etree.Element("template_definition") template_i = db.DBSession.query(Template).filter( Template.id==template_id).options( #joinedload_all('templatetypes.typeattrs.default_dataset.metadata') joinedload('templatetypes').joinedload('typeattrs').joinedload('default_dataset').joinedload('metadata') ).one() template_name = etree.SubElement(template_xml, "template_name") template_name.text = template_i.name template_description = etree.SubElement(template_xml, "template_description") template_description.text = template_i.description resources = etree.SubElement(template_xml, "resources") for type_i in template_i.templatetypes: xml_resource = etree.SubElement(resources, "resource") resource_type = etree.SubElement(xml_resource, "type") resource_type.text = type_i.resource_type name = etree.SubElement(xml_resource, "name") name.text = type_i.name description = etree.SubElement(xml_resource, "description") description.text = type_i.description alias = etree.SubElement(xml_resource, "alias") alias.text = type_i.alias if type_i.layout is not None and type_i.layout != "": layout = _get_layout_as_etree(type_i.layout) xml_resource.append(layout) for type_attr in type_i.typeattrs: attr = _make_attr_element_from_typeattr(xml_resource, type_attr) resources.append(xml_resource) xml_string = etree.tostring(template_xml, encoding="unicode") return xml_string
python
def get_template_as_xml(template_id,**kwargs): """ Turn a template into an xml template """ template_xml = etree.Element("template_definition") template_i = db.DBSession.query(Template).filter( Template.id==template_id).options( #joinedload_all('templatetypes.typeattrs.default_dataset.metadata') joinedload('templatetypes').joinedload('typeattrs').joinedload('default_dataset').joinedload('metadata') ).one() template_name = etree.SubElement(template_xml, "template_name") template_name.text = template_i.name template_description = etree.SubElement(template_xml, "template_description") template_description.text = template_i.description resources = etree.SubElement(template_xml, "resources") for type_i in template_i.templatetypes: xml_resource = etree.SubElement(resources, "resource") resource_type = etree.SubElement(xml_resource, "type") resource_type.text = type_i.resource_type name = etree.SubElement(xml_resource, "name") name.text = type_i.name description = etree.SubElement(xml_resource, "description") description.text = type_i.description alias = etree.SubElement(xml_resource, "alias") alias.text = type_i.alias if type_i.layout is not None and type_i.layout != "": layout = _get_layout_as_etree(type_i.layout) xml_resource.append(layout) for type_attr in type_i.typeattrs: attr = _make_attr_element_from_typeattr(xml_resource, type_attr) resources.append(xml_resource) xml_string = etree.tostring(template_xml, encoding="unicode") return xml_string
[ "def", "get_template_as_xml", "(", "template_id", ",", "*", "*", "kwargs", ")", ":", "template_xml", "=", "etree", ".", "Element", "(", "\"template_definition\"", ")", "template_i", "=", "db", ".", "DBSession", ".", "query", "(", "Template", ")", ".", "filte...
Turn a template into an xml template
[ "Turn", "a", "template", "into", "an", "xml", "template" ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L412-L457
train
46,102
hydraplatform/hydra-base
hydra_base/lib/template.py
import_template_json
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 required. The allow_update indicates whether an existing template of the same name should be updated, or whether it should throw an 'existing name' error. """ user_id = kwargs.get('user_id') try: template_dict = json.loads(template_json_string) except: raise HydraError("Unable to parse JSON string. Plese ensure it is JSON compatible.") return import_template_dict(template_dict, allow_update=allow_update, user_id=user_id)
python
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 required. The allow_update indicates whether an existing template of the same name should be updated, or whether it should throw an 'existing name' error. """ user_id = kwargs.get('user_id') try: template_dict = json.loads(template_json_string) except: raise HydraError("Unable to parse JSON string. Plese ensure it is JSON compatible.") return import_template_dict(template_dict, allow_update=allow_update, user_id=user_id)
[ "def", "import_template_json", "(", "template_json_string", ",", "allow_update", "=", "True", ",", "*", "*", "kwargs", ")", ":", "user_id", "=", "kwargs", ".", "get", "(", "'user_id'", ")", "try", ":", "template_dict", "=", "json", ".", "loads", "(", "temp...
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 required. The allow_update indicates whether an existing template of the same name should be updated, or whether it should throw an 'existing name' error.
[ "Add", "the", "template", "type", "and", "typeattrs", "described", "in", "a", "JSON", "file", "." ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L459-L478
train
46,103
hydraplatform/hydra-base
hydra_base/lib/template.py
set_network_template
def set_network_template(template_id, network_id, **kwargs): """ Apply an existing template to a network. Used when a template has changed, and additional attributes must be added to the network's elements. """ 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(ResourceType.ref_key=='NETWORK', ResourceType.network_id==network_id, ResourceType.type_id==TemplateType.type_id, TemplateType.template_id==template_id).one() resource_types.append(network_type) except NoResultFound: log.debug("No network type to set.") pass node_types = db.DBSession.query(ResourceType).filter(ResourceType.ref_key=='NODE', ResourceType.node_id==Node.node_id, Node.network_id==network_id, ResourceType.type_id==TemplateType.type_id, TemplateType.template_id==template_id).all() link_types = db.DBSession.query(ResourceType).filter(ResourceType.ref_key=='LINK', ResourceType.link_id==Link.link_id, Link.network_id==network_id, ResourceType.type_id==TemplateType.type_id, TemplateType.template_id==template_id).all() group_types = db.DBSession.query(ResourceType).filter(ResourceType.ref_key=='GROUP', ResourceType.group_id==ResourceGroup.group_id, ResourceGroup.network_id==network_id, ResourceType.type_id==TemplateType.type_id, TemplateType.template_id==template_id).all() resource_types.extend(node_types) resource_types.extend(link_types) resource_types.extend(group_types) assign_types_to_resources(resource_types) log.debug("Finished setting network template")
python
def set_network_template(template_id, network_id, **kwargs): """ Apply an existing template to a network. Used when a template has changed, and additional attributes must be added to the network's elements. """ 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(ResourceType.ref_key=='NETWORK', ResourceType.network_id==network_id, ResourceType.type_id==TemplateType.type_id, TemplateType.template_id==template_id).one() resource_types.append(network_type) except NoResultFound: log.debug("No network type to set.") pass node_types = db.DBSession.query(ResourceType).filter(ResourceType.ref_key=='NODE', ResourceType.node_id==Node.node_id, Node.network_id==network_id, ResourceType.type_id==TemplateType.type_id, TemplateType.template_id==template_id).all() link_types = db.DBSession.query(ResourceType).filter(ResourceType.ref_key=='LINK', ResourceType.link_id==Link.link_id, Link.network_id==network_id, ResourceType.type_id==TemplateType.type_id, TemplateType.template_id==template_id).all() group_types = db.DBSession.query(ResourceType).filter(ResourceType.ref_key=='GROUP', ResourceType.group_id==ResourceGroup.group_id, ResourceGroup.network_id==network_id, ResourceType.type_id==TemplateType.type_id, TemplateType.template_id==template_id).all() resource_types.extend(node_types) resource_types.extend(link_types) resource_types.extend(group_types) assign_types_to_resources(resource_types) log.debug("Finished setting network template")
[ "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...
Apply an existing template to a network. Used when a template has changed, and additional attributes must be added to the network's elements.
[ "Apply", "an", "existing", "template", "to", "a", "network", ".", "Used", "when", "a", "template", "has", "changed", "and", "additional", "attributes", "must", "be", "added", "to", "the", "network", "s", "elements", "." ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L807-L850
train
46,104
hydraplatform/hydra-base
hydra_base/lib/template.py
remove_template_from_network
def remove_template_from_network(network_id, template_id, remove_attrs, **kwargs): """ Remove all resource types in a network relating to the specified template. remove_attrs Flag to indicate whether the attributes associated with the template types should be removed from the resources in the network. These will only be removed if they are not shared with another template on the network """ try: network = db.DBSession.query(Network).filter(Network.id==network_id).one() except NoResultFound: raise HydraError("Network %s not found"%network_id) try: template = db.DBSession.query(Template).filter(Template.id==template_id).one() except NoResultFound: raise HydraError("Template %s not found"%template_id) type_ids = [tmpltype.id for tmpltype in template.templatetypes] node_ids = [n.id for n in network.nodes] link_ids = [l.id for l in network.links] group_ids = [g.id for g in network.resourcegroups] if remove_attrs == 'Y': #find the attributes to remove resource_attrs_to_remove = _get_resources_to_remove(network, template) for n in network.nodes: resource_attrs_to_remove.extend(_get_resources_to_remove(n, template)) for l in network.links: resource_attrs_to_remove.extend(_get_resources_to_remove(l, template)) for g in network.resourcegroups: resource_attrs_to_remove.extend(_get_resources_to_remove(g, template)) for ra in resource_attrs_to_remove: db.DBSession.delete(ra) resource_types = db.DBSession.query(ResourceType).filter( and_(or_( ResourceType.network_id==network_id, ResourceType.node_id.in_(node_ids), ResourceType.link_id.in_(link_ids), ResourceType.group_id.in_(group_ids), ), ResourceType.type_id.in_(type_ids))).all() for resource_type in resource_types: db.DBSession.delete(resource_type) db.DBSession.flush()
python
def remove_template_from_network(network_id, template_id, remove_attrs, **kwargs): """ Remove all resource types in a network relating to the specified template. remove_attrs Flag to indicate whether the attributes associated with the template types should be removed from the resources in the network. These will only be removed if they are not shared with another template on the network """ try: network = db.DBSession.query(Network).filter(Network.id==network_id).one() except NoResultFound: raise HydraError("Network %s not found"%network_id) try: template = db.DBSession.query(Template).filter(Template.id==template_id).one() except NoResultFound: raise HydraError("Template %s not found"%template_id) type_ids = [tmpltype.id for tmpltype in template.templatetypes] node_ids = [n.id for n in network.nodes] link_ids = [l.id for l in network.links] group_ids = [g.id for g in network.resourcegroups] if remove_attrs == 'Y': #find the attributes to remove resource_attrs_to_remove = _get_resources_to_remove(network, template) for n in network.nodes: resource_attrs_to_remove.extend(_get_resources_to_remove(n, template)) for l in network.links: resource_attrs_to_remove.extend(_get_resources_to_remove(l, template)) for g in network.resourcegroups: resource_attrs_to_remove.extend(_get_resources_to_remove(g, template)) for ra in resource_attrs_to_remove: db.DBSession.delete(ra) resource_types = db.DBSession.query(ResourceType).filter( and_(or_( ResourceType.network_id==network_id, ResourceType.node_id.in_(node_ids), ResourceType.link_id.in_(link_ids), ResourceType.group_id.in_(group_ids), ), ResourceType.type_id.in_(type_ids))).all() for resource_type in resource_types: db.DBSession.delete(resource_type) db.DBSession.flush()
[ "def", "remove_template_from_network", "(", "network_id", ",", "template_id", ",", "remove_attrs", ",", "*", "*", "kwargs", ")", ":", "try", ":", "network", "=", "db", ".", "DBSession", ".", "query", "(", "Network", ")", ".", "filter", "(", "Network", ".",...
Remove all resource types in a network relating to the specified template. remove_attrs Flag to indicate whether the attributes associated with the template types should be removed from the resources in the network. These will only be removed if they are not shared with another template on the network
[ "Remove", "all", "resource", "types", "in", "a", "network", "relating", "to", "the", "specified", "template", ".", "remove_attrs", "Flag", "to", "indicate", "whether", "the", "attributes", "associated", "with", "the", "template", "types", "should", "be", "remove...
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L852-L902
train
46,105
hydraplatform/hydra-base
hydra_base/lib/template.py
_get_resources_to_remove
def _get_resources_to_remove(resource, template): """ Given a resource and a template being removed, identify the resource attribtes which can be removed. """ 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 nt in resource.types: if nt.templatetype.id in type_ids: for ta in nt.templatetype.typeattrs: if node_attr_ids.get(ta.attr_id): attrs_to_remove.append(node_attr_ids[ta.attr_id]) else: for ta in nt.templatetype.typeattrs: if node_attr_ids.get(ta.attr_id): attrs_to_keep.append(node_attr_ids[ta.attr_id]) #remove any of the attributes marked for deletion as they are #marked for keeping based on being in another type. final_attrs_to_remove = set(attrs_to_remove) - set(attrs_to_keep) return list(final_attrs_to_remove)
python
def _get_resources_to_remove(resource, template): """ Given a resource and a template being removed, identify the resource attribtes which can be removed. """ 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 nt in resource.types: if nt.templatetype.id in type_ids: for ta in nt.templatetype.typeattrs: if node_attr_ids.get(ta.attr_id): attrs_to_remove.append(node_attr_ids[ta.attr_id]) else: for ta in nt.templatetype.typeattrs: if node_attr_ids.get(ta.attr_id): attrs_to_keep.append(node_attr_ids[ta.attr_id]) #remove any of the attributes marked for deletion as they are #marked for keeping based on being in another type. final_attrs_to_remove = set(attrs_to_remove) - set(attrs_to_keep) return list(final_attrs_to_remove)
[ "def", "_get_resources_to_remove", "(", "resource", ",", "template", ")", ":", "type_ids", "=", "[", "tmpltype", ".", "id", "for", "tmpltype", "in", "template", ".", "templatetypes", "]", "node_attr_ids", "=", "dict", "(", "[", "(", "ra", ".", "attr_id", "...
Given a resource and a template being removed, identify the resource attribtes which can be removed.
[ "Given", "a", "resource", "and", "a", "template", "being", "removed", "identify", "the", "resource", "attribtes", "which", "can", "be", "removed", "." ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L904-L927
train
46,106
hydraplatform/hydra-base
hydra_base/lib/template.py
get_matching_resource_types
def get_matching_resource_types(resource_type, resource_id,**kwargs): """ Get the possible types of a resource by checking its attributes against all available types. @returns A list of TypeSummary objects. """ resource_i = None if resource_type == 'NETWORK': resource_i = db.DBSession.query(Network).filter(Network.id==resource_id).one() elif resource_type == 'NODE': resource_i = db.DBSession.query(Node).filter(Node.id==resource_id).one() elif resource_type == 'LINK': resource_i = db.DBSession.query(Link).filter(Link.id==resource_id).one() elif resource_type == 'GROUP': resource_i = db.DBSession.query(ResourceGroup).filter(ResourceGroup.id==resource_id).one() matching_types = get_types_by_attr(resource_i) return matching_types
python
def get_matching_resource_types(resource_type, resource_id,**kwargs): """ Get the possible types of a resource by checking its attributes against all available types. @returns A list of TypeSummary objects. """ resource_i = None if resource_type == 'NETWORK': resource_i = db.DBSession.query(Network).filter(Network.id==resource_id).one() elif resource_type == 'NODE': resource_i = db.DBSession.query(Node).filter(Node.id==resource_id).one() elif resource_type == 'LINK': resource_i = db.DBSession.query(Link).filter(Link.id==resource_id).one() elif resource_type == 'GROUP': resource_i = db.DBSession.query(ResourceGroup).filter(ResourceGroup.id==resource_id).one() matching_types = get_types_by_attr(resource_i) return matching_types
[ "def", "get_matching_resource_types", "(", "resource_type", ",", "resource_id", ",", "*", "*", "kwargs", ")", ":", "resource_i", "=", "None", "if", "resource_type", "==", "'NETWORK'", ":", "resource_i", "=", "db", ".", "DBSession", ".", "query", "(", "Network"...
Get the possible types of a resource by checking its attributes against all available types. @returns A list of TypeSummary objects.
[ "Get", "the", "possible", "types", "of", "a", "resource", "by", "checking", "its", "attributes", "against", "all", "available", "types", "." ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L929-L947
train
46,107
hydraplatform/hydra-base
hydra_base/lib/template.py
check_type_compatibility
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 template. This function checks for any situations where different types specify the same attributes, but with different units. """ errors = [] type_1 = db.DBSession.query(TemplateType).filter(TemplateType.id==type_1_id).options(joinedload_all('typeattrs')).one() type_2 = db.DBSession.query(TemplateType).filter(TemplateType.id==type_2_id).options(joinedload_all('typeattrs')).one() template_1_name = type_1.template.name template_2_name = type_2.template.name type_1_attrs=set([t.attr_id for t in type_1.typeattrs]) type_2_attrs=set([t.attr_id for t in type_2.typeattrs]) shared_attrs = type_1_attrs.intersection(type_2_attrs) if len(shared_attrs) == 0: return [] type_1_dict = {} for t in type_1.typeattrs: if t.attr_id in shared_attrs: type_1_dict[t.attr_id]=t for ta in type_2.typeattrs: type_2_unit_id = ta.unit_id type_1_unit_id = type_1_dict[ta.attr_id].unit_id fmt_dict = { 'template_1_name': template_1_name, 'template_2_name': template_2_name, 'attr_name': ta.attr.name, 'type_1_unit_id': type_1_unit_id, 'type_2_unit_id': type_2_unit_id, 'type_name' : type_1.name } if type_1_unit_id is None and type_2_unit_id is not None: errors.append("Type %(type_name)s in template %(template_1_name)s" " stores %(attr_name)s with no units, while template" "%(template_2_name)s stores it with unit %(type_2_unit_id)s"%fmt_dict) elif type_1_unit_id is not None and type_2_unit_id is None: errors.append("Type %(type_name)s in template %(template_1_name)s" " stores %(attr_name)s in %(type_1_unit_id)s." " Template %(template_2_name)s stores it with no unit."%fmt_dict) elif type_1_unit_id != type_2_unit_id: errors.append("Type %(type_name)s in template %(template_1_name)s" " stores %(attr_name)s in %(type_1_unit_id)s, while" " template %(template_2_name)s stores it in %(type_2_unit_id)s"%fmt_dict) return errors
python
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 template. This function checks for any situations where different types specify the same attributes, but with different units. """ errors = [] type_1 = db.DBSession.query(TemplateType).filter(TemplateType.id==type_1_id).options(joinedload_all('typeattrs')).one() type_2 = db.DBSession.query(TemplateType).filter(TemplateType.id==type_2_id).options(joinedload_all('typeattrs')).one() template_1_name = type_1.template.name template_2_name = type_2.template.name type_1_attrs=set([t.attr_id for t in type_1.typeattrs]) type_2_attrs=set([t.attr_id for t in type_2.typeattrs]) shared_attrs = type_1_attrs.intersection(type_2_attrs) if len(shared_attrs) == 0: return [] type_1_dict = {} for t in type_1.typeattrs: if t.attr_id in shared_attrs: type_1_dict[t.attr_id]=t for ta in type_2.typeattrs: type_2_unit_id = ta.unit_id type_1_unit_id = type_1_dict[ta.attr_id].unit_id fmt_dict = { 'template_1_name': template_1_name, 'template_2_name': template_2_name, 'attr_name': ta.attr.name, 'type_1_unit_id': type_1_unit_id, 'type_2_unit_id': type_2_unit_id, 'type_name' : type_1.name } if type_1_unit_id is None and type_2_unit_id is not None: errors.append("Type %(type_name)s in template %(template_1_name)s" " stores %(attr_name)s with no units, while template" "%(template_2_name)s stores it with unit %(type_2_unit_id)s"%fmt_dict) elif type_1_unit_id is not None and type_2_unit_id is None: errors.append("Type %(type_name)s in template %(template_1_name)s" " stores %(attr_name)s in %(type_1_unit_id)s." " Template %(template_2_name)s stores it with no unit."%fmt_dict) elif type_1_unit_id != type_2_unit_id: errors.append("Type %(type_name)s in template %(template_1_name)s" " stores %(attr_name)s in %(type_1_unit_id)s, while" " template %(template_2_name)s stores it in %(type_2_unit_id)s"%fmt_dict) return errors
[ "def", "check_type_compatibility", "(", "type_1_id", ",", "type_2_id", ")", ":", "errors", "=", "[", "]", "type_1", "=", "db", ".", "DBSession", ".", "query", "(", "TemplateType", ")", ".", "filter", "(", "TemplateType", ".", "id", "==", "type_1_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 template. This function checks for any situations where different types specify the same attributes, but with different units.
[ "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", ...
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L1036-L1090
train
46,108
hydraplatform/hydra-base
hydra_base/lib/template.py
assign_type_to_resource
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 also be used to update resources, when a resource type has changed. """ if resource_type == 'NETWORK': resource = db.DBSession.query(Network).filter(Network.id==resource_id).one() elif resource_type == 'NODE': resource = db.DBSession.query(Node).filter(Node.id==resource_id).one() elif resource_type == 'LINK': resource = db.DBSession.query(Link).filter(Link.id==resource_id).one() elif resource_type == 'GROUP': resource = db.DBSession.query(ResourceGroup).filter(ResourceGroup.id==resource_id).one() res_attrs, res_type, res_scenarios = set_resource_type(resource, type_id, **kwargs) type_i = db.DBSession.query(TemplateType).filter(TemplateType.id==type_id).one() if resource_type != type_i.resource_type: raise HydraError("Cannot assign a %s type to a %s"% (type_i.resource_type,resource_type)) if res_type is not None: db.DBSession.bulk_insert_mappings(ResourceType, [res_type]) if len(res_attrs) > 0: db.DBSession.bulk_insert_mappings(ResourceAttr, res_attrs) if len(res_scenarios) > 0: db.DBSession.bulk_insert_mappings(ResourceScenario, res_scenarios) #Make DBsession 'dirty' to pick up the inserts by doing a fake delete. db.DBSession.query(Attr).filter(Attr.id==None).delete() db.DBSession.flush() return db.DBSession.query(TemplateType).filter(TemplateType.id==type_id).one()
python
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 also be used to update resources, when a resource type has changed. """ if resource_type == 'NETWORK': resource = db.DBSession.query(Network).filter(Network.id==resource_id).one() elif resource_type == 'NODE': resource = db.DBSession.query(Node).filter(Node.id==resource_id).one() elif resource_type == 'LINK': resource = db.DBSession.query(Link).filter(Link.id==resource_id).one() elif resource_type == 'GROUP': resource = db.DBSession.query(ResourceGroup).filter(ResourceGroup.id==resource_id).one() res_attrs, res_type, res_scenarios = set_resource_type(resource, type_id, **kwargs) type_i = db.DBSession.query(TemplateType).filter(TemplateType.id==type_id).one() if resource_type != type_i.resource_type: raise HydraError("Cannot assign a %s type to a %s"% (type_i.resource_type,resource_type)) if res_type is not None: db.DBSession.bulk_insert_mappings(ResourceType, [res_type]) if len(res_attrs) > 0: db.DBSession.bulk_insert_mappings(ResourceAttr, res_attrs) if len(res_scenarios) > 0: db.DBSession.bulk_insert_mappings(ResourceScenario, res_scenarios) #Make DBsession 'dirty' to pick up the inserts by doing a fake delete. db.DBSession.query(Attr).filter(Attr.id==None).delete() db.DBSession.flush() return db.DBSession.query(TemplateType).filter(TemplateType.id==type_id).one()
[ "def", "assign_type_to_resource", "(", "type_id", ",", "resource_type", ",", "resource_id", ",", "*", "*", "kwargs", ")", ":", "if", "resource_type", "==", "'NETWORK'", ":", "resource", "=", "db", ".", "DBSession", ".", "query", "(", "Network", ")", ".", "...
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 also be used to update resources, when a resource type has changed.
[ "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", ...
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L1190-L1228
train
46,109
hydraplatform/hydra-base
hydra_base/lib/template.py
remove_type_from_resource
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' else None resourcetype = db.DBSession.query(ResourceType).filter( ResourceType.type_id==type_id, ResourceType.ref_key==resource_type, ResourceType.node_id == node_id, ResourceType.link_id == link_id, ResourceType.group_id == group_id).one() db.DBSession.delete(resourcetype) db.DBSession.flush() return 'OK'
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' else None resourcetype = db.DBSession.query(ResourceType).filter( ResourceType.type_id==type_id, ResourceType.ref_key==resource_type, ResourceType.node_id == node_id, ResourceType.link_id == link_id, ResourceType.group_id == group_id).one() db.DBSession.delete(resourcetype) db.DBSession.flush() return 'OK'
[ "def", "remove_type_from_resource", "(", "type_id", ",", "resource_type", ",", "resource_id", ",", "*", "*", "kwargs", ")", ":", "node_id", "=", "resource_id", "if", "resource_type", "==", "'NODE'", "else", "None", "link_id", "=", "resource_id", "if", "resource_...
Remove a resource type trom a resource
[ "Remove", "a", "resource", "type", "trom", "a", "resource" ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L1329-L1347
train
46,110
hydraplatform/hydra-base
hydra_base/lib/template.py
add_template
def add_template(template, **kwargs): """ Add template and a type and typeattrs. """ tmpl = Template() tmpl.name = template.name if template.description: tmpl.description = template.description if template.layout: tmpl.layout = get_layout_as_string(template.layout) db.DBSession.add(tmpl) if template.templatetypes is not None: types = template.templatetypes for templatetype in types: ttype = _update_templatetype(templatetype) tmpl.templatetypes.append(ttype) db.DBSession.flush() return tmpl
python
def add_template(template, **kwargs): """ Add template and a type and typeattrs. """ tmpl = Template() tmpl.name = template.name if template.description: tmpl.description = template.description if template.layout: tmpl.layout = get_layout_as_string(template.layout) db.DBSession.add(tmpl) if template.templatetypes is not None: types = template.templatetypes for templatetype in types: ttype = _update_templatetype(templatetype) tmpl.templatetypes.append(ttype) db.DBSession.flush() return tmpl
[ "def", "add_template", "(", "template", ",", "*", "*", "kwargs", ")", ":", "tmpl", "=", "Template", "(", ")", "tmpl", ".", "name", "=", "template", ".", "name", "if", "template", ".", "description", ":", "tmpl", ".", "description", "=", "template", "."...
Add template and a type and typeattrs.
[ "Add", "template", "and", "a", "type", "and", "typeattrs", "." ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L1376-L1396
train
46,111
hydraplatform/hydra-base
hydra_base/lib/template.py
update_template
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 the template for tt in tmpl.templatetypes: for ta in tt.typeattrs: ta.attr if template.layout: tmpl.layout = get_layout_as_string(template.layout) type_dict = dict([(t.id, t) for t in tmpl.templatetypes]) existing_templatetypes = [] if template.types is not None or template.templatetypes is not None: types = template.types if template.types is not None else template.templatetypes for templatetype in types: if templatetype.id is not None: type_i = type_dict[templatetype.id] _update_templatetype(templatetype, type_i) existing_templatetypes.append(type_i.id) else: #Give it a template ID if it doesn't have one templatetype.template_id = template.id new_templatetype_i = _update_templatetype(templatetype) existing_templatetypes.append(new_templatetype_i.id) for tt in tmpl.templatetypes: if tt.id not in existing_templatetypes: delete_templatetype(tt.id) db.DBSession.flush() return tmpl
python
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 the template for tt in tmpl.templatetypes: for ta in tt.typeattrs: ta.attr if template.layout: tmpl.layout = get_layout_as_string(template.layout) type_dict = dict([(t.id, t) for t in tmpl.templatetypes]) existing_templatetypes = [] if template.types is not None or template.templatetypes is not None: types = template.types if template.types is not None else template.templatetypes for templatetype in types: if templatetype.id is not None: type_i = type_dict[templatetype.id] _update_templatetype(templatetype, type_i) existing_templatetypes.append(type_i.id) else: #Give it a template ID if it doesn't have one templatetype.template_id = template.id new_templatetype_i = _update_templatetype(templatetype) existing_templatetypes.append(new_templatetype_i.id) for tt in tmpl.templatetypes: if tt.id not in existing_templatetypes: delete_templatetype(tt.id) db.DBSession.flush() return tmpl
[ "def", "update_template", "(", "template", ",", "*", "*", "kwargs", ")", ":", "tmpl", "=", "db", ".", "DBSession", ".", "query", "(", "Template", ")", ".", "filter", "(", "Template", ".", "id", "==", "template", ".", "id", ")", ".", "one", "(", ")"...
Update template and a type and typeattrs.
[ "Update", "template", "and", "a", "type", "and", "typeattrs", "." ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L1398-L1437
train
46,112
hydraplatform/hydra-base
hydra_base/lib/template.py
delete_template
def delete_template(template_id,**kwargs): """ Delete a template and its type and typeattrs. """ try: tmpl = db.DBSession.query(Template).filter(Template.id==template_id).one() except NoResultFound: raise ResourceNotFoundError("Template %s not found"%(template_id,)) db.DBSession.delete(tmpl) db.DBSession.flush() return 'OK'
python
def delete_template(template_id,**kwargs): """ Delete a template and its type and typeattrs. """ try: tmpl = db.DBSession.query(Template).filter(Template.id==template_id).one() except NoResultFound: raise ResourceNotFoundError("Template %s not found"%(template_id,)) db.DBSession.delete(tmpl) db.DBSession.flush() return 'OK'
[ "def", "delete_template", "(", "template_id", ",", "*", "*", "kwargs", ")", ":", "try", ":", "tmpl", "=", "db", ".", "DBSession", ".", "query", "(", "Template", ")", ".", "filter", "(", "Template", ".", "id", "==", "template_id", ")", ".", "one", "("...
Delete a template and its type and typeattrs.
[ "Delete", "a", "template", "and", "its", "type", "and", "typeattrs", "." ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L1439-L1449
train
46,113
hydraplatform/hydra-base
hydra_base/lib/template.py
get_template
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. for tmpltype_i in tmpl_i.templatetypes: for typeattr_i in tmpltype_i.typeattrs: typeattr_i.attr return tmpl_i except NoResultFound: raise HydraError("Template %s not found"%template_id)
python
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. for tmpltype_i in tmpl_i.templatetypes: for typeattr_i in tmpltype_i.typeattrs: typeattr_i.attr return tmpl_i except NoResultFound: raise HydraError("Template %s not found"%template_id)
[ "def", "get_template", "(", "template_id", ",", "*", "*", "kwargs", ")", ":", "try", ":", "tmpl_i", "=", "db", ".", "DBSession", ".", "query", "(", "Template", ")", ".", "filter", "(", "Template", ".", "id", "==", "template_id", ")", ".", "options", ...
Get a specific resource template template, by ID.
[ "Get", "a", "specific", "resource", "template", "template", "by", "ID", "." ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L1475-L1489
train
46,114
hydraplatform/hydra-base
hydra_base/lib/template.py
get_template_by_name
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 NoResultFound: log.info("%s is not a valid identifier for a template",name) raise HydraError('Template "%s" not found'%name)
python
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 NoResultFound: log.info("%s is not a valid identifier for a template",name) raise HydraError('Template "%s" not found'%name)
[ "def", "get_template_by_name", "(", "name", ",", "*", "*", "kwargs", ")", ":", "try", ":", "tmpl_i", "=", "db", ".", "DBSession", ".", "query", "(", "Template", ")", ".", "filter", "(", "Template", ".", "name", "==", "name", ")", ".", "options", "(",...
Get a specific resource template, by name.
[ "Get", "a", "specific", "resource", "template", "by", "name", "." ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L1491-L1500
train
46,115
hydraplatform/hydra-base
hydra_base/lib/template.py
add_templatetype
def add_templatetype(templatetype,**kwargs): """ Add a template type with typeattrs. """ type_i = _update_templatetype(templatetype) db.DBSession.flush() return type_i
python
def add_templatetype(templatetype,**kwargs): """ Add a template type with typeattrs. """ type_i = _update_templatetype(templatetype) db.DBSession.flush() return type_i
[ "def", "add_templatetype", "(", "templatetype", ",", "*", "*", "kwargs", ")", ":", "type_i", "=", "_update_templatetype", "(", "templatetype", ")", "db", ".", "DBSession", ".", "flush", "(", ")", "return", "type_i" ]
Add a template type with typeattrs.
[ "Add", "a", "template", "type", "with", "typeattrs", "." ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L1502-L1511
train
46,116
hydraplatform/hydra-base
hydra_base/lib/template.py
update_templatetype
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 == templatetype.id).one() _update_templatetype(templatetype, tmpltype_i) db.DBSession.flush() return tmpltype_i
python
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 == templatetype.id).one() _update_templatetype(templatetype, tmpltype_i) db.DBSession.flush() return tmpltype_i
[ "def", "update_templatetype", "(", "templatetype", ",", "*", "*", "kwargs", ")", ":", "tmpltype_i", "=", "db", ".", "DBSession", ".", "query", "(", "TemplateType", ")", ".", "filter", "(", "TemplateType", ".", "id", "==", "templatetype", ".", "id", ")", ...
Update a resource type and its typeattrs. New typeattrs will be added. typeattrs not sent will be ignored. To delete typeattrs, call delete_typeattr
[ "Update", "a", "resource", "type", "and", "its", "typeattrs", ".", "New", "typeattrs", "will", "be", "added", ".", "typeattrs", "not", "sent", "will", "be", "ignored", ".", "To", "delete", "typeattrs", "call", "delete_typeattr" ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L1513-L1526
train
46,117
hydraplatform/hydra-base
hydra_base/lib/template.py
_set_typeattr
def _set_typeattr(typeattr, existing_ta = None): """ Add or updsate a type attribute. If an existing type attribute is provided, then update. Checks are performed to ensure that the dimension provided on the type attr (not updateable) is the same as that on the referring attribute. The unit provided (stored on tattr) must conform to the dimension stored on the referring attribute (stored on tattr). This is done so that multiple tempaltes can all use the same attribute, but specify different units. If no attr_id is provided, but an attr_name and dimension are provided, then a new attribute can be created (or retrived) and used. I.e., no attribute ID must be specified if attr_name and dimension are specified. ***WARNING*** Setting attribute ID to null means a new type attribute (and even a new attr) may be added, None are removed or replaced. To remove other type attrs, do it manually using delete_typeattr """ 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_type if hasattr(typeattr, 'default_dataset_id') and typeattr.default_dataset_id is not None: ta.default_dataset_id = typeattr.default_dataset_id ta.description = typeattr.description ta.properties = typeattr.get_properties() ta.attr_is_var = typeattr.is_var if typeattr.is_var is not None else 'N' ta.data_restriction = _parse_data_restriction(typeattr.data_restriction) if typeattr.dimension_id is None: # All right. Check passed pass else: if typeattr.attr_id is not None and typeattr.attr_id > 0: # Getting the passed attribute, so we need to check consistency between attr dimension id and typeattr dimension id attr = ta.attr if attr is not None and attr.dimension_id is not None and attr.dimension_id != typeattr.dimension_id or \ attr is not None and attr.dimension_id is not None: # In this case there is an inconsistency between attr.dimension_id and typeattr.dimension_id raise HydraError("Cannot set a dimension on type attribute which " "does not match its attribute. Create a new attribute if " "you want to use attribute %s with dimension_id %s"% (attr.name, typeattr.dimension_id)) elif typeattr.attr_id is None and typeattr.name is not None: # Getting/creating the attribute by typeattr dimension id and typeattr name # In this case the dimension_id "null"/"not null" status is ininfluent attr = _get_attr_by_name_and_dimension(typeattr.name, typeattr.dimension_id) ta.attr_id = attr.id ta.attr = attr _check_dimension(ta) if existing_ta is None: log.debug("Adding ta to DB") db.DBSession.add(ta) return ta
python
def _set_typeattr(typeattr, existing_ta = None): """ Add or updsate a type attribute. If an existing type attribute is provided, then update. Checks are performed to ensure that the dimension provided on the type attr (not updateable) is the same as that on the referring attribute. The unit provided (stored on tattr) must conform to the dimension stored on the referring attribute (stored on tattr). This is done so that multiple tempaltes can all use the same attribute, but specify different units. If no attr_id is provided, but an attr_name and dimension are provided, then a new attribute can be created (or retrived) and used. I.e., no attribute ID must be specified if attr_name and dimension are specified. ***WARNING*** Setting attribute ID to null means a new type attribute (and even a new attr) may be added, None are removed or replaced. To remove other type attrs, do it manually using delete_typeattr """ 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_type if hasattr(typeattr, 'default_dataset_id') and typeattr.default_dataset_id is not None: ta.default_dataset_id = typeattr.default_dataset_id ta.description = typeattr.description ta.properties = typeattr.get_properties() ta.attr_is_var = typeattr.is_var if typeattr.is_var is not None else 'N' ta.data_restriction = _parse_data_restriction(typeattr.data_restriction) if typeattr.dimension_id is None: # All right. Check passed pass else: if typeattr.attr_id is not None and typeattr.attr_id > 0: # Getting the passed attribute, so we need to check consistency between attr dimension id and typeattr dimension id attr = ta.attr if attr is not None and attr.dimension_id is not None and attr.dimension_id != typeattr.dimension_id or \ attr is not None and attr.dimension_id is not None: # In this case there is an inconsistency between attr.dimension_id and typeattr.dimension_id raise HydraError("Cannot set a dimension on type attribute which " "does not match its attribute. Create a new attribute if " "you want to use attribute %s with dimension_id %s"% (attr.name, typeattr.dimension_id)) elif typeattr.attr_id is None and typeattr.name is not None: # Getting/creating the attribute by typeattr dimension id and typeattr name # In this case the dimension_id "null"/"not null" status is ininfluent attr = _get_attr_by_name_and_dimension(typeattr.name, typeattr.dimension_id) ta.attr_id = attr.id ta.attr = attr _check_dimension(ta) if existing_ta is None: log.debug("Adding ta to DB") db.DBSession.add(ta) return ta
[ "def", "_set_typeattr", "(", "typeattr", ",", "existing_ta", "=", "None", ")", ":", "if", "existing_ta", "is", "None", ":", "ta", "=", "TypeAttr", "(", "attr_id", "=", "typeattr", ".", "attr_id", ")", "else", ":", "ta", "=", "existing_ta", "ta", ".", "...
Add or updsate a type attribute. If an existing type attribute is provided, then update. Checks are performed to ensure that the dimension provided on the type attr (not updateable) is the same as that on the referring attribute. The unit provided (stored on tattr) must conform to the dimension stored on the referring attribute (stored on tattr). This is done so that multiple tempaltes can all use the same attribute, but specify different units. If no attr_id is provided, but an attr_name and dimension are provided, then a new attribute can be created (or retrived) and used. I.e., no attribute ID must be specified if attr_name and dimension are specified. ***WARNING*** Setting attribute ID to null means a new type attribute (and even a new attr) may be added, None are removed or replaced. To remove other type attrs, do it manually using delete_typeattr
[ "Add", "or", "updsate", "a", "type", "attribute", ".", "If", "an", "existing", "type", "attribute", "is", "provided", "then", "update", "." ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L1528-L1601
train
46,118
hydraplatform/hydra-base
hydra_base/lib/template.py
_update_templatetype
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 not None: tmpltype_i = db.DBSession.query(TemplateType).filter(TemplateType.id == templatetype.id).one() else: tmpltype_i = TemplateType() else: tmpltype_i = existing_tt tmpltype_i.template_id = templatetype.template_id tmpltype_i.name = templatetype.name tmpltype_i.description = templatetype.description tmpltype_i.alias = templatetype.alias if templatetype.layout is not None: tmpltype_i.layout = get_layout_as_string(templatetype.layout) tmpltype_i.resource_type = templatetype.resource_type ta_dict = {} for t in tmpltype_i.typeattrs: ta_dict[t.attr_id] = t existing_attrs = [] if templatetype.typeattrs is not None: for typeattr in templatetype.typeattrs: if typeattr.attr_id in ta_dict: ta = _set_typeattr(typeattr, ta_dict[typeattr.attr_id]) existing_attrs.append(ta.attr_id) else: ta = _set_typeattr(typeattr) tmpltype_i.typeattrs.append(ta) existing_attrs.append(ta.attr_id) log.debug("Deleting any type attrs not sent") for ta in ta_dict.values(): if ta.attr_id not in existing_attrs: delete_typeattr(ta) if existing_tt is None: db.DBSession.add(tmpltype_i) return tmpltype_i
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 not None: tmpltype_i = db.DBSession.query(TemplateType).filter(TemplateType.id == templatetype.id).one() else: tmpltype_i = TemplateType() else: tmpltype_i = existing_tt tmpltype_i.template_id = templatetype.template_id tmpltype_i.name = templatetype.name tmpltype_i.description = templatetype.description tmpltype_i.alias = templatetype.alias if templatetype.layout is not None: tmpltype_i.layout = get_layout_as_string(templatetype.layout) tmpltype_i.resource_type = templatetype.resource_type ta_dict = {} for t in tmpltype_i.typeattrs: ta_dict[t.attr_id] = t existing_attrs = [] if templatetype.typeattrs is not None: for typeattr in templatetype.typeattrs: if typeattr.attr_id in ta_dict: ta = _set_typeattr(typeattr, ta_dict[typeattr.attr_id]) existing_attrs.append(ta.attr_id) else: ta = _set_typeattr(typeattr) tmpltype_i.typeattrs.append(ta) existing_attrs.append(ta.attr_id) log.debug("Deleting any type attrs not sent") for ta in ta_dict.values(): if ta.attr_id not in existing_attrs: delete_typeattr(ta) if existing_tt is None: db.DBSession.add(tmpltype_i) return tmpltype_i
[ "def", "_update_templatetype", "(", "templatetype", ",", "existing_tt", "=", "None", ")", ":", "if", "existing_tt", "is", "None", ":", "if", "\"id\"", "in", "templatetype", "and", "templatetype", ".", "id", "is", "not", "None", ":", "tmpltype_i", "=", "db", ...
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.
[ "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", "." ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L1603-L1650
train
46,119
hydraplatform/hydra-base
hydra_base/lib/template.py
delete_templatetype
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"%(type_id,)) if template_i is None: template_i = db.DBSession.query(Template).filter(Template.id==tmpltype_i.template_id).one() template_i.templatetypes.remove(tmpltype_i) db.DBSession.delete(tmpltype_i) db.DBSession.flush()
python
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"%(type_id,)) if template_i is None: template_i = db.DBSession.query(Template).filter(Template.id==tmpltype_i.template_id).one() template_i.templatetypes.remove(tmpltype_i) db.DBSession.delete(tmpltype_i) db.DBSession.flush()
[ "def", "delete_templatetype", "(", "type_id", ",", "template_i", "=", "None", ",", "*", "*", "kwargs", ")", ":", "try", ":", "tmpltype_i", "=", "db", ".", "DBSession", ".", "query", "(", "TemplateType", ")", ".", "filter", "(", "TemplateType", ".", "id",...
Delete a template type and its typeattrs.
[ "Delete", "a", "template", "type", "and", "its", "typeattrs", "." ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L1652-L1667
train
46,120
hydraplatform/hydra-base
hydra_base/lib/template.py
get_templatetype
def get_templatetype(type_id,**kwargs): """ Get a specific resource type by ID. """ templatetype = db.DBSession.query(TemplateType).filter( TemplateType.id==type_id).options( joinedload_all("typeattrs")).one() return templatetype
python
def get_templatetype(type_id,**kwargs): """ Get a specific resource type by ID. """ templatetype = db.DBSession.query(TemplateType).filter( TemplateType.id==type_id).options( joinedload_all("typeattrs")).one() return templatetype
[ "def", "get_templatetype", "(", "type_id", ",", "*", "*", "kwargs", ")", ":", "templatetype", "=", "db", ".", "DBSession", ".", "query", "(", "TemplateType", ")", ".", "filter", "(", "TemplateType", ".", "id", "==", "type_id", ")", ".", "options", "(", ...
Get a specific resource type by ID.
[ "Get", "a", "specific", "resource", "type", "by", "ID", "." ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L1669-L1678
train
46,121
hydraplatform/hydra-base
hydra_base/lib/template.py
get_templatetype_by_name
def get_templatetype_by_name(template_id, type_name,**kwargs): """ Get a specific resource type by name. """ 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 identifier for a type"%(type_name)) return templatetype
python
def get_templatetype_by_name(template_id, type_name,**kwargs): """ Get a specific resource type by name. """ 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 identifier for a type"%(type_name)) return templatetype
[ "def", "get_templatetype_by_name", "(", "template_id", ",", "type_name", ",", "*", "*", "kwargs", ")", ":", "try", ":", "templatetype", "=", "db", ".", "DBSession", ".", "query", "(", "TemplateType", ")", ".", "filter", "(", "TemplateType", ".", "id", "=="...
Get a specific resource type by name.
[ "Get", "a", "specific", "resource", "type", "by", "name", "." ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L1680-L1690
train
46,122
hydraplatform/hydra-base
hydra_base/lib/template.py
add_typeattr
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
python
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
[ "def", "add_typeattr", "(", "typeattr", ",", "*", "*", "kwargs", ")", ":", "tmpltype", "=", "get_templatetype", "(", "typeattr", ".", "type_id", ",", "user_id", "=", "kwargs", ".", "get", "(", "'user_id'", ")", ")", "ta", "=", "_set_typeattr", "(", "type...
Add an typeattr to an existing type.
[ "Add", "an", "typeattr", "to", "an", "existing", "type", "." ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L1692-L1705
train
46,123
hydraplatform/hydra-base
hydra_base/lib/template.py
delete_typeattr
def delete_typeattr(typeattr,**kwargs): """ Remove an typeattr from an existing type """ 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_id == typeattr.attr_id).one() tmpltype.typeattrs.remove(ta) db.DBSession.flush() return 'OK'
python
def delete_typeattr(typeattr,**kwargs): """ Remove an typeattr from an existing type """ 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_id == typeattr.attr_id).one() tmpltype.typeattrs.remove(ta) db.DBSession.flush() return 'OK'
[ "def", "delete_typeattr", "(", "typeattr", ",", "*", "*", "kwargs", ")", ":", "tmpltype", "=", "get_templatetype", "(", "typeattr", ".", "type_id", ",", "user_id", "=", "kwargs", ".", "get", "(", "'user_id'", ")", ")", "ta", "=", "db", ".", "DBSession", ...
Remove an typeattr from an existing type
[ "Remove", "an", "typeattr", "from", "an", "existing", "type" ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L1708-L1722
train
46,124
hydraplatform/hydra-base
hydra_base/lib/template.py
validate_attr
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_id, ResourceScenario.scenario_id==scenario_id).options( joinedload_all("resourceattr")).options( joinedload_all("dataset") ).one() error = None try: _do_validate_resourcescenario(rs, template_id) except HydraError as e: error = JSONObject(dict( ref_key = rs.resourceattr.ref_key, ref_id = rs.resourceattr.get_resource_id(), ref_name = rs.resourceattr.get_resource().get_name(), resource_attr_id = rs.resource_attr_id, attr_id = rs.resourceattr.attr.id, attr_name = rs.resourceattr.attr.name, dataset_id = rs.dataset_id, scenario_id=scenario_id, template_id=template_id, error_text=e.args[0])) return error
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_id, ResourceScenario.scenario_id==scenario_id).options( joinedload_all("resourceattr")).options( joinedload_all("dataset") ).one() error = None try: _do_validate_resourcescenario(rs, template_id) except HydraError as e: error = JSONObject(dict( ref_key = rs.resourceattr.ref_key, ref_id = rs.resourceattr.get_resource_id(), ref_name = rs.resourceattr.get_resource().get_name(), resource_attr_id = rs.resource_attr_id, attr_id = rs.resourceattr.attr.id, attr_name = rs.resourceattr.attr.name, dataset_id = rs.dataset_id, scenario_id=scenario_id, template_id=template_id, error_text=e.args[0])) return error
[ "def", "validate_attr", "(", "resource_attr_id", ",", "scenario_id", ",", "template_id", "=", "None", ")", ":", "rs", "=", "db", ".", "DBSession", ".", "query", "(", "ResourceScenario", ")", ".", "filter", "(", "ResourceScenario", ".", "resource_attr_id", "=="...
Check that a resource attribute satisfies the requirements of all the types of the resource.
[ "Check", "that", "a", "resource", "attribute", "satisfies", "the", "requirements", "of", "all", "the", "types", "of", "the", "resource", "." ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L1724-L1753
train
46,125
hydraplatform/hydra-base
hydra_base/lib/template.py
validate_attrs
def validate_attrs(resource_attr_ids, scenario_id, template_id=None): """ Check that multiple resource attribute satisfy the requirements of the types of resources to which the they are attached. """ multi_rs = db.DBSession.query(ResourceScenario).\ filter(ResourceScenario.resource_attr_id.in_(resource_attr_ids),\ ResourceScenario.scenario_id==scenario_id).\ options(joinedload_all("resourceattr")).\ options(joinedload_all("dataset")).all() errors = [] for rs in multi_rs: try: _do_validate_resourcescenario(rs, template_id) except HydraError as e: error = dict( ref_key = rs.resourceattr.ref_key, ref_id = rs.resourceattr.get_resource_id(), ref_name = rs.resourceattr.get_resource().get_name(), resource_attr_id = rs.resource_attr_id, attr_id = rs.resourceattr.attr.id, attr_name = rs.resourceattr.attr.name, dataset_id = rs.dataset_id, scenario_id = scenario_id, template_id = template_id, error_text = e.args[0]) errors.append(error) return errors
python
def validate_attrs(resource_attr_ids, scenario_id, template_id=None): """ Check that multiple resource attribute satisfy the requirements of the types of resources to which the they are attached. """ multi_rs = db.DBSession.query(ResourceScenario).\ filter(ResourceScenario.resource_attr_id.in_(resource_attr_ids),\ ResourceScenario.scenario_id==scenario_id).\ options(joinedload_all("resourceattr")).\ options(joinedload_all("dataset")).all() errors = [] for rs in multi_rs: try: _do_validate_resourcescenario(rs, template_id) except HydraError as e: error = dict( ref_key = rs.resourceattr.ref_key, ref_id = rs.resourceattr.get_resource_id(), ref_name = rs.resourceattr.get_resource().get_name(), resource_attr_id = rs.resource_attr_id, attr_id = rs.resourceattr.attr.id, attr_name = rs.resourceattr.attr.name, dataset_id = rs.dataset_id, scenario_id = scenario_id, template_id = template_id, error_text = e.args[0]) errors.append(error) return errors
[ "def", "validate_attrs", "(", "resource_attr_ids", ",", "scenario_id", ",", "template_id", "=", "None", ")", ":", "multi_rs", "=", "db", ".", "DBSession", ".", "query", "(", "ResourceScenario", ")", ".", "filter", "(", "ResourceScenario", ".", "resource_attr_id"...
Check that multiple resource attribute satisfy the requirements of the types of resources to which the they are attached.
[ "Check", "that", "multiple", "resource", "attribute", "satisfy", "the", "requirements", "of", "the", "types", "of", "resources", "to", "which", "the", "they", "are", "attached", "." ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L1755-L1786
train
46,126
hydraplatform/hydra-base
hydra_base/lib/template.py
validate_network
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. This validation will not fail if a resource has more than the required type, but will fail if it has fewer or if any attribute has a conflicting dimension or unit. """ network = db.DBSession.query(Network).filter(Network.id==network_id).options(noload('scenarios')).first() if network is None: raise HydraError("Could not find network %s"%(network_id)) resource_scenario_dict = {} if scenario_id is not None: scenario = db.DBSession.query(Scenario).filter(Scenario.id==scenario_id).first() if scenario is None: raise HydraError("Could not find scenario %s"%(scenario_id,)) for rs in scenario.resourcescenarios: resource_scenario_dict[rs.resource_attr_id] = rs template = db.DBSession.query(Template).filter(Template.id == template_id).options(joinedload_all('templatetypes')).first() if template is None: raise HydraError("Could not find template %s"%(template_id,)) resource_type_defs = { 'NETWORK' : {}, 'NODE' : {}, 'LINK' : {}, 'GROUP' : {}, } for tt in template.templatetypes: resource_type_defs[tt.resource_type][tt.id] = tt errors = [] #Only check if there are type definitions for a network in the template. if resource_type_defs.get('NETWORK'): net_types = resource_type_defs['NETWORK'] errors.extend(_validate_resource(network, net_types, resource_scenario_dict)) #check all nodes if resource_type_defs.get('NODE'): node_types = resource_type_defs['NODE'] for node in network.nodes: errors.extend(_validate_resource(node, node_types, resource_scenario_dict)) #check all links if resource_type_defs.get('LINK'): link_types = resource_type_defs['LINK'] for link in network.links: errors.extend(_validate_resource(link, link_types, resource_scenario_dict)) #check all groups if resource_type_defs.get('GROUP'): group_types = resource_type_defs['GROUP'] for group in network.resourcegroups: errors.extend(_validate_resource(group, group_types, resource_scenario_dict)) return errors
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. This validation will not fail if a resource has more than the required type, but will fail if it has fewer or if any attribute has a conflicting dimension or unit. """ network = db.DBSession.query(Network).filter(Network.id==network_id).options(noload('scenarios')).first() if network is None: raise HydraError("Could not find network %s"%(network_id)) resource_scenario_dict = {} if scenario_id is not None: scenario = db.DBSession.query(Scenario).filter(Scenario.id==scenario_id).first() if scenario is None: raise HydraError("Could not find scenario %s"%(scenario_id,)) for rs in scenario.resourcescenarios: resource_scenario_dict[rs.resource_attr_id] = rs template = db.DBSession.query(Template).filter(Template.id == template_id).options(joinedload_all('templatetypes')).first() if template is None: raise HydraError("Could not find template %s"%(template_id,)) resource_type_defs = { 'NETWORK' : {}, 'NODE' : {}, 'LINK' : {}, 'GROUP' : {}, } for tt in template.templatetypes: resource_type_defs[tt.resource_type][tt.id] = tt errors = [] #Only check if there are type definitions for a network in the template. if resource_type_defs.get('NETWORK'): net_types = resource_type_defs['NETWORK'] errors.extend(_validate_resource(network, net_types, resource_scenario_dict)) #check all nodes if resource_type_defs.get('NODE'): node_types = resource_type_defs['NODE'] for node in network.nodes: errors.extend(_validate_resource(node, node_types, resource_scenario_dict)) #check all links if resource_type_defs.get('LINK'): link_types = resource_type_defs['LINK'] for link in network.links: errors.extend(_validate_resource(link, link_types, resource_scenario_dict)) #check all groups if resource_type_defs.get('GROUP'): group_types = resource_type_defs['GROUP'] for group in network.resourcegroups: errors.extend(_validate_resource(group, group_types, resource_scenario_dict)) return errors
[ "def", "validate_network", "(", "network_id", ",", "template_id", ",", "scenario_id", "=", "None", ")", ":", "network", "=", "db", ".", "DBSession", ".", "query", "(", "Network", ")", ".", "filter", "(", "Network", ".", "id", "==", "network_id", ")", "."...
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. This validation will not fail if a resource has more than the required type, but will fail if it has fewer or if any attribute has a conflicting dimension or unit.
[ "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...
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L1859-L1921
train
46,127
hydraplatform/hydra-base
hydra_base/lib/template.py
_make_attr_element_from_typeattr
def _make_attr_element_from_typeattr(parent, type_attr_i): """ General function to add an attribute element to a resource element. resource_attr_i can also e a type_attr if being called from get_tempalte_as_xml """ 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_unit(type_attr_i.unit_id).abbreviation attr_is_var = etree.SubElement(attr, 'is_var') attr_is_var.text = type_attr_i.attr_is_var if type_attr_i.data_type is not None: attr_data_type = etree.SubElement(attr, 'data_type') attr_data_type.text = type_attr_i.data_type if type_attr_i.data_restriction is not None: attr_data_restriction = etree.SubElement(attr, 'restrictions') attr_data_restriction.text = type_attr_i.data_restriction return attr
python
def _make_attr_element_from_typeattr(parent, type_attr_i): """ General function to add an attribute element to a resource element. resource_attr_i can also e a type_attr if being called from get_tempalte_as_xml """ 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_unit(type_attr_i.unit_id).abbreviation attr_is_var = etree.SubElement(attr, 'is_var') attr_is_var.text = type_attr_i.attr_is_var if type_attr_i.data_type is not None: attr_data_type = etree.SubElement(attr, 'data_type') attr_data_type.text = type_attr_i.data_type if type_attr_i.data_restriction is not None: attr_data_restriction = etree.SubElement(attr, 'restrictions') attr_data_restriction.text = type_attr_i.data_restriction return attr
[ "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", "=", "et...
General function to add an attribute element to a resource element. resource_attr_i can also e a type_attr if being called from get_tempalte_as_xml
[ "General", "function", "to", "add", "an", "attribute", "element", "to", "a", "resource", "element", ".", "resource_attr_i", "can", "also", "e", "a", "type_attr", "if", "being", "called", "from", "get_tempalte_as_xml" ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L2093-L2116
train
46,128
hydraplatform/hydra-base
hydra_base/lib/template.py
_make_attr_element_from_resourceattr
def _make_attr_element_from_resourceattr(parent, resource_attr_i): """ General function to add an attribute element to a resource element. """ 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
python
def _make_attr_element_from_resourceattr(parent, resource_attr_i): """ General function to add an attribute element to a resource element. """ 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
[ "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'"...
General function to add an attribute element to a resource element.
[ "General", "function", "to", "add", "an", "attribute", "element", "to", "a", "resource", "element", "." ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L2118-L2128
train
46,129
hydraplatform/hydra-base
hydra_base/lib/template.py
_make_attr_element
def _make_attr_element(parent, attr_i): """ create an attribute element from an attribute DB object """ 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_i.description attr_dimension = etree.SubElement(attr, 'dimension') attr_dimension.text = units.get_dimension(attr_i.dimension_id, do_accept_dimension_id_none=True).name return attr
python
def _make_attr_element(parent, attr_i): """ create an attribute element from an attribute DB object """ 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_i.description attr_dimension = etree.SubElement(attr, 'dimension') attr_dimension.text = units.get_dimension(attr_i.dimension_id, do_accept_dimension_id_none=True).name return attr
[ "def", "_make_attr_element", "(", "parent", ",", "attr_i", ")", ":", "attr", "=", "etree", ".", "SubElement", "(", "parent", ",", "\"attribute\"", ")", "attr_name", "=", "etree", ".", "SubElement", "(", "attr", ",", "'name'", ")", "attr_name", ".", "text",...
create an attribute element from an attribute DB object
[ "create", "an", "attribute", "element", "from", "an", "attribute", "DB", "object" ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L2130-L2145
train
46,130
hydraplatform/hydra-base
hydra_base/lib/HydraTypes/Registry.py
HydraObjectFactory.valueFromDataset
def valueFromDataset(cls, datatype, value, metadata=None, tmap=None): """ Return the value contained by dataset argument, after casting to correct type and performing type-specific validation """ if tmap is None: tmap = typemap obj = cls.fromDataset(datatype, value, metadata=metadata, tmap=tmap) return obj.value
python
def valueFromDataset(cls, datatype, value, metadata=None, tmap=None): """ Return the value contained by dataset argument, after casting to correct type and performing type-specific validation """ if tmap is None: tmap = typemap obj = cls.fromDataset(datatype, value, metadata=metadata, tmap=tmap) return obj.value
[ "def", "valueFromDataset", "(", "cls", ",", "datatype", ",", "value", ",", "metadata", "=", "None", ",", "tmap", "=", "None", ")", ":", "if", "tmap", "is", "None", ":", "tmap", "=", "typemap", "obj", "=", "cls", ".", "fromDataset", "(", "datatype", "...
Return the value contained by dataset argument, after casting to correct type and performing type-specific validation
[ "Return", "the", "value", "contained", "by", "dataset", "argument", "after", "casting", "to", "correct", "type", "and", "performing", "type", "-", "specific", "validation" ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/HydraTypes/Registry.py#L28-L36
train
46,131
hydraplatform/hydra-base
hydra_base/lib/HydraTypes/Registry.py
HydraObjectFactory.fromDataset
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, metadata=metadata)
python
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, metadata=metadata)
[ "def", "fromDataset", "(", "datatype", ",", "value", ",", "metadata", "=", "None", ",", "tmap", "=", "None", ")", ":", "if", "tmap", "is", "None", ":", "tmap", "=", "typemap", "return", "tmap", "[", "datatype", ".", "upper", "(", ")", "]", ".", "fr...
Return a representation of dataset argument as an instance of the class corresponding to its datatype
[ "Return", "a", "representation", "of", "dataset", "argument", "as", "an", "instance" ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/HydraTypes/Registry.py#L39-L47
train
46,132
hydraplatform/hydra-base
hydra_base/lib/units.py
exists_dimension
def exists_dimension(dimension_name,**kwargs): """ Given a dimension returns True if it exists, False otherwise """ try: dimension = db.DBSession.query(Dimension).filter(Dimension.name==dimension_name).one() # At this point the dimension exists return True except NoResultFound: # The dimension does not exist raise False
python
def exists_dimension(dimension_name,**kwargs): """ Given a dimension returns True if it exists, False otherwise """ try: dimension = db.DBSession.query(Dimension).filter(Dimension.name==dimension_name).one() # At this point the dimension exists return True except NoResultFound: # The dimension does not exist raise False
[ "def", "exists_dimension", "(", "dimension_name", ",", "*", "*", "kwargs", ")", ":", "try", ":", "dimension", "=", "db", ".", "DBSession", ".", "query", "(", "Dimension", ")", ".", "filter", "(", "Dimension", ".", "name", "==", "dimension_name", ")", "."...
Given a dimension returns True if it exists, False otherwise
[ "Given", "a", "dimension", "returns", "True", "if", "it", "exists", "False", "otherwise" ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/units.py#L49-L59
train
46,133
hydraplatform/hydra-base
hydra_base/lib/units.py
convert_units
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 Parameters: values: single measure or an array of measures source_measure_or_unit_abbreviation: A measure in the source unit, or just the abbreviation of the source unit, from which convert the provided measure value/values target_measure_or_unit_abbreviation: A measure in the target unit, or just the abbreviation of the target unit, into which convert the provided measure value/values Returns: Always a list """ if numpy.isscalar(values): # If it is a scalar, converts to an array values = [values] float_values = [float(value) for value in values] values_to_return = convert(float_values, source_measure_or_unit_abbreviation, target_measure_or_unit_abbreviation) return values_to_return
python
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 Parameters: values: single measure or an array of measures source_measure_or_unit_abbreviation: A measure in the source unit, or just the abbreviation of the source unit, from which convert the provided measure value/values target_measure_or_unit_abbreviation: A measure in the target unit, or just the abbreviation of the target unit, into which convert the provided measure value/values Returns: Always a list """ if numpy.isscalar(values): # If it is a scalar, converts to an array values = [values] float_values = [float(value) for value in values] values_to_return = convert(float_values, source_measure_or_unit_abbreviation, target_measure_or_unit_abbreviation) return values_to_return
[ "def", "convert_units", "(", "values", ",", "source_measure_or_unit_abbreviation", ",", "target_measure_or_unit_abbreviation", ",", "*", "*", "kwargs", ")", ":", "if", "numpy", ".", "isscalar", "(", "values", ")", ":", "# If it is a scalar, converts to an array", "value...
Convert a value from one unit to another one. Example:: >>> cli = PluginLib.connect() >>> cli.service.convert_units(20.0, 'm', 'km') 0.02 Parameters: values: single measure or an array of measures source_measure_or_unit_abbreviation: A measure in the source unit, or just the abbreviation of the source unit, from which convert the provided measure value/values target_measure_or_unit_abbreviation: A measure in the target unit, or just the abbreviation of the target unit, into which convert the provided measure value/values Returns: Always a list
[ "Convert", "a", "value", "from", "one", "unit", "to", "another", "one", "." ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/units.py#L98-L121
train
46,134
hydraplatform/hydra-base
hydra_base/lib/units.py
convert
def convert(values, source_measure_or_unit_abbreviation, target_measure_or_unit_abbreviation): """ Convert a value or a list of values from an unit to another one. The two units must represent the same physical dimension. """ source_dimension = get_dimension_by_unit_measure_or_abbreviation(source_measure_or_unit_abbreviation) target_dimension = get_dimension_by_unit_measure_or_abbreviation(target_measure_or_unit_abbreviation) if source_dimension == target_dimension: source=JSONObject({}) target=JSONObject({}) source.unit_abbreviation, source.factor = _parse_unit(source_measure_or_unit_abbreviation) target.unit_abbreviation, target.factor = _parse_unit(target_measure_or_unit_abbreviation) source.unit_data = get_unit_by_abbreviation(source.unit_abbreviation) target.unit_data = get_unit_by_abbreviation(target.unit_abbreviation) source.conv_factor = JSONObject({'lf': source.unit_data.lf, 'cf': source.unit_data.cf}) target.conv_factor = JSONObject({'lf': target.unit_data.lf, 'cf': target.unit_data.cf}) if isinstance(values, float): # If values is a float => returns a float return (source.conv_factor.lf / target.conv_factor.lf * (source.factor * values) + (source.conv_factor.cf - target.conv_factor.cf) / target.conv_factor.lf) / target.factor elif isinstance(values, list): # If values is a list of floats => returns a list of floats return [(source.conv_factor.lf / target.conv_factor.lf * (source.factor * value) + (source.conv_factor.cf - target.conv_factor.cf) / target.conv_factor.lf) / target.factor for value in values] else: raise HydraError("Unit conversion: dimensions are not consistent.")
python
def convert(values, source_measure_or_unit_abbreviation, target_measure_or_unit_abbreviation): """ Convert a value or a list of values from an unit to another one. The two units must represent the same physical dimension. """ source_dimension = get_dimension_by_unit_measure_or_abbreviation(source_measure_or_unit_abbreviation) target_dimension = get_dimension_by_unit_measure_or_abbreviation(target_measure_or_unit_abbreviation) if source_dimension == target_dimension: source=JSONObject({}) target=JSONObject({}) source.unit_abbreviation, source.factor = _parse_unit(source_measure_or_unit_abbreviation) target.unit_abbreviation, target.factor = _parse_unit(target_measure_or_unit_abbreviation) source.unit_data = get_unit_by_abbreviation(source.unit_abbreviation) target.unit_data = get_unit_by_abbreviation(target.unit_abbreviation) source.conv_factor = JSONObject({'lf': source.unit_data.lf, 'cf': source.unit_data.cf}) target.conv_factor = JSONObject({'lf': target.unit_data.lf, 'cf': target.unit_data.cf}) if isinstance(values, float): # If values is a float => returns a float return (source.conv_factor.lf / target.conv_factor.lf * (source.factor * values) + (source.conv_factor.cf - target.conv_factor.cf) / target.conv_factor.lf) / target.factor elif isinstance(values, list): # If values is a list of floats => returns a list of floats return [(source.conv_factor.lf / target.conv_factor.lf * (source.factor * value) + (source.conv_factor.cf - target.conv_factor.cf) / target.conv_factor.lf) / target.factor for value in values] else: raise HydraError("Unit conversion: dimensions are not consistent.")
[ "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", "=", "...
Convert a value or a list of values from an unit to another one. The two units must represent the same physical dimension.
[ "Convert", "a", "value", "or", "a", "list", "of", "values", "from", "an", "unit", "to", "another", "one", ".", "The", "two", "units", "must", "represent", "the", "same", "physical", "dimension", "." ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/units.py#L123-L155
train
46,135
hydraplatform/hydra-base
hydra_base/lib/units.py
get_empty_dimension
def get_empty_dimension(**kwargs): """ Returns a dimension object initialized with empty values """ dimension = JSONObject(Dimension()) dimension.id = None dimension.name = '' dimension.description = '' dimension.project_id = None dimension.units = [] return dimension
python
def get_empty_dimension(**kwargs): """ Returns a dimension object initialized with empty values """ dimension = JSONObject(Dimension()) dimension.id = None dimension.name = '' dimension.description = '' dimension.project_id = None dimension.units = [] return dimension
[ "def", "get_empty_dimension", "(", "*", "*", "kwargs", ")", ":", "dimension", "=", "JSONObject", "(", "Dimension", "(", ")", ")", "dimension", ".", "id", "=", "None", "dimension", ".", "name", "=", "''", "dimension", ".", "description", "=", "''", "dimen...
Returns a dimension object initialized with empty values
[ "Returns", "a", "dimension", "object", "initialized", "with", "empty", "values" ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/units.py#L163-L173
train
46,136
hydraplatform/hydra-base
hydra_base/lib/units.py
get_dimension
def get_dimension(dimension_id, do_accept_dimension_id_none=False,**kwargs): """ Given a dimension id returns all its data """ 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() try: dimension = db.DBSession.query(Dimension).filter(Dimension.id==dimension_id).one() #lazy load units dimension.units return JSONObject(dimension) except NoResultFound: # The dimension does not exist raise ResourceNotFoundError("Dimension %s not found"%(dimension_id))
python
def get_dimension(dimension_id, do_accept_dimension_id_none=False,**kwargs): """ Given a dimension id returns all its data """ 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() try: dimension = db.DBSession.query(Dimension).filter(Dimension.id==dimension_id).one() #lazy load units dimension.units return JSONObject(dimension) except NoResultFound: # The dimension does not exist raise ResourceNotFoundError("Dimension %s not found"%(dimension_id))
[ "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 d...
Given a dimension id returns all its data
[ "Given", "a", "dimension", "id", "returns", "all", "its", "data" ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/units.py#L177-L194
train
46,137
hydraplatform/hydra-base
hydra_base/lib/units.py
get_dimensions
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(dimension.id)) return return_list
python
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(dimension.id)) return return_list
[ "def", "get_dimensions", "(", "*", "*", "kwargs", ")", ":", "dimensions_list", "=", "db", ".", "DBSession", ".", "query", "(", "Dimension", ")", ".", "options", "(", "load_only", "(", "\"id\"", ")", ")", ".", "all", "(", ")", "return_list", "=", "[", ...
Returns a list of objects describing all the dimensions with all the units.
[ "Returns", "a", "list", "of", "objects", "describing", "all", "the", "dimensions", "with", "all", "the", "units", "." ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/units.py#L197-L207
train
46,138
hydraplatform/hydra-base
hydra_base/lib/units.py
get_dimension_by_name
def get_dimension_by_name(dimension_name,**kwargs): """ Given a dimension name returns all its data. Used in convert functions """ try: if dimension_name is None: dimension_name = '' dimension = db.DBSession.query(Dimension).filter(func.lower(Dimension.name)==func.lower(dimension_name.strip())).one() return get_dimension(dimension.id) except NoResultFound: # The dimension does not exist raise ResourceNotFoundError("Dimension %s not found"%(dimension_name))
python
def get_dimension_by_name(dimension_name,**kwargs): """ Given a dimension name returns all its data. Used in convert functions """ try: if dimension_name is None: dimension_name = '' dimension = db.DBSession.query(Dimension).filter(func.lower(Dimension.name)==func.lower(dimension_name.strip())).one() return get_dimension(dimension.id) except NoResultFound: # The dimension does not exist raise ResourceNotFoundError("Dimension %s not found"%(dimension_name))
[ "def", "get_dimension_by_name", "(", "dimension_name", ",", "*", "*", "kwargs", ")", ":", "try", ":", "if", "dimension_name", "is", "None", ":", "dimension_name", "=", "''", "dimension", "=", "db", ".", "DBSession", ".", "query", "(", "Dimension", ")", "."...
Given a dimension name returns all its data. Used in convert functions
[ "Given", "a", "dimension", "name", "returns", "all", "its", "data", ".", "Used", "in", "convert", "functions" ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/units.py#L210-L223
train
46,139
hydraplatform/hydra-base
hydra_base/lib/units.py
get_unit
def get_unit(unit_id, **kwargs): """ Returns a single unit """ try: unit = db.DBSession.query(Unit).filter(Unit.id==unit_id).one() return JSONObject(unit) except NoResultFound: # The dimension does not exist raise ResourceNotFoundError("Unit %s not found"%(unit_id))
python
def get_unit(unit_id, **kwargs): """ Returns a single unit """ try: unit = db.DBSession.query(Unit).filter(Unit.id==unit_id).one() return JSONObject(unit) except NoResultFound: # The dimension does not exist raise ResourceNotFoundError("Unit %s not found"%(unit_id))
[ "def", "get_unit", "(", "unit_id", ",", "*", "*", "kwargs", ")", ":", "try", ":", "unit", "=", "db", ".", "DBSession", ".", "query", "(", "Unit", ")", ".", "filter", "(", "Unit", ".", "id", "==", "unit_id", ")", ".", "one", "(", ")", "return", ...
Returns a single unit
[ "Returns", "a", "single", "unit" ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/units.py#L233-L242
train
46,140
hydraplatform/hydra-base
hydra_base/lib/units.py
get_units
def get_units(**kwargs): """ Returns all the units """ units_list = db.DBSession.query(Unit).all() units = [] for unit in units_list: new_unit = JSONObject(unit) units.append(new_unit) return units
python
def get_units(**kwargs): """ Returns all the units """ units_list = db.DBSession.query(Unit).all() units = [] for unit in units_list: new_unit = JSONObject(unit) units.append(new_unit) return units
[ "def", "get_units", "(", "*", "*", "kwargs", ")", ":", "units_list", "=", "db", ".", "DBSession", ".", "query", "(", "Unit", ")", ".", "all", "(", ")", "units", "=", "[", "]", "for", "unit", "in", "units_list", ":", "new_unit", "=", "JSONObject", "...
Returns all the units
[ "Returns", "all", "the", "units" ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/units.py#L244-L254
train
46,141
hydraplatform/hydra-base
hydra_base/lib/units.py
get_dimension_by_unit_measure_or_abbreviation
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_unit(measure_or_unit_abbreviation) units = db.DBSession.query(Unit).filter(Unit.abbreviation==unit_abbreviation).all() if len(units) == 0: raise HydraError('Unit %s not found.'%(unit_abbreviation)) elif len(units) > 1: raise HydraError('Unit %s has multiple dimensions not found.'%(unit_abbreviation)) else: dimension = db.DBSession.query(Dimension).filter(Dimension.id==units[0].dimension_id).one() return str(dimension.name)
python
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_unit(measure_or_unit_abbreviation) units = db.DBSession.query(Unit).filter(Unit.abbreviation==unit_abbreviation).all() if len(units) == 0: raise HydraError('Unit %s not found.'%(unit_abbreviation)) elif len(units) > 1: raise HydraError('Unit %s has multiple dimensions not found.'%(unit_abbreviation)) else: dimension = db.DBSession.query(Dimension).filter(Dimension.id==units[0].dimension_id).one() return str(dimension.name)
[ "def", "get_dimension_by_unit_measure_or_abbreviation", "(", "measure_or_unit_abbreviation", ",", "*", "*", "kwargs", ")", ":", "unit_abbreviation", ",", "factor", "=", "_parse_unit", "(", "measure_or_unit_abbreviation", ")", "units", "=", "db", ".", "DBSession", ".", ...
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
[ "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" ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/units.py#L256-L272
train
46,142
hydraplatform/hydra-base
hydra_base/lib/units.py
get_unit_by_abbreviation
def get_unit_by_abbreviation(unit_abbreviation, **kwargs): """ Returns a single unit by abbreviation. Used as utility function to resolve string to id """ 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) except NoResultFound: # The dimension does not exist raise ResourceNotFoundError("Unit '%s' not found"%(unit_abbreviation))
python
def get_unit_by_abbreviation(unit_abbreviation, **kwargs): """ Returns a single unit by abbreviation. Used as utility function to resolve string to id """ 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) except NoResultFound: # The dimension does not exist raise ResourceNotFoundError("Unit '%s' not found"%(unit_abbreviation))
[ "def", "get_unit_by_abbreviation", "(", "unit_abbreviation", ",", "*", "*", "kwargs", ")", ":", "try", ":", "if", "unit_abbreviation", "is", "None", ":", "unit_abbreviation", "=", "''", "unit_i", "=", "db", ".", "DBSession", ".", "query", "(", "Unit", ")", ...
Returns a single unit by abbreviation. Used as utility function to resolve string to id
[ "Returns", "a", "single", "unit", "by", "abbreviation", ".", "Used", "as", "utility", "function", "to", "resolve", "string", "to", "id" ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/units.py#L292-L303
train
46,143
hydraplatform/hydra-base
hydra_base/lib/units.py
update_dimension
def update_dimension(dimension,**kwargs): """ Update a dimension in the DB. Raises and exception if the dimension does not exist. The key is ALWAYS the name and the name itself is not modificable """ db_dimension = None dimension = JSONObject(dimension) try: db_dimension = db.DBSession.query(Dimension).filter(Dimension.id==dimension.id).filter().one() if "description" in dimension and dimension["description"] is not None: db_dimension.description = dimension["description"] if "project_id" in dimension and dimension["project_id"] is not None and dimension["project_id"] != "" and dimension["project_id"].isdigit(): db_dimension.project_id = dimension["project_id"] except NoResultFound: raise ResourceNotFoundError("Dimension (ID=%s) does not exist"%(dimension.id)) db.DBSession.flush() return JSONObject(db_dimension)
python
def update_dimension(dimension,**kwargs): """ Update a dimension in the DB. Raises and exception if the dimension does not exist. The key is ALWAYS the name and the name itself is not modificable """ db_dimension = None dimension = JSONObject(dimension) try: db_dimension = db.DBSession.query(Dimension).filter(Dimension.id==dimension.id).filter().one() if "description" in dimension and dimension["description"] is not None: db_dimension.description = dimension["description"] if "project_id" in dimension and dimension["project_id"] is not None and dimension["project_id"] != "" and dimension["project_id"].isdigit(): db_dimension.project_id = dimension["project_id"] except NoResultFound: raise ResourceNotFoundError("Dimension (ID=%s) does not exist"%(dimension.id)) db.DBSession.flush() return JSONObject(db_dimension)
[ "def", "update_dimension", "(", "dimension", ",", "*", "*", "kwargs", ")", ":", "db_dimension", "=", "None", "dimension", "=", "JSONObject", "(", "dimension", ")", "try", ":", "db_dimension", "=", "db", ".", "DBSession", ".", "query", "(", "Dimension", ")"...
Update a dimension in the DB. Raises and exception if the dimension does not exist. The key is ALWAYS the name and the name itself is not modificable
[ "Update", "a", "dimension", "in", "the", "DB", ".", "Raises", "and", "exception", "if", "the", "dimension", "does", "not", "exist", ".", "The", "key", "is", "ALWAYS", "the", "name", "and", "the", "name", "itself", "is", "not", "modificable" ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/units.py#L340-L360
train
46,144
hydraplatform/hydra-base
hydra_base/lib/units.py
delete_dimension
def delete_dimension(dimension_id,**kwargs): """ Delete a dimension from the DB. Raises and exception if the dimension does not exist """ 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.delete(dimension) db.DBSession.flush() return True except NoResultFound: raise ResourceNotFoundError("Dimension (dimension_id=%s) does not exist"%(dimension_id))
python
def delete_dimension(dimension_id,**kwargs): """ Delete a dimension from the DB. Raises and exception if the dimension does not exist """ 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.delete(dimension) db.DBSession.flush() return True except NoResultFound: raise ResourceNotFoundError("Dimension (dimension_id=%s) does not exist"%(dimension_id))
[ "def", "delete_dimension", "(", "dimension_id", ",", "*", "*", "kwargs", ")", ":", "try", ":", "dimension", "=", "db", ".", "DBSession", ".", "query", "(", "Dimension", ")", ".", "filter", "(", "Dimension", ".", "id", "==", "dimension_id", ")", ".", "o...
Delete a dimension from the DB. Raises and exception if the dimension does not exist
[ "Delete", "a", "dimension", "from", "the", "DB", ".", "Raises", "and", "exception", "if", "the", "dimension", "does", "not", "exist" ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/units.py#L363-L376
train
46,145
hydraplatform/hydra-base
hydra_base/lib/units.py
bulk_add_dimensions
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})
python
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})
[ "def", "bulk_add_dimensions", "(", "dimension_list", ",", "*", "*", "kwargs", ")", ":", "added_dimensions", "=", "[", "]", "for", "dimension", "in", "dimension_list", ":", "added_dimensions", ".", "append", "(", "add_dimension", "(", "dimension", ",", "*", "*"...
Save all the dimensions contained in the passed list.
[ "Save", "all", "the", "dimensions", "contained", "in", "the", "passed", "list", "." ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/units.py#L380-L388
train
46,146
hydraplatform/hydra-base
hydra_base/lib/units.py
bulk_add_units
def bulk_add_units(unit_list, **kwargs): """ Save all the units contained in the passed list, with the name of their dimension. """ # 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})
python
def bulk_add_units(unit_list, **kwargs): """ Save all the units contained in the passed list, with the name of their dimension. """ # 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})
[ "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", "(", "...
Save all the units contained in the passed list, with the name of their dimension.
[ "Save", "all", "the", "units", "contained", "in", "the", "passed", "list", "with", "the", "name", "of", "their", "dimension", "." ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/units.py#L446-L457
train
46,147
hydraplatform/hydra-base
hydra_base/lib/units.py
delete_unit
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 except NoResultFound: raise ResourceNotFoundError("Unit (ID=%s) does not exist"%(unit_id))
python
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 except NoResultFound: raise ResourceNotFoundError("Unit (ID=%s) does not exist"%(unit_id))
[ "def", "delete_unit", "(", "unit_id", ",", "*", "*", "kwargs", ")", ":", "try", ":", "db_unit", "=", "db", ".", "DBSession", ".", "query", "(", "Unit", ")", ".", "filter", "(", "Unit", ".", "id", "==", "unit_id", ")", ".", "one", "(", ")", "db", ...
Delete a unit from the DB. Raises and exception if the unit does not exist
[ "Delete", "a", "unit", "from", "the", "DB", ".", "Raises", "and", "exception", "if", "the", "unit", "does", "not", "exist" ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/units.py#L463-L476
train
46,148
hydraplatform/hydra-base
hydra_base/lib/units.py
update_unit
def update_unit(unit, **kwargs): """ Update a unit in the DB. Raises and exception if the unit does not exist """ 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.abbreviation = unit.abbreviation db_unit.description = unit.description db_unit.lf = unit["lf"] db_unit.cf = unit["cf"] if "project_id" in unit and unit['project_id'] is not None and unit['project_id'] != "": db_unit.project_id = unit["project_id"] except NoResultFound: raise ResourceNotFoundError("Unit (ID=%s) does not exist"%(unit["id"])) db.DBSession.flush() return JSONObject(db_unit)
python
def update_unit(unit, **kwargs): """ Update a unit in the DB. Raises and exception if the unit does not exist """ 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.abbreviation = unit.abbreviation db_unit.description = unit.description db_unit.lf = unit["lf"] db_unit.cf = unit["cf"] if "project_id" in unit and unit['project_id'] is not None and unit['project_id'] != "": db_unit.project_id = unit["project_id"] except NoResultFound: raise ResourceNotFoundError("Unit (ID=%s) does not exist"%(unit["id"])) db.DBSession.flush() return JSONObject(db_unit)
[ "def", "update_unit", "(", "unit", ",", "*", "*", "kwargs", ")", ":", "try", ":", "db_unit", "=", "db", ".", "DBSession", ".", "query", "(", "Unit", ")", ".", "join", "(", "Dimension", ")", ".", "filter", "(", "Unit", ".", "id", "==", "unit", "["...
Update a unit in the DB. Raises and exception if the unit does not exist
[ "Update", "a", "unit", "in", "the", "DB", ".", "Raises", "and", "exception", "if", "the", "unit", "does", "not", "exist" ]
9251ff7946505f7a272c87837390acd1c435bc6e
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/units.py#L480-L504
train
46,149
multiformats/py-multibase
multibase/multibase.py
encode
def encode(encoding, data): """ Encodes the given data using the encoding that is specified :param str encoding: encoding to use, should be one of the supported encoding :param data: data to encode :type data: str or bytes :return: multibase encoded data :rtype: bytes :raises ValueError: if the encoding is not supported """ 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))
python
def encode(encoding, data): """ Encodes the given data using the encoding that is specified :param str encoding: encoding to use, should be one of the supported encoding :param data: data to encode :type data: str or bytes :return: multibase encoded data :rtype: bytes :raises ValueError: if the encoding is not supported """ 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))
[ "def", "encode", "(", "encoding", ",", "data", ")", ":", "data", "=", "ensure_bytes", "(", "data", ",", "'utf8'", ")", "try", ":", "return", "ENCODINGS_LOOKUP", "[", "encoding", "]", ".", "code", "+", "ENCODINGS_LOOKUP", "[", "encoding", "]", ".", "conve...
Encodes the given data using the encoding that is specified :param str encoding: encoding to use, should be one of the supported encoding :param data: data to encode :type data: str or bytes :return: multibase encoded data :rtype: bytes :raises ValueError: if the encoding is not supported
[ "Encodes", "the", "given", "data", "using", "the", "encoding", "that", "is", "specified" ]
8f435762b50a17f921c13b59eb0c7b9c52afc879
https://github.com/multiformats/py-multibase/blob/8f435762b50a17f921c13b59eb0c7b9c52afc879/multibase/multibase.py#L32-L47
train
46,150
multiformats/py-multibase
multibase/multibase.py
get_codec
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_bytes(data[:CODE_LENGTH], 'utf8') codec = ENCODINGS_LOOKUP[key] except KeyError: raise ValueError('Can not determine encoding for {}'.format(data)) else: return codec
python
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_bytes(data[:CODE_LENGTH], 'utf8') codec = ENCODINGS_LOOKUP[key] except KeyError: raise ValueError('Can not determine encoding for {}'.format(data)) else: return codec
[ "def", "get_codec", "(", "data", ")", ":", "try", ":", "key", "=", "ensure_bytes", "(", "data", "[", ":", "CODE_LENGTH", "]", ",", "'utf8'", ")", "codec", "=", "ENCODINGS_LOOKUP", "[", "key", "]", "except", "KeyError", ":", "raise", "ValueError", "(", ...
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
[ "Returns", "the", "codec", "used", "to", "encode", "the", "given", "data" ]
8f435762b50a17f921c13b59eb0c7b9c52afc879
https://github.com/multiformats/py-multibase/blob/8f435762b50a17f921c13b59eb0c7b9c52afc879/multibase/multibase.py#L50-L65
train
46,151
monetate/ectou-metadata
ectou_metadata/service.py
_get_role_arn
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')) if not role_arn: role_arn = _role_arn return role_arn
python
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')) if not role_arn: role_arn = _role_arn return role_arn
[ "def", "_get_role_arn", "(", ")", ":", "role_arn", "=", "bottle", ".", "request", ".", "headers", ".", "get", "(", "'X-Role-ARN'", ")", "if", "not", "role_arn", ":", "role_arn", "=", "_lookup_ip_role_arn", "(", "bottle", ".", "request", ".", "environ", "."...
Return role arn from X-Role-ARN header, lookup role arn from source IP, or fall back to command line default.
[ "Return", "role", "arn", "from", "X", "-", "Role", "-", "ARN", "header", "lookup", "role", "arn", "from", "source", "IP", "or", "fall", "back", "to", "command", "line", "default", "." ]
f5d57d086363321e6e4a1206f94c8f980971cb0c
https://github.com/monetate/ectou-metadata/blob/f5d57d086363321e6e4a1206f94c8f980971cb0c/ectou_metadata/service.py#L33-L44
train
46,152
sprockets/sprockets-dynamodb
sprockets_dynamodb/mixin.py
DynamoDBMixin._on_dynamodb_exception
def _on_dynamodb_exception(self, error): """Dynamically handle DynamoDB exceptions, returning HTTP error responses. :param exceptions.DynamoDBException error: """ if isinstance(error, exceptions.ConditionalCheckFailedException): raise web.HTTPError(409, reason='Condition Check Failure') elif isinstance(error, exceptions.NoCredentialsError): if _no_creds_should_return_429(): raise web.HTTPError(429, reason='Instance Credentials Failure') elif isinstance(error, (exceptions.ThroughputExceeded, exceptions.ThrottlingException)): raise web.HTTPError(429, reason='Too Many Requests') if hasattr(self, 'logger'): self.logger.error('DynamoDB Error: %s', error) raise web.HTTPError(500, reason=str(error))
python
def _on_dynamodb_exception(self, error): """Dynamically handle DynamoDB exceptions, returning HTTP error responses. :param exceptions.DynamoDBException error: """ if isinstance(error, exceptions.ConditionalCheckFailedException): raise web.HTTPError(409, reason='Condition Check Failure') elif isinstance(error, exceptions.NoCredentialsError): if _no_creds_should_return_429(): raise web.HTTPError(429, reason='Instance Credentials Failure') elif isinstance(error, (exceptions.ThroughputExceeded, exceptions.ThrottlingException)): raise web.HTTPError(429, reason='Too Many Requests') if hasattr(self, 'logger'): self.logger.error('DynamoDB Error: %s', error) raise web.HTTPError(500, reason=str(error))
[ "def", "_on_dynamodb_exception", "(", "self", ",", "error", ")", ":", "if", "isinstance", "(", "error", ",", "exceptions", ".", "ConditionalCheckFailedException", ")", ":", "raise", "web", ".", "HTTPError", "(", "409", ",", "reason", "=", "'Condition Check Failu...
Dynamically handle DynamoDB exceptions, returning HTTP error responses. :param exceptions.DynamoDBException error:
[ "Dynamically", "handle", "DynamoDB", "exceptions", "returning", "HTTP", "error", "responses", "." ]
2e202bcb01f23f828f91299599311007054de4aa
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/mixin.py#L39-L56
train
46,153
sprockets/sprockets-dynamodb
sprockets_dynamodb/utils.py
marshall
def marshall(values): """ Marshall a `dict` into something DynamoDB likes. :param dict values: The values to marshall :rtype: dict :raises ValueError: if an unsupported type is encountered Return the values in a nested dict structure that is required for writing the values to DynamoDB. """ serialized = {} for key in values: serialized[key] = _marshall_value(values[key]) return serialized
python
def marshall(values): """ Marshall a `dict` into something DynamoDB likes. :param dict values: The values to marshall :rtype: dict :raises ValueError: if an unsupported type is encountered Return the values in a nested dict structure that is required for writing the values to DynamoDB. """ serialized = {} for key in values: serialized[key] = _marshall_value(values[key]) return serialized
[ "def", "marshall", "(", "values", ")", ":", "serialized", "=", "{", "}", "for", "key", "in", "values", ":", "serialized", "[", "key", "]", "=", "_marshall_value", "(", "values", "[", "key", "]", ")", "return", "serialized" ]
Marshall a `dict` into something DynamoDB likes. :param dict values: The values to marshall :rtype: dict :raises ValueError: if an unsupported type is encountered Return the values in a nested dict structure that is required for writing the values to DynamoDB.
[ "Marshall", "a", "dict", "into", "something", "DynamoDB", "likes", "." ]
2e202bcb01f23f828f91299599311007054de4aa
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/utils.py#L40-L55
train
46,154
sprockets/sprockets-dynamodb
sprockets_dynamodb/utils.py
unmarshall
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] = _unmarshall_dict(values[key]) return unmarshalled
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] = _unmarshall_dict(values[key]) return unmarshalled
[ "def", "unmarshall", "(", "values", ")", ":", "unmarshalled", "=", "{", "}", "for", "key", "in", "values", ":", "unmarshalled", "[", "key", "]", "=", "_unmarshall_dict", "(", "values", "[", "key", "]", ")", "return", "unmarshalled" ]
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
[ "Transform", "a", "response", "payload", "from", "DynamoDB", "to", "a", "native", "dict" ]
2e202bcb01f23f828f91299599311007054de4aa
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/utils.py#L58-L70
train
46,155
sprockets/sprockets-dynamodb
sprockets_dynamodb/utils.py
_marshall_value
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 required. """ if PYTHON3 and isinstance(value, bytes): return {'B': base64.b64encode(value).decode('ascii')} elif PYTHON3 and isinstance(value, str): return {'S': value} elif not PYTHON3 and isinstance(value, str): if is_binary(value): return {'B': base64.b64encode(value).decode('ascii')} return {'S': value} elif not PYTHON3 and isinstance(value, unicode): return {'S': value.encode('utf-8')} elif isinstance(value, dict): return {'M': marshall(value)} elif isinstance(value, bool): return {'BOOL': value} elif isinstance(value, (int, float)): return {'N': str(value)} elif isinstance(value, datetime.datetime): return {'S': value.isoformat()} elif isinstance(value, uuid.UUID): return {'S': str(value)} elif isinstance(value, list): return {'L': [_marshall_value(v) for v in value]} elif isinstance(value, set): if PYTHON3 and all([isinstance(v, bytes) for v in value]): return {'BS': _encode_binary_set(value)} elif PYTHON3 and all([isinstance(v, str) for v in value]): return {'SS': sorted(list(value))} elif all([isinstance(v, (int, float)) for v in value]): return {'NS': sorted([str(v) for v in value])} elif not PYTHON3 and all([isinstance(v, str) for v in value]) and \ all([is_binary(v) for v in value]): return {'BS': _encode_binary_set(value)} elif not PYTHON3 and all([isinstance(v, str) for v in value]) and \ all([is_binary(v) is False for v in value]): return {'SS': sorted(list(value))} else: raise ValueError('Can not mix types in a set') elif value is None: return {'NULL': True} raise ValueError('Unsupported type: %s' % type(value))
python
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 required. """ if PYTHON3 and isinstance(value, bytes): return {'B': base64.b64encode(value).decode('ascii')} elif PYTHON3 and isinstance(value, str): return {'S': value} elif not PYTHON3 and isinstance(value, str): if is_binary(value): return {'B': base64.b64encode(value).decode('ascii')} return {'S': value} elif not PYTHON3 and isinstance(value, unicode): return {'S': value.encode('utf-8')} elif isinstance(value, dict): return {'M': marshall(value)} elif isinstance(value, bool): return {'BOOL': value} elif isinstance(value, (int, float)): return {'N': str(value)} elif isinstance(value, datetime.datetime): return {'S': value.isoformat()} elif isinstance(value, uuid.UUID): return {'S': str(value)} elif isinstance(value, list): return {'L': [_marshall_value(v) for v in value]} elif isinstance(value, set): if PYTHON3 and all([isinstance(v, bytes) for v in value]): return {'BS': _encode_binary_set(value)} elif PYTHON3 and all([isinstance(v, str) for v in value]): return {'SS': sorted(list(value))} elif all([isinstance(v, (int, float)) for v in value]): return {'NS': sorted([str(v) for v in value])} elif not PYTHON3 and all([isinstance(v, str) for v in value]) and \ all([is_binary(v) for v in value]): return {'BS': _encode_binary_set(value)} elif not PYTHON3 and all([isinstance(v, str) for v in value]) and \ all([is_binary(v) is False for v in value]): return {'SS': sorted(list(value))} else: raise ValueError('Can not mix types in a set') elif value is None: return {'NULL': True} raise ValueError('Unsupported type: %s' % type(value))
[ "def", "_marshall_value", "(", "value", ")", ":", "if", "PYTHON3", "and", "isinstance", "(", "value", ",", "bytes", ")", ":", "return", "{", "'B'", ":", "base64", ".", "b64encode", "(", "value", ")", ".", "decode", "(", "'ascii'", ")", "}", "elif", "...
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 required.
[ "Recursively", "transform", "value", "into", "an", "AttributeValue", "dict" ]
2e202bcb01f23f828f91299599311007054de4aa
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/utils.py#L83-L134
train
46,156
sprockets/sprockets-dynamodb
sprockets_dynamodb/utils.py
_unmarshall_dict
def _unmarshall_dict(value): """Unmarshall a single dict value from a row that was returned from DynamoDB, returning the value as a normal Python dict. :param dict value: The value to unmarshall :rtype: mixed :raises ValueError: if an unsupported type code is encountered """ key = list(value.keys()).pop() if key == 'B': return base64.b64decode(value[key].encode('ascii')) elif key == 'BS': return set([base64.b64decode(v.encode('ascii')) for v in value[key]]) elif key == 'BOOL': return value[key] elif key == 'L': return [_unmarshall_dict(v) for v in value[key]] elif key == 'M': return unmarshall(value[key]) elif key == 'NULL': return None elif key == 'N': return _to_number(value[key]) elif key == 'NS': return set([_to_number(v) for v in value[key]]) elif key == 'S': return value[key] elif key == 'SS': return set([v for v in value[key]]) raise ValueError('Unsupported value type: %s' % key)
python
def _unmarshall_dict(value): """Unmarshall a single dict value from a row that was returned from DynamoDB, returning the value as a normal Python dict. :param dict value: The value to unmarshall :rtype: mixed :raises ValueError: if an unsupported type code is encountered """ key = list(value.keys()).pop() if key == 'B': return base64.b64decode(value[key].encode('ascii')) elif key == 'BS': return set([base64.b64decode(v.encode('ascii')) for v in value[key]]) elif key == 'BOOL': return value[key] elif key == 'L': return [_unmarshall_dict(v) for v in value[key]] elif key == 'M': return unmarshall(value[key]) elif key == 'NULL': return None elif key == 'N': return _to_number(value[key]) elif key == 'NS': return set([_to_number(v) for v in value[key]]) elif key == 'S': return value[key] elif key == 'SS': return set([v for v in value[key]]) raise ValueError('Unsupported value type: %s' % key)
[ "def", "_unmarshall_dict", "(", "value", ")", ":", "key", "=", "list", "(", "value", ".", "keys", "(", ")", ")", ".", "pop", "(", ")", "if", "key", "==", "'B'", ":", "return", "base64", ".", "b64decode", "(", "value", "[", "key", "]", ".", "encod...
Unmarshall a single dict value from a row that was returned from DynamoDB, returning the value as a normal Python dict. :param dict value: The value to unmarshall :rtype: mixed :raises ValueError: if an unsupported type code is encountered
[ "Unmarshall", "a", "single", "dict", "value", "from", "a", "row", "that", "was", "returned", "from", "DynamoDB", "returning", "the", "value", "as", "a", "normal", "Python", "dict", "." ]
2e202bcb01f23f828f91299599311007054de4aa
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/utils.py#L148-L179
train
46,157
sprockets/sprockets-dynamodb
sprockets_dynamodb/client.py
_unwrap_result
def _unwrap_result(action, result): """Unwrap a request response and return only the response data. :param str action: The action name :param result: The result of the action :type: result: list or dict :rtype: dict | None """ 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) elif action == 'Query' or action == 'Scan': return _unwrap_query_scan(result) elif action == 'CreateTable': return _unwrap_create_table(result) elif action == 'DescribeTable': return _unwrap_describe_table(result) return result
python
def _unwrap_result(action, result): """Unwrap a request response and return only the response data. :param str action: The action name :param result: The result of the action :type: result: list or dict :rtype: dict | None """ 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) elif action == 'Query' or action == 'Scan': return _unwrap_query_scan(result) elif action == 'CreateTable': return _unwrap_create_table(result) elif action == 'DescribeTable': return _unwrap_describe_table(result) return result
[ "def", "_unwrap_result", "(", "action", ",", "result", ")", ":", "if", "not", "result", ":", "return", "elif", "action", "in", "{", "'DeleteItem'", ",", "'PutItem'", ",", "'UpdateItem'", "}", ":", "return", "_unwrap_delete_put_update_item", "(", "result", ")",...
Unwrap a request response and return only the response data. :param str action: The action name :param result: The result of the action :type: result: list or dict :rtype: dict | None
[ "Unwrap", "a", "request", "response", "and", "return", "only", "the", "response", "data", "." ]
2e202bcb01f23f828f91299599311007054de4aa
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/client.py#L943-L964
train
46,158
sprockets/sprockets-dynamodb
sprockets_dynamodb/client.py
Client.list_tables
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`` table names. :param str exclusive_start_table_name: The first table name that this operation will evaluate. Use the value that was returned for ``LastEvaluatedTableName`` in a previous operation, so that you can obtain the next page of results. :param int limit: A maximum number of table names to return. If this parameter is not specified, the limit is ``100``. .. _ListTables: http://docs.aws.amazon.com/amazondynamodb/ latest/APIReference/API_ListTables.html """ payload = {} if exclusive_start_table_name: payload['ExclusiveStartTableName'] = exclusive_start_table_name if limit: payload['Limit'] = limit return self.execute('ListTables', payload)
python
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`` table names. :param str exclusive_start_table_name: The first table name that this operation will evaluate. Use the value that was returned for ``LastEvaluatedTableName`` in a previous operation, so that you can obtain the next page of results. :param int limit: A maximum number of table names to return. If this parameter is not specified, the limit is ``100``. .. _ListTables: http://docs.aws.amazon.com/amazondynamodb/ latest/APIReference/API_ListTables.html """ payload = {} if exclusive_start_table_name: payload['ExclusiveStartTableName'] = exclusive_start_table_name if limit: payload['Limit'] = limit return self.execute('ListTables', payload)
[ "def", "list_tables", "(", "self", ",", "exclusive_start_table_name", "=", "None", ",", "limit", "=", "None", ")", ":", "payload", "=", "{", "}", "if", "exclusive_start_table_name", ":", "payload", "[", "'ExclusiveStartTableName'", "]", "=", "exclusive_start_table...
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 operation will evaluate. Use the value that was returned for ``LastEvaluatedTableName`` in a previous operation, so that you can obtain the next page of results. :param int limit: A maximum number of table names to return. If this parameter is not specified, the limit is ``100``. .. _ListTables: http://docs.aws.amazon.com/amazondynamodb/ latest/APIReference/API_ListTables.html
[ "Invoke", "the", "ListTables", "_", "function", "." ]
2e202bcb01f23f828f91299599311007054de4aa
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/client.py#L176-L200
train
46,159
sprockets/sprockets-dynamodb
sprockets_dynamodb/client.py
Client.get_item
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 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`True`, then the operation uses strongly consistent reads; otherwise, the operation uses eventually consistent reads. :param dict expression_attribute_names: One or more substitution tokens for attribute names in an expression. :param str projection_expression: A string that identifies one or more attributes to retrieve from the table. These attributes can include scalars, sets, or elements of a JSON document. The attributes in the expression must be separated by commas. If no attribute names are specified, then all attributes will be returned. If any of the requested attributes are not found, they will not appear in the result. :param str return_consumed_capacity: Determines the level of detail about provisioned throughput consumption that is returned in the response: - INDEXES: The response includes the aggregate consumed capacity for the operation, together with consumed capacity for each table and secondary index that was accessed. Note that some operations, such as *GetItem* and *BatchGetItem*, do not access any indexes at all. In these cases, specifying INDEXES will only return consumed capacity information for table(s). - TOTAL: The response includes only the aggregate consumed capacity for the operation. - NONE: No consumed capacity details are included in the response. :rtype: tornado.concurrent.Future .. _GetItem: http://docs.aws.amazon.com/amazondynamodb/ latest/APIReference/API_GetItem.html """ payload = {'TableName': table_name, 'Key': utils.marshall(key_dict), 'ConsistentRead': consistent_read} if expression_attribute_names: payload['ExpressionAttributeNames'] = expression_attribute_names if projection_expression: payload['ProjectionExpression'] = projection_expression if return_consumed_capacity: _validate_return_consumed_capacity(return_consumed_capacity) payload['ReturnConsumedCapacity'] = return_consumed_capacity return self.execute('GetItem', payload)
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 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`True`, then the operation uses strongly consistent reads; otherwise, the operation uses eventually consistent reads. :param dict expression_attribute_names: One or more substitution tokens for attribute names in an expression. :param str projection_expression: A string that identifies one or more attributes to retrieve from the table. These attributes can include scalars, sets, or elements of a JSON document. The attributes in the expression must be separated by commas. If no attribute names are specified, then all attributes will be returned. If any of the requested attributes are not found, they will not appear in the result. :param str return_consumed_capacity: Determines the level of detail about provisioned throughput consumption that is returned in the response: - INDEXES: The response includes the aggregate consumed capacity for the operation, together with consumed capacity for each table and secondary index that was accessed. Note that some operations, such as *GetItem* and *BatchGetItem*, do not access any indexes at all. In these cases, specifying INDEXES will only return consumed capacity information for table(s). - TOTAL: The response includes only the aggregate consumed capacity for the operation. - NONE: No consumed capacity details are included in the response. :rtype: tornado.concurrent.Future .. _GetItem: http://docs.aws.amazon.com/amazondynamodb/ latest/APIReference/API_GetItem.html """ payload = {'TableName': table_name, 'Key': utils.marshall(key_dict), 'ConsistentRead': consistent_read} if expression_attribute_names: payload['ExpressionAttributeNames'] = expression_attribute_names if projection_expression: payload['ProjectionExpression'] = projection_expression if return_consumed_capacity: _validate_return_consumed_capacity(return_consumed_capacity) payload['ReturnConsumedCapacity'] = return_consumed_capacity return self.execute('GetItem', payload)
[ "def", "get_item", "(", "self", ",", "table_name", ",", "key_dict", ",", "consistent_read", "=", "False", ",", "expression_attribute_names", "=", "None", ",", "projection_expression", "=", "None", ",", "return_consumed_capacity", "=", "None", ")", ":", "payload", ...
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`True`, then the operation uses strongly consistent reads; otherwise, the operation uses eventually consistent reads. :param dict expression_attribute_names: One or more substitution tokens for attribute names in an expression. :param str projection_expression: A string that identifies one or more attributes to retrieve from the table. These attributes can include scalars, sets, or elements of a JSON document. The attributes in the expression must be separated by commas. If no attribute names are specified, then all attributes will be returned. If any of the requested attributes are not found, they will not appear in the result. :param str return_consumed_capacity: Determines the level of detail about provisioned throughput consumption that is returned in the response: - INDEXES: The response includes the aggregate consumed capacity for the operation, together with consumed capacity for each table and secondary index that was accessed. Note that some operations, such as *GetItem* and *BatchGetItem*, do not access any indexes at all. In these cases, specifying INDEXES will only return consumed capacity information for table(s). - TOTAL: The response includes only the aggregate consumed capacity for the operation. - NONE: No consumed capacity details are included in the response. :rtype: tornado.concurrent.Future .. _GetItem: http://docs.aws.amazon.com/amazondynamodb/ latest/APIReference/API_GetItem.html
[ "Invoke", "the", "GetItem", "_", "function", "." ]
2e202bcb01f23f828f91299599311007054de4aa
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/client.py#L278-L331
train
46,160
sprockets/sprockets-dynamodb
sprockets_dynamodb/client.py
Client.update_item
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_item_collection_metrics=None, return_values=None): """Invoke 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 doesn't exist, or replace an existing name-value pair if it has certain expected attribute values). :param str table_name: The name of the table that contains the item to update :param dict key_dict: A dictionary of key/value pairs that are used to define the primary key values for the item. For the primary key, you must provide all of the attributes. For example, with a simple primary key, you only need to provide a value for the partition key. For a composite primary key, you must provide values for both the partition key and the sort key. :param str condition_expression: A condition that must be satisfied in order for a conditional *UpdateItem* operation to succeed. One of: ``attribute_exists``, ``attribute_not_exists``, ``attribute_type``, ``contains``, ``begins_with``, ``size``, ``=``, ``<>``, ``<``, ``>``, ``<=``, ``>=``, ``BETWEEN``, ``IN``, ``AND``, ``OR``, or ``NOT``. :param str update_expression: An expression that defines one or more attributes to be updated, the action to be performed on them, and new value(s) for them. :param dict expression_attribute_names: One or more substitution tokens for attribute names in an expression. :param dict expression_attribute_values: One or more values that can be substituted in an expression. :param str return_consumed_capacity: Determines the level of detail about provisioned throughput consumption that is returned in the response. See the `AWS documentation for ReturnConsumedCapacity <http://docs.aws.amazon.com/ amazondynamodb/latest/APIReference/API_UpdateItem.html#DDB-Update Item-request-ReturnConsumedCapacity>`_ for more information. :param str return_item_collection_metrics: Determines whether item collection metrics are returned. :param str return_values: Use ReturnValues if you want to get the item attributes as they appeared either before or after they were updated. See the `AWS documentation for ReturnValues <http://docs. aws.amazon.com/amazondynamodb/latest/APIReference/ API_UpdateItem.html#DDB-UpdateItem-request-ReturnValues>`_ :rtype: tornado.concurrent.Future .. _UpdateItem: http://docs.aws.amazon.com/amazondynamodb/ latest/APIReference/API_UpdateItem.html """ payload = {'TableName': table_name, 'Key': utils.marshall(key_dict), 'UpdateExpression': update_expression} if condition_expression: payload['ConditionExpression'] = condition_expression if expression_attribute_names: payload['ExpressionAttributeNames'] = expression_attribute_names if expression_attribute_values: payload['ExpressionAttributeValues'] = \ utils.marshall(expression_attribute_values) if return_consumed_capacity: _validate_return_consumed_capacity(return_consumed_capacity) payload['ReturnConsumedCapacity'] = return_consumed_capacity if return_item_collection_metrics: _validate_return_item_collection_metrics( return_item_collection_metrics) payload['ReturnItemCollectionMetrics'] = \ return_item_collection_metrics if return_values: _validate_return_values(return_values) payload['ReturnValues'] = return_values return self.execute('UpdateItem', payload)
python
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_item_collection_metrics=None, return_values=None): """Invoke 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 doesn't exist, or replace an existing name-value pair if it has certain expected attribute values). :param str table_name: The name of the table that contains the item to update :param dict key_dict: A dictionary of key/value pairs that are used to define the primary key values for the item. For the primary key, you must provide all of the attributes. For example, with a simple primary key, you only need to provide a value for the partition key. For a composite primary key, you must provide values for both the partition key and the sort key. :param str condition_expression: A condition that must be satisfied in order for a conditional *UpdateItem* operation to succeed. One of: ``attribute_exists``, ``attribute_not_exists``, ``attribute_type``, ``contains``, ``begins_with``, ``size``, ``=``, ``<>``, ``<``, ``>``, ``<=``, ``>=``, ``BETWEEN``, ``IN``, ``AND``, ``OR``, or ``NOT``. :param str update_expression: An expression that defines one or more attributes to be updated, the action to be performed on them, and new value(s) for them. :param dict expression_attribute_names: One or more substitution tokens for attribute names in an expression. :param dict expression_attribute_values: One or more values that can be substituted in an expression. :param str return_consumed_capacity: Determines the level of detail about provisioned throughput consumption that is returned in the response. See the `AWS documentation for ReturnConsumedCapacity <http://docs.aws.amazon.com/ amazondynamodb/latest/APIReference/API_UpdateItem.html#DDB-Update Item-request-ReturnConsumedCapacity>`_ for more information. :param str return_item_collection_metrics: Determines whether item collection metrics are returned. :param str return_values: Use ReturnValues if you want to get the item attributes as they appeared either before or after they were updated. See the `AWS documentation for ReturnValues <http://docs. aws.amazon.com/amazondynamodb/latest/APIReference/ API_UpdateItem.html#DDB-UpdateItem-request-ReturnValues>`_ :rtype: tornado.concurrent.Future .. _UpdateItem: http://docs.aws.amazon.com/amazondynamodb/ latest/APIReference/API_UpdateItem.html """ payload = {'TableName': table_name, 'Key': utils.marshall(key_dict), 'UpdateExpression': update_expression} if condition_expression: payload['ConditionExpression'] = condition_expression if expression_attribute_names: payload['ExpressionAttributeNames'] = expression_attribute_names if expression_attribute_values: payload['ExpressionAttributeValues'] = \ utils.marshall(expression_attribute_values) if return_consumed_capacity: _validate_return_consumed_capacity(return_consumed_capacity) payload['ReturnConsumedCapacity'] = return_consumed_capacity if return_item_collection_metrics: _validate_return_item_collection_metrics( return_item_collection_metrics) payload['ReturnItemCollectionMetrics'] = \ return_item_collection_metrics if return_values: _validate_return_values(return_values) payload['ReturnValues'] = return_values return self.execute('UpdateItem', payload)
[ "def", "update_item", "(", "self", ",", "table_name", ",", "key_dict", ",", "condition_expression", "=", "None", ",", "update_expression", "=", "None", ",", "expression_attribute_names", "=", "None", ",", "expression_attribute_values", "=", "None", ",", "return_cons...
Invoke 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 doesn't exist, or replace an existing name-value pair if it has certain expected attribute values). :param str table_name: The name of the table that contains the item to update :param dict key_dict: A dictionary of key/value pairs that are used to define the primary key values for the item. For the primary key, you must provide all of the attributes. For example, with a simple primary key, you only need to provide a value for the partition key. For a composite primary key, you must provide values for both the partition key and the sort key. :param str condition_expression: A condition that must be satisfied in order for a conditional *UpdateItem* operation to succeed. One of: ``attribute_exists``, ``attribute_not_exists``, ``attribute_type``, ``contains``, ``begins_with``, ``size``, ``=``, ``<>``, ``<``, ``>``, ``<=``, ``>=``, ``BETWEEN``, ``IN``, ``AND``, ``OR``, or ``NOT``. :param str update_expression: An expression that defines one or more attributes to be updated, the action to be performed on them, and new value(s) for them. :param dict expression_attribute_names: One or more substitution tokens for attribute names in an expression. :param dict expression_attribute_values: One or more values that can be substituted in an expression. :param str return_consumed_capacity: Determines the level of detail about provisioned throughput consumption that is returned in the response. See the `AWS documentation for ReturnConsumedCapacity <http://docs.aws.amazon.com/ amazondynamodb/latest/APIReference/API_UpdateItem.html#DDB-Update Item-request-ReturnConsumedCapacity>`_ for more information. :param str return_item_collection_metrics: Determines whether item collection metrics are returned. :param str return_values: Use ReturnValues if you want to get the item attributes as they appeared either before or after they were updated. See the `AWS documentation for ReturnValues <http://docs. aws.amazon.com/amazondynamodb/latest/APIReference/ API_UpdateItem.html#DDB-UpdateItem-request-ReturnValues>`_ :rtype: tornado.concurrent.Future .. _UpdateItem: http://docs.aws.amazon.com/amazondynamodb/ latest/APIReference/API_UpdateItem.html
[ "Invoke", "the", "UpdateItem", "_", "function", "." ]
2e202bcb01f23f828f91299599311007054de4aa
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/client.py#L333-L411
train
46,161
sprockets/sprockets-dynamodb
sprockets_dynamodb/client.py
Client.query
def query(self, table_name, index_name=None, consistent_read=None, key_condition_expression=None, filter_expression=None, expression_attribute_names=None, expression_attribute_values=None, projection_expression=None, select=None, exclusive_start_key=None, limit=None, scan_index_forward=True, return_consumed_capacity=None): """A `Query`_ operation uses the primary key of a table or a secondary index to directly access items from that table or index. :param str table_name: The name of the table containing the requested items. :param bool consistent_read: Determines the read consistency model: If set to ``True``, then the operation uses strongly consistent reads; otherwise, the operation uses eventually consistent reads. Strongly consistent reads are not supported on global secondary indexes. If you query a global secondary index with ``consistent_read`` set to ``True``, you will receive a :exc:`~sprockets_dynamodb.exceptions.ValidationException`. :param dict exclusive_start_key: The primary key of the first item that this operation will evaluate. Use the value that was returned for ``LastEvaluatedKey`` in the previous operation. In a parallel scan, a *Scan* request that includes ``exclusive_start_key`` must specify the same segment whose previous *Scan* returned the corresponding value of ``LastEvaluatedKey``. :param dict expression_attribute_names: One or more substitution tokens for attribute names in an expression. :param dict expression_attribute_values: One or more values that can be substituted in an expression. :param str key_condition_expression: The condition that specifies the key value(s) for items to be retrieved by the *Query* action. The condition must perform an equality test on a single partition key value, but can optionally perform one of several comparison tests on a single sort key value. The partition key equality test is required. For examples see `KeyConditionExpression <https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ Query.html#Query.KeyConditionExpressions>. :param str filter_expression: A string that contains conditions that DynamoDB applies after the *Query* operation, but before the data is returned to you. Items that do not satisfy the criteria are not returned. Note that a filter expression is applied after the items have already been read; the process of filtering does not consume any additional read capacity units. For more information, see `Filter Expressions <http://docs.aws.amazon.com/amazondynamodb/ latest/developerguide/QueryAndScan.html#FilteringResults>`_ in the Amazon DynamoDB Developer Guide. :param str projection_expression: :param str index_name: The name of a secondary index to query. This index can be any local secondary index or global secondary index. Note that if you use this parameter, you must also provide ``table_name``. :param int limit: The maximum number of items to evaluate (not necessarily the number of matching items). If DynamoDB processes the number of items up to the limit while processing the results, it stops the operation and returns the matching values up to that point, and a key in ``LastEvaluatedKey`` to apply in a subsequent operation, so that you can pick up where you left off. Also, if the processed data set size exceeds 1 MB before DynamoDB reaches this limit, it stops the operation and returns the matching values up to the limit, and a key in ``LastEvaluatedKey`` to apply in a subsequent operation to continue the operation. For more information, see `Query and Scan <http://docs.aws.amazon.com/amazo ndynamodb/latest/developerguide/QueryAndScan.html>`_ in the Amazon DynamoDB Developer Guide. :param str return_consumed_capacity: Determines the level of detail about provisioned throughput consumption that is returned in the response: - ``INDEXES``: The response includes the aggregate consumed capacity for the operation, together with consumed capacity for each table and secondary index that was accessed. Note that some operations, such as *GetItem* and *BatchGetItem*, do not access any indexes at all. In these cases, specifying ``INDEXES`` will only return consumed capacity information for table(s). - ``TOTAL``: The response includes only the aggregate consumed capacity for the operation. - ``NONE``: No consumed capacity details are included in the response. :param bool scan_index_forward: Specifies the order for index traversal: If ``True`` (default), the traversal is performed in ascending order; if ``False``, the traversal is performed in descending order. Items with the same partition key value are stored in sorted order by sort key. If the sort key data type is *Number*, the results are stored in numeric order. For type *String*, the results are stored in order of ASCII character code values. For type *Binary*, DynamoDB treats each byte of the binary data as unsigned. If set to ``True``, DynamoDB returns the results in the order in which they are stored (by sort key value). This is the default behavior. If set to ``False``, DynamoDB reads the results in reverse order by sort key value, and then returns the results to the client. :param str select: The attributes to be returned in the result. You can retrieve all item attributes, specific item attributes, the count of matching items, or in the case of an index, some or all of the attributes projected into the index. Possible values are: - ``ALL_ATTRIBUTES``: Returns all of the item attributes from the specified table or index. If you query a local secondary index, then for each matching item in the index DynamoDB will fetch the entire item from the parent table. If the index is configured to project all item attributes, then all of the data can be obtained from the local secondary index, and no fetching is required. - ``ALL_PROJECTED_ATTRIBUTES``: Allowed only when querying an index. Retrieves all attributes that have been projected into the index. If the index is configured to project all attributes, this return value is equivalent to specifying ``ALL_ATTRIBUTES``. - ``COUNT``: Returns the number of matching items, rather than the matching items themselves. :rtype: dict .. _Query: http://docs.aws.amazon.com/amazondynamodb/ latest/APIReference/API_Query.html """ payload = {'TableName': table_name, 'ScanIndexForward': scan_index_forward} if index_name: payload['IndexName'] = index_name if consistent_read is not None: payload['ConsistentRead'] = consistent_read if key_condition_expression: payload['KeyConditionExpression'] = key_condition_expression if filter_expression: payload['FilterExpression'] = filter_expression if expression_attribute_names: payload['ExpressionAttributeNames'] = expression_attribute_names if expression_attribute_values: payload['ExpressionAttributeValues'] = \ utils.marshall(expression_attribute_values) if projection_expression: payload['ProjectionExpression'] = projection_expression if select: _validate_select(select) payload['Select'] = select if exclusive_start_key: payload['ExclusiveStartKey'] = utils.marshall(exclusive_start_key) if limit: payload['Limit'] = limit if return_consumed_capacity: _validate_return_consumed_capacity(return_consumed_capacity) payload['ReturnConsumedCapacity'] = return_consumed_capacity return self.execute('Query', payload)
python
def query(self, table_name, index_name=None, consistent_read=None, key_condition_expression=None, filter_expression=None, expression_attribute_names=None, expression_attribute_values=None, projection_expression=None, select=None, exclusive_start_key=None, limit=None, scan_index_forward=True, return_consumed_capacity=None): """A `Query`_ operation uses the primary key of a table or a secondary index to directly access items from that table or index. :param str table_name: The name of the table containing the requested items. :param bool consistent_read: Determines the read consistency model: If set to ``True``, then the operation uses strongly consistent reads; otherwise, the operation uses eventually consistent reads. Strongly consistent reads are not supported on global secondary indexes. If you query a global secondary index with ``consistent_read`` set to ``True``, you will receive a :exc:`~sprockets_dynamodb.exceptions.ValidationException`. :param dict exclusive_start_key: The primary key of the first item that this operation will evaluate. Use the value that was returned for ``LastEvaluatedKey`` in the previous operation. In a parallel scan, a *Scan* request that includes ``exclusive_start_key`` must specify the same segment whose previous *Scan* returned the corresponding value of ``LastEvaluatedKey``. :param dict expression_attribute_names: One or more substitution tokens for attribute names in an expression. :param dict expression_attribute_values: One or more values that can be substituted in an expression. :param str key_condition_expression: The condition that specifies the key value(s) for items to be retrieved by the *Query* action. The condition must perform an equality test on a single partition key value, but can optionally perform one of several comparison tests on a single sort key value. The partition key equality test is required. For examples see `KeyConditionExpression <https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ Query.html#Query.KeyConditionExpressions>. :param str filter_expression: A string that contains conditions that DynamoDB applies after the *Query* operation, but before the data is returned to you. Items that do not satisfy the criteria are not returned. Note that a filter expression is applied after the items have already been read; the process of filtering does not consume any additional read capacity units. For more information, see `Filter Expressions <http://docs.aws.amazon.com/amazondynamodb/ latest/developerguide/QueryAndScan.html#FilteringResults>`_ in the Amazon DynamoDB Developer Guide. :param str projection_expression: :param str index_name: The name of a secondary index to query. This index can be any local secondary index or global secondary index. Note that if you use this parameter, you must also provide ``table_name``. :param int limit: The maximum number of items to evaluate (not necessarily the number of matching items). If DynamoDB processes the number of items up to the limit while processing the results, it stops the operation and returns the matching values up to that point, and a key in ``LastEvaluatedKey`` to apply in a subsequent operation, so that you can pick up where you left off. Also, if the processed data set size exceeds 1 MB before DynamoDB reaches this limit, it stops the operation and returns the matching values up to the limit, and a key in ``LastEvaluatedKey`` to apply in a subsequent operation to continue the operation. For more information, see `Query and Scan <http://docs.aws.amazon.com/amazo ndynamodb/latest/developerguide/QueryAndScan.html>`_ in the Amazon DynamoDB Developer Guide. :param str return_consumed_capacity: Determines the level of detail about provisioned throughput consumption that is returned in the response: - ``INDEXES``: The response includes the aggregate consumed capacity for the operation, together with consumed capacity for each table and secondary index that was accessed. Note that some operations, such as *GetItem* and *BatchGetItem*, do not access any indexes at all. In these cases, specifying ``INDEXES`` will only return consumed capacity information for table(s). - ``TOTAL``: The response includes only the aggregate consumed capacity for the operation. - ``NONE``: No consumed capacity details are included in the response. :param bool scan_index_forward: Specifies the order for index traversal: If ``True`` (default), the traversal is performed in ascending order; if ``False``, the traversal is performed in descending order. Items with the same partition key value are stored in sorted order by sort key. If the sort key data type is *Number*, the results are stored in numeric order. For type *String*, the results are stored in order of ASCII character code values. For type *Binary*, DynamoDB treats each byte of the binary data as unsigned. If set to ``True``, DynamoDB returns the results in the order in which they are stored (by sort key value). This is the default behavior. If set to ``False``, DynamoDB reads the results in reverse order by sort key value, and then returns the results to the client. :param str select: The attributes to be returned in the result. You can retrieve all item attributes, specific item attributes, the count of matching items, or in the case of an index, some or all of the attributes projected into the index. Possible values are: - ``ALL_ATTRIBUTES``: Returns all of the item attributes from the specified table or index. If you query a local secondary index, then for each matching item in the index DynamoDB will fetch the entire item from the parent table. If the index is configured to project all item attributes, then all of the data can be obtained from the local secondary index, and no fetching is required. - ``ALL_PROJECTED_ATTRIBUTES``: Allowed only when querying an index. Retrieves all attributes that have been projected into the index. If the index is configured to project all attributes, this return value is equivalent to specifying ``ALL_ATTRIBUTES``. - ``COUNT``: Returns the number of matching items, rather than the matching items themselves. :rtype: dict .. _Query: http://docs.aws.amazon.com/amazondynamodb/ latest/APIReference/API_Query.html """ payload = {'TableName': table_name, 'ScanIndexForward': scan_index_forward} if index_name: payload['IndexName'] = index_name if consistent_read is not None: payload['ConsistentRead'] = consistent_read if key_condition_expression: payload['KeyConditionExpression'] = key_condition_expression if filter_expression: payload['FilterExpression'] = filter_expression if expression_attribute_names: payload['ExpressionAttributeNames'] = expression_attribute_names if expression_attribute_values: payload['ExpressionAttributeValues'] = \ utils.marshall(expression_attribute_values) if projection_expression: payload['ProjectionExpression'] = projection_expression if select: _validate_select(select) payload['Select'] = select if exclusive_start_key: payload['ExclusiveStartKey'] = utils.marshall(exclusive_start_key) if limit: payload['Limit'] = limit if return_consumed_capacity: _validate_return_consumed_capacity(return_consumed_capacity) payload['ReturnConsumedCapacity'] = return_consumed_capacity return self.execute('Query', payload)
[ "def", "query", "(", "self", ",", "table_name", ",", "index_name", "=", "None", ",", "consistent_read", "=", "None", ",", "key_condition_expression", "=", "None", ",", "filter_expression", "=", "None", ",", "expression_attribute_names", "=", "None", ",", "expres...
A `Query`_ operation uses the primary key of a table or a secondary index to directly access items from that table or index. :param str table_name: The name of the table containing the requested items. :param bool consistent_read: Determines the read consistency model: If set to ``True``, then the operation uses strongly consistent reads; otherwise, the operation uses eventually consistent reads. Strongly consistent reads are not supported on global secondary indexes. If you query a global secondary index with ``consistent_read`` set to ``True``, you will receive a :exc:`~sprockets_dynamodb.exceptions.ValidationException`. :param dict exclusive_start_key: The primary key of the first item that this operation will evaluate. Use the value that was returned for ``LastEvaluatedKey`` in the previous operation. In a parallel scan, a *Scan* request that includes ``exclusive_start_key`` must specify the same segment whose previous *Scan* returned the corresponding value of ``LastEvaluatedKey``. :param dict expression_attribute_names: One or more substitution tokens for attribute names in an expression. :param dict expression_attribute_values: One or more values that can be substituted in an expression. :param str key_condition_expression: The condition that specifies the key value(s) for items to be retrieved by the *Query* action. The condition must perform an equality test on a single partition key value, but can optionally perform one of several comparison tests on a single sort key value. The partition key equality test is required. For examples see `KeyConditionExpression <https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ Query.html#Query.KeyConditionExpressions>. :param str filter_expression: A string that contains conditions that DynamoDB applies after the *Query* operation, but before the data is returned to you. Items that do not satisfy the criteria are not returned. Note that a filter expression is applied after the items have already been read; the process of filtering does not consume any additional read capacity units. For more information, see `Filter Expressions <http://docs.aws.amazon.com/amazondynamodb/ latest/developerguide/QueryAndScan.html#FilteringResults>`_ in the Amazon DynamoDB Developer Guide. :param str projection_expression: :param str index_name: The name of a secondary index to query. This index can be any local secondary index or global secondary index. Note that if you use this parameter, you must also provide ``table_name``. :param int limit: The maximum number of items to evaluate (not necessarily the number of matching items). If DynamoDB processes the number of items up to the limit while processing the results, it stops the operation and returns the matching values up to that point, and a key in ``LastEvaluatedKey`` to apply in a subsequent operation, so that you can pick up where you left off. Also, if the processed data set size exceeds 1 MB before DynamoDB reaches this limit, it stops the operation and returns the matching values up to the limit, and a key in ``LastEvaluatedKey`` to apply in a subsequent operation to continue the operation. For more information, see `Query and Scan <http://docs.aws.amazon.com/amazo ndynamodb/latest/developerguide/QueryAndScan.html>`_ in the Amazon DynamoDB Developer Guide. :param str return_consumed_capacity: Determines the level of detail about provisioned throughput consumption that is returned in the response: - ``INDEXES``: The response includes the aggregate consumed capacity for the operation, together with consumed capacity for each table and secondary index that was accessed. Note that some operations, such as *GetItem* and *BatchGetItem*, do not access any indexes at all. In these cases, specifying ``INDEXES`` will only return consumed capacity information for table(s). - ``TOTAL``: The response includes only the aggregate consumed capacity for the operation. - ``NONE``: No consumed capacity details are included in the response. :param bool scan_index_forward: Specifies the order for index traversal: If ``True`` (default), the traversal is performed in ascending order; if ``False``, the traversal is performed in descending order. Items with the same partition key value are stored in sorted order by sort key. If the sort key data type is *Number*, the results are stored in numeric order. For type *String*, the results are stored in order of ASCII character code values. For type *Binary*, DynamoDB treats each byte of the binary data as unsigned. If set to ``True``, DynamoDB returns the results in the order in which they are stored (by sort key value). This is the default behavior. If set to ``False``, DynamoDB reads the results in reverse order by sort key value, and then returns the results to the client. :param str select: The attributes to be returned in the result. You can retrieve all item attributes, specific item attributes, the count of matching items, or in the case of an index, some or all of the attributes projected into the index. Possible values are: - ``ALL_ATTRIBUTES``: Returns all of the item attributes from the specified table or index. If you query a local secondary index, then for each matching item in the index DynamoDB will fetch the entire item from the parent table. If the index is configured to project all item attributes, then all of the data can be obtained from the local secondary index, and no fetching is required. - ``ALL_PROJECTED_ATTRIBUTES``: Allowed only when querying an index. Retrieves all attributes that have been projected into the index. If the index is configured to project all attributes, this return value is equivalent to specifying ``ALL_ATTRIBUTES``. - ``COUNT``: Returns the number of matching items, rather than the matching items themselves. :rtype: dict .. _Query: http://docs.aws.amazon.com/amazondynamodb/ latest/APIReference/API_Query.html
[ "A", "Query", "_", "operation", "uses", "the", "primary", "key", "of", "a", "table", "or", "a", "secondary", "index", "to", "directly", "access", "items", "from", "that", "table", "or", "index", "." ]
2e202bcb01f23f828f91299599311007054de4aa
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/client.py#L502-L653
train
46,162
sprockets/sprockets-dynamodb
sprockets_dynamodb/client.py
Client.scan
def scan(self, table_name, index_name=None, consistent_read=None, projection_expression=None, filter_expression=None, expression_attribute_names=None, expression_attribute_values=None, segment=None, total_segments=None, select=None, limit=None, exclusive_start_key=None, return_consumed_capacity=None): """The `Scan`_ operation returns one or more items and item attributes by accessing every item in a table or a secondary index. If the total number of scanned items exceeds the maximum data set size limit of 1 MB, the scan stops and results are returned to the user as a ``LastEvaluatedKey`` value to continue the scan in a subsequent operation. The results also include the number of items exceeding the limit. A scan can result in no table data meeting the filter criteria. By default, Scan operations proceed sequentially; however, for faster performance on a large table or secondary index, applications can request a parallel *Scan* operation by providing the ``segment`` and ``total_segments`` parameters. For more information, see `Parallel Scan <http://docs.aws.amazon.com/amazondynamodb/latest/ developerguide/QueryAndScan.html#QueryAndScanParallelScan>`_ in the Amazon DynamoDB Developer Guide. By default, *Scan* uses eventually consistent reads when accessing the data in a table; therefore, the result set might not include the changes to data in the table immediately before the operation began. If you need a consistent copy of the data, as of the time that the *Scan* begins, you can set the ``consistent_read`` parameter to ``True``. :rtype: dict .. _Scan: http://docs.aws.amazon.com/amazondynamodb/ latest/APIReference/API_Scan.html """ payload = {'TableName': table_name} if index_name: payload['IndexName'] = index_name if consistent_read is not None: payload['ConsistentRead'] = consistent_read if filter_expression: payload['FilterExpression'] = filter_expression if expression_attribute_names: payload['ExpressionAttributeNames'] = expression_attribute_names if expression_attribute_values: payload['ExpressionAttributeValues'] = \ utils.marshall(expression_attribute_values) if projection_expression: payload['ProjectionExpression'] = projection_expression if segment: payload['Segment'] = segment if total_segments: payload['TotalSegments'] = total_segments if select: _validate_select(select) payload['Select'] = select if exclusive_start_key: payload['ExclusiveStartKey'] = utils.marshall(exclusive_start_key) if limit: payload['Limit'] = limit if return_consumed_capacity: _validate_return_consumed_capacity(return_consumed_capacity) payload['ReturnConsumedCapacity'] = return_consumed_capacity return self.execute('Scan', payload)
python
def scan(self, table_name, index_name=None, consistent_read=None, projection_expression=None, filter_expression=None, expression_attribute_names=None, expression_attribute_values=None, segment=None, total_segments=None, select=None, limit=None, exclusive_start_key=None, return_consumed_capacity=None): """The `Scan`_ operation returns one or more items and item attributes by accessing every item in a table or a secondary index. If the total number of scanned items exceeds the maximum data set size limit of 1 MB, the scan stops and results are returned to the user as a ``LastEvaluatedKey`` value to continue the scan in a subsequent operation. The results also include the number of items exceeding the limit. A scan can result in no table data meeting the filter criteria. By default, Scan operations proceed sequentially; however, for faster performance on a large table or secondary index, applications can request a parallel *Scan* operation by providing the ``segment`` and ``total_segments`` parameters. For more information, see `Parallel Scan <http://docs.aws.amazon.com/amazondynamodb/latest/ developerguide/QueryAndScan.html#QueryAndScanParallelScan>`_ in the Amazon DynamoDB Developer Guide. By default, *Scan* uses eventually consistent reads when accessing the data in a table; therefore, the result set might not include the changes to data in the table immediately before the operation began. If you need a consistent copy of the data, as of the time that the *Scan* begins, you can set the ``consistent_read`` parameter to ``True``. :rtype: dict .. _Scan: http://docs.aws.amazon.com/amazondynamodb/ latest/APIReference/API_Scan.html """ payload = {'TableName': table_name} if index_name: payload['IndexName'] = index_name if consistent_read is not None: payload['ConsistentRead'] = consistent_read if filter_expression: payload['FilterExpression'] = filter_expression if expression_attribute_names: payload['ExpressionAttributeNames'] = expression_attribute_names if expression_attribute_values: payload['ExpressionAttributeValues'] = \ utils.marshall(expression_attribute_values) if projection_expression: payload['ProjectionExpression'] = projection_expression if segment: payload['Segment'] = segment if total_segments: payload['TotalSegments'] = total_segments if select: _validate_select(select) payload['Select'] = select if exclusive_start_key: payload['ExclusiveStartKey'] = utils.marshall(exclusive_start_key) if limit: payload['Limit'] = limit if return_consumed_capacity: _validate_return_consumed_capacity(return_consumed_capacity) payload['ReturnConsumedCapacity'] = return_consumed_capacity return self.execute('Scan', payload)
[ "def", "scan", "(", "self", ",", "table_name", ",", "index_name", "=", "None", ",", "consistent_read", "=", "None", ",", "projection_expression", "=", "None", ",", "filter_expression", "=", "None", ",", "expression_attribute_names", "=", "None", ",", "expression...
The `Scan`_ operation returns one or more items and item attributes by accessing every item in a table or a secondary index. If the total number of scanned items exceeds the maximum data set size limit of 1 MB, the scan stops and results are returned to the user as a ``LastEvaluatedKey`` value to continue the scan in a subsequent operation. The results also include the number of items exceeding the limit. A scan can result in no table data meeting the filter criteria. By default, Scan operations proceed sequentially; however, for faster performance on a large table or secondary index, applications can request a parallel *Scan* operation by providing the ``segment`` and ``total_segments`` parameters. For more information, see `Parallel Scan <http://docs.aws.amazon.com/amazondynamodb/latest/ developerguide/QueryAndScan.html#QueryAndScanParallelScan>`_ in the Amazon DynamoDB Developer Guide. By default, *Scan* uses eventually consistent reads when accessing the data in a table; therefore, the result set might not include the changes to data in the table immediately before the operation began. If you need a consistent copy of the data, as of the time that the *Scan* begins, you can set the ``consistent_read`` parameter to ``True``. :rtype: dict .. _Scan: http://docs.aws.amazon.com/amazondynamodb/ latest/APIReference/API_Scan.html
[ "The", "Scan", "_", "operation", "returns", "one", "or", "more", "items", "and", "item", "attributes", "by", "accessing", "every", "item", "in", "a", "table", "or", "a", "secondary", "index", "." ]
2e202bcb01f23f828f91299599311007054de4aa
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/client.py#L655-L726
train
46,163
sprockets/sprockets-dynamodb
sprockets_dynamodb/client.py
Client.execute
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: parameters to send into the action :rtype: tornado.concurrent.Future This method creates a future that will resolve to the result of calling the specified DynamoDB function. It does it's best to unwrap the response from the function to make life a little easier for you. It does this for the ``GetItem`` and ``Query`` functions currently. :raises: :exc:`~sprockets_dynamodb.exceptions.DynamoDBException` :exc:`~sprockets_dynamodb.exceptions.ConfigNotFound` :exc:`~sprockets_dynamodb.exceptions.NoCredentialsError` :exc:`~sprockets_dynamodb.exceptions.NoProfileError` :exc:`~sprockets_dynamodb.exceptions.TimeoutException` :exc:`~sprockets_dynamodb.exceptions.RequestException` :exc:`~sprockets_dynamodb.exceptions.InternalFailure` :exc:`~sprockets_dynamodb.exceptions.LimitExceeded` :exc:`~sprockets_dynamodb.exceptions.MissingParameter` :exc:`~sprockets_dynamodb.exceptions.OptInRequired` :exc:`~sprockets_dynamodb.exceptions.ResourceInUse` :exc:`~sprockets_dynamodb.exceptions.RequestExpired` :exc:`~sprockets_dynamodb.exceptions.ResourceNotFound` :exc:`~sprockets_dynamodb.exceptions.ServiceUnavailable` :exc:`~sprockets_dynamodb.exceptions.ThroughputExceeded` :exc:`~sprockets_dynamodb.exceptions.ValidationException` """ measurements = collections.deque([], self._max_retries) for attempt in range(1, self._max_retries + 1): try: result = yield self._execute( action, parameters, attempt, measurements) except (exceptions.InternalServerError, exceptions.RequestException, exceptions.ThrottlingException, exceptions.ThroughputExceeded, exceptions.ServiceUnavailable) as error: if attempt == self._max_retries: if self._instrumentation_callback: self._instrumentation_callback(measurements) self._on_exception(error) duration = self._sleep_duration(attempt) self.logger.warning('%r on attempt %i, sleeping %.2f seconds', error, attempt, duration) yield gen.sleep(duration) except exceptions.DynamoDBException as error: if self._instrumentation_callback: self._instrumentation_callback(measurements) self._on_exception(error) else: if self._instrumentation_callback: self._instrumentation_callback(measurements) self.logger.debug('%s result: %r', action, result) raise gen.Return(_unwrap_result(action, result))
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: parameters to send into the action :rtype: tornado.concurrent.Future This method creates a future that will resolve to the result of calling the specified DynamoDB function. It does it's best to unwrap the response from the function to make life a little easier for you. It does this for the ``GetItem`` and ``Query`` functions currently. :raises: :exc:`~sprockets_dynamodb.exceptions.DynamoDBException` :exc:`~sprockets_dynamodb.exceptions.ConfigNotFound` :exc:`~sprockets_dynamodb.exceptions.NoCredentialsError` :exc:`~sprockets_dynamodb.exceptions.NoProfileError` :exc:`~sprockets_dynamodb.exceptions.TimeoutException` :exc:`~sprockets_dynamodb.exceptions.RequestException` :exc:`~sprockets_dynamodb.exceptions.InternalFailure` :exc:`~sprockets_dynamodb.exceptions.LimitExceeded` :exc:`~sprockets_dynamodb.exceptions.MissingParameter` :exc:`~sprockets_dynamodb.exceptions.OptInRequired` :exc:`~sprockets_dynamodb.exceptions.ResourceInUse` :exc:`~sprockets_dynamodb.exceptions.RequestExpired` :exc:`~sprockets_dynamodb.exceptions.ResourceNotFound` :exc:`~sprockets_dynamodb.exceptions.ServiceUnavailable` :exc:`~sprockets_dynamodb.exceptions.ThroughputExceeded` :exc:`~sprockets_dynamodb.exceptions.ValidationException` """ measurements = collections.deque([], self._max_retries) for attempt in range(1, self._max_retries + 1): try: result = yield self._execute( action, parameters, attempt, measurements) except (exceptions.InternalServerError, exceptions.RequestException, exceptions.ThrottlingException, exceptions.ThroughputExceeded, exceptions.ServiceUnavailable) as error: if attempt == self._max_retries: if self._instrumentation_callback: self._instrumentation_callback(measurements) self._on_exception(error) duration = self._sleep_duration(attempt) self.logger.warning('%r on attempt %i, sleeping %.2f seconds', error, attempt, duration) yield gen.sleep(duration) except exceptions.DynamoDBException as error: if self._instrumentation_callback: self._instrumentation_callback(measurements) self._on_exception(error) else: if self._instrumentation_callback: self._instrumentation_callback(measurements) self.logger.debug('%s result: %r', action, result) raise gen.Return(_unwrap_result(action, result))
[ "def", "execute", "(", "self", ",", "action", ",", "parameters", ")", ":", "measurements", "=", "collections", ".", "deque", "(", "[", "]", ",", "self", ".", "_max_retries", ")", "for", "attempt", "in", "range", "(", "1", ",", "self", ".", "_max_retrie...
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: parameters to send into the action :rtype: tornado.concurrent.Future This method creates a future that will resolve to the result of calling the specified DynamoDB function. It does it's best to unwrap the response from the function to make life a little easier for you. It does this for the ``GetItem`` and ``Query`` functions currently. :raises: :exc:`~sprockets_dynamodb.exceptions.DynamoDBException` :exc:`~sprockets_dynamodb.exceptions.ConfigNotFound` :exc:`~sprockets_dynamodb.exceptions.NoCredentialsError` :exc:`~sprockets_dynamodb.exceptions.NoProfileError` :exc:`~sprockets_dynamodb.exceptions.TimeoutException` :exc:`~sprockets_dynamodb.exceptions.RequestException` :exc:`~sprockets_dynamodb.exceptions.InternalFailure` :exc:`~sprockets_dynamodb.exceptions.LimitExceeded` :exc:`~sprockets_dynamodb.exceptions.MissingParameter` :exc:`~sprockets_dynamodb.exceptions.OptInRequired` :exc:`~sprockets_dynamodb.exceptions.ResourceInUse` :exc:`~sprockets_dynamodb.exceptions.RequestExpired` :exc:`~sprockets_dynamodb.exceptions.ResourceNotFound` :exc:`~sprockets_dynamodb.exceptions.ServiceUnavailable` :exc:`~sprockets_dynamodb.exceptions.ThroughputExceeded` :exc:`~sprockets_dynamodb.exceptions.ValidationException`
[ "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", "." ]
2e202bcb01f23f828f91299599311007054de4aa
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/client.py#L729-L790
train
46,164
sprockets/sprockets-dynamodb
sprockets_dynamodb/client.py
Client.set_error_callback
def set_error_callback(self, callback): """Assign a method to invoke when a request has encountered an unrecoverable error in an action execution. :param method callback: The method to invoke """ self.logger.debug('Setting error callback: %r', callback) self._on_error = callback
python
def set_error_callback(self, callback): """Assign a method to invoke when a request has encountered an unrecoverable error in an action execution. :param method callback: The method to invoke """ self.logger.debug('Setting error callback: %r', callback) self._on_error = callback
[ "def", "set_error_callback", "(", "self", ",", "callback", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Setting error callback: %r'", ",", "callback", ")", "self", ".", "_on_error", "=", "callback" ]
Assign a method to invoke when a request has encountered an unrecoverable error in an action execution. :param method callback: The method to invoke
[ "Assign", "a", "method", "to", "invoke", "when", "a", "request", "has", "encountered", "an", "unrecoverable", "error", "in", "an", "action", "execution", "." ]
2e202bcb01f23f828f91299599311007054de4aa
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/client.py#L792-L800
train
46,165
sprockets/sprockets-dynamodb
sprockets_dynamodb/client.py
Client.set_instrumentation_callback
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_callback = callback
python
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_callback = callback
[ "def", "set_instrumentation_callback", "(", "self", ",", "callback", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Setting instrumentation callback: %r'", ",", "callback", ")", "self", ".", "_instrumentation_callback", "=", "callback" ]
Assign a method to invoke when a request has completed gathering measurements. :param method callback: The method to invoke
[ "Assign", "a", "method", "to", "invoke", "when", "a", "request", "has", "completed", "gathering", "measurements", "." ]
2e202bcb01f23f828f91299599311007054de4aa
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/client.py#L802-L810
train
46,166
sprockets/sprockets-dynamodb
sprockets_dynamodb/client.py
Client._execute
def _execute(self, action, parameters, attempt, measurements): """Invoke a DynamoDB action :param str action: DynamoDB action to invoke :param dict parameters: parameters to send into the action :param int attempt: Which attempt number this is :param list measurements: A list for accumulating request measurements :rtype: tornado.concurrent.Future """ future = concurrent.Future() start = time.time() def handle_response(request): """Invoked by the IOLoop when fetch has a response to process. :param tornado.concurrent.Future request: The request future """ self._on_response( action, parameters.get('TableName', 'Unknown'), attempt, start, request, future, measurements) ioloop.IOLoop.current().add_future(self._client.fetch( 'POST', '/', body=json.dumps(parameters).encode('utf-8'), headers={ 'x-amz-target': 'DynamoDB_20120810.{}'.format(action), 'Content-Type': 'application/x-amz-json-1.0', }), handle_response) return future
python
def _execute(self, action, parameters, attempt, measurements): """Invoke a DynamoDB action :param str action: DynamoDB action to invoke :param dict parameters: parameters to send into the action :param int attempt: Which attempt number this is :param list measurements: A list for accumulating request measurements :rtype: tornado.concurrent.Future """ future = concurrent.Future() start = time.time() def handle_response(request): """Invoked by the IOLoop when fetch has a response to process. :param tornado.concurrent.Future request: The request future """ self._on_response( action, parameters.get('TableName', 'Unknown'), attempt, start, request, future, measurements) ioloop.IOLoop.current().add_future(self._client.fetch( 'POST', '/', body=json.dumps(parameters).encode('utf-8'), headers={ 'x-amz-target': 'DynamoDB_20120810.{}'.format(action), 'Content-Type': 'application/x-amz-json-1.0', }), handle_response) return future
[ "def", "_execute", "(", "self", ",", "action", ",", "parameters", ",", "attempt", ",", "measurements", ")", ":", "future", "=", "concurrent", ".", "Future", "(", ")", "start", "=", "time", ".", "time", "(", ")", "def", "handle_response", "(", "request", ...
Invoke a DynamoDB action :param str action: DynamoDB action to invoke :param dict parameters: parameters to send into the action :param int attempt: Which attempt number this is :param list measurements: A list for accumulating request measurements :rtype: tornado.concurrent.Future
[ "Invoke", "a", "DynamoDB", "action" ]
2e202bcb01f23f828f91299599311007054de4aa
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/client.py#L812-L842
train
46,167
sprockets/sprockets-dynamodb
sprockets_dynamodb/client.py
Client._on_response
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 action: The action that was taken :param str table: The table name the action was made against :param int attempt: The attempt number for the action :param float start: When the request was submitted :param tornado.concurrent.Future response: The HTTP request future :param tornado.concurrent.Future future: The action execution future :param list measurements: The measurement accumulator """ self.logger.debug('%s on %s request #%i = %r', action, table, attempt, response) now, exception = time.time(), None try: future.set_result(self._process_response(response)) except aws_exceptions.ConfigNotFound as error: exception = exceptions.ConfigNotFound(str(error)) except aws_exceptions.ConfigParserError as error: exception = exceptions.ConfigParserError(str(error)) except aws_exceptions.NoCredentialsError as error: exception = exceptions.NoCredentialsError(str(error)) except aws_exceptions.NoProfileError as error: exception = exceptions.NoProfileError(str(error)) except aws_exceptions.AWSError as error: exception = exceptions.DynamoDBException(error) except (ConnectionError, ConnectionResetError, OSError, aws_exceptions.RequestException, ssl.SSLError, _select.error, ssl.socket_error, socket.gaierror) as error: exception = exceptions.RequestException(str(error)) except TimeoutError: exception = exceptions.TimeoutException() except httpclient.HTTPError as error: if error.code == 599: exception = exceptions.TimeoutException() else: exception = exceptions.RequestException( getattr(getattr(error, 'response', error), 'body', str(error.code))) except Exception as error: exception = error if exception: future.set_exception(exception) measurements.append( Measurement(now, action, table, attempt, max(now, start) - start, exception.__class__.__name__ if exception else exception))
python
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 action: The action that was taken :param str table: The table name the action was made against :param int attempt: The attempt number for the action :param float start: When the request was submitted :param tornado.concurrent.Future response: The HTTP request future :param tornado.concurrent.Future future: The action execution future :param list measurements: The measurement accumulator """ self.logger.debug('%s on %s request #%i = %r', action, table, attempt, response) now, exception = time.time(), None try: future.set_result(self._process_response(response)) except aws_exceptions.ConfigNotFound as error: exception = exceptions.ConfigNotFound(str(error)) except aws_exceptions.ConfigParserError as error: exception = exceptions.ConfigParserError(str(error)) except aws_exceptions.NoCredentialsError as error: exception = exceptions.NoCredentialsError(str(error)) except aws_exceptions.NoProfileError as error: exception = exceptions.NoProfileError(str(error)) except aws_exceptions.AWSError as error: exception = exceptions.DynamoDBException(error) except (ConnectionError, ConnectionResetError, OSError, aws_exceptions.RequestException, ssl.SSLError, _select.error, ssl.socket_error, socket.gaierror) as error: exception = exceptions.RequestException(str(error)) except TimeoutError: exception = exceptions.TimeoutException() except httpclient.HTTPError as error: if error.code == 599: exception = exceptions.TimeoutException() else: exception = exceptions.RequestException( getattr(getattr(error, 'response', error), 'body', str(error.code))) except Exception as error: exception = error if exception: future.set_exception(exception) measurements.append( Measurement(now, action, table, attempt, max(now, start) - start, exception.__class__.__name__ if exception else exception))
[ "def", "_on_response", "(", "self", ",", "action", ",", "table", ",", "attempt", ",", "start", ",", "response", ",", "future", ",", "measurements", ")", ":", "self", ".", "logger", ".", "debug", "(", "'%s on %s request #%i = %r'", ",", "action", ",", "tabl...
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 action: The action that was taken :param str table: The table name the action was made against :param int attempt: The attempt number for the action :param float start: When the request was submitted :param tornado.concurrent.Future response: The HTTP request future :param tornado.concurrent.Future future: The action execution future :param list measurements: The measurement accumulator
[ "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", "." ]
2e202bcb01f23f828f91299599311007054de4aa
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/client.py#L855-L907
train
46,168
sprockets/sprockets-dynamodb
sprockets_dynamodb/client.py
Client._process_response
def _process_response(response): """Process the raw AWS response, returning either the mapped exception or deserialized response. :param tornado.concurrent.Future response: The request future :rtype: dict or list :raises: sprockets_dynamodb.exceptions.DynamoDBException """ error = response.exception() if error: if isinstance(error, aws_exceptions.AWSError): if error.args[1]['type'] in exceptions.MAP: raise exceptions.MAP[error.args[1]['type']]( error.args[1]['message']) raise error http_response = response.result() if not http_response or not http_response.body: raise exceptions.DynamoDBException('empty response') return json.loads(http_response.body.decode('utf-8'))
python
def _process_response(response): """Process the raw AWS response, returning either the mapped exception or deserialized response. :param tornado.concurrent.Future response: The request future :rtype: dict or list :raises: sprockets_dynamodb.exceptions.DynamoDBException """ error = response.exception() if error: if isinstance(error, aws_exceptions.AWSError): if error.args[1]['type'] in exceptions.MAP: raise exceptions.MAP[error.args[1]['type']]( error.args[1]['message']) raise error http_response = response.result() if not http_response or not http_response.body: raise exceptions.DynamoDBException('empty response') return json.loads(http_response.body.decode('utf-8'))
[ "def", "_process_response", "(", "response", ")", ":", "error", "=", "response", ".", "exception", "(", ")", "if", "error", ":", "if", "isinstance", "(", "error", ",", "aws_exceptions", ".", "AWSError", ")", ":", "if", "error", ".", "args", "[", "1", "...
Process the raw AWS response, returning either the mapped exception or deserialized response. :param tornado.concurrent.Future response: The request future :rtype: dict or list :raises: sprockets_dynamodb.exceptions.DynamoDBException
[ "Process", "the", "raw", "AWS", "response", "returning", "either", "the", "mapped", "exception", "or", "deserialized", "response", "." ]
2e202bcb01f23f828f91299599311007054de4aa
https://github.com/sprockets/sprockets-dynamodb/blob/2e202bcb01f23f828f91299599311007054de4aa/sprockets_dynamodb/client.py#L910-L929
train
46,169
oceanprotocol/oceandb-bigchaindb-driver
oceandb_bigchaindb_driver/plugin.py
Plugin.write
def write(self, obj, resource_id=None): """Write and obj in bdb. :param obj: value to be written in bdb. :param resource_id: id to make possible read and search for an resource. :return: id of the transaction """ 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.instance.transactions.prepare( operation='CREATE', signers=self.user.public_key, asset={ 'namespace': self.namespace, 'data': obj }, metadata={ 'namespace': self.namespace, 'data': obj } ) signed_tx = self.driver.instance.transactions.fulfill( prepared_creation_tx, private_keys=self.user.private_key ) self.logger.debug('bdb::write::{}'.format(signed_tx['id'])) self.driver.instance.transactions.send_commit(signed_tx) return signed_tx
python
def write(self, obj, resource_id=None): """Write and obj in bdb. :param obj: value to be written in bdb. :param resource_id: id to make possible read and search for an resource. :return: id of the transaction """ 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.instance.transactions.prepare( operation='CREATE', signers=self.user.public_key, asset={ 'namespace': self.namespace, 'data': obj }, metadata={ 'namespace': self.namespace, 'data': obj } ) signed_tx = self.driver.instance.transactions.fulfill( prepared_creation_tx, private_keys=self.user.private_key ) self.logger.debug('bdb::write::{}'.format(signed_tx['id'])) self.driver.instance.transactions.send_commit(signed_tx) return signed_tx
[ "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 ...
Write and obj in bdb. :param obj: value to be written in bdb. :param resource_id: id to make possible read and search for an resource. :return: id of the transaction
[ "Write", "and", "obj", "in", "bdb", "." ]
82315bcc9f7ba8b01beb08014bdeb541546c6671
https://github.com/oceanprotocol/oceandb-bigchaindb-driver/blob/82315bcc9f7ba8b01beb08014bdeb541546c6671/oceandb_bigchaindb_driver/plugin.py#L38-L68
train
46,170
oceanprotocol/oceandb-bigchaindb-driver
oceandb_bigchaindb_driver/plugin.py
Plugin._get
def _get(self, tx_id): """Read and obj in bdb using the tx_id. :param resource_id: id of the transaction to be read. :return: value with the data, transaction id and transaction. """ # tx_id=self._find_tx_id(resource_id) value = [ { 'data': transaction['metadata'], 'id': transaction['id'] } for transaction in self.driver.instance.transactions.get(asset_id=self.get_asset_id(tx_id)) ][-1] if value['data']['data']: self.logger.debug('bdb::read::{}'.format(value['data'])) return value else: return False
python
def _get(self, tx_id): """Read and obj in bdb using the tx_id. :param resource_id: id of the transaction to be read. :return: value with the data, transaction id and transaction. """ # tx_id=self._find_tx_id(resource_id) value = [ { 'data': transaction['metadata'], 'id': transaction['id'] } for transaction in self.driver.instance.transactions.get(asset_id=self.get_asset_id(tx_id)) ][-1] if value['data']['data']: self.logger.debug('bdb::read::{}'.format(value['data'])) return value else: return False
[ "def", "_get", "(", "self", ",", "tx_id", ")", ":", "# tx_id=self._find_tx_id(resource_id)", "value", "=", "[", "{", "'data'", ":", "transaction", "[", "'metadata'", "]", ",", "'id'", ":", "transaction", "[", "'id'", "]", "}", "for", "transaction", "in", "...
Read and obj in bdb using the tx_id. :param resource_id: id of the transaction to be read. :return: value with the data, transaction id and transaction.
[ "Read", "and", "obj", "in", "bdb", "using", "the", "tx_id", "." ]
82315bcc9f7ba8b01beb08014bdeb541546c6671
https://github.com/oceanprotocol/oceandb-bigchaindb-driver/blob/82315bcc9f7ba8b01beb08014bdeb541546c6671/oceandb_bigchaindb_driver/plugin.py#L76-L94
train
46,171
oceanprotocol/oceandb-bigchaindb-driver
oceandb_bigchaindb_driver/plugin.py
Plugin._update
def _update(self, metadata, tx_id, resource_id): """Update and obj in bdb using the tx_id. :param metadata: new metadata for the transaction. :param tx_id: id of the transaction to be updated. :return: id of the transaction. """ try: if not tx_id: sent_tx = self.write(metadata, resource_id) self.logger.debug('bdb::put::{}'.format(sent_tx['id'])) return sent_tx else: txs = self.driver.instance.transactions.get(asset_id=self.get_asset_id(tx_id)) unspent = txs[-1] sent_tx = self._put(metadata, unspent, resource_id) self.logger.debug('bdb::put::{}'.format(sent_tx)) return sent_tx except BadRequest as e: logging.error(e)
python
def _update(self, metadata, tx_id, resource_id): """Update and obj in bdb using the tx_id. :param metadata: new metadata for the transaction. :param tx_id: id of the transaction to be updated. :return: id of the transaction. """ try: if not tx_id: sent_tx = self.write(metadata, resource_id) self.logger.debug('bdb::put::{}'.format(sent_tx['id'])) return sent_tx else: txs = self.driver.instance.transactions.get(asset_id=self.get_asset_id(tx_id)) unspent = txs[-1] sent_tx = self._put(metadata, unspent, resource_id) self.logger.debug('bdb::put::{}'.format(sent_tx)) return sent_tx except BadRequest as e: logging.error(e)
[ "def", "_update", "(", "self", ",", "metadata", ",", "tx_id", ",", "resource_id", ")", ":", "try", ":", "if", "not", "tx_id", ":", "sent_tx", "=", "self", ".", "write", "(", "metadata", ",", "resource_id", ")", "self", ".", "logger", ".", "debug", "(...
Update and obj in bdb using the tx_id. :param metadata: new metadata for the transaction. :param tx_id: id of the transaction to be updated. :return: id of the transaction.
[ "Update", "and", "obj", "in", "bdb", "using", "the", "tx_id", "." ]
82315bcc9f7ba8b01beb08014bdeb541546c6671
https://github.com/oceanprotocol/oceandb-bigchaindb-driver/blob/82315bcc9f7ba8b01beb08014bdeb541546c6671/oceandb_bigchaindb_driver/plugin.py#L100-L120
train
46,172
oceanprotocol/oceandb-bigchaindb-driver
oceandb_bigchaindb_driver/plugin.py
Plugin.query
def query(self, search_model: QueryModel): """Query to bdb namespace. :param query_string: query in string format. :return: list of transactions that match with the query. """ 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.debug('bdb::result::len {}'.format(len(assets))) assets_metadata = [] for i in assets: try: assets_metadata.append(self._get(i['id'])['data']['data']) except: pass return assets_metadata
python
def query(self, search_model: QueryModel): """Query to bdb namespace. :param query_string: query in string format. :return: list of transactions that match with the query. """ 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.debug('bdb::result::len {}'.format(len(assets))) assets_metadata = [] for i in assets: try: assets_metadata.append(self._get(i['id'])['data']['data']) except: pass return assets_metadata
[ "def", "query", "(", "self", ",", "search_model", ":", "QueryModel", ")", ":", "self", ".", "logger", ".", "debug", "(", "'bdb::get::{}'", ".", "format", "(", "search_model", ".", "query", ")", ")", "assets", "=", "json", ".", "loads", "(", "requests", ...
Query to bdb namespace. :param query_string: query in string format. :return: list of transactions that match with the query.
[ "Query", "to", "bdb", "namespace", "." ]
82315bcc9f7ba8b01beb08014bdeb541546c6671
https://github.com/oceanprotocol/oceandb-bigchaindb-driver/blob/82315bcc9f7ba8b01beb08014bdeb541546c6671/oceandb_bigchaindb_driver/plugin.py#L157-L172
train
46,173
oceanprotocol/oceandb-bigchaindb-driver
oceandb_bigchaindb_driver/plugin.py
Plugin.get_asset_id
def get_asset_id(self, tx_id): """Return the tx_id of the first transaction. :param tx_id: Transaction id to start the recursive search. :return Transaction id parent. """ 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']
python
def get_asset_id(self, tx_id): """Return the tx_id of the first transaction. :param tx_id: Transaction id to start the recursive search. :return Transaction id parent. """ 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']
[ "def", "get_asset_id", "(", "self", ",", "tx_id", ")", ":", "tx", "=", "self", ".", "driver", ".", "instance", ".", "transactions", ".", "retrieve", "(", "txid", "=", "tx_id", ")", "assert", "tx", "is", "not", "None", "return", "tx", "[", "'id'", "]"...
Return the tx_id of the first transaction. :param tx_id: Transaction id to start the recursive search. :return Transaction id parent.
[ "Return", "the", "tx_id", "of", "the", "first", "transaction", "." ]
82315bcc9f7ba8b01beb08014bdeb541546c6671
https://github.com/oceanprotocol/oceandb-bigchaindb-driver/blob/82315bcc9f7ba8b01beb08014bdeb541546c6671/oceandb_bigchaindb_driver/plugin.py#L240-L248
train
46,174
johntruckenbrodt/spatialist
spatialist/envi.py
hdr
def hdr(data, filename): """ write ENVI header files Parameters ---------- data: str or dict the file or dictionary to get the info from filename: str the HDR file to write Returns ------- """ hdrobj = data if isinstance(data, HDRobject) else HDRobject(data) hdrobj.write(filename)
python
def hdr(data, filename): """ write ENVI header files Parameters ---------- data: str or dict the file or dictionary to get the info from filename: str the HDR file to write Returns ------- """ hdrobj = data if isinstance(data, HDRobject) else HDRobject(data) hdrobj.write(filename)
[ "def", "hdr", "(", "data", ",", "filename", ")", ":", "hdrobj", "=", "data", "if", "isinstance", "(", "data", ",", "HDRobject", ")", "else", "HDRobject", "(", "data", ")", "hdrobj", ".", "write", "(", "filename", ")" ]
write ENVI header files Parameters ---------- data: str or dict the file or dictionary to get the info from filename: str the HDR file to write Returns -------
[ "write", "ENVI", "header", "files" ]
007f49296a156de8d7168ad235b5a5b8e8d3633d
https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/envi.py#L12-L28
train
46,175
johntruckenbrodt/spatialist
spatialist/envi.py
HDRobject.write
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__())
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__())
[ "def", "write", "(", "self", ",", "filename", "=", "'same'", ")", ":", "if", "filename", "==", "'same'", ":", "filename", "=", "self", ".", "filename", "if", "not", "filename", ".", "endswith", "(", "'.hdr'", ")", ":", "filename", "+=", "'.hdr'", "with...
write object to an ENVI header file
[ "write", "object", "to", "an", "ENVI", "header", "file" ]
007f49296a156de8d7168ad235b5a5b8e8d3633d
https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/envi.py#L128-L137
train
46,176
MLAB-project/pymlab
examples/I2CSPI_HBSTEP_CAMPAP.py
axis.GoZero
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) self.ReleaseSW()
python
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) self.ReleaseSW()
[ "def", "GoZero", "(", "self", ",", "speed", ")", ":", "self", ".", "ReleaseSW", "(", ")", "spi", ".", "SPI_write_byte", "(", "self", ".", "CS", ",", "0x82", "|", "(", "self", ".", "Dir", "&", "1", ")", ")", "# Go to Zero", "spi", ".", "SPI_write_by...
Go to Zero position
[ "Go", "to", "Zero", "position" ]
d18d858ae83b203defcf2aead0dbd11b3c444658
https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/examples/I2CSPI_HBSTEP_CAMPAP.py#L76-L86
train
46,177
MLAB-project/pymlab
examples/I2CSPI_HBSTEP_CAMPAP.py
axis.ReadStatusBit
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 spi.SPI_write_byte(self.CS, 0x00) data1 = spi.SPI_read_byte() # 2nd byte #print hex(data0), hex(data1) if bit > 7: # extract requested bit OutputBit = (data0 >> (bit - 8)) & 1 else: OutputBit = (data1 >> bit) & 1 return OutputBit
python
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 spi.SPI_write_byte(self.CS, 0x00) data1 = spi.SPI_read_byte() # 2nd byte #print hex(data0), hex(data1) if bit > 7: # extract requested bit OutputBit = (data0 >> (bit - 8)) & 1 else: OutputBit = (data1 >> bit) & 1 return OutputBit
[ "def", "ReadStatusBit", "(", "self", ",", "bit", ")", ":", "spi", ".", "SPI_write_byte", "(", "self", ".", "CS", ",", "0x39", ")", "# Read from address 0x19 (STATUS)", "spi", ".", "SPI_write_byte", "(", "self", ".", "CS", ",", "0x00", ")", "data0", "=", ...
Report given status bit
[ "Report", "given", "status", "bit" ]
d18d858ae83b203defcf2aead0dbd11b3c444658
https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/examples/I2CSPI_HBSTEP_CAMPAP.py#L110-L122
train
46,178
MLAB-project/pymlab
src/pymlab/sensors/bus_translators.py
I2CSPI.SPI_write_byte
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)
python
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)
[ "def", "SPI_write_byte", "(", "self", ",", "chip_select", ",", "data", ")", ":", "self", ".", "bus", ".", "write_byte_data", "(", "self", ".", "address", ",", "chip_select", ",", "data", ")" ]
Writes a data to a SPI device selected by chipselect bit.
[ "Writes", "a", "data", "to", "a", "SPI", "device", "selected", "by", "chipselect", "bit", "." ]
d18d858ae83b203defcf2aead0dbd11b3c444658
https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/src/pymlab/sensors/bus_translators.py#L51-L53
train
46,179
MLAB-project/pymlab
src/pymlab/sensors/bus_translators.py
I2CSPI.SPI_write
def SPI_write(self, chip_select, data): 'Writes data to SPI device selected by chipselect bit. ' dat = list(data) dat.insert(0, chip_select) return self.bus.write_i2c_block(self.address, dat);
python
def SPI_write(self, chip_select, data): 'Writes data to SPI device selected by chipselect bit. ' dat = list(data) dat.insert(0, chip_select) return self.bus.write_i2c_block(self.address, dat);
[ "def", "SPI_write", "(", "self", ",", "chip_select", ",", "data", ")", ":", "dat", "=", "list", "(", "data", ")", "dat", ".", "insert", "(", "0", ",", "chip_select", ")", "return", "self", ".", "bus", ".", "write_i2c_block", "(", "self", ".", "addres...
Writes data to SPI device selected by chipselect bit.
[ "Writes", "data", "to", "SPI", "device", "selected", "by", "chipselect", "bit", "." ]
d18d858ae83b203defcf2aead0dbd11b3c444658
https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/src/pymlab/sensors/bus_translators.py#L60-L64
train
46,180
MLAB-project/pymlab
src/pymlab/sensors/bus_translators.py
I2CSPI.SPI_config
def SPI_config(self,config): 'Configure SPI interface parameters.' self.bus.write_byte_data(self.address, 0xF0, config) return self.bus.read_byte_data(self.address, 0xF0)
python
def SPI_config(self,config): 'Configure SPI interface parameters.' self.bus.write_byte_data(self.address, 0xF0, config) return self.bus.read_byte_data(self.address, 0xF0)
[ "def", "SPI_config", "(", "self", ",", "config", ")", ":", "self", ".", "bus", ".", "write_byte_data", "(", "self", ".", "address", ",", "0xF0", ",", "config", ")", "return", "self", ".", "bus", ".", "read_byte_data", "(", "self", ".", "address", ",", ...
Configure SPI interface parameters.
[ "Configure", "SPI", "interface", "parameters", "." ]
d18d858ae83b203defcf2aead0dbd11b3c444658
https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/src/pymlab/sensors/bus_translators.py#L70-L73
train
46,181
MLAB-project/pymlab
src/pymlab/sensors/bus_translators.py
I2CSPI.GPIO_read
def GPIO_read(self): 'Reads logic state on GPIO enabled slave-selects pins.' self.bus.write_byte_data(self.address, 0xF5, 0x0f) status = self.bus.read_byte(self.address) bits_values = dict([('SS0',status & 0x01 == 0x01),('SS1',status & 0x02 == 0x02),('SS2',status & 0x04 == 0x04),('SS3',status & 0x08 == 0x08)]) return bits_values
python
def GPIO_read(self): 'Reads logic state on GPIO enabled slave-selects pins.' self.bus.write_byte_data(self.address, 0xF5, 0x0f) status = self.bus.read_byte(self.address) bits_values = dict([('SS0',status & 0x01 == 0x01),('SS1',status & 0x02 == 0x02),('SS2',status & 0x04 == 0x04),('SS3',status & 0x08 == 0x08)]) return bits_values
[ "def", "GPIO_read", "(", "self", ")", ":", "self", ".", "bus", ".", "write_byte_data", "(", "self", ".", "address", ",", "0xF5", ",", "0x0f", ")", "status", "=", "self", ".", "bus", ".", "read_byte", "(", "self", ".", "address", ")", "bits_values", "...
Reads logic state on GPIO enabled slave-selects pins.
[ "Reads", "logic", "state", "on", "GPIO", "enabled", "slave", "-", "selects", "pins", "." ]
d18d858ae83b203defcf2aead0dbd11b3c444658
https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/src/pymlab/sensors/bus_translators.py#L87-L92
train
46,182
MLAB-project/pymlab
src/pymlab/sensors/bus_translators.py
I2CSPI.GPIO_config
def GPIO_config(self, gpio_enable, gpio_config): 'Enable or disable slave-select pins as gpio.' self.bus.write_byte_data(self.address, 0xF6, gpio_enable) self.bus.write_byte_data(self.address, 0xF7, gpio_config) return
python
def GPIO_config(self, gpio_enable, gpio_config): 'Enable or disable slave-select pins as gpio.' self.bus.write_byte_data(self.address, 0xF6, gpio_enable) self.bus.write_byte_data(self.address, 0xF7, gpio_config) return
[ "def", "GPIO_config", "(", "self", ",", "gpio_enable", ",", "gpio_config", ")", ":", "self", ".", "bus", ".", "write_byte_data", "(", "self", ".", "address", ",", "0xF6", ",", "gpio_enable", ")", "self", ".", "bus", ".", "write_byte_data", "(", "self", "...
Enable or disable slave-select pins as gpio.
[ "Enable", "or", "disable", "slave", "-", "select", "pins", "as", "gpio", "." ]
d18d858ae83b203defcf2aead0dbd11b3c444658
https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/src/pymlab/sensors/bus_translators.py#L94-L98
train
46,183
MLAB-project/pymlab
src/pymlab/sensors/rps.py
RPS01.get_address
def get_address(self): """ Returns sensors I2C address. """ LOGGER.debug("Reading RPS01A sensor's address.",) return self.bus.read_byte_data(self.address, self.address_reg)
python
def get_address(self): """ Returns sensors I2C address. """ LOGGER.debug("Reading RPS01A sensor's address.",) return self.bus.read_byte_data(self.address, self.address_reg)
[ "def", "get_address", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "\"Reading RPS01A sensor's address.\"", ",", ")", "return", "self", ".", "bus", ".", "read_byte_data", "(", "self", ".", "address", ",", "self", ".", "address_reg", ")" ]
Returns sensors I2C address.
[ "Returns", "sensors", "I2C", "address", "." ]
d18d858ae83b203defcf2aead0dbd11b3c444658
https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/src/pymlab/sensors/rps.py#L34-L39
train
46,184
MLAB-project/pymlab
src/pymlab/sensors/rps.py
RPS01.get_zero_position
def get_zero_position(self): """ Returns programmed zero position in OTP memory. """ LSB = self.bus.read_byte_data(self.address, self.zero_position_MSB) MSB = self.bus.read_byte_data(self.address, self.zero_position_LSB) DATA = (MSB << 6) + LSB return DATA
python
def get_zero_position(self): """ Returns programmed zero position in OTP memory. """ LSB = self.bus.read_byte_data(self.address, self.zero_position_MSB) MSB = self.bus.read_byte_data(self.address, self.zero_position_LSB) DATA = (MSB << 6) + LSB return DATA
[ "def", "get_zero_position", "(", "self", ")", ":", "LSB", "=", "self", ".", "bus", ".", "read_byte_data", "(", "self", ".", "address", ",", "self", ".", "zero_position_MSB", ")", "MSB", "=", "self", ".", "bus", ".", "read_byte_data", "(", "self", ".", ...
Returns programmed zero position in OTP memory.
[ "Returns", "programmed", "zero", "position", "in", "OTP", "memory", "." ]
d18d858ae83b203defcf2aead0dbd11b3c444658
https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/src/pymlab/sensors/rps.py#L41-L49
train
46,185
MLAB-project/pymlab
src/pymlab/sensors/rps.py
RPS01.get_agc_value
def get_agc_value(self): """ Returns sensor's Automatic Gain Control actual value. 0 - Represents high magtetic field 0xFF - Represents low magnetic field """ LOGGER.debug("Reading RPS01A sensor's AGC settings",) return self.bus.read_byte_data(self.address, self.AGC_reg)
python
def get_agc_value(self): """ Returns sensor's Automatic Gain Control actual value. 0 - Represents high magtetic field 0xFF - Represents low magnetic field """ LOGGER.debug("Reading RPS01A sensor's AGC settings",) return self.bus.read_byte_data(self.address, self.AGC_reg)
[ "def", "get_agc_value", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "\"Reading RPS01A sensor's AGC settings\"", ",", ")", "return", "self", ".", "bus", ".", "read_byte_data", "(", "self", ".", "address", ",", "self", ".", "AGC_reg", ")" ]
Returns sensor's Automatic Gain Control actual value. 0 - Represents high magtetic field 0xFF - Represents low magnetic field
[ "Returns", "sensor", "s", "Automatic", "Gain", "Control", "actual", "value", ".", "0", "-", "Represents", "high", "magtetic", "field", "0xFF", "-", "Represents", "low", "magnetic", "field" ]
d18d858ae83b203defcf2aead0dbd11b3c444658
https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/src/pymlab/sensors/rps.py#L75-L82
train
46,186
MLAB-project/pymlab
src/pymlab/sensors/rps.py
RPS01.get_angle
def get_angle(self, verify = False): """ Retuns measured angle in degrees in range 0-360. """ LSB = self.bus.read_byte_data(self.address, self.angle_LSB) MSB = self.bus.read_byte_data(self.address, self.angle_MSB) DATA = (MSB << 6) + LSB if not verify: return (360.0 / 2**14) * DATA else: status = self.get_diagnostics() if not (status['Comp_Low']) and not(status['Comp_High']) and not(status['COF']): return (360.0 / 2**14) * DATA else: return None
python
def get_angle(self, verify = False): """ Retuns measured angle in degrees in range 0-360. """ LSB = self.bus.read_byte_data(self.address, self.angle_LSB) MSB = self.bus.read_byte_data(self.address, self.angle_MSB) DATA = (MSB << 6) + LSB if not verify: return (360.0 / 2**14) * DATA else: status = self.get_diagnostics() if not (status['Comp_Low']) and not(status['Comp_High']) and not(status['COF']): return (360.0 / 2**14) * DATA else: return None
[ "def", "get_angle", "(", "self", ",", "verify", "=", "False", ")", ":", "LSB", "=", "self", ".", "bus", ".", "read_byte_data", "(", "self", ".", "address", ",", "self", ".", "angle_LSB", ")", "MSB", "=", "self", ".", "bus", ".", "read_byte_data", "("...
Retuns measured angle in degrees in range 0-360.
[ "Retuns", "measured", "angle", "in", "degrees", "in", "range", "0", "-", "360", "." ]
d18d858ae83b203defcf2aead0dbd11b3c444658
https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/src/pymlab/sensors/rps.py#L110-L124
train
46,187
vladsaveliev/TargQC
scripts/annotate_bed.py
main
def main(input_bed, output_file, output_features=False, genome=None, only_canonical=False, short=False, extended=False, high_confidence=False, ambiguities_method=False, coding_only=False, collapse_exons=False, work_dir=False, is_debug=False): """ Annotating BED file based on reference features annotations. """ logger.init(is_debug_=is_debug) if not genome: raise click.BadParameter('Error: please, specify genome build name with -g (e.g. `-g hg19`)', param='genome') if short: if extended: raise click.BadParameter('--short and --extended can\'t be set both', param='extended') if output_features: raise click.BadParameter('--short and --output-features can\'t be set both', param='output_features') elif output_features or extended: extended = True short = False if not verify_file(input_bed): click.BadParameter(f'Usage: {__file__} Input_BED_file -g hg19 -o Annotated_BED_file [options]', param='input_bed') input_bed = verify_file(input_bed, is_critical=True, description=f'Input BED file for {__file__}') if work_dir: work_dir = join(adjust_path(work_dir), os.path.splitext(basename(input_bed))[0]) safe_mkdir(work_dir) info(f'Created work directory {work_dir}') else: work_dir = mkdtemp('bed_annotate') debug('Created temporary work directory {work_dir}') input_bed = clean_bed(input_bed, work_dir) input_bed = verify_bed(input_bed, is_critical=True, description=f'Input BED file for {__file__} after cleaning') output_file = adjust_path(output_file) output_file = annotate( input_bed, output_file, work_dir, genome=genome, only_canonical=only_canonical, short=short, extended=extended, high_confidence=high_confidence, collapse_exons=collapse_exons, output_features=output_features, ambiguities_method=ambiguities_method, coding_only=coding_only, is_debug=is_debug) if not work_dir: debug(f'Removing work directory {work_dir}') shutil.rmtree(work_dir) info(f'Done, saved to {output_file}')
python
def main(input_bed, output_file, output_features=False, genome=None, only_canonical=False, short=False, extended=False, high_confidence=False, ambiguities_method=False, coding_only=False, collapse_exons=False, work_dir=False, is_debug=False): """ Annotating BED file based on reference features annotations. """ logger.init(is_debug_=is_debug) if not genome: raise click.BadParameter('Error: please, specify genome build name with -g (e.g. `-g hg19`)', param='genome') if short: if extended: raise click.BadParameter('--short and --extended can\'t be set both', param='extended') if output_features: raise click.BadParameter('--short and --output-features can\'t be set both', param='output_features') elif output_features or extended: extended = True short = False if not verify_file(input_bed): click.BadParameter(f'Usage: {__file__} Input_BED_file -g hg19 -o Annotated_BED_file [options]', param='input_bed') input_bed = verify_file(input_bed, is_critical=True, description=f'Input BED file for {__file__}') if work_dir: work_dir = join(adjust_path(work_dir), os.path.splitext(basename(input_bed))[0]) safe_mkdir(work_dir) info(f'Created work directory {work_dir}') else: work_dir = mkdtemp('bed_annotate') debug('Created temporary work directory {work_dir}') input_bed = clean_bed(input_bed, work_dir) input_bed = verify_bed(input_bed, is_critical=True, description=f'Input BED file for {__file__} after cleaning') output_file = adjust_path(output_file) output_file = annotate( input_bed, output_file, work_dir, genome=genome, only_canonical=only_canonical, short=short, extended=extended, high_confidence=high_confidence, collapse_exons=collapse_exons, output_features=output_features, ambiguities_method=ambiguities_method, coding_only=coding_only, is_debug=is_debug) if not work_dir: debug(f'Removing work directory {work_dir}') shutil.rmtree(work_dir) info(f'Done, saved to {output_file}')
[ "def", "main", "(", "input_bed", ",", "output_file", ",", "output_features", "=", "False", ",", "genome", "=", "None", ",", "only_canonical", "=", "False", ",", "short", "=", "False", ",", "extended", "=", "False", ",", "high_confidence", "=", "False", ","...
Annotating BED file based on reference features annotations.
[ "Annotating", "BED", "file", "based", "on", "reference", "features", "annotations", "." ]
e887c36b2194dbd73c6ea32989b6cb84c6c0e58d
https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/scripts/annotate_bed.py#L33-L79
train
46,188
MLAB-project/pymlab
src/pymlab/sensors/lioncell.py
LIONCELL.StateOfCharge
def StateOfCharge(self): """ % of Full Charge """ return (self.bus.read_byte_data(self.address, 0x02) + self.bus.read_byte_data(self.address, 0x03) * 256)
python
def StateOfCharge(self): """ % of Full Charge """ return (self.bus.read_byte_data(self.address, 0x02) + self.bus.read_byte_data(self.address, 0x03) * 256)
[ "def", "StateOfCharge", "(", "self", ")", ":", "return", "(", "self", ".", "bus", ".", "read_byte_data", "(", "self", ".", "address", ",", "0x02", ")", "+", "self", ".", "bus", ".", "read_byte_data", "(", "self", ".", "address", ",", "0x03", ")", "*"...
% of Full Charge
[ "%", "of", "Full", "Charge" ]
d18d858ae83b203defcf2aead0dbd11b3c444658
https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/src/pymlab/sensors/lioncell.py#L75-L77
train
46,189
MLAB-project/pymlab
src/pymlab/sensors/lioncell.py
LIONCELL.Chemistry
def Chemistry(self): ''' Get cells chemistry ''' length = self.bus.read_byte_data(self.address, 0x79) chem = [] for n in range(length): chem.append(self.bus.read_byte_data(self.address, 0x7A + n)) return chem
python
def Chemistry(self): ''' Get cells chemistry ''' length = self.bus.read_byte_data(self.address, 0x79) chem = [] for n in range(length): chem.append(self.bus.read_byte_data(self.address, 0x7A + n)) return chem
[ "def", "Chemistry", "(", "self", ")", ":", "length", "=", "self", ".", "bus", ".", "read_byte_data", "(", "self", ".", "address", ",", "0x79", ")", "chem", "=", "[", "]", "for", "n", "in", "range", "(", "length", ")", ":", "chem", ".", "append", ...
Get cells chemistry
[ "Get", "cells", "chemistry" ]
d18d858ae83b203defcf2aead0dbd11b3c444658
https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/src/pymlab/sensors/lioncell.py#L96-L102
train
46,190
MLAB-project/pymlab
examples/I2CSPI_BRIDGEADC01.py
BRIDGEADC01.single_read
def single_read(self, register): ''' Reads data from desired register only once. ''' comm_reg = (0b00010 << 3) + register if register == self.AD7730_STATUS_REG: bytes_num = 1 elif register == self.AD7730_DATA_REG: bytes_num = 3 elif register == self.AD7730_MODE_REG: bytes_num = 2 elif register == self.AD7730_FILTER_REG: bytes_num = 3 elif register == self.AD7730_DAC_REG: bytes_num = 1 elif register == self.AD7730_OFFSET_REG: bytes_num = 3 elif register == self.AD7730_GAIN_REG: bytes_num = 3 elif register == self.AD7730_TEST_REG: bytes_num = 3 command = [comm_reg] + ([0x00] * bytes_num) spi.SPI_write(self.CS, command) data = spi.SPI_read(bytes_num + 1) return data[1:]
python
def single_read(self, register): ''' Reads data from desired register only once. ''' comm_reg = (0b00010 << 3) + register if register == self.AD7730_STATUS_REG: bytes_num = 1 elif register == self.AD7730_DATA_REG: bytes_num = 3 elif register == self.AD7730_MODE_REG: bytes_num = 2 elif register == self.AD7730_FILTER_REG: bytes_num = 3 elif register == self.AD7730_DAC_REG: bytes_num = 1 elif register == self.AD7730_OFFSET_REG: bytes_num = 3 elif register == self.AD7730_GAIN_REG: bytes_num = 3 elif register == self.AD7730_TEST_REG: bytes_num = 3 command = [comm_reg] + ([0x00] * bytes_num) spi.SPI_write(self.CS, command) data = spi.SPI_read(bytes_num + 1) return data[1:]
[ "def", "single_read", "(", "self", ",", "register", ")", ":", "comm_reg", "=", "(", "0b00010", "<<", "3", ")", "+", "register", "if", "register", "==", "self", ".", "AD7730_STATUS_REG", ":", "bytes_num", "=", "1", "elif", "register", "==", "self", ".", ...
Reads data from desired register only once.
[ "Reads", "data", "from", "desired", "register", "only", "once", "." ]
d18d858ae83b203defcf2aead0dbd11b3c444658
https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/examples/I2CSPI_BRIDGEADC01.py#L160-L187
train
46,191
MLAB-project/pymlab
examples/I2CSPI_BRIDGEADC01.py
BRIDGEADC01.getStatus
def getStatus(self): """ RDY - Ready Bit. This bit provides the status of the RDY flag from the part. The status and function of this bit is the same as the RDY output pin. A number of events set the RDY bit high as indicated in Table XVIII in datasheet STDY - Steady Bit. This bit is updated when the filter writes a result to the Data Register. If the filter is in FASTStep mode (see Filter Register section) and responding to a step input, the STDY bit remains high as the initial conversion results become available. The RDY output and bit are set low on these initial conversions to indicate that a result is available. If the STDY is high, however, it indicates that the result being provided is not from a fully settled second-stage FIR filter. When the FIR filter has fully settled, the STDY bit will go low coincident with RDY. If the part is never placed into its FASTStep mode, the STDY bit will go low at the first Data Register read and it is not cleared by subsequent Data Register reads. A number of events set the STDY bit high as indicated in Table XVIII. STDY is set high along with RDY by all events in the table except a Data Register read. STBY - Standby Bit. This bit indicates whether the AD7730 is in its Standby Mode or normal mode of operation. The part can be placed in its standby mode using the STANDBY input pin or by writing 011 to the MD2 to MD0 bits of the Mode Register. The power-on/reset status of this bit is 0 assuming the STANDBY pin is high. NOREF - No Reference Bit. If the voltage between the REF IN(+) and REF IN(-) pins is below 0.3 V, or either of these inputs is open-circuit, the NOREF bit goes to 1. If NOREF is active on completion of a conversion, the Data Register is loaded with all 1s. If NOREF is active on completion of a calibration, updating of the calibration registers is inhibited.""" status = self.single_read(self.AD7730_STATUS_REG) bits_values = dict([('NOREF',status[0] & 0x10 == 0x10), ('STBY',status[0] & 0x20 == 0x20), ('STDY',status[0] & 0x40 == 0x40), ('RDY',status[0] & 0x80 == 0x80)]) return bits_values
python
def getStatus(self): """ RDY - Ready Bit. This bit provides the status of the RDY flag from the part. The status and function of this bit is the same as the RDY output pin. A number of events set the RDY bit high as indicated in Table XVIII in datasheet STDY - Steady Bit. This bit is updated when the filter writes a result to the Data Register. If the filter is in FASTStep mode (see Filter Register section) and responding to a step input, the STDY bit remains high as the initial conversion results become available. The RDY output and bit are set low on these initial conversions to indicate that a result is available. If the STDY is high, however, it indicates that the result being provided is not from a fully settled second-stage FIR filter. When the FIR filter has fully settled, the STDY bit will go low coincident with RDY. If the part is never placed into its FASTStep mode, the STDY bit will go low at the first Data Register read and it is not cleared by subsequent Data Register reads. A number of events set the STDY bit high as indicated in Table XVIII. STDY is set high along with RDY by all events in the table except a Data Register read. STBY - Standby Bit. This bit indicates whether the AD7730 is in its Standby Mode or normal mode of operation. The part can be placed in its standby mode using the STANDBY input pin or by writing 011 to the MD2 to MD0 bits of the Mode Register. The power-on/reset status of this bit is 0 assuming the STANDBY pin is high. NOREF - No Reference Bit. If the voltage between the REF IN(+) and REF IN(-) pins is below 0.3 V, or either of these inputs is open-circuit, the NOREF bit goes to 1. If NOREF is active on completion of a conversion, the Data Register is loaded with all 1s. If NOREF is active on completion of a calibration, updating of the calibration registers is inhibited.""" status = self.single_read(self.AD7730_STATUS_REG) bits_values = dict([('NOREF',status[0] & 0x10 == 0x10), ('STBY',status[0] & 0x20 == 0x20), ('STDY',status[0] & 0x40 == 0x40), ('RDY',status[0] & 0x80 == 0x80)]) return bits_values
[ "def", "getStatus", "(", "self", ")", ":", "status", "=", "self", ".", "single_read", "(", "self", ".", "AD7730_STATUS_REG", ")", "bits_values", "=", "dict", "(", "[", "(", "'NOREF'", ",", "status", "[", "0", "]", "&", "0x10", "==", "0x10", ")", ",",...
RDY - Ready Bit. This bit provides the status of the RDY flag from the part. The status and function of this bit is the same as the RDY output pin. A number of events set the RDY bit high as indicated in Table XVIII in datasheet STDY - Steady Bit. This bit is updated when the filter writes a result to the Data Register. If the filter is in FASTStep mode (see Filter Register section) and responding to a step input, the STDY bit remains high as the initial conversion results become available. The RDY output and bit are set low on these initial conversions to indicate that a result is available. If the STDY is high, however, it indicates that the result being provided is not from a fully settled second-stage FIR filter. When the FIR filter has fully settled, the STDY bit will go low coincident with RDY. If the part is never placed into its FASTStep mode, the STDY bit will go low at the first Data Register read and it is not cleared by subsequent Data Register reads. A number of events set the STDY bit high as indicated in Table XVIII. STDY is set high along with RDY by all events in the table except a Data Register read. STBY - Standby Bit. This bit indicates whether the AD7730 is in its Standby Mode or normal mode of operation. The part can be placed in its standby mode using the STANDBY input pin or by writing 011 to the MD2 to MD0 bits of the Mode Register. The power-on/reset status of this bit is 0 assuming the STANDBY pin is high. NOREF - No Reference Bit. If the voltage between the REF IN(+) and REF IN(-) pins is below 0.3 V, or either of these inputs is open-circuit, the NOREF bit goes to 1. If NOREF is active on completion of a conversion, the Data Register is loaded with all 1s. If NOREF is active on completion of a calibration, updating of the calibration registers is inhibited.
[ "RDY", "-", "Ready", "Bit", ".", "This", "bit", "provides", "the", "status", "of", "the", "RDY", "flag", "from", "the", "part", ".", "The", "status", "and", "function", "of", "this", "bit", "is", "the", "same", "as", "the", "RDY", "output", "pin", "....
d18d858ae83b203defcf2aead0dbd11b3c444658
https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/examples/I2CSPI_BRIDGEADC01.py#L189-L219
train
46,192
MLAB-project/pymlab
src/pymlab/sensors/sht.py
SHT31._calculate_checksum
def _calculate_checksum(value): """4.12 Checksum Calculation from an unsigned short input""" # CRC polynomial = 0x131 # //P(x)=x^8+x^5+x^4+1 = 100110001 crc = 0xFF # calculates 8-Bit checksum with given polynomial for byteCtr in [ord(x) for x in struct.pack(">H", value)]: crc ^= byteCtr for bit in range(8, 0, -1): if crc & 0x80: crc = (crc << 1) ^ polynomial else: crc = (crc << 1) return crc
python
def _calculate_checksum(value): """4.12 Checksum Calculation from an unsigned short input""" # CRC polynomial = 0x131 # //P(x)=x^8+x^5+x^4+1 = 100110001 crc = 0xFF # calculates 8-Bit checksum with given polynomial for byteCtr in [ord(x) for x in struct.pack(">H", value)]: crc ^= byteCtr for bit in range(8, 0, -1): if crc & 0x80: crc = (crc << 1) ^ polynomial else: crc = (crc << 1) return crc
[ "def", "_calculate_checksum", "(", "value", ")", ":", "# CRC", "polynomial", "=", "0x131", "# //P(x)=x^8+x^5+x^4+1 = 100110001", "crc", "=", "0xFF", "# calculates 8-Bit checksum with given polynomial", "for", "byteCtr", "in", "[", "ord", "(", "x", ")", "for", "x", "...
4.12 Checksum Calculation from an unsigned short input
[ "4", ".", "12", "Checksum", "Calculation", "from", "an", "unsigned", "short", "input" ]
d18d858ae83b203defcf2aead0dbd11b3c444658
https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/src/pymlab/sensors/sht.py#L149-L163
train
46,193
svenkreiss/databench
databench/analyses_packaged/dummypi_py/analysis.py
Dummypi_Py.run
def run(self): """Run when button is pressed.""" inside = 0 for draws in range(1, self.data['samples']): # generate points and check whether they are inside the unit circle r1, r2 = (random(), random()) if r1 ** 2 + r2 ** 2 < 1.0: inside += 1 if draws % 1000 != 0: continue # debug yield self.emit('log', {'draws': draws, 'inside': inside}) # calculate pi and its uncertainty given the current draws p = inside / draws pi = { 'estimate': 4.0 * inside / draws, 'uncertainty': 4.0 * math.sqrt(draws * p * (1.0 - p)) / draws, } # send status to frontend yield self.set_state(pi=pi) yield self.emit('log', {'action': 'done'})
python
def run(self): """Run when button is pressed.""" inside = 0 for draws in range(1, self.data['samples']): # generate points and check whether they are inside the unit circle r1, r2 = (random(), random()) if r1 ** 2 + r2 ** 2 < 1.0: inside += 1 if draws % 1000 != 0: continue # debug yield self.emit('log', {'draws': draws, 'inside': inside}) # calculate pi and its uncertainty given the current draws p = inside / draws pi = { 'estimate': 4.0 * inside / draws, 'uncertainty': 4.0 * math.sqrt(draws * p * (1.0 - p)) / draws, } # send status to frontend yield self.set_state(pi=pi) yield self.emit('log', {'action': 'done'})
[ "def", "run", "(", "self", ")", ":", "inside", "=", "0", "for", "draws", "in", "range", "(", "1", ",", "self", ".", "data", "[", "'samples'", "]", ")", ":", "# generate points and check whether they are inside the unit circle", "r1", ",", "r2", "=", "(", "...
Run when button is pressed.
[ "Run", "when", "button", "is", "pressed", "." ]
99d4adad494b60a42af6b8bfba94dd0c41ba0786
https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench/analyses_packaged/dummypi_py/analysis.py#L21-L47
train
46,194
svenkreiss/databench
databench/analysis.py
Analysis.init_datastores
def init_datastores(self): """Initialize datastores for this analysis instance. This creates instances of :class:`.Datastore` at ``data`` and ``class_data`` with the datastore domains being the current id and the class name of this analysis respectively. Overwrite this method to use other datastore backends. """ self.data = Datastore(self.id_) self.data.subscribe(lambda data: self.emit('data', data)) self.class_data = Datastore(type(self).__name__) self.class_data.subscribe(lambda data: self.emit('class_data', data))
python
def init_datastores(self): """Initialize datastores for this analysis instance. This creates instances of :class:`.Datastore` at ``data`` and ``class_data`` with the datastore domains being the current id and the class name of this analysis respectively. Overwrite this method to use other datastore backends. """ self.data = Datastore(self.id_) self.data.subscribe(lambda data: self.emit('data', data)) self.class_data = Datastore(type(self).__name__) self.class_data.subscribe(lambda data: self.emit('class_data', data))
[ "def", "init_datastores", "(", "self", ")", ":", "self", ".", "data", "=", "Datastore", "(", "self", ".", "id_", ")", "self", ".", "data", ".", "subscribe", "(", "lambda", "data", ":", "self", ".", "emit", "(", "'data'", ",", "data", ")", ")", "sel...
Initialize datastores for this analysis instance. This creates instances of :class:`.Datastore` at ``data`` and ``class_data`` with the datastore domains being the current id and the class name of this analysis respectively. Overwrite this method to use other datastore backends.
[ "Initialize", "datastores", "for", "this", "analysis", "instance", "." ]
99d4adad494b60a42af6b8bfba94dd0c41ba0786
https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench/analysis.py#L166-L178
train
46,195
svenkreiss/databench
databench/analysis.py
Analysis.emit
def emit(self, signal, message='__nomessagetoken__'): """Emit a signal to the frontend. :param str signal: name of the signal :param message: message to send :returns: return value from frontend emit function :rtype: tornado.concurrent.Future """ # call pre-emit hooks if signal == 'log': self.log_backend.info(message) elif signal == 'warn': self.log_backend.warn(message) elif signal == 'error': self.log_backend.error(message) return self.emit_to_frontend(signal, message)
python
def emit(self, signal, message='__nomessagetoken__'): """Emit a signal to the frontend. :param str signal: name of the signal :param message: message to send :returns: return value from frontend emit function :rtype: tornado.concurrent.Future """ # call pre-emit hooks if signal == 'log': self.log_backend.info(message) elif signal == 'warn': self.log_backend.warn(message) elif signal == 'error': self.log_backend.error(message) return self.emit_to_frontend(signal, message)
[ "def", "emit", "(", "self", ",", "signal", ",", "message", "=", "'__nomessagetoken__'", ")", ":", "# call pre-emit hooks", "if", "signal", "==", "'log'", ":", "self", ".", "log_backend", ".", "info", "(", "message", ")", "elif", "signal", "==", "'warn'", "...
Emit a signal to the frontend. :param str signal: name of the signal :param message: message to send :returns: return value from frontend emit function :rtype: tornado.concurrent.Future
[ "Emit", "a", "signal", "to", "the", "frontend", "." ]
99d4adad494b60a42af6b8bfba94dd0c41ba0786
https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench/analysis.py#L189-L205
train
46,196
svenkreiss/databench
databench/datastore_legacy.py
DatastoreList.set
def set(self, i, value): """Set value at position i and return a Future. :rtype: tornado.concurrent.Future """ value_encoded = encode(value, self.get_change_trigger(i)) if i in self.data and self.data[i] == value_encoded: return self self.data[i] = value_encoded return self.trigger_changed(i)
python
def set(self, i, value): """Set value at position i and return a Future. :rtype: tornado.concurrent.Future """ value_encoded = encode(value, self.get_change_trigger(i)) if i in self.data and self.data[i] == value_encoded: return self self.data[i] = value_encoded return self.trigger_changed(i)
[ "def", "set", "(", "self", ",", "i", ",", "value", ")", ":", "value_encoded", "=", "encode", "(", "value", ",", "self", ".", "get_change_trigger", "(", "i", ")", ")", "if", "i", "in", "self", ".", "data", "and", "self", ".", "data", "[", "i", "]"...
Set value at position i and return a Future. :rtype: tornado.concurrent.Future
[ "Set", "value", "at", "position", "i", "and", "return", "a", "Future", "." ]
99d4adad494b60a42af6b8bfba94dd0c41ba0786
https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench/datastore_legacy.py#L60-L71
train
46,197
svenkreiss/databench
databench/datastore_legacy.py
DatastoreLegacy.set
def set(self, key, value): """Set value at key and return a Future :rtype: tornado.concurrent.Future """ return DatastoreLegacy.store[self.domain].set(key, value)
python
def set(self, key, value): """Set value at key and return a Future :rtype: tornado.concurrent.Future """ return DatastoreLegacy.store[self.domain].set(key, value)
[ "def", "set", "(", "self", ",", "key", ",", "value", ")", ":", "return", "DatastoreLegacy", ".", "store", "[", "self", ".", "domain", "]", ".", "set", "(", "key", ",", "value", ")" ]
Set value at key and return a Future :rtype: tornado.concurrent.Future
[ "Set", "value", "at", "key", "and", "return", "a", "Future" ]
99d4adad494b60a42af6b8bfba94dd0c41ba0786
https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench/datastore_legacy.py#L265-L270
train
46,198
python-astrodynamics/spacetrack
shovel/docs.py
watch
def watch(): """Renerate documentation when it changes.""" # Start with a clean build sphinx_build['-b', 'html', '-E', 'docs', 'docs/_build/html'] & FG handler = ShellCommandTrick( shell_command='sphinx-build -b html docs docs/_build/html', patterns=['*.rst', '*.py'], ignore_patterns=['_build/*'], ignore_directories=['.tox'], drop_during_process=True) observer = Observer() observe_with(observer, handler, pathnames=['.'], recursive=True)
python
def watch(): """Renerate documentation when it changes.""" # Start with a clean build sphinx_build['-b', 'html', '-E', 'docs', 'docs/_build/html'] & FG handler = ShellCommandTrick( shell_command='sphinx-build -b html docs docs/_build/html', patterns=['*.rst', '*.py'], ignore_patterns=['_build/*'], ignore_directories=['.tox'], drop_during_process=True) observer = Observer() observe_with(observer, handler, pathnames=['.'], recursive=True)
[ "def", "watch", "(", ")", ":", "# Start with a clean build", "sphinx_build", "[", "'-b'", ",", "'html'", ",", "'-E'", ",", "'docs'", ",", "'docs/_build/html'", "]", "&", "FG", "handler", "=", "ShellCommandTrick", "(", "shell_command", "=", "'sphinx-build -b html d...
Renerate documentation when it changes.
[ "Renerate", "documentation", "when", "it", "changes", "." ]
18f63b7de989a31b983d140a11418e01bd6fd398
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/shovel/docs.py#L18-L31
train
46,199