code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if self.hidden == 'N':
return True
for owner in self.owners:
if int(owner.user_id) == int(user_id):
if owner.view == 'Y':
return True
return False | def check_user(self, user_id) | Check whether this user can read this dataset | 4.867084 | 4.280531 | 1.137028 |
ref_key = self.ref_key
if ref_key == 'NETWORK':
return self.network
elif ref_key == 'NODE':
return self.node.network
elif ref_key == 'LINK':
return self.link.network
elif ref_key == 'GROUP':
return self.group.network
... | def get_network(self) | Get the network that this resource attribute is in. | 2.846819 | 2.599914 | 1.094967 |
return self.get_resource().check_read_permission(user_id, do_raise=do_raise) | def check_read_permission(self, user_id, do_raise=True) | Check whether this user can read this resource attribute | 3.782922 | 3.019469 | 1.252843 |
return self.get_resource().check_write_permission(user_id, do_raise=do_raise) | def check_write_permission(self, user_id, do_raise=True) | Check whether this user can write this node | 3.920158 | 3.513294 | 1.115807 |
existing_link = get_session().query(Link).filter(Link.name==name, Link.network_id==self.id).first()
if existing_link is not None:
raise HydraError("A link with name %s is already in network %s"%(name, self.id))
l = Link()
l.name = name
l.description ... | def add_link(self, name, desc, layout, node_1, node_2) | Add a link to a network. Links are what effectively
define the network topology, by associating two already
existing nodes. | 2.690382 | 2.778691 | 0.968219 |
existing_node = get_session().query(Node).filter(Node.name==name, Node.network_id==self.id).first()
if existing_node is not None:
raise HydraError("A node with name %s is already in network %s"%(name, self.id))
node = Node()
node.name = name
node.desc... | def add_node(self, name, desc, layout, node_x, node_y) | Add a node to a network. | 3.43143 | 3.260026 | 1.052577 |
existing_group = get_session().query(ResourceGroup).filter(ResourceGroup.name==name, ResourceGroup.network_id==self.id).first()
if existing_group is not None:
raise HydraError("A resource group with name %s is already in network %s"%(name, self.id))
group_i = R... | def add_group(self, name, desc, status) | Add a new group to a network. | 3.01451 | 2.872878 | 1.0493 |
if _is_admin(user_id):
return True
if int(self.created_by) == int(user_id):
return True
for owner in self.owners:
if int(owner.user_id) == int(user_id):
if owner.view == 'Y':
break
else:
if do_... | def check_read_permission(self, user_id, do_raise=True) | Check whether this user can read this network | 3.576721 | 3.238389 | 1.104475 |
if _is_admin(user_id):
return
if int(self.created_by) == int(user_id):
return
for owner in self.owners:
if owner.user_id == int(user_id):
if owner.view == 'Y' and owner.share == 'Y':
break
else:
... | def check_share_permission(self, user_id) | Check whether this user can write this project | 4.400218 | 4.302111 | 1.022804 |
return self.network.check_read_permission(user_id, do_raise=do_raise) | def check_read_permission(self, user_id, do_raise=True) | Check whether this user can read this link | 4.323177 | 3.97924 | 1.086433 |
return self.network.check_write_permission(user_id, do_raise=do_raise) | def check_write_permission(self, user_id, do_raise=True) | Check whether this user can write this link | 4.429993 | 4.017548 | 1.102661 |
items = get_session().query(ResourceGroupItem)\
.filter(ResourceGroupItem.group_id==self.id).\
filter(ResourceGroupItem.scenario_id==scenario_id).all()
return items | def get_items(self, scenario_id) | Get all the items in this group, in the given scenario | 3.911687 | 3.557997 | 1.099407 |
if ref_key == 'NETWORK':
self.network_id = ref_id
elif ref_key == 'NODE':
self.node_id = ref_id
elif ref_key == 'LINK':
self.link_id = ref_id
elif ref_key == 'GROUP':
self.group_id = ref_id
elif ref_key == 'SCENARIO':
... | def set_ref(self, ref_key, ref_id) | Using a ref key and ref id set the
reference to the appropriate resource type. | 2.120833 | 2.14319 | 0.989568 |
if self.ref_key == 'NETWORK':
return self.network_id
elif self.ref_key == 'NODE':
return self.node_id
elif self.ref_key == 'LINK':
return self.link_id
elif self.ref_key == 'GROUP':
return self.group_id
elif self.ref_key ==... | def get_ref_id(self) | Return the ID of the resource to which this not is attached | 1.960997 | 1.925535 | 1.018417 |
if self.ref_key == 'NETWORK':
return self.network
elif self.ref_key == 'NODE':
return self.node
elif self.ref_key == 'LINK':
return self.link
elif self.ref_key == 'GROUP':
return self.group
elif self.ref_key == 'SCENARIO':
... | def get_ref(self) | Return the ID of the resource to which this not is attached | 2.149411 | 2.128302 | 1.009918 |
perms = set()
for r in self.roles:
perms = perms | set(r.permissions)
return perms | def permissions(self) | Return a set with all permissions granted to the user. | 4.487165 | 3.200271 | 1.40212 |
roles = []
for ur in self.roleusers:
roles.append(ur.role)
return set(roles) | def roles(self) | Return a set with all roles granted to the user. | 5.570395 | 4.033975 | 1.38087 |
for ur in self.roleusers:
if ur.role.code == 'admin':
return True
return False | def is_admin(self) | Check that the user has a role with the code 'admin' | 8.245586 | 4.84825 | 1.700735 |
if unit_id is None:
unit_id = typeattr.unit_id
dimension_id = _get_attr(typeattr.attr_id).dimension_id
if unit_id is not None and dimension_id is None:
# First error case
unit_dimension_id = units.get_dimension_by_unit_id(unit_id).id
raise HydraError("Unit %s (abbrevia... | def _check_dimension(typeattr, unit_id=None) | Check that the unit and dimension on a type attribute match.
Alternatively, pass in a unit manually to check against the dimension
of the type attribute | 2.233626 | 2.270615 | 0.98371 |
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('typeatt... | 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. | 2.811869 | 2.897525 | 0.970438 |
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("Attri... | 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. | 3.378074 | 3.323834 | 1.016318 |
user_id = kwargs['user_id']
return json.dumps(get_template_as_dict(template_id, user_id=user_id)) | def get_template_as_json(template_id, **kwargs) | Get a template (including attribute and dataset definitions) as a JSON
string. This is just a wrapper around the get_template_as_dict function. | 3.061638 | 3.649425 | 0.838937 |
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').joine... | def get_template_as_xml(template_id,**kwargs) | Turn a template into an xml template | 2.381095 | 2.363967 | 1.007246 |
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) | 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
... | 3.115866 | 3.604154 | 0.864521 |
net_i = db.DBSession.query(Network).filter(Network.id==network_id).one()
#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_id = db.DBSession.query(TemplateType.id).filter(TemplateType.template_id==template_id,
... | def apply_template_to_network(template_id, network_id, **kwargs) | For each node and link in a network, check whether it matches
a type in a given template. If so, assign the type to the node / link. | 2.402801 | 2.341741 | 1.026074 |
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',
ResourceT... | 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. | 2.009151 | 2.058038 | 0.976246 |
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... | 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 wi... | 1.897832 | 1.877668 | 1.010739 |
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:... | def _get_resources_to_remove(resource, template) | Given a resource and a template being removed, identify the resource attribtes
which can be removed. | 2.972475 | 2.948939 | 1.007981 |
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 = d... | 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. | 1.951602 | 2.115063 | 0.922716 |
#Remove duplicate values from types by turning it into a set
type_ids = list(set([rt.type_id for rt in resource_types]))
db_types = db.DBSession.query(TemplateType).filter(TemplateType.id.in_(type_ids)).options(joinedload_all('typeattrs')).all()
types = {}
for db_type in db_types:
if ... | def assign_types_to_resources(resource_types,**kwargs) | Assign new types to list of resources.
This function checks if the necessary
attributes are present and adds them if needed. Non existing attributes
are also added when the type is already assigned. This means that this
function can also be used to update resources, when a resource type ... | 2.244122 | 2.294009 | 0.978253 |
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
tem... | 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... | 1.865472 | 1.835357 | 1.016409 |
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).fil... | 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. | 2.469979 | 2.496885 | 0.989224 |
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==t... | def remove_type_from_resource( type_id, resource_type, resource_id,**kwargs) | Remove a resource type trom a resource | 2.695487 | 2.619361 | 1.029063 |
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.templ... | def add_template(template, **kwargs) | Add template and a type and typeattrs. | 3.260536 | 3.159608 | 1.031943 |
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
... | def update_template(template,**kwargs) | Update template and a type and typeattrs. | 2.993662 | 2.807336 | 1.066371 |
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) | Delete a template and its type and typeattrs. | 2.726847 | 2.972724 | 0.917289 |
if load_all is False:
templates = db.DBSession.query(Template).all()
else:
templates = db.DBSession.query(Template).options(joinedload_all('templatetypes.typeattrs')).all()
return templates | def get_templates(load_all=True, **kwargs) | Get all templates.
Args:
load_all Boolean: Returns just the template entry or the full template structure (template types and type attrs)
Returns:
List of Template objects | 4.972907 | 4.225572 | 1.17686 |
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:
... | def get_template(template_id,**kwargs) | Get a specific resource template template, by ID. | 5.395918 | 5.599682 | 0.963611 |
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('Templ... | def get_template_by_name(name,**kwargs) | Get a specific resource template, by name. | 7.322618 | 7.54143 | 0.970985 |
type_i = _update_templatetype(templatetype)
db.DBSession.flush()
return type_i | def add_templatetype(templatetype,**kwargs) | Add a template type with typeattrs. | 10.879893 | 10.736149 | 1.013389 |
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) | Update a resource type and its typeattrs.
New typeattrs will be added. typeattrs not sent will be ignored.
To delete typeattrs, call delete_typeattr | 3.834603 | 5.273344 | 0.727167 |
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:
... | 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 d... | 3.93143 | 3.94294 | 0.997081 |
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.te... | 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. | 2.156112 | 2.18785 | 0.985493 |
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... | def delete_templatetype(type_id,template_i=None, **kwargs) | Delete a template type and its typeattrs. | 2.133363 | 2.182203 | 0.977619 |
templatetype = db.DBSession.query(TemplateType).filter(
TemplateType.id==type_id).options(
joinedload_all("typeattrs")).one()
return templatetype | def get_templatetype(type_id,**kwargs) | Get a specific resource type by ID. | 6.200793 | 6.990493 | 0.887032 |
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) | Get a specific resource type by name. | 3.223023 | 3.522841 | 0.914893 |
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) | Add an typeattr to an existing type. | 7.276652 | 6.209535 | 1.171851 |
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()
... | def delete_typeattr(typeattr,**kwargs) | Remove an typeattr from an existing type | 3.650065 | 3.642185 | 1.002164 |
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
t... | 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. | 3.808727 | 3.91083 | 0.973892 |
multi_rs = db.DBSession.query(ResourceScenario).\
filter(ResourceScenario.resource_attr_id.in_(resource_attr_ids),\
ResourceScenario.scenario_id==scenario_id).\
options(joinedload_all("resourceattr")).\
... | 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. | 3.130003 | 3.232985 | 0.968146 |
res = resourcescenario.resourceattr.get_resource()
types = res.types
dataset = resourcescenario.dataset
if len(types) == 0:
return
if template_id is not None:
if template_id not in [r.templatetype.template_id for r in res.types]:
raise HydraError("Template %s is ... | def _do_validate_resourcescenario(resourcescenario, template_id=None) | Perform a check to ensure a resource scenario's datasets are correct given what the
definition of that resource (its type) specifies. | 4.699712 | 4.64097 | 1.012657 |
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)... | 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, ... | 2.025448 | 1.977574 | 1.024208 |
template_xml = etree.Element("template_definition")
net_i = db.DBSession.query(Network).filter(Network.id==network_id).one()
template_name = etree.SubElement(template_xml, "template_name")
template_name.text = "TemplateType from Network %s"%(net_i.name)
layout = _get_layout_as_etree(net_i.lay... | def get_network_as_xml_template(network_id,**kwargs) | Turn an existing network into an xml template
using its attributes.
If an optional scenario ID is passed in, default
values will be populated from that scenario. | 1.618766 | 1.62704 | 0.994915 |
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... | 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 | 2.007484 | 2.061337 | 0.973874 |
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) | General function to add an attribute element to a resource element. | 3.698067 | 3.645118 | 1.014526 |
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.tex... | def _make_attr_element(parent, attr_i) | create an attribute element from an attribute DB object | 2.850201 | 2.766662 | 1.030195 |
layout_dict = dict()
for item in layout_tree.findall('item'):
name = item.find('name').text
val_element = item.find('value')
value = val_element.text.strip()
if value == '':
children = val_element.getchildren()
value = etree.tostring(children[0], pr... | def get_etree_layout_as_dict(layout_tree) | Convert something that looks like this:
<layout>
<item>
<name>color</name>
<value>red</value>
</item>
<item>
<name>shapefile</name>
<value>blah.shp</value>
</item>
</layout>
Into something that looks like this:
{
'co... | 2.729381 | 2.586723 | 1.05515 |
if layout_dict is None:
return None
layout = etree.Element("layout")
layout_dict = eval(layout_dict)
for k, v in layout_dict.items():
item = etree.SubElement(layout, "item")
name = etree.SubElement(item, "name")
name.text = k
value = etree.SubElement(item, "... | def _get_layout_as_etree(layout_dict) | Convert something that looks like this:
{
'color' : ['red'],
'shapefile' : ['blah.shp']
}
Into something that looks like this:
<layout>
<item>
<name>color</name>
<value>red</value>
</item>
<item>
<name>shapefile</name>
... | 1.961518 | 1.895529 | 1.034813 |
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) | Return the value contained by dataset argument, after casting to
correct type and performing type-specific validation | 3.186146 | 3.184735 | 1.000443 |
if tmap is None:
tmap = typemap
return tmap[datatype.upper()].fromDataset(value, metadata=metadata) | def fromDataset(datatype, value, metadata=None, tmap=None) | Return a representation of dataset argument as an instance
of the class corresponding to its datatype | 3.913358 | 4.34428 | 0.900807 |
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) | Given a dimension returns True if it exists, False otherwise | 4.163989 | 4.150257 | 1.003309 |
try:
float(measure_or_unit_abbreviation[0])
# The measure contains the values and the unit_abbreviation
factor, unit_abbreviation = measure_or_unit_abbreviation.split(' ', 1)
return unit_abbreviation, float(factor)
except ValueError:
# The measure just contains the u... | def _parse_unit(measure_or_unit_abbreviation) | Helper function that extracts constant factors from unit specifications.
This allows to specify units similar to this: 10^6 m^3.
Return a couple (unit, factor) | 2.858563 | 2.755969 | 1.037226 |
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) | 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 measur... | 2.983045 | 3.579595 | 0.833347 |
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(... | 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. | 2.204942 | 2.199005 | 1.0027 |
dimension = JSONObject(Dimension())
dimension.id = None
dimension.name = ''
dimension.description = ''
dimension.project_id = None
dimension.units = []
return dimension | def get_empty_dimension(**kwargs) | Returns a dimension object initialized with empty values | 6.036175 | 5.566042 | 1.084465 |
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
... | def get_dimension(dimension_id, do_accept_dimension_id_none=False,**kwargs) | Given a dimension id returns all its data | 4.681331 | 4.562664 | 1.026008 |
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) | Returns a list of objects describing all the dimensions with all the units. | 4.048177 | 3.348242 | 1.209046 |
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
... | def get_dimension_by_name(dimension_name,**kwargs) | Given a dimension name returns all its data. Used in convert functions | 3.578788 | 3.587696 | 0.997517 |
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) | Returns a single unit | 4.840149 | 4.807628 | 1.006764 |
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) | Returns all the units | 4.368309 | 3.681284 | 1.186626 |
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 ... | 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 | 2.665528 | 2.944997 | 0.905104 |
if do_accept_unit_id_none == True and unit_id is None:
# In this special case, the method returns a dimension with id None
return get_empty_dimension()
try:
dimension = db.DBSession.query(Dimension).join(Unit).filter(Unit.id==unit_id).filter().one()
return get_dimension(dim... | def get_dimension_by_unit_id(unit_id, do_accept_unit_id_none=False, **kwargs) | Return the physical dimension a given unit id refers to.
if do_accept_unit_id_none is False, it raises an exception if unit_id is not valid or None
if do_accept_unit_id_none is True, and unit_id is None, the function returns a Dimension with id None (unit_id can be none in some cases) | 4.096836 | 3.931477 | 1.04206 |
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 ResourceNotFoundErr... | def get_unit_by_abbreviation(unit_abbreviation, **kwargs) | Returns a single unit by abbreviation. Used as utility function to resolve string to id | 4.331905 | 4.238272 | 1.022092 |
if numpy.isscalar(dimension):
# If it is a scalar, converts to an Object
dimension = {'name': dimension}
new_dimension = Dimension()
new_dimension.name = dimension["name"]
if "description" in dimension and dimension["description"] is not None:
new_dimension.description = d... | def add_dimension(dimension,**kwargs) | Add the dimension defined into the object "dimension" to the DB
If dimension["project_id"] is None it means that the dimension is global, otherwise is property of a project
If the dimension exists emits an exception | 3.063515 | 2.863569 | 1.069824 |
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["descriptio... | 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 | 2.865774 | 2.941055 | 0.974403 |
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 Res... | def delete_dimension(dimension_id,**kwargs) | Delete a dimension from the DB. Raises and exception if the dimension does not exist | 2.636729 | 2.624248 | 1.004756 |
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) | Save all the dimensions contained in the passed list. | 4.140344 | 3.536252 | 1.170828 |
new_unit = Unit()
new_unit.dimension_id = unit["dimension_id"]
new_unit.name = unit['name']
# Needed to uniform abbr to abbreviation
new_unit.abbreviation = unit['abbreviation']
# Needed to uniform into to description
new_unit.description = unit['description']
new_un... | def add_unit(unit,**kwargs) | Add the unit defined into the object "unit" to the DB
If unit["project_id"] is None it means that the unit is global, otherwise is property of a project
If the unit exists emits an exception
A minimal example:
.. code-block:: python
new_unit = dict(
name ... | 4.627907 | 3.728726 | 1.24115 |
# 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) | Save all the units contained in the passed list, with the name of their dimension. | 3.028602 | 3.010347 | 1.006064 |
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) | Delete a unit from the DB.
Raises and exception if the unit does not exist | 3.163857 | 3.168502 | 0.998534 |
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 =... | def update_unit(unit, **kwargs) | Update a unit in the DB.
Raises and exception if the unit does not exist | 4.525037 | 4.487518 | 1.008361 |
ds_i = db.DBSession.query(Dataset).filter(Dataset.id==dataset_id).one()
dataset_type = ds_i.type
dsval = ds_i.get_val()
source_unit_abbreviation = get_unit(ds_i.unit_id).abbreviation
if source_unit_abbreviation is not None:
if dataset_type == 'scalar':
new_val = convert(... | def convert_dataset(dataset_id, target_unit_abbreviation,**kwargs) | Convert a whole dataset (specified by 'dataset_id') to new unit ('target_unit_abbreviation').
Conversion ALWAYS creates a NEW dataset, so function returns the dataset ID of new dataset. | 2.508215 | 2.503243 | 1.001986 |
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) | 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 | 4.503675 | 5.448383 | 0.826608 |
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) | 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 | 5.654908 | 6.006744 | 0.941426 |
data = ensure_bytes(data, 'utf8')
codec = get_codec(data)
return codec.converter.decode(data[CODE_LENGTH:]) | def decode(data) | Decode the multibase decoded data
:param data: multibase encoded data
:type data: str or bytes
:return: decoded data
:rtype: str
:raises ValueError: if the data is not multibase encoded | 7.670797 | 9.816522 | 0.781417 |
# if you want to do this correctly, use a key derivation function!
if not isinstance(secret, bytes):
secret = secret.encode()
hash_bytes = sha3.keccak_256(secret).digest()
sk = Ed25519SigningKeyFromHash.generate(hash_bytes=hash_bytes)
# Private key
private_value_base58 = sk.encode... | def ed25519_generate_key_pair_from_secret(secret) | Generate a new key pair.
Args:
secret (:class:`string`): A secret that serves as a seed
Returns:
A tuple of (private_key, public_key) encoded in base58. | 3.515575 | 3.356249 | 1.047471 |
if secret:
keypair_raw = ed25519_generate_key_pair_from_secret(secret)
return CryptoKeypair(
*(k.decode() for k in keypair_raw))
else:
return generate_keypair() | def generate_key_pair(secret=None) | Generates a cryptographic key pair.
Args:
secret (:class:`string`): A secret that serves as a seed
Returns:
:class:`~bigchaindb.common.crypto.CryptoKeypair`: A
:obj:`collections.namedtuple` with named fields
:attr:`~bigchaindb.common.crypto.CryptoKeypair.private_key` and
... | 5.123691 | 5.092858 | 1.006054 |
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() | Return role arn from X-Role-ARN header,
lookup role arn from source IP,
or fall back to command line default. | 3.034249 | 2.166853 | 1.400302 |
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... | def _on_dynamodb_exception(self, error) | Dynamically handle DynamoDB exceptions, returning HTTP error
responses.
:param exceptions.DynamoDBException error: | 3.687678 | 3.643673 | 1.012077 |
"Collect data into fixed-length chunks or blocks"
# _chunk_with_padding('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue) | def _chunk_with_padding(self, iterable, n, fillvalue=None) | Collect data into fixed-length chunks or blocks | 2.398345 | 2.512593 | 0.95453 |
serialized = {}
for key in values:
serialized[key] = _marshall_value(values[key])
return serialized | 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. | 3.627272 | 4.784219 | 0.758174 |
unmarshalled = {}
for key in values:
unmarshalled[key] = _unmarshall_dict(values[key])
return unmarshalled | 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 | 3.458232 | 4.763059 | 0.726053 |
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(... | 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. | 1.74217 | 1.72386 | 1.010622 |
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':
re... | 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 | 1.935746 | 1.780083 | 1.087447 |
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)
eli... | 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 | 2.249094 | 2.276245 | 0.988072 |
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) | 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 th... | 2.186684 | 2.502737 | 0.873717 |
payload = {'TableName': table_name, 'Item': utils.marshall(item)}
if condition_expression:
payload['ConditionExpression'] = condition_expression
if expression_attribute_names:
payload['ExpressionAttributeNames'] = expression_attribute_names
if expression_... | def put_item(self, table_name, item,
condition_expression=None,
expression_attribute_names=None,
expression_attribute_values=None,
return_consumed_capacity=None,
return_item_collection_metrics=None,
return_values=None) | Invoke the `PutItem`_ function, creating a new item, or replaces an
old item with a new item. If an item that has the same primary key as
the new item already exists in the specified table, the new item
completely replaces the existing item. You can perform a conditional
put operation (a... | 1.50807 | 1.631727 | 0.924217 |
payload = {'TableName': table_name,
'Key': utils.marshall(key_dict),
'ConsistentRead': consistent_read}
if expression_attribute_names:
payload['ExpressionAttributeNames'] = expression_attribute_names
if projection_expression:
... | 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
... | 1.698423 | 1.804725 | 0.941098 |
payload = {'TableName': table_name,
'Key': utils.marshall(key_dict),
'UpdateExpression': update_expression}
if condition_expression:
payload['ConditionExpression'] = condition_expression
if expression_attribute_names:
payload... | 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_... | 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... | 1.419863 | 1.47894 | 0.960055 |
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 e... | 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,
tota... | 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`... | 1.380343 | 1.441748 | 0.957409 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.